@Test
 public void testPutExpiration() {
   unwrap(service.put("key", "value", Expiration.byDeltaMillis(1000)));
   assertTrue(unwrap(service.contains("key")));
   sync();
   assertFalse(unwrap(service.contains("key")));
 }
 public void enableRelevanceForSector(long sectorIndex) {
   memcacheService.put(
       MC_KEY_SECTOR_RELEVANCE_PREFIX + sectorIndex,
       true,
       Expiration.byDeltaMillis(SECTOR_RELEVANCE_EXPIRATION_MILLIS),
       MemcacheService.SetPolicy.SET_ALWAYS);
 }
 public String newAudioClipInMemcache(String ownerId, AudioClip audioClip)
     throws BadRequestException {
   validateUserExistance(ownerId);
   ArrayList<AudioClip> audioCLipList =
       (ArrayList<AudioClip>) syncCache.get(TuneInConstants.ALL_AUDIO_CLIPS);
   if (audioCLipList == null) {
     audioCLipList = new ArrayList<AudioClip>();
   }
   audioCLipList.add(audioClip);
   syncCache.put(TuneInConstants.ALL_AUDIO_CLIPS, audioCLipList, Expiration.byDeltaSeconds(60));
   return audioClip.getKeyname();
 }
 public static void cachePutExp(String nameSpace, Object id, Serializable o, int exp) {
   MemcacheService memcache = cacheInit(nameSpace);
   try {
     if (exp > 0) {
       memcache.put(id, o, Expiration.byDeltaSeconds(exp));
     } else {
       memcache.put(id, o);
     }
   } catch (MemcacheServiceException e) {
     // nothing can be done.
   }
 }
  @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")));
  }
 @Override
 public GetAccessTokenResult getAccessToken(Iterable<String> scopes) {
   MemcacheService memcache = MemcacheServiceFactory.getMemcacheService(MEMCACHE_NAMESPACE);
   String memcacheKey = memcacheKeyForScopes(scopes);
   GetAccessTokenResult result;
   Object memcacheResult = memcache.get(memcacheKey);
   if (memcacheResult != null) {
     result = (GetAccessTokenResult) memcacheResult;
   } else {
     result = getAccessTokenUncached(scopes);
     Date memcacheExpiration = new Date(result.getExpirationTime().getTime() - 300000);
     memcache.put(memcacheKey, result, Expiration.onDate(memcacheExpiration));
   }
   return result;
 }
Example #7
0
  /**
   * Put buckets in the cache, checking for cacheability and collisions.
   *
   * @return the set of keys that were *successfully* put without collision
   */
  private Set<Key> cachePutIfUntouched(Iterable<Bucket> buckets) {
    Map<Key, CasValues> payload = new HashMap<>();

    for (Bucket buck : buckets) {
      if (!buck.isCacheable()) continue;

      Integer expirySeconds = cacheControl.getExpirySeconds(buck.getKey());
      if (expirySeconds == null) continue;

      Expiration expiration = expirySeconds == 0 ? null : Expiration.byDeltaSeconds(expirySeconds);

      payload.put(buck.getKey(), new CasValues(buck.iv, buck.getNextToStore(), expiration));
    }

    return this.memcache.putIfUntouched(payload);
  }
  /** Cast objects: return the list of objects that must be shown in the castable device */
  @SuppressWarnings("unchecked")
  public List<CastViewObject> castObjects(CastView castView) {
    MemcacheService cache =
        MemcacheServiceFactory.getMemcacheService(CACHE_KEY + getStrategyName());
    List<CastViewObject> castViewObjects = (List<CastViewObject>) cache.get(castView.getMnemonic());

    if (castViewObjects != null) {
      return castViewObjects;
    } else {
      castViewObjects = loadObjects(castView);
      cache.put(
          castView.getMnemonic(), castViewObjects, Expiration.byDeltaSeconds(EXPIRATION_TIME));
    }

    return castViewObjects;
  }
  public List<AudioClipInstance> getOtherUsersAudioClips(String userId) throws BadRequestException {
    List<AudioClipInstance> audioClipInstanceList;

    // no need to check for user existance here! if UserId is null, then all audioClips are returned
    Filter userFilter =
        new FilterPredicate(TuneInConstants.AUDIO_CLIP_OWNER_ID, FilterOperator.NOT_EQUAL, userId);
    Query q = new Query(TuneInConstants.AUDIO_CLIP_TYPE).setFilter(userFilter);
    PreparedQuery pq = datastore.prepare(q);

    // check mem-cache for the results first
    String CACHE_KEY = TuneInConstants.OTHERS_WORK_KEY + userId;
    audioClipInstanceList = (ArrayList<AudioClipInstance>) syncCache.get(CACHE_KEY);

    if (audioClipInstanceList == null) {
      audioClipInstanceList = new ArrayList<AudioClipInstance>();
      User user;
      AudioClipInstance audioClipInstance;

      for (Entity result : pq.asIterable()) {
        user =
            userService.getUserById(
                (String) result.getProperty(TuneInConstants.AUDIO_CLIP_OWNER_ID));
        audioClipInstance =
            new AudioClipInstance(
                KeyFactory.keyToString(result.getKey()),
                (String) result.getProperty(TuneInConstants.AUDIO_CLIP_TITLE),
                user,
                (String) result.getProperty(TuneInConstants.AUDIO_CLIP_AUDIO_ID),
                (String) result.getProperty(TuneInConstants.AUDIO_CLIP_IMAGE_ID),
                (Date) result.getProperty(TuneInConstants.AUDIO_CLIP_DATE));
        audioClipInstanceList.add(audioClipInstance);
      }
      syncCache.put(CACHE_KEY, audioClipInstanceList, Expiration.byDeltaSeconds(300));
    }

    return audioClipInstanceList;
  }
