/*
overQualLastAccessTimeUpdate
Attempts to update the last access time ensuring the old value matches.
This verifies that the copy we have in cache is still valid.
187666
protected int overQualLastAccessTimeUpdate(BackedSession sess, long nowTime) {
        if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
            StringBuffer sb = new StringBuffer(" lastAccessTime= ");
            sb.append(sess.getCurrentAccessTime());
            sb.append("; nowTime= ").append(nowTime);
            LoggingUtil.SESSION_LOGGER_WAS.entering(methodClassName, methodNames[OVERQUAL_LAST_ACCESS_TIME_UPDATE], sb);
        }
        Connection con = null;
        PreparedStatement s = null;
        String id = sess.getId();
        int rowsRet = 1; //Assume that it will be cache hit.
        try {

            // PQ76937 BEGIN
            synchronized (sess) {
                con = getConnection(false);
                if (con == null) {
                    return 1;
                    /*
                     * REG if the database goes down, we will not update the lastAccessTime because we still want to find a match
                     * when the database does come back up. I do see a problem if the database goes down, we keep hitting a session
                     * and then because we haven't updated the lastAccessTime, our invalidator thread invalidates the session.
                     */
                }

                s = con.prepareStatement(optUpdatePrimRow);
                setPSLong(s, 1, nowTime);
                s.setString(2, id);
                s.setString(3, id);
                s.setString(4, sess.getAppName());
                //the currentAccessTime has not been updated so this is really the lastAccessTime until we call updateLastAccessTime
                setPSLong(s, 5, sess.getCurrentAccessTime());
                rowsRet = s.executeUpdate();

                if (rowsRet > 0) {
                    sess.updateLastAccessTime(nowTime);
                }
            }
            // PQ76937 END

            if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
                if (rowsRet > 0) {
                    LoggingUtil.SESSION_LOGGER_WAS.logp(Level.FINE, methodClassName, methodNames[OVERQUAL_LAST_ACCESS_TIME_UPDATE], "after upd (row changed " + id);
                } else {
                    //It might be either cache hit or session is not in cache
                    LoggingUtil.SESSION_LOGGER_WAS.logp(Level.FINE, methodClassName, methodNames[OVERQUAL_LAST_ACCESS_TIME_UPDATE],
                                                        "It might be either cache hit or session is not in cache for  " + id);
                }
            }
        } catch (Throwable th) {
            //           if (isStaleConnectionException(th)) {
            //               com.ibm.ws.ffdc.FFDCFilter.processException(th, "com.ibm.ws.session.store.db.DatabaseHashMap.overQualLastAccessTimeUpdate", "1527", sess);
            //               if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled()&&LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
            //                   LoggingUtil.SESSION_LOGGER_WAS.logp(Level.FINE, methodClassName, methodNames[OVERQUAL_LAST_ACCESS_TIME_UPDATE], "StaleConnectionException");
            //               }
            //           } else {
            com.ibm.ws.ffdc.FFDCFilter.processException(th, "com.ibm.ws.session.store.db.DatabaseHashMap.overQualLastAccessTimeUpdate", "1531", sess);
            LoggingUtil.SESSION_LOGGER_WAS.logp(Level.SEVERE, methodClassName, methodNames[OVERQUAL_LAST_ACCESS_TIME_UPDATE], "CommonMessage.sessionid", id);
            LoggingUtil.SESSION_LOGGER_WAS.logp(Level.SEVERE, methodClassName, methodNames[OVERQUAL_LAST_ACCESS_TIME_UPDATE], "CommonMessage.exception", th);
            //           }
        } finally {
            if (s != null) {
                closeStatement(s);
            }
            if (con != null) {
                closeConnection(con);
            }
        }

        return rowsRet;
    }
