3 namespace Org\Mxchange\CoreFramework\Stacker\Filesystem;
5 // Import framework stuff
6 use Org\Mxchange\CoreFramework\Factory\Filesystem\Stack\FileStackIndexFactory;
7 use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
8 use Org\Mxchange\CoreFramework\Filesystem\File\BaseBinaryFile;
9 use Org\Mxchange\CoreFramework\Generic\UnsupportedOperationException;
10 use Org\Mxchange\CoreFramework\Iterator\Filesystem\SeekableWritableFileIterator;
11 use Org\Mxchange\CoreFramework\Stacker\BaseStacker;
17 * A general file-based stack class
19 * @author Roland Haeder <webmaster@ship-simu.org>
21 <<<<<<< HEAD:framework/main/classes/stacker/file/class_BaseFileStack.php
22 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
24 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2016 Core Developer Team
25 >>>>>>> Some updates::inc/main/classes/stacker/file/class_BaseFileStack.php
26 * @license GNU GPL 3.0 or any newer version
27 * @link http://www.ship-simu.org
29 * This program is free software: you can redistribute it and/or modify
30 * it under the terms of the GNU General Public License as published by
31 * the Free Software Foundation, either version 3 of the License, or
32 * (at your option) any later version.
34 * This program is distributed in the hope that it will be useful,
35 * but WITHOUT ANY WARRANTY; without even the implied warranty of
36 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
37 * GNU General Public License for more details.
39 * You should have received a copy of the GNU General Public License
40 * along with this program. If not, see <http://www.gnu.org/licenses/>.
42 abstract class BaseFileStack extends BaseStacker {
44 * Magic for this stack
46 const STACK_MAGIC = 'STACKv0.1';
49 * Name of array index for gap position
51 const ARRAY_INDEX_GAP_POSITION = 'gap';
54 * Name of array index for hash
56 const ARRAY_INDEX_HASH = 'hash';
59 * Name of array index for length of raw data
61 const ARRAY_INDEX_DATA_LENGTH = 'length';
64 * Protected constructor
66 * @param $className Name of the class
69 protected function __construct ($className) {
70 // Call parent constructor
71 parent::__construct($className);
75 * Reads the file header
78 * @todo To hard assertions here, better rewrite them to exceptions
80 public function readFileHeader () {
81 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
83 // First rewind to beginning as the header sits at the beginning ...
84 $this->getIteratorInstance()->rewind();
86 // Then read it (see constructor for calculation)
87 $data = $this->getIteratorInstance()->read($this->getIteratorInstance()->getHeaderSize());
88 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Read %d bytes (%d wanted).', __METHOD__, __LINE__, strlen($data), $this->getIteratorInstance()->getHeaderSize()));
90 // Have all requested bytes been read?
91 assert(strlen($data) == $this->getIteratorInstance()->getHeaderSize());
92 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
94 // Last character must be the separator
95 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] data(-1)=%s', __METHOD__, __LINE__, dechex(ord(substr($data, -1, 1)))));
96 assert(substr($data, -1, 1) == chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES));
97 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
99 // Okay, then remove it
100 $data = substr($data, 0, -1);
102 // And update seek position
103 $this->getIteratorInstance()->updateSeekPosition();
110 * 2 => current seek position
112 $header = explode(chr(BaseBinaryFile::SEPARATOR_HEADER_DATA), $data);
115 $this->getIteratorInstance()->setHeader($header);
117 // Check if the array has only 3 elements
118 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] header(%d)=%s', __METHOD__, __LINE__, count($header), print_r($header, true)));
119 assert(count($header) == 3);
120 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
123 assert($header[0] == self::STACK_MAGIC);
124 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
126 // Check length of count and seek position
127 assert(strlen($header[1]) == BaseBinaryFile::LENGTH_COUNT);
128 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
129 assert(strlen($header[2]) == BaseBinaryFile::LENGTH_POSITION);
130 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
132 // Decode count and seek position
133 $header[1] = hex2bin($header[1]);
134 $header[2] = hex2bin($header[2]);
136 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
140 * Flushes the file header
144 public function flushFileHeader () {
145 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
147 // Put all informations together
148 $header = sprintf('%s%s%s%s%s%s',
152 // Separator magic<->count
153 chr(BaseBinaryFile::SEPARATOR_HEADER_DATA),
155 // Total entries (will be zero) and pad it to 20 chars
156 str_pad($this->dec2hex($this->getIteratorInstance()->getCounter()), BaseBinaryFile::LENGTH_COUNT, '0', STR_PAD_LEFT),
158 // Separator count<->seek position
159 chr(BaseBinaryFile::SEPARATOR_HEADER_DATA),
161 // Position (will be zero)
162 str_pad($this->dec2hex($this->getIteratorInstance()->getSeekPosition(), 2), BaseBinaryFile::LENGTH_POSITION, '0', STR_PAD_LEFT),
164 // Separator position<->entries
165 chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES)
168 // Write it to disk (header is always at seek position 0)
169 $this->getIteratorInstance()->writeData(0, $header, false);
171 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
175 * Initializes this file-based stack.
177 * @param $fileInfoInstance An instance of a SplFileInfo class
178 * @param $type Type of this stack (e.g. url_source for URL sources)
180 * @todo Currently the stack file is not cached, please implement a memory-handling class and if enough RAM is found, cache the whole stack file.
182 protected function initFileStack (SplFileInfo $fileInfoInstance, $type) {
183 // Get a stack file instance
184 $fileInstance = ObjectFactory::createObjectByConfiguredName('stack_file_class', array($fileInfoInstance, $this));
186 // Get iterator instance
187 $iteratorInstance = ObjectFactory::createObjectByConfiguredName('file_iterator_class', array($fileInstance));
189 // Is the instance implementing the right interface?
190 assert($iteratorInstance instanceof SeekableWritableFileIterator);
193 $this->setIteratorInstance($iteratorInstance);
195 // Calculate header size
196 $this->getIteratorInstance()->setHeaderSize(
197 strlen(self::STACK_MAGIC) +
198 strlen(chr(BaseBinaryFile::SEPARATOR_HEADER_DATA)) +
199 BaseBinaryFile::LENGTH_COUNT +
200 strlen(chr(BaseBinaryFile::SEPARATOR_HEADER_DATA)) +
201 BaseBinaryFile::LENGTH_POSITION +
202 strlen(chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES))
205 // Init counters and gaps array
206 $this->getIteratorInstance()->initCountersGapsArray();
208 // Is the file's header initialized?
209 if (!$this->getIteratorInstance()->isFileHeaderInitialized()) {
210 // No, then create it (which may pre-allocate the stack)
211 $this->getIteratorInstance()->createFileHeader();
213 // And pre-allocate a bit
214 $this->getIteratorInstance()->preAllocateFile('file_stack');
217 // Load the file header
218 $this->readFileHeader();
220 // Count all entries in file
221 $this->getIteratorInstance()->analyzeFile();
224 * Get stack index instance. This can be used for faster
225 * "defragmentation" and startup.
227 $indexInstance = FileStackIndexFactory::createFileStackIndexInstance($fileInfoInstance, $type);
230 $this->setIndexInstance($indexInstance);
234 * Adds a value to given stack
236 * @param $stackerName Name of the stack
237 * @param $value Value to add to this stacker
239 * @throws FullStackerException If the stack is full
241 protected function addValue ($stackerName, $value) {
243 if ($this->isStackFull($stackerName)) {
245 throw new FullStackerException(array($this, $stackerName, $value), self::EXCEPTION_STACKER_IS_FULL);
249 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName . ',value[' . gettype($value) . ']=' . print_r($value, true));
251 // No objects/resources are allowed as their serialization takes to long
252 assert(!is_object($value));
253 assert(!is_resource($value));
256 * Now add the value to the file stack which returns gap position, a
257 * hash and length of the raw data.
259 $data = $this->getIteratorInstance()->writeValueToFile($stackerName, $value);
261 // Add the hash and gap position to the index
262 $this->getIndexInstance()->addHashToIndex($stackerName, $data);
266 * Get last value from named stacker
268 * @param $stackerName Name of the stack
269 * @return $value Value of last added value
270 * @throws EmptyStackerException If the stack is empty
272 protected function getLastValue ($stackerName) {
273 // Is the stack not yet initialized or full?
274 if ($this->isStackEmpty($stackerName)) {
275 // Throw an exception
276 throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
279 // Now get the last value
280 /* NOISY-DEBUG: */ $this->partialStub('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName);
288 * Get first value from named stacker
290 * @param $stackerName Name of the stack
291 * @return $value Value of last added value
292 * @throws EmptyStackerException If the stack is empty
294 protected function getFirstValue ($stackerName) {
295 // Is the stack not yet initialized or full?
296 if ($this->isStackEmpty($stackerName)) {
297 // Throw an exception
298 throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
301 // Now get the first value
302 /* NOISY-DEBUG: */ $this->partialStub('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName);
310 * "Pops" last entry from stack
312 * @param $stackerName Name of the stack
313 * @return $value Value "poped" from array
314 * @throws EmptyStackerException If the stack is empty
316 protected function popLast ($stackerName) {
317 // Is the stack not yet initialized or full?
318 if ($this->isStackEmpty($stackerName)) {
319 // Throw an exception
320 throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
323 // Now, remove the last entry, we don't care about the return value here, see elseif() block above
324 /* NOISY-DEBUG: */ $this->partialStub('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName);
329 * "Pops" first entry from stack
331 * @param $stackerName Name of the stack
332 * @return $value Value "shifted" from array
333 * @throws EmptyStackerException If the named stacker is empty
335 protected function popFirst ($stackerName) {
336 // Is the stack not yet initialized or full?
337 if ($this->isStackEmpty($stackerName)) {
338 // Throw an exception
339 throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
342 // Now, remove the last entry, we don't care about the return value here, see elseif() block above
343 /* NOISY-DEBUG: */ $this->partialStub('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName);
348 * Checks whether the given stack is full
350 * @param $stackerName Name of the stack
351 * @return $isFull Whether the stack is full
353 protected function isStackFull ($stackerName) {
354 // File-based stacks will only run full if the disk space is low.
355 // @TODO Please implement this, returning false
363 * Checks whether the given stack is empty
365 * @param $stackerName Name of the stack
366 * @return $isEmpty Whether the stack is empty
367 * @throws NoStackerException If given stack is missing
369 public function isStackEmpty ($stackerName) {
370 // So, is the stack empty?
371 $isEmpty = (($this->getStackCount($stackerName)) == 0);
378 * Initializes given stacker
380 * @param $stackerName Name of the stack
381 * @param $forceReInit Force re-initialization
383 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
385 public function initStack ($stackerName, $forceReInit = false) {
386 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
390 * Initializes all stacks
393 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
395 public function initStacks (array $stacks, $forceReInit = false) {
396 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
400 * Checks whether the given stack is initialized (set in array $stackers)
402 * @param $stackerName Name of the stack
403 * @return $isInitialized Whether the stack is initialized
404 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
406 public function isStackInitialized ($stackerName) {
407 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
411 * Determines whether the EOF has been reached
413 * @return $isEndOfFileReached Whether the EOF has been reached
414 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
416 public function isEndOfFileReached () {
417 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
421 * Getter for size of given stack (array count)
423 * @param $stackerName Name of the stack
424 * @return $count Size of stack (array count)
426 public function getStackCount ($stackerName) {
427 // Now, simply return the found count value, this must be up-to-date then!
428 return $this->getIteratorInstance()->getCounter();
432 * Calculates minimum length for one entry/block
434 * @return $length Minimum length for one entry/block
436 public function calculateMinimumBlockLength () {
439 // Length of entry group
440 BaseBinaryFile::LENGTH_GROUP + strlen(chr(BaseBinaryFile::SEPARATOR_GROUP_HASH)) +
442 self::getHashLength() + strlen(chr(BaseBinaryFile::SEPARATOR_HASH_VALUE)) + 1 +
444 strlen(chr(BaseBinaryFile::SEPARATOR_ENTRIES));
451 * Initializes counter for valid entries, arrays for damaged entries and
452 * an array for gap seek positions. If you call this method on your own,
453 * please re-analyze the file structure. So you are better to call
454 * analyzeFile() instead of this method.
457 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
459 public function initCountersGapsArray () {
460 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
464 * Getter for header size
466 * @return $totalEntries Size of file header
467 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
469 public final function getHeaderSize () {
470 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
474 * Setter for header size
476 * @param $headerSize Size of file header
478 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
480 public final function setHeaderSize ($headerSize) {
481 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
485 * Getter for header array
487 * @return $totalEntries Size of file header
488 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
490 public final function getHeader () {
491 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
497 * @param $header Array for a file header
499 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
501 public final function setHeader (array $header) {
502 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
506 * Updates seekPosition attribute from file to avoid to much access on file.
509 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
511 public function updateSeekPosition () {
512 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
516 * Getter for total entries
518 * @return $totalEntries Total entries in this file
519 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
521 public final function getCounter () {
522 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
526 * Writes data at given position
528 * @param $seekPosition Seek position
529 * @param $data Data to be written
530 * @param $flushHeader Whether to flush the header (default: flush)
532 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
534 public function writeData ($seekPosition, $data, $flushHeader = true) {
535 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] seekPosition=%s,data[]=%s,flushHeader=%d', __METHOD__, __LINE__, $seekPosition, gettype($data), intval($flushHeader)));
536 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
540 * Writes given value to the file and returns a hash and gap position for it
542 * @param $groupId Group identifier
543 * @param $value Value to be added to the stack
544 * @return $data Hash and gap position
545 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
547 public function writeValueToFile ($groupId, $value) {
548 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] groupId=%s,value[%s]=%s', __METHOD__, __LINE__, $groupId, gettype($value), print_r($value, true)));
549 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
553 * Searches for next suitable gap the given length of data can fit in
554 * including padding bytes.
556 * @param $length Length of raw data
557 * @return $seekPosition Found next gap's seek position
558 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
560 public function searchNextGap ($length) {
561 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] length=%s', __METHOD__, __LINE__, $length));
562 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
566 * "Getter" for file size
568 * @return $fileSize Size of currently loaded file
570 public function getFileSize () {
571 // Call iterator's method
572 return $this->getIteratorInstance()->getFileSize();
576 * Writes given raw data to the file and returns a gap position and length
578 * @param $groupId Group identifier
579 * @param $hash Hash from encoded value
580 * @param $encoded Encoded value to be written to the file
581 * @return $data Gap position and length of the raw data
583 public function writeDataToFreeGap ($groupId, $hash, $encoded) {
585 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] groupId=%s,hash=%s,encoded()=%d - CALLED!', __METHOD__, __LINE__, $groupId, $hash, strlen($encoded)));
587 // Raw data been written to the file
588 $rawData = sprintf('%s%s%s%s%s',
590 BaseBinaryFile::SEPARATOR_GROUP_HASH,
592 BaseBinaryFile::SEPARATOR_HASH_VALUE,
597 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] groupId=%s,hash=%s,rawData()=%d', __METHOD__, __LINE__, $groupId, $hash, strlen($rawData)));
599 // Search for next free gap
600 $gapPosition = $this->getIteratorInstance()->searchNextGap(strlen($rawData));
602 // Gap position cannot be smaller than header length + 1
603 assert($gapPosition > $this->getIteratorInstance()->getHeaderSize());
606 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] groupId=%s,hash=%s,gapPosition=%s', __METHOD__, __LINE__, $groupId, $hash, $gapPosition));
608 // Then write the data at that gap
609 $this->getIteratorInstance()->writeData($gapPosition, $rawData);
612 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] groupId=%s,hash=%s,rawData()=%d - EXIT!', __METHOD__, __LINE__, $groupId, $hash, strlen($rawData)));
614 // Return gap position, hash and length of raw data
616 self::ARRAY_INDEX_GAP_POSITION => $gapPosition,
617 self::ARRAY_INDEX_HASH => $hash,
618 self::ARRAY_INDEX_DATA_LENGTH => strlen($rawData)