Get the next state based on this checkpoint state.

@param recovering if in recovering phase
@return the next checkpoint state based on this state.
333405
public CheckPointState nextState(boolean recovering) {
        CheckPointState nextState;
        switch (state) {
            case PREPARING:
                nextState = recovering ? new CheckPointState(txid - 1, State.COMMITTED) : new CheckPointState(txid, State.COMMITTING);
                break;
            case COMMITTING:
                nextState = new CheckPointState(txid, State.COMMITTED);
                break;
            case COMMITTED:
                nextState = recovering ? this : new CheckPointState(txid + 1, State.PREPARING);
                break;
            default:
                throw new IllegalStateException("Unknown state " + state);
        }
        return nextState;
    }
608739
@Override
	public T next() {

		validateState();

		if (!hasNext()) {
			throw new NoSuchElementException("No more elements available for cursor " + getCursorMark() + ".");
		}

		T next = moveNext(delegate);
		position++;
		return next;
	}
738270
@Override
    @Transactional
    public Restoration transitionRestoreStatus(String restorationId,
                                               RestoreStatus status,
                                               String message)
        throws InvalidStateTransitionException, RestorationNotFoundException {

        Restoration restoration = getRestoration(restorationId);
        return _transitionRestoreStatus(status, message, restoration);
    }
74717
@Nullable
    public String getState() {
        lifecycleLock.readLock().lock();
        try {
            return state == null ? null : state.toString();
        } finally {
            lifecycleLock.readLock().unlock();
        }
    }