133557
void writeCachedLastAccessedTimes(Connection nukerCon) throws Exception {
        if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
            LoggingUtil.SESSION_LOGGER_WAS.entering(methodClassName, methodNames[WRITE_CACHED_LAST_ACCESSED_TIMES]);
        }

        // create a copy for the updates, then atomically clear the table
        // the hashtable table clone is shallow, it will not dup the keys/elements
        Hashtable updTab = (Hashtable) cachedLastAccessedTimes.clone();
        cachedLastAccessedTimes.clear();
        Enumeration updEnum = updTab.keys();
        String id = null;
        PreparedStatement ps = null;
        boolean psClose = false;

        while (updEnum.hasMoreElements()) {

            id = (String) updEnum.nextElement();
            Long timeObj = (Long) updTab.get(id);
            long time = timeObj.longValue();
            try {
                ps = nukerCon.prepareStatement(asyncUpdate);
                setPSLong(ps, 1, time);
                ps.setString(2, id);
                ps.setString(3, id);
                ps.setString(4, getIStore().getId());

                ps.executeUpdate();
                ps.close();
                psClose = true;
                if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
                    LoggingUtil.SESSION_LOGGER_WAS.logp(Level.FINE, methodClassName, methodNames[WRITE_CACHED_LAST_ACCESSED_TIMES], "handleAsyncUpdates"
                                                                                                                                    + " - Updating LastAccess for " + id);
                }
            } catch (Exception se1) {
                //                if (isStaleConnectionException(se1)) {
                //                    com.ibm.ws.ffdc.FFDCFilter.processException(se1, "com.ibm.ws.session.store.db.DatabaseHashMap.writeCachedLastAccessedTimes", "2102", id);
                //                    if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled()&&LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
                //                        LoggingUtil.SESSION_LOGGER_WAS.logp(Level.FINE, methodClassName, methodNames[WRITE_CACHED_LAST_ACCESSED_TIMES], "StaleConnectionException");
                //                    }
                //                    throw se1;
                //                } else {
                com.ibm.ws.ffdc.FFDCFilter.processException(se1, "com.ibm.ws.session.store.db.DatabaseHashMap.writeCachedLastAccessedTimes", "2109", id);
                LoggingUtil.SESSION_LOGGER_WAS.logp(Level.SEVERE, methodClassName, methodNames[WRITE_CACHED_LAST_ACCESSED_TIMES], "DatabaseHashMap.handleAsyncError");
                LoggingUtil.SESSION_LOGGER_WAS.logp(Level.SEVERE, methodClassName, methodNames[WRITE_CACHED_LAST_ACCESSED_TIMES], "CommonMessage.sessionid", id);
                LoggingUtil.SESSION_LOGGER_WAS.logp(Level.SEVERE, methodClassName, methodNames[WRITE_CACHED_LAST_ACCESSED_TIMES], "CommonMessage.exception", se1);
                throw se1;
                //                }
            } finally {
                if (!psClose && ps != null) {
                    closeStatement(ps);
                }
            }
        }

    }
360840
public int updateExpirationTime(Object id, long oldExpirationTime, int size, long newExpirationTime, long newValidatorExpirationTime) {
        int returnCode = this.htod.updateExpirationTime(id, oldExpirationTime, size, newExpirationTime, newValidatorExpirationTime);
        if (returnCode == HTODDynacache.DISK_EXCEPTION) {
            stopOnError(this.htod.diskCacheException);
        }
        return returnCode;
    }
284145
public long getLastAccessedTime() {
        if (!_iSess.isValid())
            throw new IllegalStateException();
        long value = 0;
        if (_iSess != null) {
            value = _iSess.getLastAccessedTime();
        }
        return value;
    }
1335471
@Override
	public long getLastModified(String filePath) {
		long lastModified = 0;
		File f = new File(filePath);
		if (f.exists()) {
			lastModified = f.lastModified();
		}
		return lastModified;
	}