/**
 * A Configuration class for {@link ShardedCounterService}.
 *
 * @author David Fuelling <*****@*****.**>
 */
@Getter
@ToString
@EqualsAndHashCode
@Immutable
public class ShardedCounterServiceConfiguration {
  // The number of shards to begin with for this counter.
  static final int DEFAULT_NUM_COUNTER_SHARDS = 3;

  static final int SIXTY_MINUTES_IN_SECONDS = 60 * 60;

  // 5 Minute Expiration (by default) for counter counts in memcache before a
  // Datastore query is attempted to get the new count.
  static final Expiration DEFAULT_EXPIRATION = Expiration.byDeltaSeconds(SIXTY_MINUTES_IN_SECONDS);

  // The number of counter shards to create when a new counter is created. The
  // default value is 3.
  private final int numInitialShards;

  // The default Memcache expiration for counter objects.
  private final Expiration defaultExpiration;

  // The name of the queue that will be used to delete shards in an async
  // fashion
  private final String deleteCounterShardQueueName;

  // The optional value of {@link TaskBuilder#url} when interacting with the
  // queue used to delete CounterShards.
  private final String relativeUrlPathForDeleteTaskQueue;

  /**
   * The default constructor for building a ShardedCounterService configuration class. Private so
   * that only the builder can build this class.
   *
   * @param builder
   */
  private ShardedCounterServiceConfiguration(Builder builder) {
    Preconditions.checkNotNull(builder);
    this.numInitialShards = builder.numInitialShards;
    this.deleteCounterShardQueueName = builder.deleteCounterShardQueueName;
    this.relativeUrlPathForDeleteTaskQueue = builder.relativeUrlPathForDeleteTaskQueue;
    this.defaultExpiration = builder.getDefaultExpiration();
  }

  /**
   * Constructs a {@link ShardedCounterServiceConfiguration} object with default values.
   *
   * @return
   */
  public static ShardedCounterServiceConfiguration defaultConfiguration() {
    ShardedCounterServiceConfiguration.Builder builder =
        new ShardedCounterServiceConfiguration.Builder();
    return new ShardedCounterServiceConfiguration(builder);
  }

  /**
   * A Builder for {@link ShardedCounterServiceConfiguration}.
   *
   * @author david
   */
  public static final class Builder {
    @Getter @Setter private int numInitialShards;

    /** Note: {@code null} may be used here to specify no specific expiration. */
    @Getter @Setter private Expiration defaultExpiration;

    @Getter @Setter private String deleteCounterShardQueueName;

    @Getter @Setter private String relativeUrlPathForDeleteTaskQueue;

    /** Default Constructor. Sets up this buildr with 1 shard by default. */
    public Builder() {
      this.numInitialShards = DEFAULT_NUM_COUNTER_SHARDS;
      this.defaultExpiration = DEFAULT_EXPIRATION;
    }

    public Builder withNumInitialShards(int numInitialShards) {
      Preconditions.checkArgument(
          numInitialShards > 0, "Number of Shards for a new CounterData must be greater than 0!");
      this.numInitialShards = numInitialShards;
      return this;
    }

    public Builder withDeleteCounterShardQueueName(String deleteCounterShardQueueName) {
      this.deleteCounterShardQueueName = deleteCounterShardQueueName;
      return this;
    }

    public Builder withRelativeUrlPathForDeleteTaskQueue(String relativeUrlPathForDeleteTaskQueue) {
      this.relativeUrlPathForDeleteTaskQueue = relativeUrlPathForDeleteTaskQueue;
      return this;
    }

    /**
     * Method to build a new {@link ShardedCounterServiceConfiguration}.
     *
     * @return
     */
    public ShardedCounterServiceConfiguration build() {
      return new ShardedCounterServiceConfiguration(this);
    }
  }
}
 public Collection<CacheUtils.Wrapper<Transportation>> getSectorTransportations(long sectorIndex) {
   return new CacheUtils.FixedCollection<Transportation>(
       MC_KEY_TRANSPORTATION + sectorIndex,
       MC_TRANSPORTATION_PER_SECTOR_LIMIT,
       Expiration.byDeltaSeconds(MC_TRANSPORTATION_EXPIRATION_SECS));
 }