/*
doTimeBasedWrites - called periodically when time-based-writes is configured
344251
public void doTimeBasedWrites(boolean forceWrite) {
        //create local variable - JIT performance improvement
        final boolean isTraceOn = com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled();
        if (isTraceOn && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINER)) {
            LoggingUtil.SESSION_LOGGER_WAS.entering(methodClassName, methodNames[DO_TIME_BASED_WRITES]);
        }

        BackedSession cachedSession;
        Object currentKey;

        if (forceWrite) {
            if (isTraceOn && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
                LoggingUtil.SESSION_LOGGER_WAS.logp(Level.FINE, methodClassName, methodNames[DO_TIME_BASED_WRITES], "Entered for forceWrite request");
            }
        }

        long now = System.currentTimeMillis();
        long writeInterval = _smc.getPropertyWriterInterval() * 1000; //convert seconds to milliseconds

        Enumeration vEnum = tableKeys();
        if (isTraceOn && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
            LoggingUtil.SESSION_LOGGER_WAS.logp(Level.FINE, methodClassName, methodNames[DO_TIME_BASED_WRITES], "!!!!!!!!!!PropertyWriteThread Loop STARTS Here!!!!!!!!!!!!! ");
        }
        while (vEnum.hasMoreElements()) {
            //LoggingUtil.SESSION_LOGGER_WAS.logp(Level.FINE, methodClassName, methodName, "Look at next Cache Element");
            currentKey = (Object) vEnum.nextElement();
            cachedSession = (BackedSession) super.get(currentKey);
            if (cachedSession != null) {
                //LoggingUtil.SESSION_LOGGER_WAS.logp(Level.FINE, methodClassName, methodName, "Cache element NOT NULL");

                long lastWrite = cachedSession.getLastWriteTime();
                long lastAccess = cachedSession.getCurrentAccessTime();

                //  English Translation for the test below:
                //
                //    If lastWrite is -1
                //       then the session must have just been read into
                //       the cache... Don't know when the lastWrite was or
                //       if something has changed since the read.. Therefore
                //       do the write.  This shouldn't happen often.
                //
                //    If the Write Interval has elapsed and the session has been
                //       changed then do the write. This should be the normal case.
                //

                if ((lastWrite == -1) || ((((now - lastWrite) > writeInterval) || forceWrite) && (lastAccess > lastWrite))) {

                    /*
                     * commented out in old code
                     * // LoggingUtil.SESSION_LOGGER_WAS.debug(SessionContext.tc, SessionConstants.doTimeBasedWrites + " Passed test... consider doing the write");
                     * end of commented out code
                     */

                    // Hold synchronized lock while we check if this session is
                    // executing in the servlet service method.  New request threads
                    // for this session will call the incrementInServiceMethodCount()
                    // method.  That method also does a "synchronized" on the session
                    // object, therefore guaranteeing that no new requests will update the
                    // session object until this write completes.

                    synchronized (cachedSession) {

                        //  Now that we have the session Object locked, check that the
                        //  session is still valid.  It is possible that the servlet
                        //  called the session.invalidate() method under a different
                        //  thread after we got the keys from the cache.  Since
                        //  sessionData.invalidate() does a sync on the session, it is now
                        //  safe to check...
                        //
                        //  Also, account for the case where the session was aged out
                        //  of the cache after we got the keys above...

                        //  We will never get here for a Timed Out invalidation since
                        //  the Invalidation time must be at least twice the Write Interval
                        //  and the write will always be done before an invalidation condition
                        //  can occur.

                        //cachedSession = (DatabaseSessionData) ((BackedHashtable) mSessions).superGet(currentKey);

                        if (cachedSession.isValid()) {
                            String id = cachedSession.getId();
                            //if the refCount!=0, it is still active in the service method
                            if (cachedSession.getRefCount() != 0) {
                                // skip the entry.. The next time this thread runs
                                // it will get tried again...
                                cachedSession.deferWriteUntilNextTick++;
                                if (isTraceOn && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
                                    LoggingUtil.SESSION_LOGGER_WAS.logp(Level.FINE, methodClassName, methodNames[DO_TIME_BASED_WRITES],
                                                                        "Defer write until next time since session is in the service method "
                                                                                        + cachedSession.deferWriteUntilNextTick + " " + id);
                                }
                                // Failed to write on 5 tries. Force the write to database!!
                                if (cachedSession.deferWriteUntilNextTick > 5) {
                                    if (isTraceOn && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
                                        LoggingUtil.SESSION_LOGGER_WAS.logp(Level.FINE, methodClassName, methodNames[DO_TIME_BASED_WRITES],
                                                                            "Failed to write on 5 tries. Force the write to database!! " + " " + id);
                                    }
                                    cachedSession.setLastWriteTime(now);
                                    // cachedSession.sync();
                                    cachedSession.flush();
                                    cachedSession.deferWriteUntilNextTick = 0;
                                }
                            } else {
                                if (isTraceOn && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
                                    LoggingUtil.SESSION_LOGGER_WAS.logp(Level.FINE, methodClassName, methodNames[DO_TIME_BASED_WRITES],
                                                                        "Do the session Write and update lastWriteTime " + id);
                                }

                                // It is important to note that lastWriteTime is being
                                // updated to the current time (now), though lastAccess may
                                // contain a value up to Now-WriteInterval.  After this
                                // write completes it is possible that the Session is
                                // used again.  The Write of LastAccess will not take
                                // place again until WriteInterval elapses again.  So, in order
                                // for this session not to be inadvertently invalidated
                                // by a different clone, it is necessary that the invalidation
                                // time be AT LEAST 2 TIMES the WriteInterval.  This should
                                // be enforced in the GUI.

                                cachedSession.setLastWriteTime(now);
                                cachedSession.flush(); // do the write
                                cachedSession.deferWriteUntilNextTick = 0;
                            }
                        } else {
                            if (isTraceOn && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
                                LoggingUtil.SESSION_LOGGER_WAS.logp(Level.FINE, methodClassName, methodNames[DO_TIME_BASED_WRITES], "Session no longer in Cache!");
                            }
                        }
                    } //end of synchronized
                } else {
                    //Database Write did NOT occur
                    //LoggingUtil.SESSION_LOGGER_WAS.logp(Level.FINE, methodClassName, methodName, "Database Write did NOT occur!");
                }
            } else {
                if (isTraceOn && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
                    LoggingUtil.SESSION_LOGGER_WAS.logp(Level.FINE, methodClassName, methodNames[DO_TIME_BASED_WRITES], "The Cache element is NULL");
                }
            }
        }
        if (isTraceOn && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
            LoggingUtil.SESSION_LOGGER_WAS.logp(Level.FINE, methodClassName, methodNames[DO_TIME_BASED_WRITES], "!!!!!!!!!! PropertyWriteThread Loop ENDS Here!!!!!!!!!!!!!");
        }
    }
