com.google.appengine.api.memcache.Expiration Java Examples

The following examples show how to use com.google.appengine.api.memcache.Expiration. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ShardedCounter.java    From appengine-sharded-counters-java with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieve the value of this sharded counter.
 *
 * @return Summed total of all shards' counts
 */
public final long getCount() {
    Long value = (Long) mc.get(kind);
    if (value != null) {
        return value;
    }

    long sum = 0;
    Query query = new Query(kind);
    for (Entity shard : DS.prepare(query).asIterable()) {
        sum += (Long) shard.getProperty(CounterShard.COUNT);
    }
    mc.put(kind, sum, Expiration.byDeltaSeconds(CACHE_PERIOD),
            SetPolicy.ADD_ONLY_IF_NOT_PRESENT);

    return sum;
}
 
Example #2
Source File: MemcacheAsync2Test.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
@Test
public void testPutIfUntouchedExpire() {
    final String TS_KEY = createTimeStampKey("testPutIfUntouched");

    memcache.put(TS_KEY, STR_VALUE);
    IdentifiableValue oldOriginalIdValue = memcache.getIdentifiable(TS_KEY);
    final String NEW_VALUE = "new-" + STR_VALUE;
    Future<Boolean> future;
    Boolean valueWasStored;

    // Store NEW_VALUE if no other value stored since oldOriginalIdValue was retrieved.
    // memcache.get() has not been called, so this put should succeed.
    future = asyncMemcache.putIfUntouched(TS_KEY, oldOriginalIdValue, NEW_VALUE, Expiration.byDeltaSeconds(1));
    valueWasStored = waitOnFuture(future);
    assertEquals(true, valueWasStored);
    assertEquals(NEW_VALUE, memcache.get(TS_KEY));

    // Value should not be stored after expiration period.
    sync(3000);
    assertNull(memcache.get(TS_KEY));
}
 
Example #3
Source File: MemcacheTest.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
@Test
public void testPutIfUntouchedExpire() {
    final String TS_KEY = createTimeStampKey("testPutIfUntouched");

    memcache.put(TS_KEY, STR_VALUE);
    MemcacheService.IdentifiableValue oldOriginalIdValue = memcache.getIdentifiable(TS_KEY);
    final String NEW_VALUE = "new-" + STR_VALUE;

    // Store NEW_VALUE if no other value stored since oldOriginalIdValue was retrieved.
    // memcache.get() has not been called, so this put should succeed.
    Boolean valueWasStored = memcache.putIfUntouched(TS_KEY, oldOriginalIdValue, NEW_VALUE, Expiration.byDeltaSeconds(1));
    assertEquals(true, valueWasStored);
    assertEquals(NEW_VALUE, memcache.get(TS_KEY));

    // Value should not be stored after expiration period.
    sync(3000);
    assertNull(memcache.get(TS_KEY));
}
 
Example #4
Source File: ShardedCounter.java    From appengine-modules-sample-java with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieve the value of this sharded counter.
 *
 * @return Summed total of all shards' counts
 */
public long getCount() {
  final Long value = (Long) mc.get(kind);
  if (value != null) {
    return value;
  }

  long sum = 0;
  final Query query = new Query(kind);
  for (final Entity shard : ds.prepare(query).asIterable()) {
    sum += (Long) shard.getProperty(CounterShard.COUNT);
  }
  mc.put(kind, sum, Expiration.byDeltaSeconds(60),
      SetPolicy.ADD_ONLY_IF_NOT_PRESENT);

  return sum;
}
 
Example #5
Source File: MemcacheTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test
public void testPutAllExpiration() {
    HashMap<Object, Object> map = new HashMap<Object, Object>();
    map.put("key1", "value1");
    map.put("key2", "value2");

    memcache.putAll(map, Expiration.byDeltaMillis(1000));
    assertTrue(memcache.contains("key1"));
    assertTrue(memcache.contains("key2"));
    sync();
    assertFalse(memcache.contains("key1"));
    assertFalse(memcache.contains("key2"));
}
 
Example #6
Source File: AppEngineMemcachedClientTest.java    From memcached-spring-boot with Apache License 2.0 5 votes vote down vote up
@Test
public void whenTouch_thenCorrectMethodInvoked() throws ExecutionException, InterruptedException {
    memcachedClient.touch("my-key", 700);

    verify(service).getIdentifiable("my-key");
    verify(service).putIfUntouched("my-key", IDENTIFIABLE_VALUE, IDENTIFIABLE_VALUE.getValue(), Expiration.byDeltaSeconds(700));
}
 
Example #7
Source File: MemcacheTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test
public void testPutExpiration() {
    memcache.put("key", "value", Expiration.byDeltaMillis(1000));
    assertTrue(memcache.contains("key"));
    sync();
    assertFalse(memcache.contains("key"));
}
 
