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
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
15 * For performance reasons, this class should only be instanciated once and then
16 * used as a "pipe-through" class.
18 * @author Roland Haeder <webmaster@ship-simu.org>
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
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.
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.
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/>.
38 class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, Registerable, Visitable {
40 * Package mask for compressing package data:
41 * 0: Compressor extension
43 * 2: Tags, seperated by semicolons, no semicolon is required if only one tag is needed
47 const PACKAGE_MASK = '%s%s%s%s%s%s%s';
50 * Separator for the above mask
52 const PACKAGE_MASK_SEPARATOR = '^';
55 * SEPARATOR for checksum
57 const PACKAGE_CHECKSUM_SEPARATOR = '_';
60 * Array indexes for above mask, start with zero
62 const INDEX_COMPRESSOR_EXTENSION = 0;
63 const INDEX_PACKAGE_DATA = 1;
65 const INDEX_CHECKSUM = 3;
68 * Array indexes for raw package array
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 const INDEX_PACKAGE_SIGNATURE = 4;
77 * Named array elements for package data
79 const PACKAGE_DATA_SENDER = 'sender';
80 const PACKAGE_DATA_RECIPIENT = 'recipient';
81 const PACKAGE_DATA_CONTENT = 'content';
82 const PACKAGE_DATA_STATUS = 'status';
83 const PACKAGE_DATA_SIGNATURE = 'signature';
88 const PACKAGE_STATUS_NEW = 'new';
89 const PACKAGE_STATUS_FAILED = 'failed';
90 const PACKAGE_STATUS_DECODED = 'decoded';
95 const PACKAGE_TAGS_SEPARATOR = ';';
98 * Raw package data separator
100 const PACKAGE_DATA_SEPARATOR = '#';
103 * Network target (alias): 'upper hubs'
105 const NETWORK_TARGET_UPPER_HUBS = 'upper';
108 * Network target (alias): 'self'
110 const NETWORK_TARGET_SELF = 'self';
113 * TCP package size in bytes
115 const TCP_PACKAGE_SIZE = 512;
117 /**************************************************************************
118 * Stacker for out-going packages *
119 **************************************************************************/
122 * Stacker name for "undeclared" packages
124 const STACKER_NAME_UNDECLARED = 'package_undeclared';
127 * Stacker name for "declared" packages (which are ready to send out)
129 const STACKER_NAME_DECLARED = 'package_declared';
132 * Stacker name for "out-going" packages
134 const STACKER_NAME_OUTGOING = 'package_outgoing';
136 /**************************************************************************
137 * Stacker for incoming packages *
138 **************************************************************************/
141 * Stacker name for "incoming" decoded raw data
143 const STACKER_NAME_DECODED_INCOMING = 'package_decoded_data';
146 * Stacker name for handled decoded raw data
148 const STACKER_NAME_DECODED_HANDLED = 'package_handled_decoded';
151 * Stacker name for "chunked" decoded raw data
153 const STACKER_NAME_DECODED_CHUNKED = 'package_chunked_decoded';
155 /**************************************************************************
156 * Stacker for other/internal purposes *
157 **************************************************************************/
160 * Stacker name for "back-buffered" packages
162 const STACKER_NAME_BACK_BUFFER = 'package_backbuffer';
165 * Protected constructor
169 protected function __construct () {
170 // Call parent constructor
171 parent::__construct(__CLASS__);
175 * Creates an instance of this class
177 * @param $compressorInstance A Compressor instance for compressing the content
178 * @return $packageInstance An instance of a Deliverable class
180 public static final function createNetworkPackage (Compressor $compressorInstance) {
182 $packageInstance = new NetworkPackage();
184 // Now set the compressor instance
185 $packageInstance->setCompressorInstance($compressorInstance);
188 * We need to initialize a stack here for our packages even for those
189 * which have no recipient address and stamp... ;-) This stacker will
190 * also be used for incoming raw data to handle it.
192 $stackerInstance = ObjectFactory::createObjectByConfiguredName('network_package_stacker_class');
194 // At last, set it in this class
195 $packageInstance->setStackerInstance($stackerInstance);
198 $packageInstance->initStackers();
200 // Get a visitor instance for speeding up things
201 $visitorInstance = ObjectFactory::createObjectByConfiguredName('node_raw_data_monitor_visitor_class', array($packageInstance));
203 // Set it in this package
204 $packageInstance->setVisitorInstance($visitorInstance);
206 // Get crypto instance and set it in this package
207 $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
208 $packageInstance->setCryptoInstance($cryptoInstance);
210 // Return the prepared instance
211 return $packageInstance;
215 * Initialize all stackers
217 * @param $forceReInit Whether to force reinitialization of all stacks
220 protected function initStackers ($forceReInit = false) {
224 self::STACKER_NAME_UNDECLARED,
225 self::STACKER_NAME_DECLARED,
226 self::STACKER_NAME_OUTGOING,
227 self::STACKER_NAME_DECODED_INCOMING,
228 self::STACKER_NAME_DECODED_HANDLED,
229 self::STACKER_NAME_DECODED_CHUNKED,
230 self::STACKER_NAME_BACK_BUFFER
233 $this->getStackerInstance()->initStacker($stackerName, $forceReInit);
238 * "Getter" for hash from given content and helper instance
240 * @param $content Raw package content
241 * @param $helperInstance An instance of a HelpableHub class
242 * @param $nodeInstance An instance of a NodeHelper class
243 * @return $hash Hash for given package content
244 * @todo $helperInstance is unused
246 private function getHashFromContent ($content, HelpableHub $helperInstance, NodeHelper $nodeInstance) {
248 // @TODO crc32() is very weak, but it needs to be fast
251 self::PACKAGE_CHECKSUM_SEPARATOR .
252 $nodeInstance->getSessionId() .
253 self::PACKAGE_CHECKSUM_SEPARATOR .
254 $this->getCompressorInstance()->getCompressorExtension()
262 * Change the package with given status in given stack
264 * @param $packageData Raw package data in an array
265 * @param $stackerName Name of the stacker
266 * @param $newStatus New status to set
269 private function changePackageStatus (array $packageData, $stackerName, $newStatus) {
270 // Skip this for empty stacks
271 if ($this->getStackerInstance()->isStackEmpty($stackerName)) {
272 // This avoids an exception after all packages has failed
276 // Pop the entry (it should be it)
277 $nextData = $this->getStackerInstance()->popNamed($stackerName);
279 // Compare both arrays
280 assert($nextData[self::PACKAGE_DATA_SIGNATURE] == $packageData[self::PACKAGE_DATA_SIGNATURE]);
282 // Temporary set the new status
283 $packageData[self::PACKAGE_DATA_STATUS] = $newStatus;
286 $this->getStackerInstance()->pushNamed($stackerName, $packageData);
289 ///////////////////////////////////////////////////////////////////////////
290 // Delivering packages / raw data
291 ///////////////////////////////////////////////////////////////////////////
294 * Delivers the given raw package data.
296 * @param $packageData Raw package data in an array
299 private function declareRawPackageData (array $packageData) {
301 * We need to disover every recipient, just in case we have a
302 * multi-recipient entry like 'upper' is. 'all' may be a not so good
303 * target because it causes an overload on the network and may be
304 * abused for attacking the network with large packages.
306 $discoveryInstance = PackageDiscoveryFactory::createPackageDiscoveryInstance();
308 // Discover all recipients, this may throw an exception
309 $discoveryInstance->discoverRecipients($packageData);
311 // Now get an iterator
312 $iteratorInstance = $discoveryInstance->getIterator();
314 // Rewind back to the beginning
315 $iteratorInstance->rewind();
317 // ... and begin iteration
318 while ($iteratorInstance->valid()) {
320 $currentRecipient = $iteratorInstance->current();
323 $packageData[self::PACKAGE_DATA_RECIPIENT] = $currentRecipient;
325 // And enqueue it to the writer class
326 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECLARED, $packageData);
329 $this->debugOutput('PACKAGE: Package declared for recipient ' . $currentRecipient);
331 // Skip to next entry
332 $iteratorInstance->next();
336 * The recipient list can be cleaned up here because the package which
337 * shall be delivered has already been added for all entries from the
340 $discoveryInstance->clearRecipients();
344 * Delivers raw package data. In short, this will discover the raw socket
345 * resource through a discovery class (which will analyse the receipient of
346 * the package), register the socket with the connection (handler/helper?)
347 * instance and finally push the raw data on our outgoing queue.
349 * @param $packageData Raw package data in an array
352 private function deliverRawPackageData (array $packageData) {
354 * This package may become big, depending on the shared object size or
355 * delivered message size which shouldn't be so long (to save
356 * bandwidth). Because of the nature of the used protocol (TCP) we need
357 * to split it up into smaller pieces to fit it into a TCP frame.
359 * So first we need (again) a discovery class but now a protocol
360 * discovery to choose the right socket resource. The discovery class
361 * should take a look at the raw package data itself and then decide
362 * which (configurable!) protocol should be used for that type of
365 $discoveryInstance = SocketDiscoveryFactory::createSocketDiscoveryInstance();
367 // Now discover the right protocol
368 $socketResource = $discoveryInstance->discoverSocket($packageData);
371 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: Reached line ' . __LINE__ . ' after discoverSocket() has been called.');
373 // We have to put this socket in our registry, so get an instance
374 $registryInstance = SocketRegistry::createSocketRegistry();
376 // Get the listener from registry
377 $helperInstance = Registry::getRegistry()->getInstance('connection');
380 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: stateInstance=' . $helperInstance->getStateInstance());
381 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: Reached line ' . __LINE__ . ' before isSocketRegistered() has been called.');
384 if ((is_resource($socketResource)) && (!$registryInstance->isSocketRegistered($helperInstance, $socketResource))) {
386 $this->debugOutput('PACKAGE: Registering socket ' . $socketResource . ' ...');
389 $registryInstance->registerSocket($helperInstance, $socketResource, $packageData);
390 } elseif (!$helperInstance->getStateInstance()->isPeerStateConnected()) {
391 // Is not connected, then we cannot send
392 $this->debugOutput('PACKAGE: Unexpected peer state ' . $helperInstance->getStateInstance()->__toString() . ' detected.');
394 // Shutdown the socket
395 $this->shutdownSocket($socketResource);
399 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: Reached line ' . __LINE__ . ' after isSocketRegistered() has been called.');
401 // Make sure the connection is up
402 $helperInstance->getStateInstance()->validatePeerStateConnected();
405 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: Reached line ' . __LINE__ . ' after validatePeerStateConnected() has been called.');
407 // Enqueue it again on the out-going queue, the connection is up and working at this point
408 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_OUTGOING, $packageData);
411 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: Reached line ' . __LINE__ . ' after pushNamed() has been called.');
415 * Sends waiting packages
417 * @param $packageData Raw package data
420 private function sendOutgoingRawPackageData (array $packageData) {
424 // Get the right connection instance
425 $helperInstance = SocketRegistry::createSocketRegistry()->getHandlerInstanceFromPackageData($packageData);
427 // Is this connection still alive?
428 if ($helperInstance->isShuttedDown()) {
429 // This connection is shutting down
430 // @TODO We may want to do somthing more here?
434 // Sent out package data
435 $sentBytes = $helperInstance->sendRawPackageData($packageData);
437 // Remember unsent raw bytes in back-buffer, if any
438 $this->storeUnsentBytesInBackBuffer($packageData, $sentBytes);
442 * Generates a signature for given raw package content and sender id
444 * @param $content Raw package data
445 * @param $senderId Sender id to generate a signature for
446 * @return $signature Signature as BASE64-encoded string
448 private function generatePackageSignature ($content, $senderId) {
449 // ash content and sender id together, use md5() as last algo
450 $hash = md5($this->getCryptoInstance()->hashString($senderId . $content));
452 // Encrypt the content again with the hash as a key
453 $encryptedContent = $this->getCryptoInstance()->encryptString($content, $hash);
455 // Encode it with BASE64
456 $signature = base64_encode($encryptedContent);
463 * "Enqueues" raw content into this delivery class by reading the raw content
464 * from given template instance and pushing it on the 'undeclared' stack.
466 * @param $helperInstance An instance of a HelpableHub class
467 * @param $nodeInstance An instance of a NodeHelper class
470 public function enqueueRawDataFromTemplate (HelpableHub $helperInstance, NodeHelper $nodeInstance) {
471 // Get the raw content ...
472 $content = $helperInstance->getTemplateInstance()->getRawTemplateData();
474 // ... and compress it
475 $content = $this->getCompressorInstance()->compressStream($content);
477 // Add magic in front of it and hash behind it, including BASE64 encoding
478 $content = sprintf(self::PACKAGE_MASK,
479 // 1.) Compressor's extension
480 $this->getCompressorInstance()->getCompressorExtension(),
482 self::PACKAGE_MASK_SEPARATOR,
483 // 2.) Raw package content, encoded with BASE64
484 base64_encode($content),
486 self::PACKAGE_MASK_SEPARATOR,
488 implode(self::PACKAGE_TAGS_SEPARATOR, $helperInstance->getPackageTags()),
490 self::PACKAGE_MASK_SEPARATOR,
492 $this->getHashFromContent($content, $helperInstance, $nodeInstance)
495 // Now prepare the temporary array and push it on the 'undeclared' stack
496 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_UNDECLARED, array(
497 self::PACKAGE_DATA_SENDER => $nodeInstance->getSessionId(),
498 self::PACKAGE_DATA_RECIPIENT => $helperInstance->getRecipientType(),
499 self::PACKAGE_DATA_CONTENT => $content,
500 self::PACKAGE_DATA_STATUS => self::PACKAGE_STATUS_NEW,
501 self::PACKAGE_DATA_SIGNATURE => $this->generatePackageSignature($content, $nodeInstance->getSessionId())
506 * Checks whether a package has been enqueued for delivery.
508 * @return $isEnqueued Whether a package is enqueued
510 public function isPackageEnqueued () {
511 // Check whether the stacker is not empty
512 $isEnqueued = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_UNDECLARED)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_UNDECLARED)));
519 * Checks whether a package has been declared
521 * @return $isDeclared Whether a package is declared
523 public function isPackageDeclared () {
524 // Check whether the stacker is not empty
525 $isDeclared = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_DECLARED)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_DECLARED)));
532 * Checks whether a package should be sent out
534 * @return $isWaitingDelivery Whether a package is waiting for delivery
536 public function isPackageWaitingForDelivery () {
537 // Check whether the stacker is not empty
538 $isWaitingDelivery = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_OUTGOING)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_OUTGOING)));
541 return $isWaitingDelivery;
545 * Delivers an enqueued package to the stated destination. If a non-session
546 * id is provided, recipient resolver is being asked (and instanced once).
547 * This allows that a single package is being delivered to multiple targets
548 * without enqueueing it for every target. If no target is provided or it
549 * can't be determined a NoTargetException is being thrown.
552 * @throws NoTargetException If no target can't be determined
554 public function declareEnqueuedPackage () {
555 // Make sure this method isn't working if there is no package enqueued
556 if (!$this->isPackageEnqueued()) {
557 // This is not fatal but should be avoided
558 // @TODO Add some logging here
562 // Now we know for sure there are packages to deliver, we can start
563 // with the first one.
564 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_UNDECLARED);
566 // Declare the raw package data for delivery
567 $this->declareRawPackageData($packageData);
569 // And remove it finally
570 $this->getStackerInstance()->popNamed(self::STACKER_NAME_UNDECLARED);
574 * Delivers the next declared package. Only one package per time will be sent
575 * because this may take time and slows down the whole delivery
580 public function deliverDeclaredPackage () {
581 // Sanity check if we have packages declared
582 if (!$this->isPackageDeclared()) {
583 // This is not fatal but should be avoided
584 $this->debugOutput('PACKAGE: No package has been declared, but ' . __METHOD__ . ' has been called!');
589 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_DECLARED);
592 // And try to send it
593 $this->deliverRawPackageData($packageData);
595 // And remove it finally
596 $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECLARED);
597 } catch (InvalidStateException $e) {
598 // The state is not excepected (shall be 'connected')
599 $this->debugOutput('PACKAGE: Caught ' . $e->__toString() . ',message=' . $e->getMessage());
601 // Mark the package with status failed
602 $this->changePackageStatus($packageData, self::STACKER_NAME_DECLARED, self::PACKAGE_STATUS_FAILED);
607 * Sends waiting packages out for delivery
611 public function sendWaitingPackage () {
612 // Send any waiting bytes in the back-buffer before sending a new package
613 $this->sendBackBufferBytes();
615 // Sanity check if we have packages waiting for delivery
616 if (!$this->isPackageWaitingForDelivery()) {
617 // This is not fatal but should be avoided
618 $this->debugOutput('PACKAGE: No package is waiting for delivery, but ' . __METHOD__ . ' was called.');
623 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_OUTGOING);
626 // Now try to send it
627 $this->sendOutgoingRawPackageData($packageData);
629 // And remove it finally
630 $this->getStackerInstance()->popNamed(self::STACKER_NAME_OUTGOING);
631 } catch (InvalidSocketException $e) {
632 // Output exception message
633 $this->debugOutput('PACKAGE: Package was not delivered: ' . $e->getMessage());
635 // Mark package as failed
636 $this->changePackageStatus($packageData, self::STACKER_NAME_OUTGOING, self::PACKAGE_STATUS_FAILED);
640 ///////////////////////////////////////////////////////////////////////////
641 // Receiving packages / raw data
642 ///////////////////////////////////////////////////////////////////////////
645 * Checks whether decoded raw data is pending
647 * @return $isPending Whether decoded raw data is pending
649 private function isDecodedDataPending () {
650 // Just return whether the stack is not empty
651 $isPending = (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_DECODED_INCOMING));
658 * Checks whether new raw package data has arrived at a socket
660 * @param $poolInstance An instance of a PoolableListener class
661 * @return $hasArrived Whether new raw package data has arrived for processing
663 public function isNewRawDataPending (PoolableListener $poolInstance) {
664 // Visit the pool. This monitors the pool for incoming raw data.
665 $poolInstance->accept($this->getVisitorInstance());
667 // Check for new data arrival
668 $hasArrived = $this->isDecodedDataPending();
675 * Handles the incoming decoded raw data. This method does not "convert" the
676 * decoded data back into a package array, it just "handles" it and pushs it
681 public function handleIncomingDecodedData () {
683 * This method should only be called if decoded raw data is pending,
686 if (!$this->isDecodedDataPending()) {
687 // This is not fatal but should be avoided
688 // @TODO Add some logging here
692 // Very noisy debug message:
693 /* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: Stacker size is ' . $this->getStackerInstance()->getStackCount(self::STACKER_NAME_DECODED_INCOMING) . ' entries.');
695 // "Pop" the next entry (the same array again) from the stack
696 $decodedData = $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECODED_INCOMING);
698 // Make sure both array elements are there
700 (is_array($decodedData)) &&
701 (isset($decodedData[BaseRawDataHandler::PACKAGE_DECODED_DATA])) &&
702 (isset($decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE]))
706 * Also make sure the error code is SOCKET_ERROR_UNHANDLED because we
707 * only want to handle unhandled packages here.
709 assert($decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE] == BaseRawDataHandler::SOCKET_ERROR_UNHANDLED);
711 // Remove the last chunk SEPARATOR (because it is being added and we don't need it)
712 if (substr($decodedData[BaseRawDataHandler::PACKAGE_DECODED_DATA], -1, 1) == PackageFragmenter::CHUNK_SEPARATOR) {
713 // It is there and should be removed
714 $decodedData[BaseRawDataHandler::PACKAGE_DECODED_DATA] = substr($decodedData[BaseRawDataHandler::PACKAGE_DECODED_DATA], 0, -1);
717 // This package is "handled" and can be pushed on the next stack
718 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECODED_HANDLED, $decodedData);
722 * Adds raw decoded data from the given handler instance to this receiver
724 * @param $handlerInstance An instance of a Networkable class
727 public function addDecodedDataToIncomingStack (Networkable $handlerInstance) {
729 * Get the decoded data from the handler, this is an array with
730 * 'decoded_data' and 'error_code' as elements.
732 $decodedData = $handlerInstance->getNextDecodedData();
734 // Very noisy debug message:
735 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: decodedData[' . gettype($decodedData) . ']=' . print_r($decodedData, true));
737 // And push it on our stack
738 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECODED_INCOMING, $decodedData);
742 * Checks whether incoming decoded data is handled.
744 * @return $isHandled Whether incoming decoded data is handled
746 public function isIncomingDecodedDataHandled () {
747 // Determine if the stack is not empty
748 $isHandled = (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_DECODED_HANDLED));
755 * Assembles incoming decoded data so it will become an abstract network
756 * package again. The assembler does later do it's job by an other task,
757 * not this one to keep best speed possible.
761 public function assembleDecodedDataToPackage () {
762 // Make sure the raw decoded package data is handled
763 assert($this->isIncomingDecodedDataHandled());
765 // Get current package content (an array with two elements; see handleIncomingDecodedData() for details)
766 $packageContent = $this->getStackerInstance()->getNamed(self::STACKER_NAME_DECODED_HANDLED);
768 // Get a singleton package assembler instance from factory
769 $assemblerInstance = PackageAssemblerFactory::createAssemblerInstance();
771 // Start assembling the raw package data array by chunking it
772 $assemblerInstance->chunkPackageContent($packageContent);
774 // Remove the package from 'handled_decoded' stack ...
775 $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECODED_HANDLED);
777 // ... and push it on the 'chunked' stacker
778 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECODED_CHUNKED, $packageContent);
782 * Checks whether a new package has arrived
784 * @return $hasArrived Whether a new package has arrived for processing
786 public function isNewPackageArrived () {
787 // @TODO Add some content here
791 * Accepts the visitor to process the visit "request"
793 * @param $visitorInstance An instance of a Visitor class
796 public function accept (Visitor $visitorInstance) {
798 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: ' . $visitorInstance->__toString() . ' has visited - START');
801 $visitorInstance->visitNetworkPackage($this);
804 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: ' . $visitorInstance->__toString() . ' has visited - FINISHED');
812 public function clearAllStacker () {
813 // Call the init method to force re-initialization
814 $this->initStackers(true);
817 /* DEBUG: */ $this->debugOutput('PACKAGE: All stacker have been re-initialized.');
821 * Removes the first failed outoging package from the stack to continue
822 * with next one (it will never work until the issue is fixed by you).
825 * @throws UnexpectedPackageStatusException If the package status is not 'failed'
826 * @todo This may be enchanced for outgoing packages?
828 public function removeFirstFailedPackage () {
829 // Get the package again
830 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_DECLARED);
832 // Is the package status 'failed'?
833 if ($packageData[self::PACKAGE_DATA_STATUS] != self::PACKAGE_STATUS_FAILED) {
835 throw new UnexpectedPackageStatusException(array($this, $packageData, self::PACKAGE_STATUS_FAILED), BaseListener::EXCEPTION_UNEXPECTED_PACKAGE_STATUS);
839 $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECLARED);
843 * "Decode" the package content into the same array when it was sent.
845 * @param $rawPackageContent The raw package content to be "decoded"
846 * @return $decodedData An array with 'sender', 'recipient', 'content' and 'status' elements
848 public function decodeRawContent ($rawPackageContent) {
849 // Use the separator '#' to "decode" it
850 $decodedArray = explode(self::PACKAGE_DATA_SEPARATOR, $rawPackageContent);
852 // Assert on count (should be always 3)
853 assert(count($decodedArray) == 3);
855 // Create 'decodedData' array with all assoziative array elements
856 $decodedData = array(
857 self::PACKAGE_DATA_SENDER => $decodedArray[self::INDEX_PACKAGE_SENDER],
858 self::PACKAGE_DATA_RECIPIENT => $decodedArray[self::INDEX_PACKAGE_RECIPIENT],
859 self::PACKAGE_DATA_CONTENT => $decodedArray[self::INDEX_PACKAGE_CONTENT],
860 self::PACKAGE_DATA_STATUS => self::PACKAGE_STATUS_DECODED,
861 self::PACKAGE_DATA_SIGNATURE => $this->generatePackageSignature($decodedArray[self::INDEX_PACKAGE_CONTENT], $decodedArray[self::INDEX_PACKAGE_SENDER])