Appends an entry to the Raft log and compacts logs if necessary.

@param entry   the entry to append
@param attempt the append attempt count
@param <E>     the entry type
@return a completable future to be completed once the entry has been appended
552439
protected <E extends RaftLogEntry> CompletableFuture<Indexed<E>> appendAndCompact(E entry, int attempt) {
    if (attempt == MAX_APPEND_ATTEMPTS) {
      return Futures.exceptionalFuture(new StorageException.OutOfDiskSpace("Not enough space to append entry"));
    } else {
      try {
        return CompletableFuture.completedFuture(raft.getLogWriter().append(entry))
            .thenApply(indexed -> {
              log.trace("Appended {}", indexed);
              return indexed;
            });
      } catch (StorageException.TooLarge e) {
        return Futures.exceptionalFuture(e);
      } catch (StorageException.OutOfDiskSpace e) {
        log.warn("Caught OutOfDiskSpace error! Force compacting logs...");
        return raft.getServiceManager().compact().thenCompose(v -> appendAndCompact(entry, attempt + 1));
      }
    }
  }
879787
public CompletableFuture<Long> appendEntries(long index) {
    raft.checkThread();

    if (index == 0) {
      return appendEntries();
    }

    if (index <= raft.getCommitIndex()) {
      return CompletableFuture.completedFuture(index);
    }

    // If there are no other stateful servers in the cluster, immediately commit the index.
    if (raft.getCluster().getActiveMemberStates().isEmpty() && raft.getCluster().getPassiveMemberStates().isEmpty()) {
      long previousCommitIndex = raft.getCommitIndex();
      raft.setCommitIndex(index);
      completeCommits(previousCommitIndex, index);
      return CompletableFuture.completedFuture(index);
    }
    // If there are no other active members in the cluster, update the commit index and complete the commit.
    // The updated commit index will be sent to passive/reserve members on heartbeats.
    else if (raft.getCluster().getActiveMemberStates().isEmpty()) {
      long previousCommitIndex = raft.getCommitIndex();
      raft.setCommitIndex(index);
      completeCommits(previousCommitIndex, index);
      return CompletableFuture.completedFuture(index);
    }

    // Only send entry-specific AppendRequests to active members of the cluster.
    return appendFutures.computeIfAbsent(index, i -> {
      for (RaftMemberContext member : raft.getCluster().getActiveMemberStates()) {
        appendEntries(member);
      }
      return new CompletableFuture<>();
    });
  }
1351496
void add(Entry<String, Point2d[]> entry) {
        if (entry != null) templateMap.put(entry.getKey(), entry.getValue());
    }
972980
private void writeLogEntries(Iterable<LogEntry> logEntries, WriteOption... writeOptions) {
    switch (this.writeSynchronicity) {
      case SYNC:
        get(writeAsync(logEntries, writeOptions));
        break;

      case ASYNC:
      default:
        final ApiFuture<Void> writeFuture = writeAsync(logEntries, writeOptions);
        final Object pendingKey = new Object();
        pendingWrites.put(pendingKey, writeFuture);
        ApiFutures.addCallback(
            writeFuture,
            new ApiFutureCallback<Void>() {
              private void removeFromPending() {
                pendingWrites.remove(pendingKey);
              }

              @Override
              public void onSuccess(Void v) {
                removeFromPending();
              }

              @Override
              public void onFailure(Throwable t) {
                try {
                  Exception ex = t instanceof Exception ? (Exception) t : new Exception(t);
                  throw new RuntimeException(ex);
                } finally {
                  removeFromPending();
                }
              }
            });
        break;
    }
  }
560464
public void compact(ServerStoreProxy.ChainEntry entry) {
    ChainBuilder builder = new ChainBuilder();
    for (PutOperation<K, V> operation : resolveAll(entry).values()) {
      builder = builder.add(codec.encode(operation));
    }
    Chain compacted = builder.build();
    if (compacted.length() < entry.length()) {
      entry.replaceAtHead(compacted);
    }
  }