Example #8
Source File: StocksRepositoryImpl.java    From phisix with Apache License 2.0 5 votes vote down vote up
@Override
public Stocks findAll() {
	Stocks stocks = (Stocks) memcache.get("ALL");
	if (stocks == null) {
		stocks = pseClient.getSecuritiesAndIndicesForPublic(PseClientConstants.REFERER, "getSecuritiesAndIndicesForPublic", true);
		memcache.put("ALL", stocks, Expiration.byDeltaSeconds(60));
	}
	if (gaClient != null) {
		gaClient.eventTracking(GaClientConstants.VERSION, GaClientConstants.TRACKING_ID, GaClientConstants.CLIENT_ID, GaClientConstants.EVENT_HIT, "stocks", "all", GaClientConstants.USER_AGENT);
	}
	return stocks;
}
 
Example #9
Source File: MemcacheAsyncTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test
public void testPutAllExpiration() {
    HashMap<Object, Object> map = new HashMap<Object, Object>();
    map.put("key1", "value1");
    map.put("key2", "value2");

    unwrap(service.putAll(map, Expiration.byDeltaMillis(1000)));
    assertTrue(unwrap(service.contains("key1")));
    assertTrue(unwrap(service.contains("key2")));
    sync();
    assertFalse(unwrap(service.contains("key1")));
    assertFalse(unwrap(service.contains("key2")));
}
 
Example #10
Source File: GetMotdServiceImpl.java    From appinventor-extensions with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the current Motd
 *
 * @return  the current Motd
 */
@Override
public Motd getMotd() {

  Motd motd = (Motd) memcache.get(motdcachekey); // Attempt to use memcache to fetch it
  if (motd != null)
    return motd;

  motd = storageIo.getCurrentMotd();
  memcache.put(motdcachekey, motd, Expiration.byDeltaSeconds(600)); // Hold it for ten minutes
  return motd;
}
 
Example #11
Source File: MemcacheAsyncTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test
public void testPutExpiration() {
    unwrap(service.put("key", "value", Expiration.byDeltaMillis(1000)));
    assertTrue(unwrap(service.contains("key")));
    sync();
    assertFalse(unwrap(service.contains("key")));
}
 
Example #12
Source File: Worker.java    From solutions-mobile-backend-starter-java with Apache License 2.0 4 votes vote down vote up
private void recordTaskProcessed(TaskHandle task) {
  cache.put(task.getName(), 1, Expiration.byDeltaSeconds(60 * 60 * 2));
  Entity entity = new Entity(PROCESSED_NOTIFICATION_TASKS_ENTITY_KIND, task.getName());
  entity.setProperty("processedAt", new Date());
  dataStore.put(entity);
}
 
Example #13
Source File: PushNotificationWorker.java    From solutions-ios-push-notification-sample-backend-java with Apache License 2.0 4 votes vote down vote up
private void recordTaskProcessed(TaskHandle task) {
  cache.put(task.getName(), 1, Expiration.byDeltaSeconds(60 * 60 * 2));
  Entity entity = new Entity(PROCESSED_NOTIFICATION_TASKS_ENTITY_KIND, task.getName());
  entity.setProperty("processedAt", new Date());
  dataStore.put(entity);
}
 
Example #14
Source File: Worker.java    From io2014-codelabs with Apache License 2.0 4 votes vote down vote up
private void recordTaskProcessed(TaskHandle task) {
  cache.put(task.getName(), 1, Expiration.byDeltaSeconds(60 * 60 * 2));
  Entity entity = new Entity(PROCESSED_NOTIFICATION_TASKS_ENTITY_KIND, task.getName());
  entity.setProperty("processedAt", new Date());
  dataStore.put(entity);
}
 
Example #15
Source File: AppEngineDataStoreFactory.java    From google-http-java-client with Apache License 2.0 4 votes vote down vote up
/** Returns the Memcache expiration policy on puts. */
public final Expiration getMemcacheExpiration() {
  return memcacheExpiration;
}
 
Example #16
Source File: AppEngineMemcachedClientTest.java    From memcached-spring-boot with Apache License 2.0 4 votes vote down vote up
@Test
public void whenSet_thenCorrectMethodInvoked() {
    memcachedClient.set("my-key", 12000, "my-value");

    verify(service).put("my-key", "my-value", Expiration.byDeltaSeconds(12000));
}
 
Example #17
Source File: AppEngineMemcachedClient.java    From memcached-spring-boot with Apache License 2.0 4 votes vote down vote up
@Override
public void touch(String key, int exp) {
    final MemcacheService.IdentifiableValue identifiable = this.service.getIdentifiable(key);
    this.service.putIfUntouched(key, identifiable, identifiable.getValue(), Expiration.byDeltaSeconds(exp));
}
 
