Close segment, write it to disk and return segment info

@return Zend_Search_Lucene_Index_SegmentInfo
345572
public function close()
    {
        if ($this->_docCount == 0) {
            return null;
        }

        $this->_dumpFNM();
        $this->_generateCFS();

        /**
 * Zend_Search_Lucene_Index_SegmentInfo 
*/
        include_once 'Zend/Search/Lucene/Index/SegmentInfo.php';

        return new Zend_Search_Lucene_Index_SegmentInfo(
            $this->_directory,
            $this->_name,
            $this->_docCount,
            -1,
            null,
            true,
            true
        );
    }
91657
public static function getUriSegment(int $segment)
    {
        $segments = self::getUriSegments();
        return isset($segments[$segment]) ? $segments[$segment] : null;
    }
803549
private function _readPre21SegmentsFile()
    {
        $segmentsFile = $this->_directory->getFileObject('segments');

        $format = $segmentsFile->readInt();

        if ($format != (int)0xFFFFFFFF) {
            include_once 'Zend/Search/Lucene/Exception.php';
            throw new Zend_Search_Lucene_Exception('Wrong segments file format');
        }

        // read version
        $segmentsFile->readLong();

        // read segment name counter
        $segmentsFile->readInt();

        $segments = $segmentsFile->readInt();

        $this->_docCount = 0;

        // read segmentInfos
        for ($count = 0; $count < $segments; $count++) {
            $segName = $segmentsFile->readString();
            $segSize = $segmentsFile->readInt();
            $this->_docCount += $segSize;

            $this->_segmentInfos[$segName] =
                                new Zend_Search_Lucene_Index_SegmentInfo(
                                    $this->_directory,
                                    $segName,
                                    $segSize
                                );
        }

        // Use 2.1 as a target version. Index will be reorganized at update time.
        $this->_formatVersion = self::FORMAT_2_1;
    }
1147894
public function termDocs(Zend_Search_Lucene_Index_Term $term, $shift = 0, $docsFilter = null)
    {
        $termInfo = $this->getTermInfo($term);

        if (!$termInfo instanceof Zend_Search_Lucene_Index_TermInfo) {
            if ($docsFilter !== null  &&  $docsFilter instanceof Zend_Search_Lucene_Index_DocsFilter) {
                $docsFilter->segmentFilters[$this->_name] = array();
            }
            return array();
        }

        $frqFile = $this->openCompoundFile('.frq');
        $frqFile->seek($termInfo->freqPointer,SEEK_CUR);
        $docId  = 0;
        $result = array();

        if ($docsFilter !== null) {
            if (!$docsFilter instanceof Zend_Search_Lucene_Index_DocsFilter) {
                require_once 'Zend/Search/Lucene/Exception.php';
                throw new Zend_Search_Lucene_Exception('Documents filter must be an instance of Zend_Search_Lucene_Index_DocsFilter or null.');
            }

            if (isset($docsFilter->segmentFilters[$this->_name])) {
                // Filter already has some data for the current segment

                // Make short name for the filter (which doesn't need additional dereferencing)
                $filter = &$docsFilter->segmentFilters[$this->_name];

                // Check if filter is not empty
                if (count($filter) == 0) {
                    return array();
                }

                if ($this->_docCount/count($filter) < self::FULL_SCAN_VS_FETCH_BOUNDARY) {
                    // Perform fetching
// ---------------------------------------------------------------
                    $updatedFilterData = array();

                    for( $count=0; $count < $termInfo->docFreq; $count++ ) {
                        $docDelta = $frqFile->readVInt();
                        if( $docDelta % 2 == 1 ) {
                            $docId += ($docDelta-1)/2;
                        } else {
                            $docId += $docDelta/2;
                            // read freq
                            $frqFile->readVInt();
                        }

                        if (isset($filter[$docId])) {
                           $result[] = $shift + $docId;
                           $updatedFilterData[$docId] = 1; // 1 is just a some constant value, so we don't need additional var dereference here
                        }
                    }
                    $docsFilter->segmentFilters[$this->_name] = $updatedFilterData;
// ---------------------------------------------------------------
                } else {
                    // Perform full scan
                    $updatedFilterData = array();

                    for( $count=0; $count < $termInfo->docFreq; $count++ ) {
                        $docDelta = $frqFile->readVInt();
                        if( $docDelta % 2 == 1 ) {
                            $docId += ($docDelta-1)/2;
                        } else {
                            $docId += $docDelta/2;
                            // read freq
                            $frqFile->readVInt();
                        }

                        if (isset($filter[$docId])) {
                           $result[] = $shift + $docId;
                           $updatedFilterData[$docId] = 1; // 1 is just a some constant value, so we don't need additional var dereference here
                        }
                    }
                    $docsFilter->segmentFilters[$this->_name] = $updatedFilterData;
                }
            } else {
                // Filter is present, but doesn't has data for the current segment yet
                $filterData = array();
                for( $count=0; $count < $termInfo->docFreq; $count++ ) {
                    $docDelta = $frqFile->readVInt();
                    if( $docDelta % 2 == 1 ) {
                        $docId += ($docDelta-1)/2;
                    } else {
                        $docId += $docDelta/2;
                        // read freq
                        $frqFile->readVInt();
                    }

                    $result[] = $shift + $docId;
                    $filterData[$docId] = 1; // 1 is just a some constant value, so we don't need additional var dereference here
                }
                $docsFilter->segmentFilters[$this->_name] = $filterData;
            }
        } else {
            for( $count=0; $count < $termInfo->docFreq; $count++ ) {
                $docDelta = $frqFile->readVInt();
                if( $docDelta % 2 == 1 ) {
                    $docId += ($docDelta-1)/2;
                } else {
                    $docId += $docDelta/2;
                    // read freq
                    $frqFile->readVInt();
                }

                $result[] = $shift + $docId;
            }
        }

        return $result;
    }