478446
private void updateEntry(HashtableEntry entry)
                    throws IOException, EOFException, FileManagerException, ClassNotFoundException {
        //
        // We'll write the header, key, and data into a byte arry first,
        // then allocate, seek, and write with a single write operation.
        // It is necessary to buffer the data first like this because we cannot
        // determine the size of storage to allocate without first examining the
        // size of the serialize object.
        //

        //
        // Serialize key and data.  If the data is already a byte[] array, we can
        // bypass serialization.
        //
        byte[] serializedKey = entry.serializedKey;
        int keySize = 0;
        byte[] serializedValue = null;
        int valueSize = -1;
        int bytes = 0;
        byte[] serializedCacheValue = entry.serializedCacheValue;
        int cacheValueSize = -1;
        int dataSize = HTENTRY_OVERHEAD_SIZE;

        if (serializedKey == null) {
            if (keyout == null) {
                keyout = new ByteArrayPlusOutputStream(500);
            } else {
                keyout.reset();
            }
            serializeTimer.reset();
            ObjectOutputStream out = new ObjectOutputStream(keyout);
            out.writeObject(entry.key);
            out.close();
            serializedKey = keyout.getTheBuffer();
            keySize = keyout.size();
            bytes_serialized += keySize;
        } else {
            keySize = entry.serializedKey.length;
        }
        dataSize += keySize;

        if (entry.value != null) {
            if (isByteArray(entry.value)) {
                bytes = 1;
                serializedValue = (byte[]) entry.value;
                if (entry.valuelen != -1) {
                    valueSize = entry.valuelen;
                } else {
                    valueSize = serializedValue.length;
                }
            } else {
                if (dataout == null) {
                    dataout = new ByteArrayPlusOutputStream(500);
                } else {
                    dataout.reset();
                }
                ObjectOutputStream out = new ObjectOutputStream(dataout);
                out.writeObject(entry.value);
                out.close();
                serializedValue = dataout.getTheBuffer();
                valueSize = dataout.size();
                bytes_serialized += valueSize;
                //
                // If an unusally large object is written it bloats the buffer, which can
                // hog resources.  If this happens dump the static buffer and start a new 
                // one on the next write.
                //
                if (valueSize > 100000) {
                    dataout = null;
                }
            }
        }

        serialize_time += serializeTimer.elapsed();

        int allocateSize = DWORDSIZE + // room for "next"
                           SWORDSIZE + // room for fastpath hash key
                           DWORDSIZE + // room for old format: last-modified
                                       //          new format: validator expiration time(VET)
                           DWORDSIZE + // room for old format: last-referenced;   // LI4337-17
                                       //          new format: H-Word = unused 
                                       //                      L-word = cache value hashcode 
                           DWORDSIZE + // room for first_created
                           DWORDSIZE + // room for expiration (RET)
                           DWORDSIZE + // room for flag + object size
                           SWORDSIZE + // room for size of the key
                           keySize + // room for serialized key
                           SWORDSIZE + // room for bytes flag
                           SWORDSIZE; // room for size of the value

        if (valueSize != -1) {
            allocateSize += valueSize; // room for serialized value
            dataSize += valueSize; // add value size to data size 
        }

        if (this.bHasCacheValue && !entry.bAliasId) {
            allocateSize += SWORDSIZE; // room for size of cacheValue
            if (serializedCacheValue != null) { // any cacheValue?
                cacheValueSize = serializedCacheValue.length; // size of the cacheValue
                allocateSize += cacheValueSize; // room for serialized cacheValue
                dataSize += cacheValueSize; // add cacheValue size to data size
            }
        }
        if (dataSize % 512 != 0) { // size adjustment for 512 blocks
            dataSize = (dataSize / 512 + 1) * 512;
        }
        //System.out.println("**** HashtableOnDisk: id=" + entry.key + " size=" + dataSize + " allocateSize=" + allocateSize);
        long tempData = 0;
        if (entry.bAliasId) {
            tempData = HTENTRY_MAGIC + HTENTRY_VERSION + HTENTRY_ALIAS_ID + dataSize;
        } else {
            tempData = HTENTRY_MAGIC + HTENTRY_VERSION + dataSize;
        }

        // end write key and value
        //
        // physical allocation
        //

        // For testing for cache id 
        //String testId = (String)entry.key;
        //if (testId.indexOf("928") > 0 || testId.indexOf("1028") > 0) {
        //    throw new IOException(com.ibm.ws.cache.HTODDynacache.DISK_CACHE_IN_GB_OVER_LIMIT_MSG);
        //}
        // For testing for depid/template
        //if (!this.bHasCacheValue) {
        //    String testId = (String)entry.key;
        //    if (testId.indexOf("926") > 0) {
        //        throw new IOException(com.ibm.ws.cache.HTODDynacache.DISK_CACHE_IN_GB_OVER_LIMIT_MSG);
        //    }
        //}
        entry.location = filemgr.allocate(allocateSize);

        initWriteBuffer();
        headerout.writeLong(entry.next);
        headerout.writeInt(entry.hash);
        //headerout.writeLong(System.currentTimeMillis());  // old format: last update
        headerout.writeLong(entry.validatorExpiration); // new format: VET
        //headerout.writeLong(System.currentTimeMillis());  // old format: last reference
        headerout.writeInt(0); // new format: unused    // LI4337-17
        headerout.writeInt(entry.cacheValueHashcode); //             cache value hashcode
        headerout.writeLong(entry.first_created); // when object is first created
        headerout.writeLong(entry.expiration); // expiration (RET) 
        headerout.writeLong(tempData); // write magic, version, flag & data size 
        headerout.writeInt(keySize);
        headerout.flush();

        //
        // Physical write the record like this:
        filemgr.seek(entry.location);
        filemgr.write(headeroutbuf);
        //
        // int keysize;            length of key
        // byte[] serialized key;  The key
        // int valueSize           length of value
        // int value_is_byte_array 0 if value is serialized obj 1 if a byte array
        // byte[] value            serialized value
        //
        filemgr.write(serializedKey, 0, keySize);
        filemgr.writeInt(bytes);
        filemgr.writeInt(valueSize);
        if (valueSize != -1) {
            filemgr.write(serializedValue, 0, valueSize);
        }

        //
        // if there is any cacheValue
        // int cacheValueSize      size of cacheValue - -1 if cacheValue is empty
        // byte[] cacheValue   serialized cacheValue
        //
        if (this.bHasCacheValue) {
            filemgr.writeInt(cacheValueSize);
            if (cacheValueSize != -1) {
                filemgr.write(serializedCacheValue, 0, cacheValueSize);
            }
        }

        //if (serializedCacheValue != null) {
        //   traceDebug("updateEntry()", "cacheName=" + this.htoddc.cacheName + " key=" + entry.key + " allocateSize=" + allocateSize + " dataSize=" + dataSize + " valueSize=" + valueSize + " cacheValueSize=" + cacheValueSize);
        //} else {
        //    traceDebug("updateEntry()", "cacheName=" + this.htoddc.cacheName + " key=" + entry.key + " allocateSize=" + allocateSize + " valueSize=" + valueSize);
        //}
    }