1224039
public V getValue(long timeout, Callable<V> updater, boolean returnExpiredWhileUpdating, Object cacheRequestObject) {
        if (!isInitialized() || hasExpired(timeout, cacheRequestObject)) {
            boolean lockAcquired = false;
            try {
                long beforeLockingCreatedMillis = createdMillis;
                if(returnExpiredWhileUpdating) {
                    if(!writeLock.tryLock()) {
                        if(isInitialized()) {
                            return getValueWhileUpdating(cacheRequestObject);
                        } else {
                            if(LOG.isDebugEnabled()) {
                                LOG.debug("Locking cache for update");
                            }
                            writeLock.lock();
                        }
                    }
                } else {
                    LOG.debug("Locking cache for update");
                    writeLock.lock();
                }
                lockAcquired = true;
                V value;
                if (!isInitialized() || shouldUpdate(beforeLockingCreatedMillis, cacheRequestObject)) {
                    try {
                        value = updateValue(getValue(), updater, cacheRequestObject);
                        if(LOG.isDebugEnabled()) {
                            LOG.debug("Updating cache for value [{}]", value);
                        }
                        setValue(value);
                    }
                    catch (Exception e) {
                        throw new UpdateException(e);
                    }
                } else {
                    value = getValue();
                    resetTimestamp(false);
                }
                return value;
            } finally {
                if(lockAcquired) {
                    if(LOG.isDebugEnabled()) {
                        LOG.debug("Unlocking cache for update");
                    }
                    writeLock.unlock();
                }
            }
        } else {
            return getValue();
        }
    }
1334475
@Override
    public synchronized void updateLastAccessTime(long accessTime) {
        if (_lastAccessedTime == 0) { // newly created session object
            _lastAccessedTime = accessTime;
        } else {
            _lastAccessedTime = _currentAccessTime;
        }
        _currentAccessTime = accessTime;
        if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_CORE.isLoggable(Level.FINE)) {
            LoggingUtil.SESSION_LOGGER_CORE.logp(Level.FINE, methodClassName, methodNames[UPDATE_LAST_ACCESS_TIME], "" + accessTime);
        }
    }
415972
public PoolEvaluateAutoScaleHeaders withLastModified(DateTime lastModified) {
        if (lastModified == null) {
            this.lastModified = null;
        } else {
            this.lastModified = new DateTimeRfc1123(lastModified);
        }
        return this;
    }
344412
protected int updateLastAccessTime(BackedSession sess, long nowTime) {
        if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
            LoggingUtil.SESSION_LOGGER_WAS.entering(methodClassName, methodNames[UPDATE_LAST_ACCESS_TIME]);
        }
        Connection con = getConnection(false);
        if (con == null)
            return 1;

        PreparedStatement s = null;
        String id = sess.getId();
        int rowsRet = 0;
        try {
            s = con.prepareStatement(asyncUpdate);
            setPSLong(s, 1, nowTime);
            s.setString(2, id);
            s.setString(3, id);
            s.setString(4, getIStore().getId()); //getId returns the appName

            if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
                LoggingUtil.SESSION_LOGGER_WAS.logp(Level.FINE, methodClassName, methodNames[UPDATE_LAST_ACCESS_TIME], "before lastacc upd for " + id);
            }

            rowsRet = s.executeUpdate();
            if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
                if (rowsRet > 0) {
                    LoggingUtil.SESSION_LOGGER_WAS.logp(Level.FINE, methodClassName, methodNames[UPDATE_LAST_ACCESS_TIME], "after upd (row changed " + id);
                } else {
                    //Ooops..someother jvm  has invalidated this
                    //reset the value, so that concurrent access to this session won't try
                    //update the database again.
                    LoggingUtil.SESSION_LOGGER_WAS.logp(Level.FINE, methodClassName, methodNames[UPDATE_LAST_ACCESS_TIME], "row does not exist for " + id);
                }
            }

        } catch (Throwable th) {
            //            if (isStaleConnectionException(th)) {
            //                com.ibm.ws.ffdc.FFDCFilter.processException(th, "com.ibm.ws.session.store.db.DatabaseHashMap.updateLastAccessTime", "1472", sess);
            //                if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled()&&LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
            //                    LoggingUtil.SESSION_LOGGER_WAS.logp(Level.FINE, methodClassName, methodNames[UPDATE_LAST_ACCESS_TIME], "StaleConnectionException");
            //                }
            //            } else {
            com.ibm.ws.ffdc.FFDCFilter.processException(th, "com.ibm.ws.session.store.db.DatabaseHashMap.updateLastAccessTime", "1476", sess);
            LoggingUtil.SESSION_LOGGER_WAS.logp(Level.SEVERE, methodClassName, methodNames[UPDATE_LAST_ACCESS_TIME], "CommonMessage.sessionid", id);
            LoggingUtil.SESSION_LOGGER_WAS.logp(Level.SEVERE, methodClassName, methodNames[UPDATE_LAST_ACCESS_TIME], "CommonMessage.exception", th);
            //            }
        } finally {
            if (s != null) {
                closeStatement(s);
            }
            closeConnection(con); //findbugs 106329
        }

        return rowsRet;
    }