568495
public function closeCursor()
    {
        try {
            return $this->_stmt->closeCursor();
        } catch (PDOException $e) {
            // require_once 'Zend/Db/Statement/Exception.php';
            throw new Zend_Db_Statement_Exception($e->getMessage(), $e->getCode(), $e);
        }
    }
688506
public function forceOpen()
    {
        if (!$this->isOpen()) {
            $this->fireEvent(self::CLOSED, self::OPEN);
        }

        $failTime = time();
        for ($i = 0; $i < $this->threshold; $i ++) {
            $this->failures[] = $failTime;
        }
        return $this->write();
    }
383988
public function closeCursor() {
		if (is_resource($this->stmt)) {
			// Free statement
			$res = @oci_free_statement($this->stmt);
			$this->checkError($res);
		}
		else {
			$res = true;
		}

		// Free LOBs if any
		if (!empty($this->_lobs)) {
			foreach ($this->_lobs as $key => &$value) {
				$res = $value['lob']->free();
				$this->checkError($res);
			}
			$this->_lobs = array();
			$this->_lobsCount = 0;

			$res = true;
		}

		return $res;
	}
1280690
public function hasTerm(Zend_Search_Lucene_Index_Term $term)
    {
        foreach ($this->_segmentInfos as $segInfo) {
            if ($segInfo->getTermInfo($term) !== null) {
                return true;
            }
        }

        return false;
    }
1194873
public static function getResultSetLimit()
    {
        if (count($this->_indices) == 0) {
            include_once 'Zend/Search/Lucene/Exception.php';
            throw new Zend_Search_Lucene_Exception('Indices list is empty');
        }

        $defaultResultSetLimit = reset($this->_indices)->getResultSetLimit();

        foreach ($this->_indices as $index) {
            if ($index->getResultSetLimit() !== $defaultResultSetLimit) {
                include_once 'Zend/Search/Lucene/Exception.php';
                throw new Zend_Search_Lucene_Exception('Indices have different default search field.');
            }
        }

        return $defaultResultSetLimit;
    }
260142
public List<MemorySegment> close() throws IOException
	{
		// send off set last segment
		writeSegment(getCurrentSegment(), getCurrentPositionInSegment(), true);
		clear();
		
		// close the writer and gather all segments
		final LinkedBlockingQueue<MemorySegment> queue = this.writer.getReturnQueue();
		this.writer.close();
		
		// re-collect all memory segments
		ArrayList<MemorySegment> list = new ArrayList<MemorySegment>(this.numSegments);	
		for (int i = 0; i < this.numSegments; i++) {
			final MemorySegment m = queue.poll();
			if (m == null) {
				// we get null if the queue is empty. that should not be the case if the reader was properly closed.
				throw new RuntimeException("ChannelWriterOutputView: MemorySegments have been taken from return queue by different actor.");
			}
			list.add(m);
		}
		
		return list;
	}
1278016
public function write(): string
    {
        $this->targetFile->removeIfExists();

        return $this->fileWriter->write($this->targetFile);
    }
416038
private function _maybeMergeSegments()
    {
        if (Zend_Search_Lucene_LockManager::obtainOptimizationLock($this->_directory) === false) {
            return;
        }

        if (!$this->_hasAnythingToMerge()) {
            Zend_Search_Lucene_LockManager::releaseOptimizationLock($this->_directory);
            return;
        }

        // Update segments list to be sure all segments are not merged yet by another process
        //
        // Segment merging functionality is concentrated in this class and surrounded
        // by optimization lock obtaining/releasing.
        // _updateSegments() refreshes segments list from the latest index generation.
        // So only new segments can be added to the index while we are merging some already existing
        // segments.
        // Newly added segments will be also included into the index by the _updateSegments() call
        // either by another process or by the current process with the commit() call at the end of _mergeSegments() method.
        // That's guaranteed by the serialisation of _updateSegments() execution using exclusive locks.
        $this->_updateSegments();

        // Perform standard auto-optimization procedure
        $segmentSizes = array();
        foreach ($this->_segmentInfos as $segName => $segmentInfo) {
            $segmentSizes[$segName] = $segmentInfo->count();
        }

        $mergePool   = array();
        $poolSize    = 0;
        $sizeToMerge = $this->maxBufferedDocs;
        asort($segmentSizes, SORT_NUMERIC);
        foreach ($segmentSizes as $segName => $size) {
            // Check, if segment comes into a new merging block
            while ($size >= $sizeToMerge) {
                // Merge previous block if it's large enough
                if ($poolSize >= $sizeToMerge) {
                    $this->_mergeSegments($mergePool);
                }
                $mergePool   = array();
                $poolSize    = 0;

                $sizeToMerge *= $this->mergeFactor;

                if ($sizeToMerge > $this->maxMergeDocs) {
                    Zend_Search_Lucene_LockManager::releaseOptimizationLock($this->_directory);
                    return;
                }
            }

            $mergePool[] = $this->_segmentInfos[$segName];
            $poolSize += $size;
        }

        if ($poolSize >= $sizeToMerge) {
            $this->_mergeSegments($mergePool);
        }

        Zend_Search_Lucene_LockManager::releaseOptimizationLock($this->_directory);
    }