785406
public void append(final LoggingEvent event) {
        boolean isBufferSpaceAvailable = (batcher.isSpaceAvailable() && (logSummaryMap
                .size() == 0));
        boolean isBufferPutSuccessful = false;
        LocationInfo locationInfo = null;
        // Reject it when we have a fast property as these can be expensive
        Stopwatch s = locationInfoTimer.start();
        if (CONFIGURATION.shouldSummarizeOverflow(this.originalAppenderName)) {
            if (CONFIGURATION.shouldGenerateBlitz4jLocationInfo()) {
                locationInfo = LoggingContext.getInstance()
                        .generateLocationInfo(event);
            } else if (CONFIGURATION.shouldGenerateLog4jLocationInfo()) {
                locationInfo = event.getLocationInformation();
            }
        }
        s.stop();

        if (isBufferSpaceAvailable) {
            // Save the thread local info in the event so that the
            // processing threads can have access to the thread local of the arriving event
            Stopwatch sThreadLocal = saveThreadLocalTimer.start();
            saveThreadLocalInfo(event);
            sThreadLocal.stop();
            isBufferPutSuccessful = putInBuffer(event);
        }
        // If the buffer is full, then summarize the information
        if (CONFIGURATION.shouldSummarizeOverflow(this.originalAppenderName) && (!isBufferPutSuccessful)) {
            summarizeEventCounter.increment();
            Stopwatch t = putDiscardMapTimeTracer.start();
            String loggerKey = event.getLoggerName();
            if (locationInfo != null) {
                loggerKey = locationInfo.getClassName() + "_"
                        + locationInfo.getLineNumber();
            }

            LogSummary summary = (LogSummary) logSummaryMap.get(loggerKey);
            if (summary == null) {
                // Saving the thread local info is needed only for the first
                // time
                // creation of the summary
                saveThreadLocalInfo(event);
                summary = new LogSummary(event);
                logSummaryMap.put(loggerKey, summary);
            } else {
                // The event summary is already there, just increment the
                // count
                summary.add(event);
            }
            t.stop();
        } else if (!CONFIGURATION.shouldSummarizeOverflow(this.originalAppenderName) && (!isBufferPutSuccessful)) {
            // Record the event that are not summarized and which are just
            // discarded
            discardEventCounter.increment();
        }

    }