64881
@Override
    public void directInitialization(FailureScope failureScope) throws RecoveryFailedException {
        if (tc.isEntryEnabled())
            Tr.entry(tc, "directInitialization", new Object[] { failureScope, this });

        // Use configuration to determine if recovery is local (for z/OS).
        final FailureScope currentFailureScope = Configuration.localFailureScope(); /* @LI1578-22A */

        // Synchronize to ensure consistency with the registerService
        // method. The remainder of the method is not synchronized on this in order that two independant
        // recovery processes may be driven concurrently on two different threads.
        synchronized (_registeredRecoveryAgents) {
            // Ensure that further RecoveryAgent registrations are prohibited.
            _registrationAllowed = false;
        }

        if (currentFailureScope.equals(failureScope)) /* @LI1578-22C */
        {
            Tr.info(tc, "CWRLS0010_PERFORM_LOCAL_RECOVERY", failureScope.serverName());
        } else {
            Tr.info(tc, "CWRLS0011_PERFORM_PEER_RECOVERY", failureScope.serverName());
        }

        // Extract the 'values' collection from the _registeredRecoveryAgents map and create an iterator
        // from it. This iterator will return ArrayList objects each containing a set of RecoveryAgent
        // objects. Each ArrayList corrisponds to a different sequence priority value.
        final Collection registeredRecoveryAgentsValues = _registeredRecoveryAgents.values();

        Iterator registeredRecoveryAgentsValuesIterator = registeredRecoveryAgentsValues.iterator();
        while (registeredRecoveryAgentsValuesIterator.hasNext()) {
            // Extract the next ArrayList and create an iterator from it. This iterator will return RecoveryAgent
            // objects that are registered at the same sequence priority value.
            final ArrayList registeredRecoveryAgentsArray = (java.util.ArrayList) registeredRecoveryAgentsValuesIterator.next();
            final Iterator registeredRecoveryAgentsArrayIterator = registeredRecoveryAgentsArray.iterator();

            while (registeredRecoveryAgentsArrayIterator.hasNext()) {
                // Extract the next RecoveryAgent object
                final RecoveryAgent recoveryAgent = (RecoveryAgent) registeredRecoveryAgentsArrayIterator.next();
                recoveryAgent.prepareForRecovery(failureScope);

                // Prepare the maps for the recovery event.
                addInitializationRecord(recoveryAgent, failureScope);
                addRecoveryRecord(recoveryAgent, failureScope);
            }
        }

        // This is the opportunity to kick off any Network Parition Detection logic that we deem necessary. Right
        // now we are relying on the Hardware quorum support within the HA framework itself if NP's are tro be
        // handled.

        if (Configuration.HAEnabled()) {
            // Join the "dynamic cluster" in order that IOR references can be associated with the
            // resulting identity. Only do this in an HA-enabled environment.
            Configuration.getRecoveryLogComponent().joinCluster(failureScope);
        }

        // If callbacks are registered, drive then now.
        if (_registeredCallbacks != null) {
            driveCallBacks(CALLBACK_RECOVERYSTARTED, failureScope);
        }

        // Re-set the iterator.
        registeredRecoveryAgentsValuesIterator = registeredRecoveryAgentsValues.iterator();

        while (registeredRecoveryAgentsValuesIterator.hasNext()) {
            // Extract the next ArrayList and create an iterator from it. This iterator will return RecoveryAgent
            // objects that are registered at the same sequence priority value.
            final ArrayList registeredRecoveryAgentsArray = (java.util.ArrayList) registeredRecoveryAgentsValuesIterator.next();
            final Iterator registeredRecoveryAgentsArrayIterator = registeredRecoveryAgentsArray.iterator();

            while (registeredRecoveryAgentsArrayIterator.hasNext()) {
                // Extract the next RecoveryAgent object
                final RecoveryAgent recoveryAgent = (RecoveryAgent) registeredRecoveryAgentsArrayIterator.next();

                // Direct the RecoveryAgent instance to process this failure scope.
                try {
                    // Notify the listeners we're about to make the call
                    _eventListeners.clientRecoveryInitiated(failureScope, recoveryAgent.clientIdentifier()); /* @MD19638A */

                    recoveryAgent.initiateRecovery(failureScope);
                } catch (RecoveryFailedException exc) {
                    FFDCFilter.processException(exc, "com.ibm.ws.recoverylog.spi.RecoveryDirectorImpl.directInitialization", "410", this);
                    if (tc.isEntryEnabled())
                        Tr.exit(tc, "directInitialization", exc);
                    throw exc;
                }

                // Wait for 'serialRecoveryComplete' to be called. This callback may be issued from another thread.
                synchronized (_outstandingInitializationRecords) {
                    while (initializationOutstanding(recoveryAgent, failureScope)) {
                        try {
                            _outstandingInitializationRecords.wait();
                        } catch (InterruptedException exc) {
                            // This exception is recieved if another thread interrupts this thread by calling this threads
                            // Thread.interrupt method. The RecoveryDirectorImpl class does not use this mechanism for
                            // breaking out of the wait call - it uses notifyAll to wake up all waiting threads. This
                            // exception should never be generated. If for some reason it is called then ignore it and
                            //start to wait again.
                            FFDCFilter.processException(exc, "com.ibm.ws.recoverylog.spi.RecoveryDirectorImpl.directInitialization", "432", this);
                        }
                    }
                }
            }
        }

        if (currentFailureScope.equals(failureScope)) /* @LI1578-22C */
        {
            Tr.info(tc, "CWRLS0012_DIRECT_LOCAL_RECOVERY", failureScope.serverName());
        } else {
            Tr.info(tc, "CWRLS0013_DIRECT_PEER_RECOVERY", failureScope.serverName());
        }

        if (tc.isEntryEnabled())
            Tr.exit(tc, "directInitialization");
    }
363390
private void checkpoint(IRecordProcessorCheckpointer checkpointer) {
        LOG.info("Checkpointing shard " + kinesisShardId);
        for (int i = 0; i < NUM_RETRIES; i++) {
            try {
                checkpointer.checkpoint();
                break;
            } catch (ShutdownException se) {
                // Ignore checkpoint if the processor instance has been shutdown (fail over).
                LOG.info("Caught shutdown exception, skipping checkpoint.", se);
                break;
            } catch (ThrottlingException e) {
                // Backoff and re-attempt checkpoint upon transient failures
                if (i >= (NUM_RETRIES - 1)) {
                    LOG.error("Checkpoint failed after " + (i + 1) + "attempts.", e);
                    break;
                } else {
                    LOG.info("Transient issue when checkpointing - attempt " + (i + 1) + " of "
                            + NUM_RETRIES, e);
                }
            } catch (InvalidStateException e) {
                // This indicates an issue with the DynamoDB table (check for table, provisioned IOPS).
                LOG.error("Cannot save checkpoint to the DynamoDB table used by the Amazon Kinesis Client Library.", e);
                break;
            }
            try {
                Thread.sleep(BACKOFF_TIME_IN_MILLIS);
            } catch (InterruptedException e) {
                LOG.debug("Interrupted sleep", e);
            }
        }
    }
