@GET
  @Path("/{id}")
  public Response get(@PathParam("id") int id, @Context Request request) {
    // Create cache control header
    CacheControl cc = new CacheControl();
    // Set max age to one day
    cc.setMaxAge(86400);

    Response.ResponseBuilder rb = null;

    // Calculate the ETag on last modified date of user resource
    EntityTag etag = new EntityTag(UserDao.getLastModifiedById(id).hashCode() + "");

    // Verify if it matched with etag available in http request
    rb = request.evaluatePreconditions(etag);

    // If ETag matches the rb will be non-null;
    // Use the rb to return the response without any further processing
    if (rb != null) {
      return rb.cacheControl(cc).tag(etag).build();
    }

    // If rb is null then either it is first time request; or resource is modified
    // Get the updated representation and return with Etag attached to it
    rb = Response.ok(UserDao.get(id).get()).cacheControl(cc).tag(etag);
    return rb.build();
  }
Beispiel #2
0
 @Test
 public void timeDurationTruncatedToMaxValue() throws Exception {
   CacheControl cacheControl =
       new CacheControl.Builder()
           .maxAge(365 * 100, TimeUnit.DAYS) // Longer than Integer.MAX_VALUE seconds.
           .build();
   assertEquals(Integer.MAX_VALUE, cacheControl.maxAgeSeconds());
 }
Beispiel #3
0
 public t> cacheControl(CacheControl cachecontrol)
 {
     cachecontrol = cachecontrol.toString();
     if (cachecontrol.isEmpty())
     {
         return removeHeader("Cache-Control");
     } else
     {
         return header("Cache-Control", cachecontrol);
     }
 }
Beispiel #4
0
  /**
   * Revert a set of keys to the empty state. Will loop on this several times just in case the
   * memcache write fails - we don't want to leave the cache in a nasty state.
   */
  public void empty(Iterable<Key> keys) {
    Map<Key, Object> updates = new HashMap<>();

    for (Key key : keys) if (cacheControl.getExpirySeconds(key) != null) updates.put(key, null);

    this.memcacheWithRetry.putAll(updates);
  }
 public void cancel() {
   clearImagesToGrab();
   if (cacheControl != null) {
     while (!cacheControl.isCachePipeEmpty()) {
       Main.info("Try to close a WMSLayer which is currently saving in cache : wait 1 sec.");
       CadastrePlugin.safeSleep(1000);
     }
   }
 }
Beispiel #6
0
  private void clearCache(RolapCube cube) {
    // Clear the cache for the Sales cube, so the query runs as if
    // for the first time. (TODO: Cleaner way to do this.)
    final Cube salesCube = getConnection().getSchema().lookupCube("Sales", true);
    RolapHierarchy hierarchy =
        (RolapHierarchy)
            salesCube.lookupHierarchy(new Id.NameSegment("Store", Id.Quoting.UNQUOTED), false);
    SmartMemberReader memberReader = (SmartMemberReader) hierarchy.getMemberReader();
    MemberCacheHelper cacheHelper = memberReader.cacheHelper;
    cacheHelper.mapLevelToMembers.cache.clear();
    cacheHelper.mapMemberToChildren.cache.clear();

    // Flush the cache, to ensure that the query gets executed.
    cube.clearCachedAggregations(true);

    CacheControl cacheControl = getConnection().getCacheControl(null);
    final CacheControl.CellRegion measuresRegion = cacheControl.createMeasuresRegion(cube);
    cacheControl.flush(measuresRegion);
  }
Beispiel #7
0
  /**
   * Gets the Buckets for the specified keys. A bucket is built around an IdentifiableValue so you
   * can putAll() them without the risk of overwriting other threads' changes. Buckets also hide the
   * underlying details of storage for negative, empty, and uncacheable results.
   *
   * <p>Note that worst case (a cold cache), obtaining each bucket might require three memcache
   * requests: a getIdentifiable() which returns null, a put(EMPTY), and another getIdentifiable().
   * Since there is no batch getIdentifiable(), this is *per key*.
   *
   * <p>When keys are uncacheable (per CacheControl) or the memcache is down, you will still get an
   * empty bucket back. The bucket will have null IdentifiableValue so we can identify it as
   * uncacheable.
   *
   * @return the buckets requested. Buckets will never be null. You will always get a bucket for
   *     every key.
   */
  public Map<Key, Bucket> getAll(Iterable<Key> keys) {
    Map<Key, Bucket> result = new HashMap<>();

    // Sort out the ones that are uncacheable
    Set<Key> potentials = new HashSet<>();

    for (Key key : keys) {
      if (cacheControl.getExpirySeconds(key) == null) result.put(key, new Bucket(key));
      else potentials.add(key);
    }

    Map<Key, IdentifiableValue> ivs;
    try {
      ivs = this.memcache.getIdentifiables(potentials);
    } catch (Exception ex) {
      // This should really only be a problem if the serialization format for an Entity changes,
      // or someone put a badly-serializing object in the cache underneath us.
      log.log(Level.WARNING, "Error obtaining cache for " + potentials, ex);
      ivs = new HashMap<>();
    }

    // Figure out cold cache values
    Map<Key, Object> cold = new HashMap<>();
    for (Key key : potentials) if (ivs.get(key) == null) cold.put(key, null);

    if (!cold.isEmpty()) {
      // The cache is cold for those values, so start them out with nulls that we can make an IV for
      this.memcache.putAll(cold);

      try {
        Map<Key, IdentifiableValue> ivs2 = this.memcache.getIdentifiables(cold.keySet());
        ivs.putAll(ivs2);
      } catch (Exception ex) {
        // At this point we should just not worry about it, the ivs will be null and uncacheable
      }
    }

    // Now create the remaining buckets
    for (Key key : keys) {
      // iv might still be null, which is ok - that means uncacheable
      IdentifiableValue iv = ivs.get(key);
      Bucket buck = (iv == null) ? new Bucket(key) : new Bucket(key, iv);
      result.put(key, buck);

      if (buck.isEmpty()) this.stats.recordMiss(buck.getKey());
      else this.stats.recordHit(buck.getKey());
    }

    return result;
  }