832772
protected Entry<K, V> insertNewEntry(K key, int hc, int val) {
    Entry<K,V> e = new Entry<K,V>(extractIntKeyObj(key), val);
    Entry<K, V> e2;
    final OptimisticLock l = hash.getSegmentLock(hc);
    final long _stamp = l.writeLock();
    boolean _needsEviction = false;
    try {
      e2 = hash.insertWithinLock(e, hc, val);
      if (e == e2) {
        _needsEviction = eviction.submitWithoutEviction(e);
      }
    } finally {
      l.unlockWrite(_stamp);
    }
    if (_needsEviction) {
      eviction.evictEventually(hc);
    }
    hash.checkExpand(hc);
    return e2;
  }
1271391
def _add_entry (self, entry):
        
        if "*" in entry.useragents:
            # the default entry is considered last
            self.default_entry = entry
        else:
            self.entries.append(entry)
477070
public StoreTxLogPosition append(byte[] entry) throws IOException {

        int length = entry.length;

        if (length > storeConfig.getMaxxLogEntryLength()) {
            throw new DBException("Value size can not great than " + storeConfig.getMaxxLogEntryLength());
        }

        // 检查当前文件容量是否足够
        if (fileLength + length + ENTRY_HEAD_LENGTH > storeConfig.getTxLogFileSize()) {
            throw new CapacityNotEnoughException();
        }

        StoreTxLogPosition result = new StoreTxLogPosition();
        result.setRecordId(getNextRecordId());

        boolean ok = false;
        try {

            entryBuffer.clear();
            entryBuffer.put(magic);                      // 1 byte
            entryBuffer.putInt(length);                         // 4 byte
            entryBuffer.put(entry);                             // entry.length
            entryBuffer.flip();

            fileChannel.position(fileLength);
            fileChannel.write(entryBuffer);

            int entryLength = (ENTRY_HEAD_LENGTH + length);
            fileLength += entryLength;

            ok = true;
        } finally {
            if (ok) {
                if (syncTimerTask == null || syncTimerTask.isDone()) {
                    syncTimerTask = new FutureTimerTask("ltsdb-dblog-sync-timertask", syncCallable);
                    syncTimer.schedule(syncTimerTask, storeConfig.getDbLogFlushInterval());
                }
            }
        }
        return result;
    }
1144006
public void updateEntry(CmsClientSitemapEntry entry) {

        getListItemWidget().setTitleLabel(entry.getTitle());
        getListItemWidget().reInitAdditionalInfo(getInfoBean(entry, CmsSitemapView.getInstance().isNavigationMode()));
        updateSitePath(entry.getSitePath());
        updateDetailPageStatus();
        updateLock(entry);
        updateInNavigation(entry);
        getListItemWidget().setIcon(CmsSitemapView.getInstance().getIconForEntry(entry));
        setAdditionalStyles(entry, getListItemWidget());
        setDropEnabled(getSitemapEntry().isFolderType() && !getSitemapEntry().hasForeignFolderLock());
        if (entry.isSubSitemapType() || entry.isLeafType()) {
            hideOpeners();
        } else {
            showOpeners();
        }
        getListItemWidget().updateTruncation();
    }
330672
public void updateFromEntry(UpdateInodeEntry entry) {
    if (entry.hasAcl()) {
      setInternalAcl(ProtoUtils.fromProto(entry.getAcl()));
    }
    if (entry.hasCreationTimeMs()) {
      setCreationTimeMs(entry.getCreationTimeMs());
    }
    if (entry.hasGroup()) {
      setGroup(entry.getGroup());
    }
    if (entry.hasLastModificationTimeMs()) {
      setLastModificationTimeMs(entry.getLastModificationTimeMs(),
          entry.getOverwriteModificationTime());
    }
    if (entry.hasMode()) {
      setMode((short) entry.getMode());
    }
    if (entry.hasName()) {
      setName(entry.getName());
    }
    if (entry.hasOwner()) {
      setOwner(entry.getOwner());
    }
    if (entry.hasParentId()) {
      setParentId(entry.getParentId());
    }
    if (entry.hasPersistenceState()) {
      setPersistenceState(PersistenceState.valueOf(entry.getPersistenceState()));
    }
    if (entry.hasPinned()) {
      setPinned(entry.getPinned());
    }
    if (entry.hasTtl()) {
      setTtl(entry.getTtl());
    }
    if (entry.hasTtlAction()) {
      setTtlAction(ProtobufUtils.fromProtobuf(entry.getTtlAction()));
    }
    if (entry.hasUfsFingerprint()) {
      setUfsFingerprint(entry.getUfsFingerprint());
    }
  }
