]> git.mxchange.org Git - hub.git/blob - application/hub/main/package/class_NetworkPackage.php
Continued on development of 'hub' project with many refactorings/addings:
[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';
48
49         /**
50          * Seperator for the above mask
51          */
52         const PACKAGE_MASK_SEPERATOR = ':';
53
54         /**
55          * Seperator for checksum
56          */
57         const PACKAGE_CHECKSUM_SEPERATOR = ':';
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 seperator
91          */
92         const PACKAGE_TAGS_SEPERATOR = ';';
93
94         /**
95          * Raw package data seperator
96          */
97         const PACKAGE_DATA_SEPERATOR = '#';
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_SEPERATOR .
226                         $nodeInstance->getSessionId() .
227                         self::PACKAGE_CHECKSUM_SEPERATOR .
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                         // 2.) Raw package content, encoded with BASE64
417                         base64_encode($content),
418                         // 3.) Tags
419                         implode(self::PACKAGE_TAGS_SEPERATOR, $helperInstance->getPackageTags()),
420                         // 4.) Checksum
421                         $this->getHashFromContent($content, $helperInstance, $nodeInstance)
422                 );
423
424                 // Now prepare the temporary array and push it on the 'undeclared' stack
425                 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_UNDECLARED, array(
426                         self::PACKAGE_DATA_SENDER    => $nodeInstance->getSessionId(),
427                         self::PACKAGE_DATA_RECIPIENT => $helperInstance->getRecipientType(),
428                         self::PACKAGE_DATA_CONTENT   => $content,
429                         self::PACKAGE_DATA_STATUS    => self::PACKAGE_STATUS_NEW
430                 ));
431         }
432
433         /**
434          * Checks wether a package has been enqueued for delivery.
435          *
436          * @return      $isEnqueued             Wether a package is enqueued
437          */
438         public function isPackageEnqueued () {
439                 // Check wether the stacker is not empty
440                 $isEnqueued = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_UNDECLARED)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_UNDECLARED)));
441
442                 // Return the result
443                 return $isEnqueued;
444         }
445
446         /**
447          * Checks wether a package has been declared
448          *
449          * @return      $isDeclared             Wether a package is declared
450          */
451         public function isPackageDeclared () {
452                 // Check wether the stacker is not empty
453                 $isDeclared = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_DECLARED)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_DECLARED)));
454
455                 // Return the result
456                 return $isDeclared;
457         }
458
459         /**
460          * Checks wether a package should be sent out
461          *
462          * @return      $isWaitingDelivery      Wether a package is waiting for delivery
463          */
464         public function isPackageWaitingForDelivery () {
465                 // Check wether the stacker is not empty
466                 $isWaitingDelivery = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_OUTGOING)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_OUTGOING)));
467
468                 // Return the result
469                 return $isWaitingDelivery;
470         }
471
472         /**
473          * Delivers an enqueued package to the stated destination. If a non-session
474          * id is provided, recipient resolver is being asked (and instanced once).
475          * This allows that a single package is being delivered to multiple targets
476          * without enqueueing it for every target. If no target is provided or it
477          * can't be determined a NoTargetException is being thrown.
478          *
479          * @return      void
480          * @throws      NoTargetException       If no target can't be determined
481          */
482         public function declareEnqueuedPackage () {
483                 // Make sure this method isn't working if there is no package enqueued
484                 if (!$this->isPackageEnqueued()) {
485                         // This is not fatal but should be avoided
486                         // @TODO Add some logging here
487                         return;
488                 } // END - if
489
490                 // Now we know for sure there are packages to deliver, we can start
491                 // with the first one.
492                 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_UNDECLARED);
493
494                 // Declare the raw package data for delivery
495                 $this->declareRawPackageData($packageData);
496
497                 // And remove it finally
498                 $this->getStackerInstance()->popNamed(self::STACKER_NAME_UNDECLARED);
499         }
500
501         /**
502          * Delivers the next declared package. Only one package per time will be sent
503          * because this may take time and slows down the whole delivery
504          * infrastructure.
505          *
506          * @return      void
507          */
508         public function deliverDeclaredPackage () {
509                 // Sanity check if we have packages declared
510                 if (!$this->isPackageDeclared()) {
511                         // This is not fatal but should be avoided
512                         // @TODO Add some logging here
513                         return;
514                 } // END - if
515
516                 // Get the package
517                 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_DECLARED);
518
519                 try {
520                         // And try to send it
521                         $this->deliverRawPackageData($packageData);
522
523                         // And remove it finally
524                         $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECLARED);
525                 } catch (InvalidStateException $e) {
526                         // The state is not excepected (shall be 'connected')
527                         $this->debugOutput('PACKAGE: Caught exception ' . $e->__toString() . ' with message=' . $e->getMessage());
528
529                         // Mark the package with status failed
530                         $this->changePackageStatus($packageData, self::STACKER_NAME_DECLARED, self::PACKAGE_STATUS_FAILED);
531                 }
532         }
533
534         /**
535          * Sends waiting packages out for delivery
536          *
537          * @return      void
538          */
539         public function sendWaitingPackage () {
540                 // Send any waiting bytes in the back-buffer before sending a new package
541                 $this->sendBackBufferBytes();
542
543                 // Sanity check if we have packages waiting for delivery
544                 if (!$this->isPackageWaitingForDelivery()) {
545                         // This is not fatal but should be avoided
546                         $this->debugOutput('PACKAGE: No package is waiting for delivery, but ' . __METHOD__ . ' was called.');
547                         return;
548                 } // END - if
549
550                 // Get the package
551                 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_OUTGOING);
552
553                 try {
554                         // Now try to send it
555                         $this->sendOutgoingRawPackageData($packageData);
556
557                         // And remove it finally
558                         $this->getStackerInstance()->popNamed(self::STACKER_NAME_OUTGOING);
559                 } catch (InvalidSocketException $e) {
560                         // Output exception message
561                         $this->debugOutput('PACKAGE: Package was not delivered: ' . $e->getMessage());
562
563                         // Mark package as failed
564                         $this->changePackageStatus($packageData, self::STACKER_NAME_OUTGOING, self::PACKAGE_STATUS_FAILED);
565                 }
566         }
567
568         ///////////////////////////////////////////////////////////////////////////
569         //                   Receiving packages / raw data
570         ///////////////////////////////////////////////////////////////////////////
571
572         /**
573          * Checks wether decoded raw data is pending
574          *
575          * @return      $isPending      Wether decoded raw data is pending
576          */
577         private function isDecodedDataPending () {
578                 // Just return wether the stack is not empty
579                 $isPending = (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_DECODED_INCOMING));
580
581                 // Return the status
582                 return $isPending;
583         }
584
585         /**
586          * Checks wether new raw package data has arrived at a socket
587          *
588          * @param       $poolInstance   An instance of a PoolableListener class
589          * @return      $hasArrived             Wether new raw package data has arrived for processing
590          */
591         public function isNewRawDataPending (PoolableListener $poolInstance) {
592                 // Visit the pool. This monitors the pool for incoming raw data.
593                 $poolInstance->accept($this->getVisitorInstance());
594
595                 // Check for new data arrival
596                 $hasArrived = $this->isDecodedDataPending();
597
598                 // Return the status
599                 return $hasArrived;
600         }
601
602         /**
603          * Handles the incoming decoded raw data. This method does not "convert" the
604          * decoded data back into a package array, it just "handles" it and pushs it
605          * on the next stack.
606          *
607          * @return      void
608          */
609         public function handleIncomingDecodedData () {
610                 /*
611                  * This method should only be called if decoded raw data is pending,
612                  * so check it again.
613                  */
614                 if (!$this->isDecodedDataPending()) {
615                         // This is not fatal but should be avoided
616                         // @TODO Add some logging here
617                         return;
618                 } // END - if
619
620                 // Very noisy debug message:
621                 /* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: Stacker size is ' . $this->getStackerInstance()->getStackCount(self::STACKER_NAME_DECODED_INCOMING) . ' entries.');
622
623                 // "Pop" the next entry (the same array again) from the stack
624                 $decodedData = $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECODED_INCOMING);
625
626                 // Make sure both array elements are there
627                 assert((is_array($decodedData)) && (isset($decodedData[BaseRawDataHandler::PACKAGE_DECODED_DATA])) && (isset($decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE])));
628
629                 /*
630                  * Also make sure the error code is SOCKET_ERROR_UNHANDLED because we
631                  * only want to handle unhandled packages here.
632                  */
633                 assert($decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE] == BaseRawDataHandler::SOCKET_ERROR_UNHANDLED);
634
635                 // Remove the last chunk seperator (because it is being added and we don't need it)
636                 if (substr($decodedData[BaseRawDataHandler::PACKAGE_DECODED_DATA], -1, 1) == PackageFragmenter::CHUNK_SEPERATOR) {
637                         // It is there and should be removed
638                         $decodedData[BaseRawDataHandler::PACKAGE_DECODED_DATA] = substr($decodedData[BaseRawDataHandler::PACKAGE_DECODED_DATA], 0, -1);
639                 } // END - if
640
641                 // This package is "handled" and can be pushed on the next stack
642                 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECODED_HANDLED, $decodedData);
643         }
644
645         /**
646          * Adds raw decoded data from the given handler instance to this receiver
647          *
648          * @param       $handlerInstance        An instance of a Networkable class
649          * @return      void
650          */
651         public function addDecodedDataToIncomingStack (Networkable $handlerInstance) {
652                 /*
653                  * Get the decoded data from the handler, this is an array with
654                  * 'decoded_data' and 'error_code' as elements.
655                  */
656                 $decodedData = $handlerInstance->getNextDecodedData();
657
658                 // Very noisy debug message:
659                 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: decodedData[' . gettype($decodedData) . ']=' . print_r($decodedData, true));
660
661                 // And push it on our stack
662                 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECODED_INCOMING, $decodedData);
663         }
664
665         /**
666          * Checks wether incoming decoded data is handled.
667          *
668          * @return      $isHandled      Wether incoming decoded data is handled
669          */
670         public function isIncomingDecodedDataHandled () {
671                 // Determine if the stack is not empty
672                 $isHandled = (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_DECODED_HANDLED));
673
674                 // Return it
675                 return $isHandled;
676         }
677
678         /**
679          * Assembles incoming decoded data so it will become an abstract network
680          * package again.
681          *
682          * @return      void
683          */
684         public function assembleDecodedDataToPackage () {
685                 $this->getStackerInstance()->debugInstance();
686                 $this->partialStub('Please implement this method.');
687         }
688
689         /**
690          * Checks wether a new package has arrived
691          *
692          * @return      $hasArrived             Wether a new package has arrived for processing
693          */
694         public function isNewPackageArrived () {
695                 // @TODO Add some content here
696         }
697
698         /**
699          * Accepts the visitor to process the visit "request"
700          *
701          * @param       $visitorInstance        An instance of a Visitor class
702          * @return      void
703          */
704         public function accept (Visitor $visitorInstance) {
705                 // Debug message
706                 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: ' . $visitorInstance->__toString() . ' has visited - START');
707
708                 // Visit the package
709                 $visitorInstance->visitNetworkPackage($this);
710
711                 // Debug message
712                 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: ' . $visitorInstance->__toString() . ' has visited - FINISHED');
713         }
714
715         /**
716          * Clears all stacker
717          *
718          * @return      void
719          */
720         public function clearAllStacker () {
721                 // Do the cleanup (no flushing)
722                 foreach (
723                         array(
724                                 self::STACKER_NAME_UNDECLARED,
725                                 self::STACKER_NAME_DECLARED,
726                                 self::STACKER_NAME_OUTGOING,
727                                 self::STACKER_NAME_DECODED_INCOMING,
728                                 self::STACKER_NAME_DECODED_HANDLED,
729                                 self::STACKER_NAME_BACK_BUFFER
730                         ) as $stackerName) {
731                                 // Clear this stacker by forcing an init
732                                 $this->getStackerInstance()->initStacker($stackerName, true);
733                 } // END - foreach
734
735                 // Debug message
736                 /* DEBUG: */ $this->debugOutput('PACKAGE: All stacker have been re-initialized.');
737         }
738
739         /**
740          * Removes the first failed outoging package from the stack to continue
741          * with next one (it will never work until the issue is fixed by you).
742          *
743          * @return      void
744          * @throws      UnexpectedPackageStatusException        If the package status is not 'failed'
745          * @todo        This may be enchanced for outgoing packages?
746          */
747         public function removeFirstFailedPackage () {
748                 // Get the package again
749                 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_DECLARED);
750
751                 // Is the package status 'failed'?
752                 if ($packageData[self::PACKAGE_DATA_STATUS] != self::PACKAGE_STATUS_FAILED) {
753                         // Not failed!
754                         throw new UnexpectedPackageStatusException(array($this, $packageData, self::PACKAGE_STATUS_FAILED), BaseListener::EXCEPTION_UNEXPECTED_PACKAGE_STATUS);
755                 } // END - if
756
757                 // Remove this entry
758                 $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECLARED);
759         }
760 }
761
762 // [EOF]
763 ?>