1144287
def retryable_writes_supported(self):
        """"""
        return (
            self._ls_timeout_minutes is not None and
            self._server_type in (SERVER_TYPE.Mongos, SERVER_TYPE.RSPrimary))
591280
private static void writeZonePropsByDOM(Writer writer, boolean isDst, String tzname, int fromOffset, int toOffset,
            int month, int dayOfMonth, long startTime, long untilTime) throws IOException {
        beginZoneProps(writer, isDst, tzname, fromOffset, toOffset, startTime);

        beginRRULE(writer, month);
        writer.write(ICAL_BYMONTHDAY);
        writer.write(EQUALS_SIGN);
        writer.write(Integer.toString(dayOfMonth));

        if (untilTime != MAX_TIME) {
            appendUNTIL(writer, getDateTimeString(untilTime + fromOffset));
        }
        writer.write(NEWLINE);

        endZoneProps(writer, isDst);
    }
476190
private static ScheduledThreadPoolExecutor buildWriterMetricsUpdater() {
    return new ScheduledThreadPoolExecutor(1,
        ExecutorsUtils.newThreadFactory(Optional.of(log), Optional.of("WriterMetricsUpdater-%d")));
  }
110098
public static void writeMemento(final File resourceDir, final Resource resource,
            final Instant time) {
        try (final BufferedWriter writer = newBufferedWriter(
                        getNquadsFile(resourceDir, time).toPath(), UTF_8, CREATE, WRITE,
                        TRUNCATE_EXISTING)) {

            try (final Stream<String> quads = generateServerManaged(resource).map(FileUtils::serializeQuad)) {
                final Iterator<String> lineIter = quads.iterator();
                while (lineIter.hasNext()) {
                    writer.write(lineIter.next() + lineSeparator());
                }
            }

            try (final Stream<String> quads = resource.stream().filter(FileUtils::notServerManaged)
                    .map(FileUtils::serializeQuad)) {
                final Iterator<String> lineiter = quads.iterator();
                while (lineiter.hasNext()) {
                    writer.write(lineiter.next() + lineSeparator());
                }
            }
        } catch (final IOException ex) {
            throw new UncheckedIOException(
                            "Error writing resource version for " + resource.getIdentifier().getIRIString(), ex);
        }
    }