710971
public function writeAttempt()
    {
        $result = self::OK;

        if (empty($this->filepath)) {
            return self::ERROR;
        }

        /**
         * Open the file for writing only. If the file does not exist, it is created.
         * If it exists, it is not truncated (as opposed to 'w'). File pointer is moved to beginning.
         *
         * "c" is needed instead of "w", because if lock is not acquired, old version of the file is returned.
         * If "w" option is used, file is truncated no matter what, and empty file is returned.
         */
        $fp = fopen($this->filepath, 'c');

        if ($fp === false) {
            return self::ERROR_OPEN;
        }

        /**
         * File locking disabled?
         */
        if (empty($this->file_lock)) {
            ftruncate($fp, 0);
            if (fwrite($fp, $this->content) === false) {
                $result = self::ERROR_WRITE;
            }
            fclose($fp);

            return $result;
        }

        /**
         * File locking is enabled
         *
         * Try to acquire File Write Lock. If lock is not acquired read file and return old contents.
         *
         * Recommended is: LOCK_EX | LOCK_NB.
         * LOCK_EX to acquire an exclusive lock (writer).
         * LOCK_NB - prevents flock() from blocking while locking, so that others could still read
         * (but not write) while lock is active
         */
        if (flock($fp, $this->file_lock)) {
            /**
             * since "c" was used with fopen, file is not truncated. Truncate manually.
             */
            ftruncate($fp, 0);

            //write content
            if (fwrite($fp, $this->content) === false) {
                $result = self::ERROR_WRITE;
            }

            //release lock
            flock($fp, LOCK_UN);
        } else {
            /**
             * Lock was not granted.
             */

            $result = self::ERROR_LOCK;
        }

        fclose($fp);

        return $result;
    }
581995
public function termDocs(Zend_Search_Lucene_Index_Term $term, $docsFilter = null)
    {
        $subResults = array();
        $segmentStartDocId = 0;

        foreach ($this->_segmentInfos as $segmentInfo) {
            $subResults[] = $segmentInfo->termDocs($term, $segmentStartDocId, $docsFilter);

            $segmentStartDocId += $segmentInfo->count();
        }

        if (count($subResults) == 0) {
            return array();
        } else if (count($subResults) == 1) {
            // Index is optimized (only one segment)
            // Do not perform array reindexing
            return reset($subResults);
        } else {
            $result = call_user_func_array('array_merge', $subResults);
        }

        return $result;
    }
113482
public function resetTermsStream()
    {
        if ($this->_termsStream === null) {
            /**
 * Zend_Search_Lucene_TermStreamsPriorityQueue 
*/
            include_once 'Zend/Search/Lucene/TermStreamsPriorityQueue.php';

            $this->_termsStream = new Zend_Search_Lucene_TermStreamsPriorityQueue($this->_segmentInfos);
        } else {
            $this->_termsStream->resetTermsStream();
        }
    }
106125
public void close()
    {
        try
        {
            if (w != null && readyForCommit)
            {
                w.commit();
                copy(index, FSDirectory.open(getIndexDirectory().toPath()));
            }
        }

        catch (Exception e)
        {
            log.error("Error while closing lucene indexes, Caused by: ", e);
            throw new LuceneIndexingException("Error while closing lucene indexes.", e);
        }
    }
974930
private function _mergeSegments($segments)
    {
        $newName = $this->_newSegmentName();

        /**
 * Zend_Search_Lucene_Index_SegmentMerger 
*/
        include_once 'Zend/Search/Lucene/Index/SegmentMerger.php';
        $merger = new Zend_Search_Lucene_Index_SegmentMerger(
            $this->_directory,
            $newName
        );
        foreach ($segments as $segmentInfo) {
            $merger->addSource($segmentInfo);
            $this->_segmentsToDelete[$segmentInfo->getName()] = $segmentInfo->getName();
        }

        $newSegment = $merger->merge();
        if ($newSegment !== null) {
            $this->_newSegments[$newSegment->getName()] = $newSegment;
        }

        $this->commit();
    }