1205111
public int recover() throws IOException
    {
        FilenameFilter unmanagedFilesFilter = new FilenameFilter()
        {
            public boolean accept(File dir, String name)
            {
                // we used to try to avoid instantiating commitlog (thus creating an empty segment ready for writes)
                // until after recover was finished.  this turns out to be fragile; it is less error-prone to go
                // ahead and allow writes before recover(), and just skip active segments when we do.
                return CommitLogDescriptor.isValid(name) && !instance.allocator.manages(name);
            }
        };

        // submit all existing files in the commit log dir for archiving prior to recovery - CASSANDRA-6904
        for (File file : new File(DatabaseDescriptor.getCommitLogLocation()).listFiles(unmanagedFilesFilter))
        {
            archiver.maybeArchive(file.getPath(), file.getName());
            archiver.maybeWaitForArchiving(file.getName());
        }

        assert archiver.archivePending.isEmpty() : "Not all commit log archive tasks were completed before restore";
        archiver.maybeRestoreArchive();

        File[] files = new File(DatabaseDescriptor.getCommitLogLocation()).listFiles(unmanagedFilesFilter);
        int replayed = 0;
        if (files.length == 0)
        {
            logger.info("No commitlog files found; skipping replay");
        }
        else
        {
            Arrays.sort(files, new CommitLogSegmentFileComparator());
            logger.info("Replaying {}", StringUtils.join(files, ", "));
            replayed = recover(files);
            logger.info("Log replay complete, {} replayed mutations", replayed);

            for (File f : files)
                CommitLog.instance.allocator.recycleSegment(f);
        }

        allocator.enableReserveSegmentCreation();
        return replayed;
    }
676666
public Object getPersistentState() {
    Map<String, Object> persistentState = new HashMap<String, Object>();
    persistentState.put("suspensionState", this.suspensionState);
    persistentState.put("historyTimeToLive", this.historyTimeToLive);
    return persistentState;
  }
975180
@Override
    @Transactional
    public Restoration restartRestore(String restoreId) throws SnapshotException {
        Restoration restoration = this.jobManager.stopRestore(restoreId);
        restoration.setEndDate(null);
        restoration.setStatus(RestoreStatus.RETRIEVING_FROM_STORAGE);
        restoration = restoreRepo.save(restoration);
        eventLog.logRestoreUpdate(restoration);
        return this.restoreCompleted(restoration);
    }
297169
public boolean recover(RecoveryManager recoveryManager, ClassLoader cl, Xid[] xids) {
        boolean success = true; // flag to indicate that we recovered all RMs

        if (tc.isEntryEnabled())
            Tr.entry(tc, "recover", new Object[] { this, _failureScopeController.serverName() });

        final int restartEpoch = recoveryManager.getCurrentEpoch();
        final byte[] cruuid = recoveryManager.getApplId();

        for (PartnerLogData pld : _partnerLogTable) {
            if (!pld.recover(cl, xids, null, cruuid, restartEpoch)) {
                success = false;
            }

            // Determine if shutdown processing started on another thread. 
            // If it has, no further action can be taken.
            if (recoveryManager.shutdownInProgress()) {
                success = false;
                break;
            }
        }

        if (tc.isEntryEnabled())
            Tr.exit(tc, "recover", success);
        return success;
    }
156762
public void checkpointStart()
  {
    if (_isWhileCheckpoint) {
      throw new IllegalStateException();
    }
    
    _isWhileCheckpoint = true;
    
    long sequence = ++_sequence;
    
    setSequence(sequence);
    
    byte []headerBuffer = _headerBuffer;
    BitsUtil.writeInt16(headerBuffer, 0, CHECKPOINT_START);
    writeImpl(headerBuffer, 0, 2);
    
    _lastCheckpointStart = _index - _startAddress;
  }
