3 namespace Org\Mxchange\CoreFramework\Stacker\Filesystem;
5 // Import framework stuff
6 use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
7 use Org\Mxchange\CoreFramework\Filesystem\File\BaseBinaryFile;
8 use Org\Mxchange\CoreFramework\Generic\UnsupportedOperationException;
9 use Org\Mxchange\CoreFramework\Iterator\Filesystem\SeekableWritableFileIterator;
10 use Org\Mxchange\CoreFramework\Stacker\BaseStacker;
16 * A general file-based stack class
18 * @author Roland Haeder <webmaster@ship-simu.org>
20 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
21 * @license GNU GPL 3.0 or any newer version
22 * @link http://www.ship-simu.org
24 * This program is free software: you can redistribute it and/or modify
25 * it under the terms of the GNU General Public License as published by
26 * the Free Software Foundation, either version 3 of the License, or
27 * (at your option) any later version.
29 * This program is distributed in the hope that it will be useful,
30 * but WITHOUT ANY WARRANTY; without even the implied warranty of
31 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
32 * GNU General Public License for more details.
34 * You should have received a copy of the GNU General Public License
35 * along with this program. If not, see <http://www.gnu.org/licenses/>.
37 abstract class BaseFileStack extends BaseStacker {
39 * Magic for this stack
41 const STACK_MAGIC = 'STACKv0.1';
44 * Name of array index for gap position
46 const ARRAY_INDEX_GAP_POSITION = 'gap';
49 * Name of array index for hash
51 const ARRAY_INDEX_HASH = 'hash';
54 * Name of array index for length of raw data
56 const ARRAY_INDEX_DATA_LENGTH = 'length';
59 * Protected constructor
61 * @param $className Name of the class
64 protected function __construct ($className) {
65 // Call parent constructor
66 parent::__construct($className);
70 * Reads the file header
73 * @todo To hard assertions here, better rewrite them to exceptions
75 public function readFileHeader () {
76 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
78 // First rewind to beginning as the header sits at the beginning ...
79 $this->getIteratorInstance()->rewind();
81 // Then read it (see constructor for calculation)
82 $data = $this->getIteratorInstance()->read($this->getIteratorInstance()->getHeaderSize());
83 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Read %d bytes (%d wanted).', __METHOD__, __LINE__, strlen($data), $this->getIteratorInstance()->getHeaderSize()));
85 // Have all requested bytes been read?
86 assert(strlen($data) == $this->getIteratorInstance()->getHeaderSize());
87 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
89 // Last character must be the separator
90 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] data(-1)=%s', __METHOD__, __LINE__, dechex(ord(substr($data, -1, 1)))));
91 assert(substr($data, -1, 1) == chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES));
92 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
94 // Okay, then remove it
95 $data = substr($data, 0, -1);
97 // And update seek position
98 $this->getIteratorInstance()->updateSeekPosition();
105 * 2 => current seek position
107 $header = explode(chr(BaseBinaryFile::SEPARATOR_HEADER_DATA), $data);
110 $this->getIteratorInstance()->setHeader($header);
112 // Check if the array has only 3 elements
113 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] header(%d)=%s', __METHOD__, __LINE__, count($header), print_r($header, true)));
114 assert(count($header) == 3);
115 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
118 assert($header[0] == self::STACK_MAGIC);
119 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
121 // Check length of count and seek position
122 assert(strlen($header[1]) == BaseBinaryFile::LENGTH_COUNT);
123 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
124 assert(strlen($header[2]) == BaseBinaryFile::LENGTH_POSITION);
125 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
127 // Decode count and seek position
128 $header[1] = hex2bin($header[1]);
129 $header[2] = hex2bin($header[2]);
131 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
135 * Flushes the file header
139 public function flushFileHeader () {
140 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
142 // Put all informations together
143 $header = sprintf('%s%s%s%s%s%s',
147 // Separator magic<->count
148 chr(BaseBinaryFile::SEPARATOR_HEADER_DATA),
150 // Total entries (will be zero) and pad it to 20 chars
151 str_pad($this->dec2hex($this->getIteratorInstance()->getCounter()), BaseBinaryFile::LENGTH_COUNT, '0', STR_PAD_LEFT),
153 // Separator count<->seek position
154 chr(BaseBinaryFile::SEPARATOR_HEADER_DATA),
156 // Position (will be zero)
157 str_pad($this->dec2hex($this->getIteratorInstance()->getSeekPosition(), 2), BaseBinaryFile::LENGTH_POSITION, '0', STR_PAD_LEFT),
159 // Separator position<->entries
160 chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES)
163 // Write it to disk (header is always at seek position 0)
164 $this->getIteratorInstance()->writeData(0, $header, false);
166 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
170 * Initializes this file-based stack.
172 * @param $fileInfoInstance An instance of a SplFileInfo class
173 * @param $type Type of this stack (e.g. url_source for URL sources)
175 * @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.
177 protected function initFileStack (SplFileInfo $fileInfoInstance, $type) {
178 // Get a stack file instance
179 $fileInstance = ObjectFactory::createObjectByConfiguredName('stack_file_class', array($fileInfoInstance, $this));
181 // Get iterator instance
182 $iteratorInstance = ObjectFactory::createObjectByConfiguredName('file_iterator_class', array($fileInstance));
184 // Is the instance implementing the right interface?
185 assert($iteratorInstance instanceof SeekableWritableFileIterator);
188 $this->setIteratorInstance($iteratorInstance);
190 // Calculate header size
191 $this->getIteratorInstance()->setHeaderSize(
192 strlen(self::STACK_MAGIC) +
193 strlen(chr(BaseBinaryFile::SEPARATOR_HEADER_DATA)) +
194 BaseBinaryFile::LENGTH_COUNT +
195 strlen(chr(BaseBinaryFile::SEPARATOR_HEADER_DATA)) +
196 BaseBinaryFile::LENGTH_POSITION +
197 strlen(chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES))
200 // Init counters and gaps array
201 $this->getIteratorInstance()->initCountersGapsArray();
203 // Is the file's header initialized?
204 if (!$this->getIteratorInstance()->isFileHeaderInitialized()) {
205 // No, then create it (which may pre-allocate the stack)
206 $this->getIteratorInstance()->createFileHeader();
208 // And pre-allocate a bit
209 $this->getIteratorInstance()->preAllocateFile('file_stack');
212 // Load the file header
213 $this->readFileHeader();
215 // Count all entries in file
216 $this->getIteratorInstance()->analyzeFile();
219 * Get stack index instance. This can be used for faster
220 * "defragmentation" and startup.
222 $indexInstance = FileStackIndexFactory::createFileStackIndexInstance($fileInfoInstance, $type);
225 $this->setIndexInstance($indexInstance);
229 * Adds a value to given stack
231 * @param $stackerName Name of the stack
232 * @param $value Value to add to this stacker
234 * @throws FullStackerException If the stack is full
236 protected function addValue ($stackerName, $value) {
238 if ($this->isStackFull($stackerName)) {
240 throw new FullStackerException(array($this, $stackerName, $value), self::EXCEPTION_STACKER_IS_FULL);
244 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName . ',value[' . gettype($value) . ']=' . print_r($value, true));
246 // No objects/resources are allowed as their serialization takes to long
247 assert(!is_object($value));
248 assert(!is_resource($value));
251 * Now add the value to the file stack which returns gap position, a
252 * hash and length of the raw data.
254 $data = $this->getIteratorInstance()->writeValueToFile($stackerName, $value);
256 // Add the hash and gap position to the index
257 $this->getIndexInstance()->addHashToIndex($stackerName, $data);
261 * Get last value from named stacker
263 * @param $stackerName Name of the stack
264 * @return $value Value of last added value
265 * @throws EmptyStackerException If the stack is empty
267 protected function getLastValue ($stackerName) {
268 // Is the stack not yet initialized or full?
269 if ($this->isStackEmpty($stackerName)) {
270 // Throw an exception
271 throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
274 // Now get the last value
275 /* NOISY-DEBUG: */ $this->partialStub('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName);
283 * Get first value from named stacker
285 * @param $stackerName Name of the stack
286 * @return $value Value of last added value
287 * @throws EmptyStackerException If the stack is empty
289 protected function getFirstValue ($stackerName) {
290 // Is the stack not yet initialized or full?
291 if ($this->isStackEmpty($stackerName)) {
292 // Throw an exception
293 throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
296 // Now get the first value
297 /* NOISY-DEBUG: */ $this->partialStub('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName);
305 * "Pops" last entry from stack
307 * @param $stackerName Name of the stack
308 * @return $value Value "poped" from array
309 * @throws EmptyStackerException If the stack is empty
311 protected function popLast ($stackerName) {
312 // Is the stack not yet initialized or full?
313 if ($this->isStackEmpty($stackerName)) {
314 // Throw an exception
315 throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
318 // Now, remove the last entry, we don't care about the return value here, see elseif() block above
319 /* NOISY-DEBUG: */ $this->partialStub('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName);
324 * "Pops" first entry from stack
326 * @param $stackerName Name of the stack
327 * @return $value Value "shifted" from array
328 * @throws EmptyStackerException If the named stacker is empty
330 protected function popFirst ($stackerName) {
331 // Is the stack not yet initialized or full?
332 if ($this->isStackEmpty($stackerName)) {
333 // Throw an exception
334 throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
337 // Now, remove the last entry, we don't care about the return value here, see elseif() block above
338 /* NOISY-DEBUG: */ $this->partialStub('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName);
343 * Checks whether the given stack is full
345 * @param $stackerName Name of the stack
346 * @return $isFull Whether the stack is full
348 protected function isStackFull ($stackerName) {
349 // File-based stacks will only run full if the disk space is low.
350 // @TODO Please implement this, returning false
358 * Checks whether the given stack is empty
360 * @param $stackerName Name of the stack
361 * @return $isEmpty Whether the stack is empty
362 * @throws NoStackerException If given stack is missing
364 public function isStackEmpty ($stackerName) {
365 // So, is the stack empty?
366 $isEmpty = (($this->getStackCount($stackerName)) == 0);
373 * Initializes given stacker
375 * @param $stackerName Name of the stack
376 * @param $forceReInit Force re-initialization
378 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
380 public function initStack ($stackerName, $forceReInit = false) {
381 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
385 * Initializes all stacks
388 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
390 public function initStacks (array $stacks, $forceReInit = false) {
391 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
395 * Checks whether the given stack is initialized (set in array $stackers)
397 * @param $stackerName Name of the stack
398 * @return $isInitialized Whether the stack is initialized
399 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
401 public function isStackInitialized ($stackerName) {
402 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
406 * Determines whether the EOF has been reached
408 * @return $isEndOfFileReached Whether the EOF has been reached
409 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
411 public function isEndOfFileReached () {
412 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
416 * Getter for size of given stack (array count)
418 * @param $stackerName Name of the stack
419 * @return $count Size of stack (array count)
421 public function getStackCount ($stackerName) {
422 // Now, simply return the found count value, this must be up-to-date then!
423 return $this->getIteratorInstance()->getCounter();
427 * Calculates minimum length for one entry/block
429 * @return $length Minimum length for one entry/block
431 public function calculateMinimumBlockLength () {
434 // Length of entry group
435 BaseBinaryFile::LENGTH_GROUP + strlen(chr(BaseBinaryFile::SEPARATOR_GROUP_HASH)) +
437 self::getHashLength() + strlen(chr(BaseBinaryFile::SEPARATOR_HASH_VALUE)) + 1 +
439 strlen(chr(BaseBinaryFile::SEPARATOR_ENTRIES));
446 * Initializes counter for valid entries, arrays for damaged entries and
447 * an array for gap seek positions. If you call this method on your own,
448 * please re-analyze the file structure. So you are better to call
449 * analyzeFile() instead of this method.
452 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
454 public function initCountersGapsArray () {
455 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
459 * Getter for header size
461 * @return $totalEntries Size of file header
462 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
464 public final function getHeaderSize () {
465 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
469 * Setter for header size
471 * @param $headerSize Size of file header
473 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
475 public final function setHeaderSize ($headerSize) {
476 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
480 * Getter for header array
482 * @return $totalEntries Size of file header
483 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
485 public final function getHeader () {
486 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
492 * @param $header Array for a file header
494 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
496 public final function setHeader (array $header) {
497 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
501 * Updates seekPosition attribute from file to avoid to much access on file.
504 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
506 public function updateSeekPosition () {
507 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
511 * Getter for total entries
513 * @return $totalEntries Total entries in this file
514 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
516 public final function getCounter () {
517 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
521 * Writes data at given position
523 * @param $seekPosition Seek position
524 * @param $data Data to be written
525 * @param $flushHeader Whether to flush the header (default: flush)
527 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
529 public function writeData ($seekPosition, $data, $flushHeader = true) {
530 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] seekPosition=%s,data[]=%s,flushHeader=%d', __METHOD__, __LINE__, $seekPosition, gettype($data), intval($flushHeader)));
531 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
535 * Writes given value to the file and returns a hash and gap position for it
537 * @param $groupId Group identifier
538 * @param $value Value to be added to the stack
539 * @return $data Hash and gap position
540 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
542 public function writeValueToFile ($groupId, $value) {
543 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] groupId=%s,value[%s]=%s', __METHOD__, __LINE__, $groupId, gettype($value), print_r($value, true)));
544 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
548 * Searches for next suitable gap the given length of data can fit in
549 * including padding bytes.
551 * @param $length Length of raw data
552 * @return $seekPosition Found next gap's seek position
553 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
555 public function searchNextGap ($length) {
556 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] length=%s', __METHOD__, __LINE__, $length));
557 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
561 * "Getter" for file size
563 * @return $fileSize Size of currently loaded file
565 public function getFileSize () {
566 // Call iterator's method
567 return $this->getIteratorInstance()->getFileSize();
571 * Writes given raw data to the file and returns a gap position and length
573 * @param $groupId Group identifier
574 * @param $hash Hash from encoded value
575 * @param $encoded Encoded value to be written to the file
576 * @return $data Gap position and length of the raw data
578 public function writeDataToFreeGap ($groupId, $hash, $encoded) {
580 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] groupId=%s,hash=%s,encoded()=%d - CALLED!', __METHOD__, __LINE__, $groupId, $hash, strlen($encoded)));
582 // Raw data been written to the file
583 $rawData = sprintf('%s%s%s%s%s',
585 BaseBinaryFile::SEPARATOR_GROUP_HASH,
587 BaseBinaryFile::SEPARATOR_HASH_VALUE,
592 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] groupId=%s,hash=%s,rawData()=%d', __METHOD__, __LINE__, $groupId, $hash, strlen($rawData)));
594 // Search for next free gap
595 $gapPosition = $this->getIteratorInstance()->searchNextGap(strlen($rawData));
597 // Gap position cannot be smaller than header length + 1
598 assert($gapPosition > $this->getIteratorInstance()->getHeaderSize());
601 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] groupId=%s,hash=%s,gapPosition=%s', __METHOD__, __LINE__, $groupId, $hash, $gapPosition));
603 // Then write the data at that gap
604 $this->getIteratorInstance()->writeData($gapPosition, $rawData);
607 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] groupId=%s,hash=%s,rawData()=%d - EXIT!', __METHOD__, __LINE__, $groupId, $hash, strlen($rawData)));
609 // Return gap position, hash and length of raw data
611 self::ARRAY_INDEX_GAP_POSITION => $gapPosition,
612 self::ARRAY_INDEX_HASH => $hash,
613 self::ARRAY_INDEX_DATA_LENGTH => strlen($rawData)