Beispiel #8
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);
  }
Beispiel #9
0
 @Test
 public void parse() throws Exception {
   String header =
       "no-cache, no-store, max-age=1, s-maxage=2, public, must-revalidate, "
           + "max-stale=3, min-fresh=4, only-if-cached, no-transform";
   CacheControl cacheControl =
       CacheControl.parse(new Headers.Builder().set("Cache-Control", header).build());
   assertTrue(cacheControl.noCache());
   assertTrue(cacheControl.noStore());
   assertEquals(1, cacheControl.maxAgeSeconds());
   assertEquals(2, cacheControl.sMaxAgeSeconds());
   assertTrue(cacheControl.isPublic());
   assertTrue(cacheControl.mustRevalidate());
   assertEquals(3, cacheControl.maxStaleSeconds());
   assertEquals(4, cacheControl.minFreshSeconds());
   assertTrue(cacheControl.onlyIfCached());
   assertTrue(cacheControl.noTransform());
   assertEquals(header, cacheControl.toString());
 }
Beispiel #10
0
 @Test
 public void parseEmpty() throws Exception {
   CacheControl cacheControl =
       CacheControl.parse(new Headers.Builder().set("Cache-Control", "").build());
   assertEquals("", cacheControl.toString());
   assertFalse(cacheControl.noCache());
   assertFalse(cacheControl.noStore());
   assertEquals(-1, cacheControl.maxAgeSeconds());
   assertEquals(-1, cacheControl.sMaxAgeSeconds());
   assertFalse(cacheControl.isPublic());
   assertFalse(cacheControl.mustRevalidate());
   assertEquals(-1, cacheControl.maxStaleSeconds());
   assertEquals(-1, cacheControl.minFreshSeconds());
   assertFalse(cacheControl.onlyIfCached());
   assertFalse(cacheControl.mustRevalidate());
 }
Beispiel #11
0
  @Test
  public void completeBuilder() throws Exception {
    CacheControl cacheControl =
        new CacheControl.Builder()
            .noCache()
            .noStore()
            .maxAge(1, TimeUnit.SECONDS)
            .maxStale(2, TimeUnit.SECONDS)
            .minFresh(3, TimeUnit.SECONDS)
            .onlyIfCached()
            .noTransform()
            .build();
    assertEquals(
        "no-cache, no-store, max-age=1, max-stale=2, min-fresh=3, only-if-cached, "
            + "no-transform",
        cacheControl.toString());
    assertTrue(cacheControl.noCache());
    assertTrue(cacheControl.noStore());
    assertEquals(1, cacheControl.maxAgeSeconds());
    assertEquals(2, cacheControl.maxStaleSeconds());
    assertEquals(3, cacheControl.minFreshSeconds());
    assertTrue(cacheControl.onlyIfCached());

    // These members are accessible to response headers only.
    assertEquals(-1, cacheControl.sMaxAgeSeconds());
    assertFalse(cacheControl.isPublic());
    assertFalse(cacheControl.mustRevalidate());
  }
Beispiel #12
0
 @Test
 public void emptyBuilderIsEmpty() throws Exception {
   CacheControl cacheControl = new CacheControl.Builder().build();
   assertEquals("", cacheControl.toString());
   assertFalse(cacheControl.noCache());
   assertFalse(cacheControl.noStore());
   assertEquals(-1, cacheControl.maxAgeSeconds());
   assertEquals(-1, cacheControl.sMaxAgeSeconds());
   assertFalse(cacheControl.isPublic());
   assertFalse(cacheControl.mustRevalidate());
   assertEquals(-1, cacheControl.maxStaleSeconds());
   assertEquals(-1, cacheControl.minFreshSeconds());
   assertFalse(cacheControl.onlyIfCached());
   assertFalse(cacheControl.mustRevalidate());
 }
Beispiel #13
0
 @Test
 public void timePrecisionIsTruncatedToSeconds() throws Exception {
   CacheControl cacheControl =
       new CacheControl.Builder().maxAge(4999, TimeUnit.MILLISECONDS).build();
   assertEquals(4, cacheControl.maxAgeSeconds());
 }
Beispiel #14
0
 static {
   RuntimeDelegate.setInstance(new RuntimeDelegateImpl());
   cacheControl = new CacheControl();
   cacheControl.setNoCache(true);
   cacheControl.setNoStore(true);
 }
Beispiel #15
0
 /**
  * Returns the cache control directives for this response. This is never null, even if this
  * response contains no {@code Cache-Control} header.
  */
 public CacheControl cacheControl() {
   CacheControl result = cacheControl;
   return result != null ? result : (cacheControl = CacheControl.parse(headers));
 }
Beispiel #16
0
 private CacheControl cacheControlNoStore() {
   CacheControl cacheControl = new CacheControl();
   cacheControl.setNoStore(true);
   return cacheControl;
 }