1223368
public void performRecovery(ObjectManagerState objectManagerState)
                    throws ObjectManagerException
    {
        if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
            trace.entry(this, cclass
                        , "performRecovery"
                        , " objectManager=" + objectManagerState + "(ObjectManagerState)"
                          + ")"
                            );

        objectManagerState.checkpointEndSeen = true;

        if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
            trace.exit(this, cclass
                       , "performRecovery"
                            );
    }
762640
@Override
	public RocksDBRestoreResult restore() throws Exception {

		if (restoreStateHandles == null || restoreStateHandles.isEmpty()) {
			return null;
		}

		final KeyedStateHandle theFirstStateHandle = restoreStateHandles.iterator().next();

		boolean isRescaling = (restoreStateHandles.size() > 1 ||
			!Objects.equals(theFirstStateHandle.getKeyGroupRange(), keyGroupRange));

		if (isRescaling) {
			restoreWithRescaling(restoreStateHandles);
		} else {
			restoreWithoutRescaling(theFirstStateHandle);
		}
		return new RocksDBRestoreResult(this.db, defaultColumnFamilyHandle,
			nativeMetricMonitor, lastCompletedCheckpointId, backendUID, restoredSstFiles);
	}
530179
@Override
    public int next() {
        // if we have cached break positions and we're still in the range
        // covered by them, just move one step forward in the cache
        if (fCachedBreakPositions != null) {
            if (fPositionInCache < fCachedBreakPositions.length - 1) {
                ++fPositionInCache;
                int pos = fCachedBreakPositions[fPositionInCache];
                fText.setIndex(pos);
                return pos;
            }
            else {
                reset();
            }
        }

        int startPos = current();
        fDictionaryCharCount = 0;
        int result = handleNext(fRData.fFTable);
        if (fDictionaryCharCount > 0) {
            result = checkDictionary(startPos, result, false);
        }
        return result;
    }
900173
public T next() {
        if (!hasNext()) {
            throw new NoSuchElementException();
        }
        // 'next' is guaranteed non-null by a hasNext() which returned true
        T returnObj = this.next;
        this.next = null;
        return returnObj;
    }
134769
public static final RecoveryProcessor getInstance() {

    if (tc.isEntryEnabled()) {
      SibTr.entry(tc, "getInstance");
    }

    if (_processor == null) {
      try {
        Class c = Class.forName("com.ibm.ws.sib.processor.impl.RecoveryProcessorImpl");
        _processor = (RecoveryProcessor) c.newInstance();
      }
      catch (Exception e) {
        e.printStackTrace();
        
      }
    }

    if (tc.isEntryEnabled()) {
      SibTr.exit(tc, "getMBean", _processor);
    }

    return _processor;
  }
396528
public synchronized Entry next()
  {
    if (tc.isEntryEnabled())
      SibTr.entry(tc, "next");

    // can only do anything if the cursor is still pointing in to a list
    checkEntryParent();
    
    Entry nextEntry = null;
    
    synchronized(parentList)
    {
      //get the next entry in the list
      nextEntry = getNextEntry();
      //if the next entry is null
      if(nextEntry == null)
      {
        //then hopefully we're at the end of the list
        if(current == parentList.last)
        {
          //so move the cursor to the bottom of the list,
          //not pointing to any actual entry
          moveToBottom();
        }
        else if(!atBottom)                   
        {
          //it should not be possible for the next entry to be null but the current
          //not be the last one in the list or already at the bottom
          SIErrorException e = new SIErrorException(
            nls.getFormattedMessage(
              "INTERNAL_MESSAGING_ERROR_CWSIP0001",
              new Object[] { "Cursor", "1:160:1.15" },
              null));
    
          FFDCFilter.processException(
            e,
            "com.ibm.ws.sib.processor.utils.linkedlist.Cursor.next",
            "1:166:1.15",
            this);
      
          SibTr.exception(tc, e);      
    
          if (tc.isEntryEnabled())
            SibTr.exit(tc, "next", e);
    
          throw e;
        }
      }
      else
      {
        //move the cursor to the next entry
        moveCursor(nextEntry);
      }
    }
    
    if (tc.isEntryEnabled())
      SibTr.exit(tc, "next", nextEntry);

    return nextEntry;
  }