]> git.mxchange.org Git - hub.git/blob - application/hub/main/package/assembler/class_PackageAssembler.php
"Cached" method names to skip some expensive code, re-enabled debug line.
[hub.git] / application / hub / main / package / assembler / class_PackageAssembler.php
1 <?php
2 /**
3  * A PackageAssembler class to assemble a package content stream fragemented
4  * by PackageFragmenter back to a raw package data array.
5  *
6  * @author              Roland Haeder <webmaster@shipsimu.org>
7  * @version             0.0.0
8  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2012 Hub Developer Team
9  * @license             GNU GPL 3.0 or any newer version
10  * @link                http://www.shipsimu.org
11  *
12  * This program is free software: you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation, either version 3 of the License, or
15  * (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
24  */
25 class PackageAssembler extends BaseHubSystem implements Assembler, Registerable {
26         /**
27          * Pending data
28          */
29         private $pendingData = '';
30
31         /**
32          * Private call-back methods
33          */
34         private $callbacks = array();
35
36         /**
37          * Protected constructor
38          *
39          * @return      void
40          */
41         protected function __construct () {
42                 // Call parent constructor
43                 parent::__construct(__CLASS__);
44         }
45
46         /**
47          * Creates an instance of this class
48          *
49          * @param       $packageInstance        An instance of a Receivable class
50          * @return      $assemblerInstance      An instance of an Assembler class
51          */
52         public static final function createPackageAssembler (Receivable $packageInstance) {
53                 // Get new instance
54                 $assemblerInstance = new PackageAssembler();
55
56                 // Set package instance here
57                 $assemblerInstance->setPackageInstance($packageInstance);
58
59                 // Create an instance of a raw data input stream
60                 $streamInstance = ObjectFactory::createObjectByConfiguredName('node_raw_data_input_stream_class');
61
62                 // And set it
63                 $assemblerInstance->setInputStreamInstance($streamInstance);
64
65                 // Return the prepared instance
66                 return $assemblerInstance;
67         }
68
69         /**
70          * Checks whether the input buffer (stacker to be more preceise) is empty.
71          *
72          * @return      $isInputBufferEmpty             Whether the input buffer is empty
73          */
74         private function ifInputBufferIsEmpty () {
75                 // Check it
76                 $isInputBufferEmpty = $this->getPackageInstance()->getStackerInstance()->isStackEmpty(NetworkPackage::STACKER_NAME_DECODED_HANDLED);
77
78                 // Debug message
79                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('PACKAGE-ASSEMBLER: isInputBufferEmpty=' . intval($isInputBufferEmpty));
80
81                 // Return it
82                 return $isInputBufferEmpty;
83         }
84
85         /**
86          * Checks whether given package content is completed (start/end markers are found)
87          *
88          * @param       $packageContent         An array with two elements: 'raw_data' and 'error_code'
89          * @return      $isCompleted            Whether the given package content is completed
90          */
91         private function isPackageContentCompleted (array $packageContent) {
92                 // Check both
93                 $isCompleted = $this->ifStartEndMarkersSet($packageContent[BaseRawDataHandler::PACKAGE_RAW_DATA]);
94
95                 // Return status
96                 return $isCompleted;
97         }
98
99         /**
100          * Assembles the content from $packageContent. This method does only
101          * initialize the whole process by creating a call-back which will then
102          * itself (99.9% of all cases) "explode" the decoded data stream and add
103          * it to a chunk assembler queue.
104          *
105          * If the call-back method or this would attempt to assemble the package
106          * chunks and (maybe) re-request some chunks from the sender, this would
107          * take to much time and therefore slow down this node again.
108          *
109          * @param       $packageContent         An array with two elements: 'raw_data' and 'error_code'
110          * @return      void
111          * @throws      UnsupportedPackageCodeHandlerException  If the package code handler is not implemented
112          */
113         public function chunkPackageContent (array $packageContent) {
114                 // Validate the package content array again
115                 assert(
116                         (isset($packageContent[BaseRawDataHandler::PACKAGE_RAW_DATA])) &&
117                         (isset($packageContent[BaseRawDataHandler::PACKAGE_ERROR_CODE]))
118                 );
119
120                 // Construct call-back name from package error code
121                 $this->callbacks[$packageContent[BaseRawDataHandler::PACKAGE_ERROR_CODE]] = 'handlePackageBy' . $this->convertToClassName($packageContent[BaseRawDataHandler::PACKAGE_ERROR_CODE]);
122
123                 // Abort if the call-back method is not there
124                 if (!method_exists($this, $this->callbacks[$packageContent[BaseRawDataHandler::PACKAGE_ERROR_CODE]])) {
125                         // Throw an exception
126                         throw new UnsupportedPackageCodeHandlerException(array($this, $this->callbacks[$packageContent[BaseRawDataHandler::PACKAGE_ERROR_CODE]], $packageContent), BaseListener::EXCEPTION_UNSUPPORTED_PACKAGE_CODE_HANDLER);
127                 } // END - if
128
129                 // Call it back
130                 call_user_func(array($this, $this->callbacks[$packageContent[BaseRawDataHandler::PACKAGE_ERROR_CODE]]), $packageContent);
131         }
132
133         /**************************************************************************
134          *                 Call-back methods for above method                     *
135          **************************************************************************/
136
137         /**
138          * Call-back handler to handle unhandled package data. This method
139          * "explodes" the string with the chunk separator from PackageFragmenter
140          * class, does some low checks on it and feeds it into another queue for
141          * verification and re-request for bad chunks.
142          *
143          * @param       $packageContent         An array with two elements: 'raw_data' and 'error_code'
144          * @return      void
145          */
146         private function handlePackageByUnhandledPackage (array $packageContent) {
147                 // Debug message
148                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('PACKAGE-ASSEMBLER: packageData[' . BaseRawDataHandler::PACKAGE_RAW_DATA . ']=' . $packageContent[BaseRawDataHandler::PACKAGE_RAW_DATA]);
149
150                 // Check for some conditions
151                 if ((!$this->ifInputBufferIsEmpty()) || (!$this->isPackageContentCompleted($packageContent))) {
152                         // Last chunk is not valid, so wait for more
153                         $this->pendingData .= $packageContent[BaseRawDataHandler::PACKAGE_RAW_DATA];
154
155                         // Debug message
156                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('PACKAGE-ASSEMBLER: Partial data received. Waiting for more ... ( ' . strlen($packageContent[BaseRawDataHandler::PACKAGE_RAW_DATA]) . ' bytes)');
157                 } else {
158                         // Debug message
159                         /* DEBUG */ self::createDebugInstance(__CLASS__)->debugOutput('PACKAGE-ASSEMBLER: packageContent=' . print_r($packageContent, TRUE) . ',chunks='.print_r($chunks, TRUE));
160                 }
161         }
162
163         /**
164          * Checks whether the assembler's pending data is empty which means it has
165          * no pending data left for handling ... ;-)
166          *
167          * @return      $ifPendingDataIsEmpty   Whether pending data is empty
168          */
169         public function isPendingDataEmpty () {
170                 // A simbple check
171                 $ifPendingDataIsEmpty = empty($this->pendingData);
172
173                 // Return it
174                 return $ifPendingDataIsEmpty;
175         }
176
177         /**
178          * Handles the assembler's pending data
179          *
180          * @return      void
181          */
182         public function handlePendingData () {
183                 // Debug output
184                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('PACKAGE-ASSEMBLER: Going to decode ' . strlen($this->pendingData) . ' Bytes of pending data. pendingData=' . $this->pendingData);
185
186                 // Assert on condition
187                 assert(!$this->isPendingDataEmpty());
188
189                 // Init fake array
190                 $packageContent = array(
191                         BaseRawDataHandler::PACKAGE_RAW_DATA   => $this->getInputStreamInstance()->streamData($this->pendingData),
192                         BaseRawDataHandler::PACKAGE_ERROR_CODE => BaseRawDataHandler::SOCKET_ERROR_UNHANDLED
193                 );
194
195                 // Clear pending data
196                 $this->pendingData = '';
197
198                 // Debug message
199                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('PACKAGE-ASSEMBLER: Last block of partial data received. A total of ' . strlen($packageContent[BaseRawDataHandler::PACKAGE_RAW_DATA]) . ' bytes has been received.');
200
201                 // Make sure last CHUNK_SEPARATOR is not there
202                 if (substr($packageContent[BaseRawDataHandler::PACKAGE_RAW_DATA], -1, 1) == PackageFragmenter::CHUNK_SEPARATOR) {
203                         // Remove it
204                         $packageContent[BaseRawDataHandler::PACKAGE_RAW_DATA] = substr($packageContent[BaseRawDataHandler::PACKAGE_RAW_DATA], 0, -1);
205                 } // END - if
206
207                 /*
208                  * "explode" the string from 'raw_data' with chunk separator to
209                  * get an array of chunks. These chunks must then be verified by
210                  * their checksums. Also the final chunk must be handled.
211                  */
212                 $chunks = explode(PackageFragmenter::CHUNK_SEPARATOR, $packageContent[BaseRawDataHandler::PACKAGE_RAW_DATA]);
213
214                 // Now get a chunk handler instance
215                 $handlerInstance = ChunkHandlerFactory::createChunkHandlerInstance();
216
217                 // Add all chunks because the last final chunk is found
218                 $handlerInstance->addAllChunksWithFinal($chunks);
219         }
220 }
221
222 // [EOF]
223 ?>