602186
@GuardedBy("evictionLock")
  void expireAfterWriteEntries(long now) {
    if (!expiresAfterWrite()) {
      return;
    }
    long duration = expiresAfterWriteNanos();
    for (;;) {
      final Node<K, V> node = writeOrderDeque().peekFirst();
      if ((node == null) || ((now - node.getWriteTime()) < duration)) {
        break;
      }
      evictEntry(node, RemovalCause.EXPIRED, now);
    }
  }
215042
private void writeDuration(long beginTime) throws XMLStreamException {
        xmlStreamWriter.writeStartElement("duration");
        xmlStreamWriter.writeCharacters(Long.toString(System.currentTimeMillis() - beginTime));
        xmlStreamWriter.writeEndElement(); // duration
    }
532928
public void write(PrintWriter out, boolean includeDoc) {
        // getValue() will update the timestamp (if relevant)
        T localValue = getValue();
        if (includeDoc) {
            out.println();
            Long lastUpdate = getLastUpdated();
            if (hasDoc() || lastUpdate != null) {
                out.print("# ");
                if (hasDoc()) {
                    out.print(makePropertiesSafe(getDoc(), null));
                }
                if (lastUpdate != null) {
                    out.print(" (last update: " + lastUpdate + ")");
                }
                out.println();
            }
        }
        out.println(toString());
    }
182835
private void handleWrites(final MemcachedNode node) throws IOException {
    node.fillWriteBuffer(shouldOptimize);
    boolean canWriteMore = node.getBytesRemainingToWrite() > 0;
    while (canWriteMore) {
      int wrote = node.writeSome();
      metrics.updateHistogram(OVERALL_AVG_BYTES_WRITE_METRIC, wrote);
      node.fillWriteBuffer(shouldOptimize);
      canWriteMore = wrote > 0 && node.getBytesRemainingToWrite() > 0;
    }
  }
1275102
@Override
  public void write(JsonWriter out, WordTiming wordTiming) throws IOException {
    out.beginArray();

    out.value(wordTiming.getWord());
    out.value(wordTiming.getStartTime());
    out.value(wordTiming.getEndTime());

    out.endArray();
    out.flush();
  }
187758
@Override
  public void write(JsonWriterImpl out, ZonedDateTime value)
  {
    out.write(value.format(_formatter));
  }
14241
@Override
    public void doFilterWriteListeners(final long sessionId, final long sessionWrittenBytes, final WriteRequest writeRequest) {
        runManagementTask(new Runnable() {
            @Override
            public void run() {
                try {
                    // The particular management listeners change on strategy, so get them here.
                    for (final GatewayManagementListener listener : getManagementListeners()) {
                        listener.doFilterWrite(GatewayManagementBeanImpl.this, sessionId);
                    }

                    markChanged();  // mark ourselves as changed, possibly tell listeners
                } catch (Exception ex) {
                    logger.warn("Error during filterWrite gateway listener notifications:", ex);
                }
            }
        });
    }
44500
private void marshalCreatedAndUpdatedTimestamp() {
    PropertyMetadata createdTimestampMetadata = entityMetadata.getCreatedTimestampMetadata();
    PropertyMetadata updatedTimestampMetadata = entityMetadata.getUpdatedTimestampMetadata();
    long millis = System.currentTimeMillis();
    if (createdTimestampMetadata != null) {
      applyAutoTimestamp(createdTimestampMetadata, millis);
    }
    if (updatedTimestampMetadata != null) {
      applyAutoTimestamp(updatedTimestampMetadata, millis);
    }
  }