531290
static String encodeEntry(Entry<String, Point2d[]> entry) {
        StringBuilder sb = new StringBuilder();
        sb.append(entry.getKey());
        sb.append(' ');
        sb.append(encodeCoordinates(entry.getValue()));
        return sb.toString();
    }
916366
public static void addEntry(final File zip, final ZipEntrySource entry) {
    operateInPlace(zip, new InPlaceAction() {
      public boolean act(File tmpFile) {
        addEntry(zip, entry, tmpFile);
        return true;
      }
    });
  }
1255036
private void startNewAlarm(LinkedListEntry entry)
  {
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.entry(tc, "startNewAlarm", new Object[] { entry });

    //start a new alarm
    entry.alarm = am.create(delta, percentLate, this, entry);
    
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.exit(tc, "startNewAlarm");
  }
382199
public void entry(Object... argArray) {
        if (instanceofLAL && logger.isTraceEnabled(ENTRY_MARKER)) {
            String messagePattern = null;
            if (argArray.length < ENTRY_MESSAGE_ARRAY_LEN) {
                messagePattern = ENTRY_MESSAGE_ARRAY[argArray.length];
            } else {
                messagePattern = buildMessagePattern(argArray.length);
            }
            FormattingTuple tp = MessageFormatter.arrayFormat(messagePattern, argArray);
            ((LocationAwareLogger) logger).log(ENTRY_MARKER, FQCN, LocationAwareLogger.TRACE_INT, tp.getMessage(), argArray, tp.getThrowable());
        }
    }
1272760
public long append(Entry entry) {
    Assert.notNull(entry, "entry");
    Assert.stateNot(isFull(), "segment is full");

    long index = nextIndex();
    Assert.index(index == entry.getIndex(), "inconsistent index: %s", entry.getIndex());

    // Calculate the offset of the entry.
    long offset = relativeOffset(index);

    // Get the term from the entry.
    long term = entry.getTerm();

    // Get the highest term in the index.
    long lastTerm = termIndex.term();

    // The entry term must be positive and >= the last term in the segment.
    Assert.arg(term > 0 && term >= lastTerm, "term must be monotonically increasing");

    // Mark the starting position of the record and record the starting position of the new entry.
    long position = buffer.position();

    // Determine whether to skip writing the term to the segment.
    boolean skipTerm = term == lastTerm;

    // Calculate the length of the entry header bytes.
    int headerLength = INTEGER + LONG + BOOLEAN + (skipTerm ? 0 : LONG);

    // Clear the memory and skip the size and header.
    memory.clear().skip(headerLength);

    // Serialize the object into the in-memory buffer.
    serializer.writeObject(entry, memory);

    // Flip the in-memory buffer indexes.
    memory.flip();

    // The total length of the entry is the in-memory buffer limit.
    int totalLength = (int) memory.limit();

    // Calculate the length of the serialized bytes based on the in-memory buffer limit and header length.
    int entryLength = totalLength - headerLength;

    // Set the entry size.
    entry.setSize(totalLength);

    // Compute the checksum for the entry.
    Checksum crc32 = new CRC32();
    crc32.update(memory.array(), headerLength, entryLength);
    long checksum = crc32.getValue();

    // Rewind the in-memory buffer and write the length, checksum, and offset.
    memory.rewind()
      .writeUnsignedInt(checksum)
      .writeLong(offset);

    // If the term has not yet been written, write the term to this entry.
    if (skipTerm) {
      memory.writeBoolean(false);
    } else {
      memory.writeBoolean(true).writeLong(term);
    }

    // Write the entry length and entry to the segment.
    buffer.writeInt(totalLength)
      .write(memory.rewind());

    // Index the offset, position, and length.
    offsetIndex.index(offset, position);

    // If the entry term is greater than the last indexed term, index the term.
    if (term > lastTerm) {
      termIndex.index(offset, term);
    }

    // Reset skip to zero since we wrote a new entry.
    skip = 0;

    return index;
  }