1143830
@Override
    public boolean update(Object key, Object value, Object currentVersion, Object previousVersion) throws CacheException {
        log.debug("region access strategy nonstrict-read-write entity update() {} {}", getInternalRegion().getCacheNamespace(), key);
        return false;
    }
1013123
public void sessionLastAccessTimeSet(ISession session, long old, long newaccess) {
        // ArrayList sessionStateObservers = null;

        /*
         * Check to see if there is a non-empty list of sessionStateObservers.
         */
        if (_sessionStateObservers == null || _sessionStateObservers.size() < 1) {
            return;
        }

        // synchronized(_sessionStateObservers) {
        // sessionStateObservers = (ArrayList)_sessionStateObservers.clone();
        // }

        ISessionStateObserver sessionStateObserver = null;
        for (int i = 0; i < _sessionStateObservers.size(); i++) {
            sessionStateObserver = (ISessionStateObserver) _sessionStateObservers.get(i);
            sessionStateObserver.sessionLastAccessTimeSet(session, old, newaccess);
        }

    }
463788
private boolean isNotModified(HttpRequest request, long lastModified) throws ParseException {
    String ifModifiedSince = request.headers().get(HttpHeaderNames.IF_MODIFIED_SINCE);
    if (ifModifiedSince != null && !ifModifiedSince.equals("")) {
      SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
      Date ifModifiedSinceDate = dateFormatter.parse(ifModifiedSince);

      // Only compare up to the second because the datetime format we send to the client does
      // not have milliseconds
      long ifModifiedSinceDateSeconds = ifModifiedSinceDate.getTime() / 1000;
      long fileLastModifiedSeconds = lastModified / 1000;
      return ifModifiedSinceDateSeconds == fileLastModifiedSeconds;
    }
    return false;
  }
1049882
private void updateLastForce()
    {
        if (Double.compare(fhLast, fhDest) != 0)
        {
            fhLast = fhDest;
            arrivedH = false;
        }
        if (Double.compare(fvLast, fvDest) != 0)
        {
            fvLast = fvDest;
            arrivedV = false;
        }
    }
924108
function Request_isHeaderCacheUnModified() {

        var etagMatches = true,
            notModified = true,
            modifiedSince = this.getRequestHeader('if-modified-since'),
            noneMatch = this.getRequestHeader('if-none-match'),
            cc = this.getRequestHeader('cache-control'),
            lastModified = this.getHeader('last-modified'),
            etag = this.getHeader('etag');


        // unconditional request
        if (!modifiedSince && !noneMatch) {
            return false;
            // check for no-cache cache request directive
        } else if (cc && cc.indexOf('no-cache') !== -1) {
            return false;
        }

        // parse if-none-match
        if (noneMatch) {
            noneMatch = noneMatch.split(/ *, */);
        }
        // if-none-match
        if (noneMatch) {
            etagMatches = ~noneMatch.indexOf(etag) || '*' == noneMatch[0];
        }
        // if-modified-since
        if (modifiedSince) {
            modifiedSince = Date.parse(modifiedSince);
            lastModified = Date.parse(lastModified);
            notModified = lastModified <= modifiedSince;
        }

        return !!(etagMatches && notModified);
    }
234279
@Override
  public boolean isModified()
  {
    long now = CurrentTime.currentTime();
    long lastCheckTime = _lastCheckTime.get();
    
    if (now <= lastCheckTime + _checkInterval) {
      return _isModified;
    }

    if (! _lastCheckTime.compareAndSet(lastCheckTime, now)) {
      return _isModified;
    }

    if (isModifiedImpl()) {
      _isModified = true;
      //_lastCheckTime.set(0);
    }
    else {
      _isModified = false;
    }

    return _isModified;
  }