Example #18
Source File: AppEngineMemcachedClient.java    From memcached-spring-boot with Apache License 2.0 4 votes vote down vote up
@Override
public void set(String key, int exp, Object value) {
    this.service.put(key, value, Expiration.byDeltaSeconds(exp));
}
 
Example #19
Source File: ObjectifyStorageIo.java    From appinventor-extensions with Apache License 2.0 4 votes vote down vote up
@Override
public User getUser(final String userId, final String email) {
  String cachekey = User.usercachekey + "|" + userId;
  User tuser = (User) memcache.get(cachekey);
  if (tuser != null && tuser.getUserTosAccepted() && ((email == null) || (tuser.getUserEmail().equals(email)))) {
    if (tuser.getUserName()==null) {
      setUserName(userId,tuser.getDefaultName());
      tuser.setUserName(tuser.getDefaultName());
    }
    return tuser;
  } else {                    // If not in memcache, or tos
                              // not yet accepted, fetch from datastore
      tuser = new User(userId, email, null, null, 0, false, false, 0, null);
  }
  final User user = tuser;
  try {
    runJobWithRetries(new JobRetryHelper() {
      @Override
      public void run(Objectify datastore) {
        UserData userData = datastore.find(userKey(userId));
        boolean viaemail = false; // Which datastore copy did we find it with...
        Objectify qDatastore = null;
        if (userData == null) { // Attempt to find them by email
          LOG.info("Did not find userId " + userId);
          if (email != null) {
            qDatastore = ObjectifyService.begin(); // Need an instance not in this transaction
            userData = qDatastore.query(UserData.class).filter("email", email).get();
            if (userData == null) { // Still null!
              userData = qDatastore.query(UserData.class).filter("emaillower", email.toLowerCase()).get();
            }
            // Need to fix userId...
            if (userData != null) {
              LOG.info("Found based on email, userData.id = " + userData.id);
              if (!userData.id.equals(userId)) {
                user.setUserId(userData.id);
                LOG.info("Set user.setUserId");
              }
              viaemail = true;
            }
          }
          if (userData == null) { // No joy, create it.
            userData = createUser(datastore, userId, email);
          }
        } else if (email != null && !email.equals(userData.email)) {
          userData.email = email;
          userData.emaillower = email.toLowerCase();
          datastore.put(userData);
        }
        // Add emaillower if it isn't already there
        if (userData.emaillower == null) {
          userData.emaillower = userData.email.toLowerCase();
          if (viaemail) {
            qDatastore.put(userData);
          } else {
            datastore.put(userData);
          }
        }
        if(userData.emailFrequency == 0){
          // when users of old version access UserData,
          // emailFrequency will be automatically set as 0
          // force it to be DEFAULT_EMAIL_NOTIFICATION_FREQUENCY
          userData.emailFrequency = User.DEFAULT_EMAIL_NOTIFICATION_FREQUENCY;
          datastore.put(userData);
        }
        user.setUserEmail(userData.email);
        user.setUserName(userData.name);
        user.setUserLink(userData.link);
        user.setUserEmailFrequency(userData.emailFrequency);
        user.setType(userData.type);
        user.setUserTosAccepted(userData.tosAccepted || !requireTos.get());
        user.setIsAdmin(userData.isAdmin);
        user.setSessionId(userData.sessionid);
        user.setPassword(userData.password);
      }
    }, false);                // Transaction not needed. If we fail there is nothing to rollback
  } catch (ObjectifyException e) {
    throw CrashReport.createAndLogError(LOG, null, collectUserErrorInfo(userId), e);
  }
  memcache.put(cachekey, user, Expiration.byDeltaSeconds(60)); // Remember for one minute
  // The choice of one minute here is arbitrary. getUser() is called on every authenticated
  // RPC call to the system (out of OdeAuthFilter), so using memcache will save a significant
  // number of calls to the datastore. If someone is idle for more then a minute, it isn't
  // unreasonable to hit the datastore again. By pruning memcache ourselves, we have a
  // bit more control (maybe) of how things are flushed from memcache. Otherwise we are
  // at the whim of whatever algorithm App Engine employs now or in the future.
  return user;
}
 
Example #20
Source File: AppEngineDataStoreFactory.java    From google-http-java-client with Apache License 2.0 2 votes vote down vote up
/**
 * Sets the Memcache expiration policy on puts.
 *
 * <p>Overriding is only supported for the purpose of calling the super implementation and
 * changing the return type, but nothing else.
 */
public Builder setMemcacheExpiration(Expiration memcacheExpiration) {
  this.memcacheExpiration = memcacheExpiration;
  return this;
}