250753
private void writeCalendarHours(ProjectCalendar parentCalendar, ProjectCalendarHours record) throws IOException
   {
      m_buffer.setLength(0);

      int recordNumber;

      if (!parentCalendar.isDerived())
      {
         recordNumber = MPXConstants.BASE_CALENDAR_HOURS_RECORD_NUMBER;
      }
      else
      {
         recordNumber = MPXConstants.RESOURCE_CALENDAR_HOURS_RECORD_NUMBER;
      }

      DateRange range1 = record.getRange(0);
      if (range1 == null)
      {
         range1 = DateRange.EMPTY_RANGE;
      }

      DateRange range2 = record.getRange(1);
      if (range2 == null)
      {
         range2 = DateRange.EMPTY_RANGE;
      }

      DateRange range3 = record.getRange(2);
      if (range3 == null)
      {
         range3 = DateRange.EMPTY_RANGE;
      }

      m_buffer.append(recordNumber);
      m_buffer.append(m_delimiter);
      m_buffer.append(format(record.getDay()));
      m_buffer.append(m_delimiter);
      m_buffer.append(format(formatTime(range1.getStart())));
      m_buffer.append(m_delimiter);
      m_buffer.append(format(formatTime(range1.getEnd())));
      m_buffer.append(m_delimiter);
      m_buffer.append(format(formatTime(range2.getStart())));
      m_buffer.append(m_delimiter);
      m_buffer.append(format(formatTime(range2.getEnd())));
      m_buffer.append(m_delimiter);
      m_buffer.append(format(formatTime(range3.getStart())));
      m_buffer.append(m_delimiter);
      m_buffer.append(format(formatTime(range3.getEnd())));
      stripTrailingDelimiters(m_buffer);
      m_buffer.append(MPXConstants.EOL);

      m_writer.write(m_buffer.toString());
   }
163608
public void writeTimestamp(Timestamp timestamp) throws IOException {
		_writeArrayFieldNameIfNeeded();
		_verifyValueWrite("write timestamp");
		_buffer.putByte(_typeMarker, BsonConstants.TYPE_TIMESTAMP);
		_buffer.putInt(timestamp.getInc());
		_buffer.putInt(timestamp.getTime());
		flushBuffer();
	}
295111
public void xmlWriteOn(FormattedWriter writer) throws IOException 
    {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd @ HH:mm:ss.SSS");
        String timeNow = dateFormat.format(new Date());
        writer.newLine(); 
        writer.startTag(XML_EXPIRER);
        writer.indent();
        writer.newLine();
        writer.taggedValue("timeNow", timeNow);
        writer.newLine();
        writer.taggedValue("interval", interval);
        writer.newLine();
        writer.taggedValue("addEnabled", Boolean.valueOf(addEnabled));
        writer.newLine();
        writer.taggedValue("runEnabled", Boolean.valueOf(runEnabled));
        writer.newLine();
        writer.taggedValue("cleanupFlag", Boolean.valueOf(cleanupDeletedItems));
        writer.newLine();
        writer.taggedValue("expirerStartTime", dateFormat.format(new Date(expirerStartTime)));
        writer.newLine();
        writer.taggedValue("expirerStopTime", dateFormat.format(new Date(expirerStopTime)));
        writer.newLine();
        writer.taggedValue("nextLogIndex", diagIndex);
        writer.newLine();

        for (int i = 0; i < MAX_DIAG_LOG; i++)
        {
            String str =
            "Cycle="
            + i
            + (diagIndex == i ? ":*" : ": ")
            + dateFormat.format(new Date(alarmTime[i]))
            + " size="
            + logIndexSize[i]
            + " processed="
            + logProcessed[i]
            + " expired="
            + logExpired[i]
            + " remain="
            + logRemain[i]
            + " gone="
            + logGone[i]
            + " cleaned="
            + logCleaned[i];
            writer.taggedValue("info", str);
            writer.newLine();
        }

        writer.startTag(XML_STORED_EXCEPTION);
        if (lastException == null)
        {
            writer.write("No exceptions recorded");
        }
        else
        {
            writer.indent();
            writer.newLine();
            writer.taggedValue("time", new Date(lastExceptionTime));
            writer.outdent();
            writer.write(lastException);
            writer.newLine();
        }
        writer.endTag(XML_STORED_EXCEPTION);

        writer.outdent();
        writer.newLine();
        writer.endTag(XML_EXPIRER);
    }
198794
public void writeUTCDate(long time)
        throws IOException
    {
        os.write('d');
        os.write((byte) (time >> 56));
        os.write((byte) (time >> 48));
        os.write((byte) (time >> 40));
        os.write((byte) (time >> 32));
        os.write((byte) (time >> 24));
        os.write((byte) (time >> 16));
        os.write((byte) (time >> 8));
        os.write((byte) (time));
    }