904135
private boolean doHandleTopologyUpdate(String cacheName, CacheTopology cacheTopology,
                                          AvailabilityMode availabilityMode, int viewId, Address sender,
                                          LocalCacheStatus cacheStatus) {
      try {
         waitForView(viewId, cacheStatus.getJoinInfo().getTimeout(), TimeUnit.MILLISECONDS);
      } catch (InterruptedException e) {
         // Shutting down, ignore the exception and the rebalance
         return false;
      }

      synchronized (cacheStatus) {
         if (cacheTopology == null) {
            // No topology yet: happens when a cache is being restarted from state.
            // Still, return true because we don't want to re-send the join request.
            return true;
         }
         // Register all persistent UUIDs locally
         registerPersistentUUID(cacheTopology);
         CacheTopology existingTopology = cacheStatus.getCurrentTopology();
         if (existingTopology != null && cacheTopology.getTopologyId() <= existingTopology.getTopologyId()) {
            log.debugf("Ignoring late consistent hash update for cache %s, current topology is %s: %s",
                  cacheName, existingTopology.getTopologyId(), cacheTopology);
            return false;
         }

         if (!updateCacheTopology(cacheName, cacheTopology, viewId, sender, cacheStatus))
            return false;

         CacheTopologyHandler handler = cacheStatus.getHandler();
         resetLocalTopologyBeforeRebalance(cacheName, cacheTopology, existingTopology, handler);

         ConsistentHash currentCH = cacheTopology.getCurrentCH();
         ConsistentHash pendingCH = cacheTopology.getPendingCH();
         ConsistentHash unionCH = null;
         if (pendingCH != null) {
            ConsistentHashFactory chf = cacheStatus.getJoinInfo().getConsistentHashFactory();
            switch (cacheTopology.getPhase()) {
               case READ_NEW_WRITE_ALL:
                  // When removing members from topology, we have to make sure that the unionCH has
                  // owners from pendingCH (which is used as the readCH in this phase) before
                  // owners from currentCH, as primary owners must match in readCH and writeCH.
                  unionCH = chf.union(pendingCH, currentCH);
                  break;
               default:
                  unionCH = chf.union(currentCH, pendingCH);
            }
         }

         CacheTopology unionTopology = new CacheTopology(cacheTopology.getTopologyId(), cacheTopology.getRebalanceId(),
               currentCH, pendingCH, unionCH, cacheTopology.getPhase(),
               cacheTopology.getActualMembers(), persistentUUIDManager.mapAddresses(cacheTopology.getActualMembers()));
         unionTopology.logRoutingTableInformation();

         boolean updateAvailabilityModeFirst = availabilityMode != AvailabilityMode.AVAILABLE;
         if (updateAvailabilityModeFirst && availabilityMode != null) {
            // TODO: handle this async?
            CompletionStages.join(cacheStatus.getPartitionHandlingManager().setAvailabilityMode(availabilityMode));
         }

         boolean startConflictResolution = cacheTopology.getPhase() == CacheTopology.Phase.CONFLICT_RESOLUTION;
         if (!startConflictResolution && (existingTopology == null || existingTopology.getRebalanceId() != cacheTopology.getRebalanceId())
               && unionCH != null) {
            // This CH_UPDATE command was sent after a REBALANCE_START command, but arrived first.
            // We will start the rebalance now and ignore the REBALANCE_START command when it arrives.
            log.tracef("This topology update has a pending CH, starting the rebalance now");
            handler.rebalance(unionTopology);
         } else {
            handler.updateConsistentHash(unionTopology);
         }

         if (!updateAvailabilityModeFirst) {
            // TODO: handle this async?
            CompletionStages.join(cacheStatus.getPartitionHandlingManager().setAvailabilityMode(availabilityMode));
         }
         return true;
      }
   }
403624
def _update_inplace(self, result, verify_is_copy=True):
        
        # NOTE: This does *not* call __finalize__ and that's an explicit
        # decision that we may revisit in the future.

        self._reset_cache()
        self._clear_item_cache()
        self._data = getattr(result, '_data', result)
        self._maybe_update_cacher(verify_is_copy=verify_is_copy)