]> git.mxchange.org Git - hub.git/blob - application/hub/main/package/class_NetworkPackage.php
12487d829b2d8078ba5e975a4e94dcd36c425302
[hub.git] / application / hub / main / package / class_NetworkPackage.php
1 <?php
2 /**
3  * A NetworkPackage class. This class implements Deliverable and Receivable
4  * because all network packages should be deliverable to other nodes and
5  * receivable from other nodes. It further provides methods for reading raw
6  * content from template engines and feeding it to the stacker for undeclared
7  * packages.
8  *
9  * The factory method requires you to provide a compressor class (which must
10  * implement the Compressor interface). If you don't want any compression (not
11  * adviceable due to increased network load), please use the NullCompressor
12  * class and encode it with BASE64 for a more error-free transfer over the
13  * Internet.
14  *
15  * For performance reasons, this class should only be instanciated once and then
16  * used as a "pipe-through" class.
17  *
18  * @author              Roland Haeder <webmaster@ship-simu.org>
19  * @version             0.0.0
20  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2011 Hub Developer Team
21  * @license             GNU GPL 3.0 or any newer version
22  * @link                http://www.ship-simu.org
23  * @todo                Needs to add functionality for handling the object's type
24  *
25  * This program is free software: you can redistribute it and/or modify
26  * it under the terms of the GNU General Public License as published by
27  * the Free Software Foundation, either version 3 of the License, or
28  * (at your option) any later version.
29  *
30  * This program is distributed in the hope that it will be useful,
31  * but WITHOUT ANY WARRANTY; without even the implied warranty of
32  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
33  * GNU General Public License for more details.
34  *
35  * You should have received a copy of the GNU General Public License
36  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
37  */
38 class NetworkPackage extends BaseFrameworkSystem implements Deliverable, Receivable, Registerable, Visitable {
39         /**
40          * Package mask for compressing package data:
41          * 0: Compressor extension
42          * 1: Raw package data
43          * 2: Tags, seperated by semicolons, no semicolon is required if only one tag is needed
44          * 3: Checksum
45          *                     0  1  2  3
46          */
47         const PACKAGE_MASK = '%s%s%s%s%s%s%s';
48
49         /**
50          * Separator for the above mask
51          */
52         const PACKAGE_MASK_SEPARATOR = '^';
53
54         /**
55          * SEPARATOR for checksum
56          */
57         const PACKAGE_CHECKSUM_SEPARATOR = '_';
58
59         /**
60          * Array indexes for above mask, start with zero
61          */
62         const INDEX_COMPRESSOR_EXTENSION = 0;
63         const INDEX_PACKAGE_DATA         = 1;
64         const INDEX_TAGS                 = 2;
65         const INDEX_CHECKSUM             = 3;
66
67         /**
68          * Array indexes for raw package array
69          */
70         const INDEX_PACKAGE_SENDER    = 0;
71         const INDEX_PACKAGE_RECIPIENT = 1;
72         const INDEX_PACKAGE_CONTENT   = 2;
73         const INDEX_PACKAGE_STATUS    = 3;
74
75         /**
76          * Named array elements for package data
77          */
78         const PACKAGE_DATA_SENDER    = 'sender';
79         const PACKAGE_DATA_RECIPIENT = 'recipient';
80         const PACKAGE_DATA_CONTENT   = 'content';
81         const PACKAGE_DATA_STATUS    = 'status';
82
83         /**
84          * All package status
85          */
86         const PACKAGE_STATUS_NEW     = 'new';
87         const PACKAGE_STATUS_FAILED  = 'failed';
88
89         /**
90          * Tags SEPARATOR
91          */
92         const PACKAGE_TAGS_SEPARATOR = ';';
93
94         /**
95          * Raw package data SEPARATOR
96          */
97         const PACKAGE_DATA_SEPARATOR = '#';
98
99         /**
100          * Stacker name for "undeclared" packages
101          */
102         const STACKER_NAME_UNDECLARED = 'package_undeclared';
103
104         /**
105          * Stacker name for "declared" packages (which are ready to send out)
106          */
107         const STACKER_NAME_DECLARED = 'package_declared';
108
109         /**
110          * Stacker name for "out-going" packages
111          */
112         const STACKER_NAME_OUTGOING = 'package_outgoing';
113
114         /**
115          * Stacker name for "incoming" decoded raw data
116          */
117         const STACKER_NAME_DECODED_INCOMING = 'package_decoded_data';
118
119         /**
120          * Stacker name for handled decoded raw data
121          */
122         const STACKER_NAME_DECODED_HANDLED = 'package_handled_decoded';
123
124         /**
125          * Stacker name for "chunked" decoded raw data
126          */
127         const STACKER_NAME_DECODED_CHUNKED = 'package_chunked_decoded';
128
129         /**
130          * Stacker name for "back-buffered" packages
131          */
132         const STACKER_NAME_BACK_BUFFER = 'package_backbuffer';
133
134         /**
135          * Network target (alias): 'upper hubs'
136          */
137         const NETWORK_TARGET_UPPER_HUBS = 'upper';
138
139         /**
140          * Network target (alias): 'self'
141          */
142         const NETWORK_TARGET_SELF = 'self';
143
144         /**
145          * TCP package size in bytes
146          */
147         const TCP_PACKAGE_SIZE = 512;
148
149         /**
150          * Protected constructor
151          *
152          * @return      void
153          */
154         protected function __construct () {
155                 // Call parent constructor
156                 parent::__construct(__CLASS__);
157         }
158
159         /**
160          * Creates an instance of this class
161          *
162          * @param       $compressorInstance             A Compressor instance for compressing the content
163          * @return      $packageInstance                An instance of a Deliverable class
164          */
165         public static final function createNetworkPackage (Compressor $compressorInstance) {
166                 // Get new instance
167                 $packageInstance = new NetworkPackage();
168
169                 // Now set the compressor instance
170                 $packageInstance->setCompressorInstance($compressorInstance);
171
172                 /*
173                  * We need to initialize a stack here for our packages even for those
174                  * which have no recipient address and stamp... ;-) This stacker will
175                  * also be used for incoming raw data to handle it.
176                  */
177                 $stackerInstance = ObjectFactory::createObjectByConfiguredName('network_package_stacker_class');
178
179                 // At last, set it in this class
180                 $packageInstance->setStackerInstance($stackerInstance);
181
182                 // Init all stacker
183                 $packageInstance->initStackers();
184
185                 // Get a visitor instance for speeding up things
186                 $visitorInstance = ObjectFactory::createObjectByConfiguredName('node_raw_data_monitor_visitor_class', array($packageInstance));
187
188                 // Set it in this package
189                 $packageInstance->setVisitorInstance($visitorInstance);
190
191                 // Return the prepared instance
192                 return $packageInstance;
193         }
194
195         /**
196          * Initialize all stackers
197          *
198          * @param       $forceReInit    Whether to force reinitialization of all stacks
199          * @return      void
200          */
201         protected function initStackers ($forceReInit = false) {
202                 // Initialize all
203                 foreach (
204                         array(
205                                 self::STACKER_NAME_UNDECLARED,
206                                 self::STACKER_NAME_DECLARED,
207                                 self::STACKER_NAME_OUTGOING,
208                                 self::STACKER_NAME_DECODED_INCOMING,
209                                 self::STACKER_NAME_DECODED_HANDLED,
210                                 self::STACKER_NAME_DECODED_CHUNKED,
211                                 self::STACKER_NAME_BACK_BUFFER
212                         ) as $stackerName) {
213                                 // Init this stacker
214                                 $this->getStackerInstance()->initStacker($stackerName, $forceReInit);
215                 } // END - foreach
216         }
217
218         /**
219          * "Getter" for hash from given content and helper instance
220          *
221          * @param       $content                        Raw package content
222          * @param       $helperInstance         An instance of a HelpableHub class
223          * @param       $nodeInstance           An instance of a NodeHelper class
224          * @return      $hash                           Hash for given package content
225          * @todo        $helperInstance is unused
226          */
227         private function getHashFromContent ($content, HelpableHub $helperInstance, NodeHelper $nodeInstance) {
228                 // Create the hash
229                 // @TODO crc32() is very weak, but it needs to be fast
230                 $hash = crc32(
231                         $content .
232                         self::PACKAGE_CHECKSUM_SEPARATOR .
233                         $nodeInstance->getSessionId() .
234                         self::PACKAGE_CHECKSUM_SEPARATOR .
235                         $this->getCompressorInstance()->getCompressorExtension()
236                 );
237
238                 // And return it
239                 return $hash;
240         }
241
242         /**
243          * Change the package with given status in given stack
244          *
245          * @param       $packageData    Raw package data in an array
246          * @param       $stackerName    Name of the stacker
247          * @param       $newStatus              New status to set
248          * @return      void
249          */
250         private function changePackageStatus (array $packageData, $stackerName, $newStatus) {
251                 // Skip this for empty stacks
252                 if ($this->getStackerInstance()->isStackEmpty($stackerName)) {
253                         // This avoids an exception after all packages has failed
254                         return;
255                 } // END - if
256
257                 // Pop the entry (it should be it)
258                 $this->getStackerInstance()->popNamed($stackerName);
259
260                 // Temporary set the new status
261                 $packageData[self::PACKAGE_DATA_STATUS] = $newStatus;
262
263                 // And push it again
264                 $this->getStackerInstance()->pushNamed($stackerName, $packageData);
265         }
266
267         ///////////////////////////////////////////////////////////////////////////
268         //                   Delivering packages / raw data
269         ///////////////////////////////////////////////////////////////////////////
270
271         /**
272          * Delivers the given raw package data.
273          *
274          * @param       $packageData    Raw package data in an array
275          * @return      void
276          */
277         private function declareRawPackageData (array $packageData) {
278                 /*
279                  * We need to disover every recipient, just in case we have a
280                  * multi-recipient entry like 'upper' is. 'all' may be a not so good
281                  * target because it causes an overload on the network and may be
282                  * abused for attacking the network with large packages.
283                  */
284                 $discoveryInstance = PackageDiscoveryFactory::createPackageDiscoveryInstance();
285
286                 // Discover all recipients, this may throw an exception
287                 $discoveryInstance->discoverRecipients($packageData);
288
289                 // Now get an iterator
290                 $iteratorInstance = $discoveryInstance->getIterator();
291
292                 // ... and begin iteration
293                 while ($iteratorInstance->valid()) {
294                         // Get current entry
295                         $currentRecipient = $iteratorInstance->current();
296
297                         // Debug message
298                         $this->debugOutput('PACKAGE: Package declared for recipient ' . $currentRecipient);
299
300                         // Set the recipient
301                         $packageData[self::PACKAGE_DATA_RECIPIENT] = $currentRecipient;
302
303                         // And enqueue it to the writer class
304                         $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECLARED, $packageData);
305
306                         // Skip to next entry
307                         $iteratorInstance->next();
308                 } // END - while
309
310                 /*
311                  * The recipient list can be cleaned up here because the package which
312                  * shall be delivered has already been added for all entries from the
313                  * list.
314                  */
315                 $discoveryInstance->clearRecipients();
316         }
317
318         /**
319          * Delivers raw package data. In short, this will discover the raw socket
320          * resource through a discovery class (which will analyse the receipient of
321          * the package), register the socket with the connection (handler/helper?)
322          * instance and finally push the raw data on our outgoing queue.
323          *
324          * @param       $packageData    Raw package data in an array
325          * @return      void
326          */
327         private function deliverRawPackageData (array $packageData) {
328                 /*
329                  * This package may become big, depending on the shared object size or
330                  * delivered message size which shouldn't be so long (to save
331                  * bandwidth). Because of the nature of the used protocol (TCP) we need
332                  * to split it up into smaller pieces to fit it into a TCP frame.
333                  *
334                  * So first we need (again) a discovery class but now a protocol
335                  * discovery to choose the right socket resource. The discovery class
336                  * should take a look at the raw package data itself and then decide
337                  * which (configurable!) protocol should be used for that type of
338                  * package.
339                  */
340                 $discoveryInstance = SocketDiscoveryFactory::createSocketDiscoveryInstance();
341
342                 // Now discover the right protocol
343                 $socketResource = $discoveryInstance->discoverSocket($packageData);
344
345                 // Debug message
346                 //* NOISY-DEBUG: */ $this->debugOutput('NETWORK-PACKAGE: Reached line ' . __LINE__ . ' after discoverSocket() has been called.');
347
348                 // We have to put this socket in our registry, so get an instance
349                 $registryInstance = SocketRegistry::createSocketRegistry();
350
351                 // Get the listener from registry
352                 $helperInstance = Registry::getRegistry()->getInstance('connection');
353
354                 // Debug message
355                 //* NOISY-DEBUG: */ $this->debugOutput('NETWORK-PACKAGE: Reached line ' . __LINE__ . ' before isSocketRegistered() has been called.');
356
357                 // Is it not there?
358                 if ((is_resource($socketResource)) && (!$registryInstance->isSocketRegistered($helperInstance, $socketResource))) {
359                         // Then register it
360                         $registryInstance->registerSocket($helperInstance, $socketResource, $packageData);
361                 } // END - if
362
363                 // Debug message
364                 //* NOISY-DEBUG: */ $this->debugOutput('NETWORK-PACKAGE: Reached line ' . __LINE__ . ' after isSocketRegistered() has been called.');
365
366                 // Make sure the connection is up
367                 $helperInstance->getStateInstance()->validatePeerStateConnected();
368
369                 // Debug message
370                 //* NOISY-DEBUG: */ $this->debugOutput('NETWORK-PACKAGE: Reached line ' . __LINE__ . ' after validatePeerStateConnected() has been called.');
371
372                 // Enqueue it again on the out-going queue, the connection is up and working at this point
373                 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_OUTGOING, $packageData);
374         }
375
376         /**
377          * Sends waiting packages
378          *
379          * @param       $packageData    Raw package data
380          * @return      void
381          */
382         private function sendOutgoingRawPackageData (array $packageData) {
383                 // Init sent bytes
384                 $sentBytes = 0;
385
386                 // Get the right connection instance
387                 $helperInstance = SocketRegistry::createSocketRegistry()->getHandlerInstanceFromPackageData($packageData);
388
389                 // Is this connection still alive?
390                 if ($helperInstance->isShuttedDown()) {
391                         // This connection is shutting down
392                         // @TODO We may want to do somthing more here?
393                         return;
394                 } // END - if
395
396                 // Sent out package data
397                 $sentBytes = $helperInstance->sendRawPackageData($packageData);
398
399                 // Remember unsent raw bytes in back-buffer, if any
400                 $this->storeUnsentBytesInBackBuffer($packageData, $sentBytes);
401         }
402
403         /**
404          * "Enqueues" raw content into this delivery class by reading the raw content
405          * from given template instance and pushing it on the 'undeclared' stack.
406          *
407          * @param       $helperInstance         An instance of a HelpableHub class
408          * @param       $nodeInstance           An instance of a NodeHelper class
409          * @return      void
410          */
411         public function enqueueRawDataFromTemplate (HelpableHub $helperInstance, NodeHelper $nodeInstance) {
412                 // Get the raw content ...
413                 $content = $helperInstance->getTemplateInstance()->getRawTemplateData();
414
415                 // ... and compress it
416                 $content = $this->getCompressorInstance()->compressStream($content);
417
418                 // Add magic in front of it and hash behind it, including BASE64 encoding
419                 $content = sprintf(self::PACKAGE_MASK,
420                         // 1.) Compressor's extension
421                         $this->getCompressorInstance()->getCompressorExtension(),
422                         // - separator
423                         self::PACKAGE_MASK_SEPARATOR,
424                         // 2.) Raw package content, encoded with BASE64
425                         base64_encode($content),
426                         // - separator
427                         self::PACKAGE_MASK_SEPARATOR,
428                         // 3.) Tags
429                         implode(self::PACKAGE_TAGS_SEPARATOR, $helperInstance->getPackageTags()),
430                         // - separator
431                         self::PACKAGE_MASK_SEPARATOR,
432                         // 4.) Checksum
433                         $this->getHashFromContent($content, $helperInstance, $nodeInstance)
434                 );
435
436                 // Now prepare the temporary array and push it on the 'undeclared' stack
437                 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_UNDECLARED, array(
438                         self::PACKAGE_DATA_SENDER    => $nodeInstance->getSessionId(),
439                         self::PACKAGE_DATA_RECIPIENT => $helperInstance->getRecipientType(),
440                         self::PACKAGE_DATA_CONTENT   => $content,
441                         self::PACKAGE_DATA_STATUS    => self::PACKAGE_STATUS_NEW
442                 ));
443         }
444
445         /**
446          * Checks wether a package has been enqueued for delivery.
447          *
448          * @return      $isEnqueued             Wether a package is enqueued
449          */
450         public function isPackageEnqueued () {
451                 // Check wether the stacker is not empty
452                 $isEnqueued = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_UNDECLARED)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_UNDECLARED)));
453
454                 // Return the result
455                 return $isEnqueued;
456         }
457
458         /**
459          * Checks wether a package has been declared
460          *
461          * @return      $isDeclared             Wether a package is declared
462          */
463         public function isPackageDeclared () {
464                 // Check wether the stacker is not empty
465                 $isDeclared = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_DECLARED)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_DECLARED)));
466
467                 // Return the result
468                 return $isDeclared;
469         }
470
471         /**
472          * Checks wether a package should be sent out
473          *
474          * @return      $isWaitingDelivery      Wether a package is waiting for delivery
475          */
476         public function isPackageWaitingForDelivery () {
477                 // Check wether the stacker is not empty
478                 $isWaitingDelivery = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_OUTGOING)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_OUTGOING)));
479
480                 // Return the result
481                 return $isWaitingDelivery;
482         }
483
484         /**
485          * Delivers an enqueued package to the stated destination. If a non-session
486          * id is provided, recipient resolver is being asked (and instanced once).
487          * This allows that a single package is being delivered to multiple targets
488          * without enqueueing it for every target. If no target is provided or it
489          * can't be determined a NoTargetException is being thrown.
490          *
491          * @return      void
492          * @throws      NoTargetException       If no target can't be determined
493          */
494         public function declareEnqueuedPackage () {
495                 // Make sure this method isn't working if there is no package enqueued
496                 if (!$this->isPackageEnqueued()) {
497                         // This is not fatal but should be avoided
498                         // @TODO Add some logging here
499                         return;
500                 } // END - if
501
502                 // Now we know for sure there are packages to deliver, we can start
503                 // with the first one.
504                 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_UNDECLARED);
505
506                 // Declare the raw package data for delivery
507                 $this->declareRawPackageData($packageData);
508
509                 // And remove it finally
510                 $this->getStackerInstance()->popNamed(self::STACKER_NAME_UNDECLARED);
511         }
512
513         /**
514          * Delivers the next declared package. Only one package per time will be sent
515          * because this may take time and slows down the whole delivery
516          * infrastructure.
517          *
518          * @return      void
519          */
520         public function deliverDeclaredPackage () {
521                 // Sanity check if we have packages declared
522                 if (!$this->isPackageDeclared()) {
523                         // This is not fatal but should be avoided
524                         // @TODO Add some logging here
525                         return;
526                 } // END - if
527
528                 // Get the package
529                 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_DECLARED);
530
531                 try {
532                         // And try to send it
533                         $this->deliverRawPackageData($packageData);
534
535                         // And remove it finally
536                         $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECLARED);
537                 } catch (InvalidStateException $e) {
538                         // The state is not excepected (shall be 'connected')
539                         $this->debugOutput('PACKAGE: Caught exception ' . $e->__toString() . ' with message=' . $e->getMessage());
540
541                         // Mark the package with status failed
542                         $this->changePackageStatus($packageData, self::STACKER_NAME_DECLARED, self::PACKAGE_STATUS_FAILED);
543                 }
544         }
545
546         /**
547          * Sends waiting packages out for delivery
548          *
549          * @return      void
550          */
551         public function sendWaitingPackage () {
552                 // Send any waiting bytes in the back-buffer before sending a new package
553                 $this->sendBackBufferBytes();
554
555                 // Sanity check if we have packages waiting for delivery
556                 if (!$this->isPackageWaitingForDelivery()) {
557                         // This is not fatal but should be avoided
558                         $this->debugOutput('PACKAGE: No package is waiting for delivery, but ' . __METHOD__ . ' was called.');
559                         return;
560                 } // END - if
561
562                 // Get the package
563                 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_OUTGOING);
564
565                 try {
566                         // Now try to send it
567                         $this->sendOutgoingRawPackageData($packageData);
568
569                         // And remove it finally
570                         $this->getStackerInstance()->popNamed(self::STACKER_NAME_OUTGOING);
571                 } catch (InvalidSocketException $e) {
572                         // Output exception message
573                         $this->debugOutput('PACKAGE: Package was not delivered: ' . $e->getMessage());
574
575                         // Mark package as failed
576                         $this->changePackageStatus($packageData, self::STACKER_NAME_OUTGOING, self::PACKAGE_STATUS_FAILED);
577                 }
578         }
579
580         ///////////////////////////////////////////////////////////////////////////
581         //                   Receiving packages / raw data
582         ///////////////////////////////////////////////////////////////////////////
583
584         /**
585          * Checks wether decoded raw data is pending
586          *
587          * @return      $isPending      Wether decoded raw data is pending
588          */
589         private function isDecodedDataPending () {
590                 // Just return wether the stack is not empty
591                 $isPending = (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_DECODED_INCOMING));
592
593                 // Return the status
594                 return $isPending;
595         }
596
597         /**
598          * Checks wether new raw package data has arrived at a socket
599          *
600          * @param       $poolInstance   An instance of a PoolableListener class
601          * @return      $hasArrived             Wether new raw package data has arrived for processing
602          */
603         public function isNewRawDataPending (PoolableListener $poolInstance) {
604                 // Visit the pool. This monitors the pool for incoming raw data.
605                 $poolInstance->accept($this->getVisitorInstance());
606
607                 // Check for new data arrival
608                 $hasArrived = $this->isDecodedDataPending();
609
610                 // Return the status
611                 return $hasArrived;
612         }
613
614         /**
615          * Handles the incoming decoded raw data. This method does not "convert" the
616          * decoded data back into a package array, it just "handles" it and pushs it
617          * on the next stack.
618          *
619          * @return      void
620          */
621         public function handleIncomingDecodedData () {
622                 /*
623                  * This method should only be called if decoded raw data is pending,
624                  * so check it again.
625                  */
626                 if (!$this->isDecodedDataPending()) {
627                         // This is not fatal but should be avoided
628                         // @TODO Add some logging here
629                         return;
630                 } // END - if
631
632                 // Very noisy debug message:
633                 /* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: Stacker size is ' . $this->getStackerInstance()->getStackCount(self::STACKER_NAME_DECODED_INCOMING) . ' entries.');
634
635                 // "Pop" the next entry (the same array again) from the stack
636                 $decodedData = $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECODED_INCOMING);
637
638                 // Make sure both array elements are there
639                 assert(
640                         (is_array($decodedData)) &&
641                         (isset($decodedData[BaseRawDataHandler::PACKAGE_DECODED_DATA])) &&
642                         (isset($decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE]))
643                 );
644
645                 /*
646                  * Also make sure the error code is SOCKET_ERROR_UNHANDLED because we
647                  * only want to handle unhandled packages here.
648                  */
649                 assert($decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE] == BaseRawDataHandler::SOCKET_ERROR_UNHANDLED);
650
651                 // Remove the last chunk SEPARATOR (because it is being added and we don't need it)
652                 if (substr($decodedData[BaseRawDataHandler::PACKAGE_DECODED_DATA], -1, 1) == PackageFragmenter::CHUNK_SEPARATOR) {
653                         // It is there and should be removed
654                         $decodedData[BaseRawDataHandler::PACKAGE_DECODED_DATA] = substr($decodedData[BaseRawDataHandler::PACKAGE_DECODED_DATA], 0, -1);
655                 } // END - if
656
657                 // This package is "handled" and can be pushed on the next stack
658                 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECODED_HANDLED, $decodedData);
659         }
660
661         /**
662          * Adds raw decoded data from the given handler instance to this receiver
663          *
664          * @param       $handlerInstance        An instance of a Networkable class
665          * @return      void
666          */
667         public function addDecodedDataToIncomingStack (Networkable $handlerInstance) {
668                 /*
669                  * Get the decoded data from the handler, this is an array with
670                  * 'decoded_data' and 'error_code' as elements.
671                  */
672                 $decodedData = $handlerInstance->getNextDecodedData();
673
674                 // Very noisy debug message:
675                 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: decodedData[' . gettype($decodedData) . ']=' . print_r($decodedData, true));
676
677                 // And push it on our stack
678                 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECODED_INCOMING, $decodedData);
679         }
680
681         /**
682          * Checks wether incoming decoded data is handled.
683          *
684          * @return      $isHandled      Wether incoming decoded data is handled
685          */
686         public function isIncomingDecodedDataHandled () {
687                 // Determine if the stack is not empty
688                 $isHandled = (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_DECODED_HANDLED));
689
690                 // Return it
691                 return $isHandled;
692         }
693
694         /**
695          * Assembles incoming decoded data so it will become an abstract network
696          * package again. The assembler does later do it's job by an other task,
697          * not this one to keep best speed possible.
698          *
699          * @return      void
700          */
701         public function assembleDecodedDataToPackage () {
702                 // Make sure the raw decoded package data is handled
703                 assert($this->isIncomingDecodedDataHandled());
704
705                 // Get current package content (an array with two elements; see handleIncomingDecodedData() for details)
706                 $packageContent = $this->getStackerInstance()->getNamed(self::STACKER_NAME_DECODED_HANDLED);
707
708                 // Get a singleton package assembler instance from factory
709                 $assemblerInstance = PackageAssemblerFactory::createAssemblerInstance();
710
711                 // Start assembling the raw package data array by chunking it
712                 $assemblerInstance->chunkPackageContent($packageContent);
713
714                 // Remove the package from 'handled_decoded' stack ...
715                 $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECODED_HANDLED);
716
717                 // ... and push it on the 'chunked' stacker
718                 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECODED_CHUNKED, $packageContent);
719         }
720
721         /**
722          * Checks wether a new package has arrived
723          *
724          * @return      $hasArrived             Wether a new package has arrived for processing
725          */
726         public function isNewPackageArrived () {
727                 // @TODO Add some content here
728         }
729
730         /**
731          * Accepts the visitor to process the visit "request"
732          *
733          * @param       $visitorInstance        An instance of a Visitor class
734          * @return      void
735          */
736         public function accept (Visitor $visitorInstance) {
737                 // Debug message
738                 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: ' . $visitorInstance->__toString() . ' has visited - START');
739
740                 // Visit the package
741                 $visitorInstance->visitNetworkPackage($this);
742
743                 // Debug message
744                 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: ' . $visitorInstance->__toString() . ' has visited - FINISHED');
745         }
746
747         /**
748          * Clears all stacker
749          *
750          * @return      void
751          */
752         public function clearAllStacker () {
753                 // Call the init method to force re-initialization
754                 $this->initStackers(true);
755
756                 // Debug message
757                 /* DEBUG: */ $this->debugOutput('PACKAGE: All stacker have been re-initialized.');
758         }
759
760         /**
761          * Removes the first failed outoging package from the stack to continue
762          * with next one (it will never work until the issue is fixed by you).
763          *
764          * @return      void
765          * @throws      UnexpectedPackageStatusException        If the package status is not 'failed'
766          * @todo        This may be enchanced for outgoing packages?
767          */
768         public function removeFirstFailedPackage () {
769                 // Get the package again
770                 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_DECLARED);
771
772                 // Is the package status 'failed'?
773                 if ($packageData[self::PACKAGE_DATA_STATUS] != self::PACKAGE_STATUS_FAILED) {
774                         // Not failed!
775                         throw new UnexpectedPackageStatusException(array($this, $packageData, self::PACKAGE_STATUS_FAILED), BaseListener::EXCEPTION_UNEXPECTED_PACKAGE_STATUS);
776                 } // END - if
777
778                 // Remove this entry
779                 $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECLARED);
780         }
781 }
782
783 // [EOF]
784 ?>