]> git.mxchange.org Git - hub.git/blob - application/hub/main/package/class_NetworkPackage.php
Renamed 'seperator' to 'separator'
[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 "back-buffered" packages
126          */
127         const STACKER_NAME_BACK_BUFFER = 'package_backbuffer';
128
129         /**
130          * Network target (alias): 'upper hubs'
131          */
132         const NETWORK_TARGET_UPPER_HUBS = 'upper';
133
134         /**
135          * Network target (alias): 'self'
136          */
137         const NETWORK_TARGET_SELF = 'self';
138
139         /**
140          * TCP package size in bytes
141          */
142         const TCP_PACKAGE_SIZE = 512;
143
144         /**
145          * Protected constructor
146          *
147          * @return      void
148          */
149         protected function __construct () {
150                 // Call parent constructor
151                 parent::__construct(__CLASS__);
152         }
153
154         /**
155          * Creates an instance of this class
156          *
157          * @param       $compressorInstance             A Compressor instance for compressing the content
158          * @return      $packageInstance                An instance of a Deliverable class
159          */
160         public static final function createNetworkPackage (Compressor $compressorInstance) {
161                 // Get new instance
162                 $packageInstance = new NetworkPackage();
163
164                 // Now set the compressor instance
165                 $packageInstance->setCompressorInstance($compressorInstance);
166
167                 /*
168                  * We need to initialize a stack here for our packages even for those
169                  * which have no recipient address and stamp... ;-) This stacker will
170                  * also be used for incoming raw data to handle it.
171                  */
172                 $stackerInstance = ObjectFactory::createObjectByConfiguredName('network_package_stacker_class');
173
174                 // At last, set it in this class
175                 $packageInstance->setStackerInstance($stackerInstance);
176
177                 // Init all stacker
178                 $packageInstance->initStackers();
179
180                 // Get a visitor instance for speeding up things
181                 $visitorInstance = ObjectFactory::createObjectByConfiguredName('node_raw_data_monitor_visitor_class', array($packageInstance));
182
183                 // Set it in this package
184                 $packageInstance->setVisitorInstance($visitorInstance);
185
186                 // Return the prepared instance
187                 return $packageInstance;
188         }
189
190         /**
191          * Initialize all stackers
192          *
193          * @return      void
194          */
195         protected function initStackers () {
196                 // Initialize all
197                 foreach (
198                         array(
199                                 self::STACKER_NAME_UNDECLARED,
200                                 self::STACKER_NAME_DECLARED,
201                                 self::STACKER_NAME_OUTGOING,
202                                 self::STACKER_NAME_DECODED_INCOMING,
203                                 self::STACKER_NAME_DECODED_HANDLED,
204                                 self::STACKER_NAME_BACK_BUFFER
205                         ) as $stackerName) {
206                                 // Init this stacker
207                                 $this->getStackerInstance()->initStacker($stackerName);
208                 } // END - foreach
209         }
210
211         /**
212          * "Getter" for hash from given content and helper instance
213          *
214          * @param       $content                        Raw package content
215          * @param       $helperInstance         An instance of a HelpableHub class
216          * @param       $nodeInstance           An instance of a NodeHelper class
217          * @return      $hash                           Hash for given package content
218          * @todo        $helperInstance is unused
219          */
220         private function getHashFromContent ($content, HelpableHub $helperInstance, NodeHelper $nodeInstance) {
221                 // Create the hash
222                 // @TODO crc32() is very weak, but it needs to be fast
223                 $hash = crc32(
224                         $content .
225                         self::PACKAGE_CHECKSUM_SEPARATOR .
226                         $nodeInstance->getSessionId() .
227                         self::PACKAGE_CHECKSUM_SEPARATOR .
228                         $this->getCompressorInstance()->getCompressorExtension()
229                 );
230
231                 // And return it
232                 return $hash;
233         }
234
235         /**
236          * Change the package with given status in given stack
237          *
238          * @param       $packageData    Raw package data in an array
239          * @param       $stackerName    Name of the stacker
240          * @param       $newStatus              New status to set
241          * @return      void
242          */
243         private function changePackageStatus (array $packageData, $stackerName, $newStatus) {
244                 // Skip this for empty stacks
245                 if ($this->getStackerInstance()->isStackEmpty($stackerName)) {
246                         // This avoids an exception after all packages has failed
247                         return;
248                 } // END - if
249
250                 // Pop the entry (it should be it)
251                 $this->getStackerInstance()->popNamed($stackerName);
252
253                 // Temporary set the new status
254                 $packageData[self::PACKAGE_DATA_STATUS] = $newStatus;
255
256                 // And push it again
257                 $this->getStackerInstance()->pushNamed($stackerName, $packageData);
258         }
259
260         ///////////////////////////////////////////////////////////////////////////
261         //                   Delivering packages / raw data
262         ///////////////////////////////////////////////////////////////////////////
263
264         /**
265          * Delivers the given raw package data.
266          *
267          * @param       $packageData    Raw package data in an array
268          * @return      void
269          */
270         private function declareRawPackageData (array $packageData) {
271                 /*
272                  * We need to disover every recipient, just in case we have a
273                  * multi-recipient entry like 'upper' is. 'all' may be a not so good
274                  * target because it causes an overload on the network and may be
275                  * abused for attacking the network with large packages.
276                  */
277                 $discoveryInstance = PackageDiscoveryFactory::createPackageDiscoveryInstance();
278
279                 // Discover all recipients, this may throw an exception
280                 $discoveryInstance->discoverRecipients($packageData);
281
282                 // Now get an iterator
283                 $iteratorInstance = $discoveryInstance->getIterator();
284
285                 // ... and begin iteration
286                 while ($iteratorInstance->valid()) {
287                         // Get current entry
288                         $currentRecipient = $iteratorInstance->current();
289
290                         // Debug message
291                         $this->debugOutput('PACKAGE: Package declared for recipient ' . $currentRecipient);
292
293                         // Set the recipient
294                         $packageData[self::PACKAGE_DATA_RECIPIENT] = $currentRecipient;
295                         var_dump($packageData);
296
297                         // And enqueue it to the writer class
298                         $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECLARED, $packageData);
299
300                         // Skip to next entry
301                         $iteratorInstance->next();
302                 } // END - while
303
304                 /*
305                  * The recipient list can be cleaned up here because the package which
306                  * shall be delivered has already been added for all entries from the
307                  * list.
308                  */
309                 $discoveryInstance->clearRecipients();
310         }
311
312         /**
313          * Delivers raw package data. In short, this will discover the raw socket
314          * resource through a discovery class (which will analyse the receipient of
315          * the package), register the socket with the connection (handler/helper?)
316          * instance and finally push the raw data on our outgoing queue.
317          *
318          * @param       $packageData    Raw package data in an array
319          * @return      void
320          */
321         private function deliverRawPackageData (array $packageData) {
322                 /*
323                  * This package may become big, depending on the shared object size or
324                  * delivered message size which shouldn't be so long (to save
325                  * bandwidth). Because of the nature of the used protocol (TCP) we need
326                  * to split it up into smaller pieces to fit it into a TCP frame.
327                  *
328                  * So first we need (again) a discovery class but now a protocol
329                  * discovery to choose the right socket resource. The discovery class
330                  * should take a look at the raw package data itself and then decide
331                  * which (configurable!) protocol should be used for that type of
332                  * package.
333                  */
334                 $discoveryInstance = SocketDiscoveryFactory::createSocketDiscoveryInstance();
335
336                 // Now discover the right protocol
337                 $socketResource = $discoveryInstance->discoverSocket($packageData);
338
339                 // Debug message
340                 //* NOISY-DEBUG: */ $this->debugOutput('NETWORK-PACKAGE: Reached line ' . __LINE__ . ' after discoverSocket() has been called.');
341
342                 // We have to put this socket in our registry, so get an instance
343                 $registryInstance = SocketRegistry::createSocketRegistry();
344
345                 // Get the listener from registry
346                 $helperInstance = Registry::getRegistry()->getInstance('connection');
347
348                 // Debug message
349                 //* NOISY-DEBUG: */ $this->debugOutput('NETWORK-PACKAGE: Reached line ' . __LINE__ . ' before isSocketRegistered() has been called.');
350
351                 // Is it not there?
352                 if ((is_resource($socketResource)) && (!$registryInstance->isSocketRegistered($helperInstance, $socketResource))) {
353                         // Then register it
354                         $registryInstance->registerSocket($helperInstance, $socketResource, $packageData);
355                 } // END - if
356
357                 // Debug message
358                 //* NOISY-DEBUG: */ $this->debugOutput('NETWORK-PACKAGE: Reached line ' . __LINE__ . ' after isSocketRegistered() has been called.');
359
360                 // Make sure the connection is up
361                 $helperInstance->getStateInstance()->validatePeerStateConnected();
362
363                 // Debug message
364                 //* NOISY-DEBUG: */ $this->debugOutput('NETWORK-PACKAGE: Reached line ' . __LINE__ . ' after validatePeerStateConnected() has been called.');
365
366                 // Enqueue it again on the out-going queue, the connection is up and working at this point
367                 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_OUTGOING, $packageData);
368         }
369
370         /**
371          * Sends waiting packages
372          *
373          * @param       $packageData    Raw package data
374          * @return      void
375          */
376         private function sendOutgoingRawPackageData (array $packageData) {
377                 // Init sent bytes
378                 $sentBytes = 0;
379
380                 // Get the right connection instance
381                 $helperInstance = SocketRegistry::createSocketRegistry()->getHandlerInstanceFromPackageData($packageData);
382
383                 // Is this connection still alive?
384                 if ($helperInstance->isShuttedDown()) {
385                         // This connection is shutting down
386                         // @TODO We may want to do somthing more here?
387                         return;
388                 } // END - if
389
390                 // Sent out package data
391                 $sentBytes = $helperInstance->sendRawPackageData($packageData);
392
393                 // Remember unsent raw bytes in back-buffer, if any
394                 $this->storeUnsentBytesInBackBuffer($packageData, $sentBytes);
395         }
396
397         /**
398          * "Enqueues" raw content into this delivery class by reading the raw content
399          * from given template instance and pushing it on the 'undeclared' stack.
400          *
401          * @param       $helperInstance         An instance of a HelpableHub class
402          * @param       $nodeInstance           An instance of a NodeHelper class
403          * @return      void
404          */
405         public function enqueueRawDataFromTemplate (HelpableHub $helperInstance, NodeHelper $nodeInstance) {
406                 // Get the raw content ...
407                 $content = $helperInstance->getTemplateInstance()->getRawTemplateData();
408
409                 // ... and compress it
410                 $content = $this->getCompressorInstance()->compressStream($content);
411
412                 // Add magic in front of it and hash behind it, including BASE64 encoding
413                 $content = sprintf(self::PACKAGE_MASK,
414                         // 1.) Compressor's extension
415                         $this->getCompressorInstance()->getCompressorExtension(),
416                         // - separator
417                         self::PACKAGE_MASK_SEPARATOR,
418                         // 2.) Raw package content, encoded with BASE64
419                         base64_encode($content),
420                         // - separator
421                         self::PACKAGE_MASK_SEPARATOR,
422                         // 3.) Tags
423                         implode(self::PACKAGE_TAGS_SEPARATOR, $helperInstance->getPackageTags()),
424                         // - separator
425                         self::PACKAGE_MASK_SEPARATOR,
426                         // 4.) Checksum
427                         $this->getHashFromContent($content, $helperInstance, $nodeInstance)
428                 );
429
430                 // Now prepare the temporary array and push it on the 'undeclared' stack
431                 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_UNDECLARED, array(
432                         self::PACKAGE_DATA_SENDER    => $nodeInstance->getSessionId(),
433                         self::PACKAGE_DATA_RECIPIENT => $helperInstance->getRecipientType(),
434                         self::PACKAGE_DATA_CONTENT   => $content,
435                         self::PACKAGE_DATA_STATUS    => self::PACKAGE_STATUS_NEW
436                 ));
437         }
438
439         /**
440          * Checks wether a package has been enqueued for delivery.
441          *
442          * @return      $isEnqueued             Wether a package is enqueued
443          */
444         public function isPackageEnqueued () {
445                 // Check wether the stacker is not empty
446                 $isEnqueued = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_UNDECLARED)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_UNDECLARED)));
447
448                 // Return the result
449                 return $isEnqueued;
450         }
451
452         /**
453          * Checks wether a package has been declared
454          *
455          * @return      $isDeclared             Wether a package is declared
456          */
457         public function isPackageDeclared () {
458                 // Check wether the stacker is not empty
459                 $isDeclared = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_DECLARED)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_DECLARED)));
460
461                 // Return the result
462                 return $isDeclared;
463         }
464
465         /**
466          * Checks wether a package should be sent out
467          *
468          * @return      $isWaitingDelivery      Wether a package is waiting for delivery
469          */
470         public function isPackageWaitingForDelivery () {
471                 // Check wether the stacker is not empty
472                 $isWaitingDelivery = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_OUTGOING)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_OUTGOING)));
473
474                 // Return the result
475                 return $isWaitingDelivery;
476         }
477
478         /**
479          * Delivers an enqueued package to the stated destination. If a non-session
480          * id is provided, recipient resolver is being asked (and instanced once).
481          * This allows that a single package is being delivered to multiple targets
482          * without enqueueing it for every target. If no target is provided or it
483          * can't be determined a NoTargetException is being thrown.
484          *
485          * @return      void
486          * @throws      NoTargetException       If no target can't be determined
487          */
488         public function declareEnqueuedPackage () {
489                 // Make sure this method isn't working if there is no package enqueued
490                 if (!$this->isPackageEnqueued()) {
491                         // This is not fatal but should be avoided
492                         // @TODO Add some logging here
493                         return;
494                 } // END - if
495
496                 // Now we know for sure there are packages to deliver, we can start
497                 // with the first one.
498                 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_UNDECLARED);
499
500                 // Declare the raw package data for delivery
501                 $this->declareRawPackageData($packageData);
502
503                 // And remove it finally
504                 $this->getStackerInstance()->popNamed(self::STACKER_NAME_UNDECLARED);
505         }
506
507         /**
508          * Delivers the next declared package. Only one package per time will be sent
509          * because this may take time and slows down the whole delivery
510          * infrastructure.
511          *
512          * @return      void
513          */
514         public function deliverDeclaredPackage () {
515                 // Sanity check if we have packages declared
516                 if (!$this->isPackageDeclared()) {
517                         // This is not fatal but should be avoided
518                         // @TODO Add some logging here
519                         return;
520                 } // END - if
521
522                 // Get the package
523                 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_DECLARED);
524
525                 try {
526                         // And try to send it
527                         $this->deliverRawPackageData($packageData);
528
529                         // And remove it finally
530                         $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECLARED);
531                 } catch (InvalidStateException $e) {
532                         // The state is not excepected (shall be 'connected')
533                         $this->debugOutput('PACKAGE: Caught exception ' . $e->__toString() . ' with message=' . $e->getMessage());
534
535                         // Mark the package with status failed
536                         $this->changePackageStatus($packageData, self::STACKER_NAME_DECLARED, self::PACKAGE_STATUS_FAILED);
537                 }
538         }
539
540         /**
541          * Sends waiting packages out for delivery
542          *
543          * @return      void
544          */
545         public function sendWaitingPackage () {
546                 // Send any waiting bytes in the back-buffer before sending a new package
547                 $this->sendBackBufferBytes();
548
549                 // Sanity check if we have packages waiting for delivery
550                 if (!$this->isPackageWaitingForDelivery()) {
551                         // This is not fatal but should be avoided
552                         $this->debugOutput('PACKAGE: No package is waiting for delivery, but ' . __METHOD__ . ' was called.');
553                         return;
554                 } // END - if
555
556                 // Get the package
557                 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_OUTGOING);
558
559                 try {
560                         // Now try to send it
561                         $this->sendOutgoingRawPackageData($packageData);
562
563                         // And remove it finally
564                         $this->getStackerInstance()->popNamed(self::STACKER_NAME_OUTGOING);
565                 } catch (InvalidSocketException $e) {
566                         // Output exception message
567                         $this->debugOutput('PACKAGE: Package was not delivered: ' . $e->getMessage());
568
569                         // Mark package as failed
570                         $this->changePackageStatus($packageData, self::STACKER_NAME_OUTGOING, self::PACKAGE_STATUS_FAILED);
571                 }
572         }
573
574         ///////////////////////////////////////////////////////////////////////////
575         //                   Receiving packages / raw data
576         ///////////////////////////////////////////////////////////////////////////
577
578         /**
579          * Checks wether decoded raw data is pending
580          *
581          * @return      $isPending      Wether decoded raw data is pending
582          */
583         private function isDecodedDataPending () {
584                 // Just return wether the stack is not empty
585                 $isPending = (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_DECODED_INCOMING));
586
587                 // Return the status
588                 return $isPending;
589         }
590
591         /**
592          * Checks wether new raw package data has arrived at a socket
593          *
594          * @param       $poolInstance   An instance of a PoolableListener class
595          * @return      $hasArrived             Wether new raw package data has arrived for processing
596          */
597         public function isNewRawDataPending (PoolableListener $poolInstance) {
598                 // Visit the pool. This monitors the pool for incoming raw data.
599                 $poolInstance->accept($this->getVisitorInstance());
600
601                 // Check for new data arrival
602                 $hasArrived = $this->isDecodedDataPending();
603
604                 // Return the status
605                 return $hasArrived;
606         }
607
608         /**
609          * Handles the incoming decoded raw data. This method does not "convert" the
610          * decoded data back into a package array, it just "handles" it and pushs it
611          * on the next stack.
612          *
613          * @return      void
614          */
615         public function handleIncomingDecodedData () {
616                 /*
617                  * This method should only be called if decoded raw data is pending,
618                  * so check it again.
619                  */
620                 if (!$this->isDecodedDataPending()) {
621                         // This is not fatal but should be avoided
622                         // @TODO Add some logging here
623                         return;
624                 } // END - if
625
626                 // Very noisy debug message:
627                 /* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: Stacker size is ' . $this->getStackerInstance()->getStackCount(self::STACKER_NAME_DECODED_INCOMING) . ' entries.');
628
629                 // "Pop" the next entry (the same array again) from the stack
630                 $decodedData = $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECODED_INCOMING);
631
632                 // Make sure both array elements are there
633                 assert((is_array($decodedData)) && (isset($decodedData[BaseRawDataHandler::PACKAGE_DECODED_DATA])) && (isset($decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE])));
634
635                 /*
636                  * Also make sure the error code is SOCKET_ERROR_UNHANDLED because we
637                  * only want to handle unhandled packages here.
638                  */
639                 assert($decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE] == BaseRawDataHandler::SOCKET_ERROR_UNHANDLED);
640
641                 // Remove the last chunk SEPARATOR (because it is being added and we don't need it)
642                 if (substr($decodedData[BaseRawDataHandler::PACKAGE_DECODED_DATA], -1, 1) == PackageFragmenter::CHUNK_SEPARATOR) {
643                         // It is there and should be removed
644                         $decodedData[BaseRawDataHandler::PACKAGE_DECODED_DATA] = substr($decodedData[BaseRawDataHandler::PACKAGE_DECODED_DATA], 0, -1);
645                 } // END - if
646
647                 // This package is "handled" and can be pushed on the next stack
648                 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECODED_HANDLED, $decodedData);
649         }
650
651         /**
652          * Adds raw decoded data from the given handler instance to this receiver
653          *
654          * @param       $handlerInstance        An instance of a Networkable class
655          * @return      void
656          */
657         public function addDecodedDataToIncomingStack (Networkable $handlerInstance) {
658                 /*
659                  * Get the decoded data from the handler, this is an array with
660                  * 'decoded_data' and 'error_code' as elements.
661                  */
662                 $decodedData = $handlerInstance->getNextDecodedData();
663
664                 // Very noisy debug message:
665                 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: decodedData[' . gettype($decodedData) . ']=' . print_r($decodedData, true));
666
667                 // And push it on our stack
668                 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECODED_INCOMING, $decodedData);
669         }
670
671         /**
672          * Checks wether incoming decoded data is handled.
673          *
674          * @return      $isHandled      Wether incoming decoded data is handled
675          */
676         public function isIncomingDecodedDataHandled () {
677                 // Determine if the stack is not empty
678                 $isHandled = (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_DECODED_HANDLED));
679
680                 // Return it
681                 return $isHandled;
682         }
683
684         /**
685          * Assembles incoming decoded data so it will become an abstract network
686          * package again.
687          *
688          * @return      void
689          */
690         public function assembleDecodedDataToPackage () {
691                 // Make sure the raw decoded package data is handled
692                 assert($this->isIncomingDecodedDataHandled());
693                 $this->getStackerInstance()->debugInstance();
694                 $this->partialStub('Please implement this method.');
695         }
696
697         /**
698          * Checks wether a new package has arrived
699          *
700          * @return      $hasArrived             Wether a new package has arrived for processing
701          */
702         public function isNewPackageArrived () {
703                 // @TODO Add some content here
704         }
705
706         /**
707          * Accepts the visitor to process the visit "request"
708          *
709          * @param       $visitorInstance        An instance of a Visitor class
710          * @return      void
711          */
712         public function accept (Visitor $visitorInstance) {
713                 // Debug message
714                 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: ' . $visitorInstance->__toString() . ' has visited - START');
715
716                 // Visit the package
717                 $visitorInstance->visitNetworkPackage($this);
718
719                 // Debug message
720                 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: ' . $visitorInstance->__toString() . ' has visited - FINISHED');
721         }
722
723         /**
724          * Clears all stacker
725          *
726          * @return      void
727          */
728         public function clearAllStacker () {
729                 // Do the cleanup (no flushing)
730                 foreach (
731                         array(
732                                 self::STACKER_NAME_UNDECLARED,
733                                 self::STACKER_NAME_DECLARED,
734                                 self::STACKER_NAME_OUTGOING,
735                                 self::STACKER_NAME_DECODED_INCOMING,
736                                 self::STACKER_NAME_DECODED_HANDLED,
737                                 self::STACKER_NAME_BACK_BUFFER
738                         ) as $stackerName) {
739                                 // Clear this stacker by forcing an init
740                                 $this->getStackerInstance()->initStacker($stackerName, true);
741                 } // END - foreach
742
743                 // Debug message
744                 /* DEBUG: */ $this->debugOutput('PACKAGE: All stacker have been re-initialized.');
745         }
746
747         /**
748          * Removes the first failed outoging package from the stack to continue
749          * with next one (it will never work until the issue is fixed by you).
750          *
751          * @return      void
752          * @throws      UnexpectedPackageStatusException        If the package status is not 'failed'
753          * @todo        This may be enchanced for outgoing packages?
754          */
755         public function removeFirstFailedPackage () {
756                 // Get the package again
757                 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_DECLARED);
758
759                 // Is the package status 'failed'?
760                 if ($packageData[self::PACKAGE_DATA_STATUS] != self::PACKAGE_STATUS_FAILED) {
761                         // Not failed!
762                         throw new UnexpectedPackageStatusException(array($this, $packageData, self::PACKAGE_STATUS_FAILED), BaseListener::EXCEPTION_UNEXPECTED_PACKAGE_STATUS);
763                 } // END - if
764
765                 // Remove this entry
766                 $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECLARED);
767         }
768 }
769
770 // [EOF]
771 ?>