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;
118 * Size of the decoded data array
120 const DECODED_DATA_ARRAY_SIZE = 4;
122 /**************************************************************************
123 * Stacker for out-going packages *
124 **************************************************************************/
127 * Stacker name for "undeclared" packages
129 const STACKER_NAME_UNDECLARED = 'package_undeclared';
132 * Stacker name for "declared" packages (which are ready to send out)
134 const STACKER_NAME_DECLARED = 'package_declared';
137 * Stacker name for "out-going" packages
139 const STACKER_NAME_OUTGOING = 'package_outgoing';
141 /**************************************************************************
142 * Stacker for incoming packages *
143 **************************************************************************/
146 * Stacker name for "incoming" decoded raw data
148 const STACKER_NAME_DECODED_INCOMING = 'package_decoded_data';
151 * Stacker name for handled decoded raw data
153 const STACKER_NAME_DECODED_HANDLED = 'package_handled_decoded';
156 * Stacker name for "chunked" decoded raw data
158 const STACKER_NAME_DECODED_CHUNKED = 'package_chunked_decoded';
160 /**************************************************************************
161 * Stacker for other/internal purposes *
162 **************************************************************************/
165 * Stacker name for "back-buffered" packages
167 const STACKER_NAME_BACK_BUFFER = 'package_backbuffer';
170 * Protected constructor
174 protected function __construct () {
175 // Call parent constructor
176 parent::__construct(__CLASS__);
180 * Creates an instance of this class
182 * @param $compressorInstance A Compressor instance for compressing the content
183 * @return $packageInstance An instance of a Deliverable class
185 public static final function createNetworkPackage (Compressor $compressorInstance) {
187 $packageInstance = new NetworkPackage();
189 // Now set the compressor instance
190 $packageInstance->setCompressorInstance($compressorInstance);
193 * We need to initialize a stack here for our packages even for those
194 * which have no recipient address and stamp... ;-) This stacker will
195 * also be used for incoming raw data to handle it.
197 $stackerInstance = ObjectFactory::createObjectByConfiguredName('network_package_stacker_class');
199 // At last, set it in this class
200 $packageInstance->setStackerInstance($stackerInstance);
203 $packageInstance->initStackers();
205 // Get a visitor instance for speeding up things
206 $visitorInstance = ObjectFactory::createObjectByConfiguredName('node_raw_data_monitor_visitor_class', array($packageInstance));
208 // Set it in this package
209 $packageInstance->setVisitorInstance($visitorInstance);
211 // Get crypto instance and set it in this package
212 $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
213 $packageInstance->setCryptoInstance($cryptoInstance);
215 // Get a singleton package assembler instance from factory and set it here
216 $assemblerInstance = PackageAssemblerFactory::createAssemblerInstance($packageInstance);
217 $packageInstance->setAssemblerInstance($assemblerInstance);
219 // Return the prepared instance
220 return $packageInstance;
224 * Initialize all stackers
226 * @param $forceReInit Whether to force reinitialization of all stacks
229 protected function initStackers ($forceReInit = false) {
233 self::STACKER_NAME_UNDECLARED,
234 self::STACKER_NAME_DECLARED,
235 self::STACKER_NAME_OUTGOING,
236 self::STACKER_NAME_DECODED_INCOMING,
237 self::STACKER_NAME_DECODED_HANDLED,
238 self::STACKER_NAME_DECODED_CHUNKED,
239 self::STACKER_NAME_BACK_BUFFER
242 $this->getStackerInstance()->initStacker($stackerName, $forceReInit);
247 * "Getter" for hash from given content and helper instance
249 * @param $content Raw package content
250 * @param $helperInstance An instance of a HelpableHub class
251 * @param $nodeInstance An instance of a NodeHelper class
252 * @return $hash Hash for given package content
254 private function getHashFromContent ($content) {
256 // @TODO crc32() is very weak, but it needs to be fast
259 self::PACKAGE_CHECKSUM_SEPARATOR .
260 $this->getSessionId() .
261 self::PACKAGE_CHECKSUM_SEPARATOR .
262 $this->getCompressorInstance()->getCompressorExtension()
270 * Change the package with given status in given stack
272 * @param $packageData Raw package data in an array
273 * @param $stackerName Name of the stacker
274 * @param $newStatus New status to set
277 private function changePackageStatus (array $packageData, $stackerName, $newStatus) {
278 // Skip this for empty stacks
279 if ($this->getStackerInstance()->isStackEmpty($stackerName)) {
280 // This avoids an exception after all packages has failed
284 // Pop the entry (it should be it)
285 $nextData = $this->getStackerInstance()->popNamed($stackerName);
287 // Compare both arrays
288 assert($nextData[self::PACKAGE_DATA_SIGNATURE] == $packageData[self::PACKAGE_DATA_SIGNATURE]);
290 // Temporary set the new status
291 $packageData[self::PACKAGE_DATA_STATUS] = $newStatus;
294 $this->getStackerInstance()->pushNamed($stackerName, $packageData);
297 ///////////////////////////////////////////////////////////////////////////
298 // Delivering packages / raw data
299 ///////////////////////////////////////////////////////////////////////////
302 * Delivers the given raw package data.
304 * @param $packageData Raw package data in an array
307 private function declareRawPackageData (array $packageData) {
309 * We need to disover every recipient, just in case we have a
310 * multi-recipient entry like 'upper' is. 'all' may be a not so good
311 * target because it causes an overload on the network and may be
312 * abused for attacking the network with large packages.
314 $discoveryInstance = PackageDiscoveryFactory::createPackageDiscoveryInstance();
316 // Discover all recipients, this may throw an exception
317 $discoveryInstance->discoverRecipients($packageData);
319 // Now get an iterator
320 $iteratorInstance = $discoveryInstance->getIterator();
322 // Rewind back to the beginning
323 $iteratorInstance->rewind();
325 // ... and begin iteration
326 while ($iteratorInstance->valid()) {
328 $currentRecipient = $iteratorInstance->current();
331 $packageData[self::PACKAGE_DATA_RECIPIENT] = $currentRecipient;
333 // And enqueue it to the writer class
334 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECLARED, $packageData);
337 $this->debugOutput('PACKAGE: Package declared for recipient ' . $currentRecipient);
339 // Skip to next entry
340 $iteratorInstance->next();
344 * The recipient list can be cleaned up here because the package which
345 * shall be delivered has already been added for all entries from the
348 $discoveryInstance->clearRecipients();
352 * Delivers raw package data. In short, this will discover the raw socket
353 * resource through a discovery class (which will analyse the receipient of
354 * the package), register the socket with the connection (handler/helper?)
355 * instance and finally push the raw data on our outgoing queue.
357 * @param $packageData Raw package data in an array
360 private function deliverRawPackageData (array $packageData) {
362 * This package may become big, depending on the shared object size or
363 * delivered message size which shouldn't be so long (to save
364 * bandwidth). Because of the nature of the used protocol (TCP) we need
365 * to split it up into smaller pieces to fit it into a TCP frame.
367 * So first we need (again) a discovery class but now a protocol
368 * discovery to choose the right socket resource. The discovery class
369 * should take a look at the raw package data itself and then decide
370 * which (configurable!) protocol should be used for that type of
373 $discoveryInstance = SocketDiscoveryFactory::createSocketDiscoveryInstance();
375 // Now discover the right protocol
376 $socketResource = $discoveryInstance->discoverSocket($packageData);
379 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: Reached line ' . __LINE__ . ' after discoverSocket() has been called.');
381 // We have to put this socket in our registry, so get an instance
382 $registryInstance = SocketRegistry::createSocketRegistry();
384 // Get the listener from registry
385 $helperInstance = Registry::getRegistry()->getInstance('connection');
388 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: stateInstance=' . $helperInstance->getStateInstance());
389 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: Reached line ' . __LINE__ . ' before isSocketRegistered() has been called.');
392 if ((is_resource($socketResource)) && (!$registryInstance->isSocketRegistered($helperInstance, $socketResource))) {
394 $this->debugOutput('PACKAGE: Registering socket ' . $socketResource . ' ...');
397 $registryInstance->registerSocket($helperInstance, $socketResource, $packageData);
398 } elseif (!$helperInstance->getStateInstance()->isPeerStateConnected()) {
399 // Is not connected, then we cannot send
400 $this->debugOutput('PACKAGE: Unexpected peer state ' . $helperInstance->getStateInstance()->__toString() . ' detected.');
402 // Shutdown the socket
403 $this->shutdownSocket($socketResource);
407 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: Reached line ' . __LINE__ . ' after isSocketRegistered() has been called.');
409 // Make sure the connection is up
410 $helperInstance->getStateInstance()->validatePeerStateConnected();
413 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: Reached line ' . __LINE__ . ' after validatePeerStateConnected() has been called.');
415 // Enqueue it again on the out-going queue, the connection is up and working at this point
416 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_OUTGOING, $packageData);
419 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: Reached line ' . __LINE__ . ' after pushNamed() has been called.');
423 * Sends waiting packages
425 * @param $packageData Raw package data
428 private function sendOutgoingRawPackageData (array $packageData) {
432 // Get the right connection instance
433 $helperInstance = SocketRegistry::createSocketRegistry()->getHandlerInstanceFromPackageData($packageData);
435 // Is this connection still alive?
436 if ($helperInstance->isShuttedDown()) {
437 // This connection is shutting down
438 // @TODO We may want to do somthing more here?
442 // Sent out package data
443 $sentBytes = $helperInstance->sendRawPackageData($packageData);
445 // Remember unsent raw bytes in back-buffer, if any
446 $this->storeUnsentBytesInBackBuffer($packageData, $sentBytes);
450 * Generates a signature for given raw package content and sender id
452 * @param $content Raw package data
453 * @param $senderId Sender id to generate a signature for
454 * @return $signature Signature as BASE64-encoded string
456 private function generatePackageSignature ($content, $senderId) {
457 // ash content and sender id together, use md5() as last algo
458 $hash = md5($this->getCryptoInstance()->hashString($senderId . $content, $this->getNodeId(), false));
460 // Encrypt the content again with the hash as a key
461 $encryptedContent = $this->getCryptoInstance()->encryptString($content, $hash);
463 // Encode it with BASE64
464 $signature = base64_encode($encryptedContent);
471 * "Enqueues" raw content into this delivery class by reading the raw content
472 * from given template instance and pushing it on the 'undeclared' stack.
474 * @param $helperInstance An instance of a HelpableHub class
477 public function enqueueRawDataFromTemplate (HelpableHub $helperInstance) {
478 // Get the raw content ...
479 $content = $helperInstance->getTemplateInstance()->getRawTemplateData();
481 // ... and compress it
482 $content = $this->getCompressorInstance()->compressStream($content);
484 // Add magic in front of it and hash behind it, including BASE64 encoding
485 $content = sprintf(self::PACKAGE_MASK,
486 // 1.) Compressor's extension
487 $this->getCompressorInstance()->getCompressorExtension(),
489 self::PACKAGE_MASK_SEPARATOR,
490 // 2.) Raw package content, encoded with BASE64
491 base64_encode($content),
493 self::PACKAGE_MASK_SEPARATOR,
495 implode(self::PACKAGE_TAGS_SEPARATOR, $helperInstance->getPackageTags()),
497 self::PACKAGE_MASK_SEPARATOR,
499 $this->getHashFromContent($content)
502 // Now prepare the temporary array and push it on the 'undeclared' stack
503 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_UNDECLARED, array(
504 self::PACKAGE_DATA_SENDER => $this->getSessionId(),
505 self::PACKAGE_DATA_RECIPIENT => $helperInstance->getRecipientType(),
506 self::PACKAGE_DATA_CONTENT => $content,
507 self::PACKAGE_DATA_STATUS => self::PACKAGE_STATUS_NEW,
508 self::PACKAGE_DATA_SIGNATURE => $this->generatePackageSignature($content, $this->getSessionId())
513 * Checks whether a package has been enqueued for delivery.
515 * @return $isEnqueued Whether a package is enqueued
517 public function isPackageEnqueued () {
518 // Check whether the stacker is not empty
519 $isEnqueued = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_UNDECLARED)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_UNDECLARED)));
526 * Checks whether a package has been declared
528 * @return $isDeclared Whether a package is declared
530 public function isPackageDeclared () {
531 // Check whether the stacker is not empty
532 $isDeclared = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_DECLARED)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_DECLARED)));
539 * Checks whether a package should be sent out
541 * @return $isWaitingDelivery Whether a package is waiting for delivery
543 public function isPackageWaitingForDelivery () {
544 // Check whether the stacker is not empty
545 $isWaitingDelivery = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_OUTGOING)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_OUTGOING)));
548 return $isWaitingDelivery;
552 * Delivers an enqueued package to the stated destination. If a non-session
553 * id is provided, recipient resolver is being asked (and instanced once).
554 * This allows that a single package is being delivered to multiple targets
555 * without enqueueing it for every target. If no target is provided or it
556 * can't be determined a NoTargetException is being thrown.
559 * @throws NoTargetException If no target can't be determined
561 public function declareEnqueuedPackage () {
562 // Make sure this method isn't working if there is no package enqueued
563 if (!$this->isPackageEnqueued()) {
564 // This is not fatal but should be avoided
565 // @TODO Add some logging here
569 // Now we know for sure there are packages to deliver, we can start
570 // with the first one.
571 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_UNDECLARED);
573 // Declare the raw package data for delivery
574 $this->declareRawPackageData($packageData);
576 // And remove it finally
577 $this->getStackerInstance()->popNamed(self::STACKER_NAME_UNDECLARED);
581 * Delivers the next declared package. Only one package per time will be sent
582 * because this may take time and slows down the whole delivery
587 public function deliverDeclaredPackage () {
588 // Sanity check if we have packages declared
589 if (!$this->isPackageDeclared()) {
590 // This is not fatal but should be avoided
591 $this->debugOutput('PACKAGE: No package has been declared, but ' . __METHOD__ . ' has been called!');
596 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_DECLARED);
599 // And try to send it
600 $this->deliverRawPackageData($packageData);
602 // And remove it finally
603 $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECLARED);
604 } catch (InvalidStateException $e) {
605 // The state is not excepected (shall be 'connected')
606 $this->debugOutput('PACKAGE: Caught ' . $e->__toString() . ',message=' . $e->getMessage());
608 // Mark the package with status failed
609 $this->changePackageStatus($packageData, self::STACKER_NAME_DECLARED, self::PACKAGE_STATUS_FAILED);
614 * Sends waiting packages out for delivery
618 public function sendWaitingPackage () {
619 // Send any waiting bytes in the back-buffer before sending a new package
620 $this->sendBackBufferBytes();
622 // Sanity check if we have packages waiting for delivery
623 if (!$this->isPackageWaitingForDelivery()) {
624 // This is not fatal but should be avoided
625 $this->debugOutput('PACKAGE: No package is waiting for delivery, but ' . __METHOD__ . ' was called.');
630 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_OUTGOING);
633 // Now try to send it
634 $this->sendOutgoingRawPackageData($packageData);
636 // And remove it finally
637 $this->getStackerInstance()->popNamed(self::STACKER_NAME_OUTGOING);
638 } catch (InvalidSocketException $e) {
639 // Output exception message
640 $this->debugOutput('PACKAGE: Package was not delivered: ' . $e->getMessage());
642 // Mark package as failed
643 $this->changePackageStatus($packageData, self::STACKER_NAME_OUTGOING, self::PACKAGE_STATUS_FAILED);
647 ///////////////////////////////////////////////////////////////////////////
648 // Receiving packages / raw data
649 ///////////////////////////////////////////////////////////////////////////
652 * Checks whether decoded raw data is pending
654 * @return $isPending Whether decoded raw data is pending
656 private function isDecodedDataPending () {
657 // Just return whether the stack is not empty
658 $isPending = (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_DECODED_INCOMING));
665 * Checks whether new raw package data has arrived at a socket
667 * @param $poolInstance An instance of a PoolableListener class
668 * @return $hasArrived Whether new raw package data has arrived for processing
670 public function isNewRawDataPending (PoolableListener $poolInstance) {
671 // Visit the pool. This monitors the pool for incoming raw data.
672 $poolInstance->accept($this->getVisitorInstance());
674 // Check for new data arrival
675 $hasArrived = $this->isDecodedDataPending();
682 * Handles the incoming decoded raw data. This method does not "convert" the
683 * decoded data back into a package array, it just "handles" it and pushs it
688 public function handleIncomingDecodedData () {
690 * This method should only be called if decoded raw data is pending,
693 if (!$this->isDecodedDataPending()) {
694 // This is not fatal but should be avoided
695 // @TODO Add some logging here
699 // Very noisy debug message:
700 /* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: Stacker size is ' . $this->getStackerInstance()->getStackCount(self::STACKER_NAME_DECODED_INCOMING) . ' entries.');
702 // "Pop" the next entry (the same array again) from the stack
703 $decodedData = $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECODED_INCOMING);
705 // Make sure both array elements are there
707 (is_array($decodedData)) &&
708 (isset($decodedData[BaseRawDataHandler::PACKAGE_DECODED_DATA])) &&
709 (isset($decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE]))
713 * Also make sure the error code is SOCKET_ERROR_UNHANDLED because we
714 * only want to handle unhandled packages here.
716 /* NOISY-DEBUG: */ $this->debugOutput('NETWORK-PACKAGE: errorCode=' . $decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE]);
717 assert($decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE] == BaseRawDataHandler::SOCKET_ERROR_UNHANDLED);
719 // Remove the last chunk SEPARATOR (because it is being added and we don't need it)
720 if (substr($decodedData[BaseRawDataHandler::PACKAGE_DECODED_DATA], -1, 1) == PackageFragmenter::CHUNK_SEPARATOR) {
721 // It is there and should be removed
722 $decodedData[BaseRawDataHandler::PACKAGE_DECODED_DATA] = substr($decodedData[BaseRawDataHandler::PACKAGE_DECODED_DATA], 0, -1);
725 // This package is "handled" and can be pushed on the next stack
726 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECODED_HANDLED, $decodedData);
730 * Adds raw decoded data from the given handler instance to this receiver
732 * @param $handlerInstance An instance of a Networkable class
735 public function addDecodedDataToIncomingStack (Networkable $handlerInstance) {
737 * Get the decoded data from the handler, this is an array with
738 * 'decoded_data' and 'error_code' as elements.
740 $decodedData = $handlerInstance->getNextDecodedData();
742 // Very noisy debug message:
743 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: decodedData[' . gettype($decodedData) . ']=' . print_r($decodedData, true));
745 // And push it on our stack
746 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECODED_INCOMING, $decodedData);
750 * Checks whether incoming decoded data is handled.
752 * @return $isHandled Whether incoming decoded data is handled
754 public function isIncomingDecodedDataHandled () {
755 // Determine if the stack is not empty
756 $isHandled = (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_DECODED_HANDLED));
763 * Checks whether the assembler has pending data left
765 * @return $isHandled Whether the assembler has pending data left
767 public function ifAssemblerHasPendingDataLeft () {
768 // Determine if the stack is not empty
769 $isHandled = (!$this->getAssemblerInstance()->isPendingDataEmpty());
776 * Handles the attached assemler's pending data queue to be finally
777 * assembled to the raw package data back.
781 public function handleAssemblerPendingData () {
783 $this->getAssemblerInstance()->handlePendingData();
787 * Assembles incoming decoded data so it will become an abstract network
788 * package again. The assembler does later do it's job by an other task,
789 * not this one to keep best speed possible.
793 public function assembleDecodedDataToPackage () {
794 // Make sure the raw decoded package data is handled
795 assert($this->isIncomingDecodedDataHandled());
797 // Get current package content (an array with two elements; see handleIncomingDecodedData() for details)
798 $packageContent = $this->getStackerInstance()->getNamed(self::STACKER_NAME_DECODED_HANDLED);
800 // Start assembling the raw package data array by chunking it
801 $this->getAssemblerInstance()->chunkPackageContent($packageContent);
803 // Remove the package from 'handled_decoded' stack ...
804 $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECODED_HANDLED);
806 // ... and push it on the 'chunked' stacker
807 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECODED_CHUNKED, $packageContent);
811 * Checks whether a new package has arrived
813 * @return $hasArrived Whether a new package has arrived for processing
815 public function isNewPackageArrived () {
816 // @TODO Add some content here
820 * Accepts the visitor to process the visit "request"
822 * @param $visitorInstance An instance of a Visitor class
825 public function accept (Visitor $visitorInstance) {
827 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: ' . $visitorInstance->__toString() . ' has visited - START');
830 $visitorInstance->visitNetworkPackage($this);
833 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: ' . $visitorInstance->__toString() . ' has visited - FINISHED');
841 public function clearAllStacker () {
842 // Call the init method to force re-initialization
843 $this->initStackers(true);
846 /* DEBUG: */ $this->debugOutput('PACKAGE: All stacker have been re-initialized.');
850 * Removes the first failed outoging package from the stack to continue
851 * with next one (it will never work until the issue is fixed by you).
854 * @throws UnexpectedPackageStatusException If the package status is not 'failed'
855 * @todo This may be enchanced for outgoing packages?
857 public function removeFirstFailedPackage () {
858 // Get the package again
859 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_DECLARED);
861 // Is the package status 'failed'?
862 if ($packageData[self::PACKAGE_DATA_STATUS] != self::PACKAGE_STATUS_FAILED) {
864 throw new UnexpectedPackageStatusException(array($this, $packageData, self::PACKAGE_STATUS_FAILED), BaseListener::EXCEPTION_UNEXPECTED_PACKAGE_STATUS);
868 $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECLARED);
872 * "Decode" the package content into the same array when it was sent.
874 * @param $rawPackageContent The raw package content to be "decoded"
875 * @return $decodedData An array with 'sender', 'recipient', 'content' and 'status' elements
877 public function decodeRawContent ($rawPackageContent) {
878 // Use the separator '#' to "decode" it
879 $decodedArray = explode(self::PACKAGE_DATA_SEPARATOR, $rawPackageContent);
881 // Assert on count (should be always 3)
882 assert(count($decodedArray) == self::DECODED_DATA_ARRAY_SIZE);
884 // Create 'decodedData' array with all assoziative array elements
885 $decodedData = array(
886 self::PACKAGE_DATA_SENDER => $decodedArray[self::INDEX_PACKAGE_SENDER],
887 self::PACKAGE_DATA_RECIPIENT => $decodedArray[self::INDEX_PACKAGE_RECIPIENT],
888 self::PACKAGE_DATA_CONTENT => $decodedArray[self::INDEX_PACKAGE_CONTENT],
889 self::PACKAGE_DATA_STATUS => self::PACKAGE_STATUS_DECODED,
890 self::PACKAGE_DATA_SIGNATURE => $this->generatePackageSignature($decodedArray[self::INDEX_PACKAGE_CONTENT], $decodedArray[self::INDEX_PACKAGE_SENDER])