コード例 #1
1
  @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();
  }
コード例 #2
0
  @Autowired
  public IncogitoResource(IncogitoApplication incogito) {
    this.incogito = incogito;

    cacheForOneHourCacheControl = new CacheControl();
    cacheForOneHourCacheControl.setMaxAge(3600);
  }
コード例 #3
0
ファイル: Renderer.java プロジェクト: jmfield2/usf-mobullity
  private static Response generateStreamingGeotiffResponse(final GridCoverage2D coverage) {

    StreamingOutput streamingOutput =
        new StreamingOutput() {
          public void write(OutputStream outStream) {
            try {
              long t0 = System.currentTimeMillis();
              GeoTiffWriteParams wp = new GeoTiffWriteParams();
              wp.setCompressionMode(GeoTiffWriteParams.MODE_EXPLICIT);
              wp.setCompressionType("LZW");
              ParameterValueGroup params = new GeoTiffFormat().getWriteParameters();
              params
                  .parameter(AbstractGridFormat.GEOTOOLS_WRITE_PARAMS.getName().toString())
                  .setValue(wp);
              new GeoTiffWriter(outStream)
                  .write(
                      coverage,
                      (GeneralParameterValue[])
                          params.values().toArray(new GeneralParameterValue[1]));
              // new GeoTiffWriter(outStream).write(coverage, null); //wasn't this line writing
              // twice and trashing compressed version?
              long t1 = System.currentTimeMillis();
              LOG.debug("wrote geotiff in {}msec", t1 - t0);
            } catch (Exception e) {
              LOG.error("exception while preparing geotiff : {}", e.getMessage());
              throw new WebApplicationException(e);
            }
          }
        };

    CacheControl cc = new CacheControl();
    cc.setMaxAge(3600);
    cc.setNoCache(false);
    return Response.ok(streamingOutput).type("image/geotiff").cacheControl(cc).build();
  }
コード例 #4
0
ファイル: Renderer.java プロジェクト: jmfield2/usf-mobullity
  public static Response generateStreamingImageResponse(
      final BufferedImage image, final MIMEImageFormat format) {

    if (image == null) {
      LOG.warn("response image is null");
    }

    StreamingOutput streamingOutput =
        new StreamingOutput() {
          public void write(OutputStream outStream) {
            try {
              long t0 = System.currentTimeMillis();
              ImageIO.write(image, format.type, outStream);
              long t1 = System.currentTimeMillis();
              LOG.debug("wrote image in {}msec", (int) (t1 - t0));
            } catch (Exception e) {
              LOG.error("exception while preparing image : {}", e.getMessage());
              throw new WebApplicationException(e);
            }
          }
        };

    CacheControl cc = new CacheControl();
    cc.setMaxAge(3600);
    cc.setNoCache(false);
    return Response.ok(streamingOutput).type(format.toString()).cacheControl(cc).build();
  }
コード例 #5
0
ファイル: CacheControlFilter.java プロジェクト: 9esa/Resteasy
 public void filter(ContainerRequestContext req, ContainerResponseContext res) throws IOException {
   if (req.getMethod().equals("GET")) {
     CacheControl cc = new CacheControl();
     cc.setMaxAge(this.maxAge);
     res.getHeaders().add("Cache-Control", cc);
   }
 }
コード例 #6
0
ファイル: AuthService.java プロジェクト: rutadaki/Rutadaki
  private Response.ResponseBuilder getNoCacheResponseBuilder(Response.Status status) {
    CacheControl cc = new CacheControl();
    cc.setNoCache(true);
    cc.setMaxAge(-1);
    cc.setMustRevalidate(true);

    return Response.status(status).cacheControl(cc);
  }
コード例 #7
0
  /**
   * Get the binary content of a datastream
   *
   * @param rangeValue the range value
   * @return Binary blob
   * @throws IOException if io exception occurred
   */
  protected Response getBinaryContent(final String rangeValue) throws IOException {
    final FedoraBinary binary = (FedoraBinary) resource();

    // we include an explicit etag, because the default behavior is to use the JCR node's etag, not
    // the jcr:content node digest. The etag is only included if we are not within a transaction.
    final String txId = TransactionServiceImpl.getCurrentTransactionId(session());
    if (txId == null) {
      checkCacheControlHeaders(request, servletResponse, binary, session());
    }
    final CacheControl cc = new CacheControl();
    cc.setMaxAge(0);
    cc.setMustRevalidate(true);
    Response.ResponseBuilder builder;

    if (rangeValue != null && rangeValue.startsWith("bytes")) {

      final Range range = Range.convert(rangeValue);

      final long contentSize = binary.getContentSize();

      final String endAsString;

      if (range.end() == -1) {
        endAsString = Long.toString(contentSize - 1);
      } else {
        endAsString = Long.toString(range.end());
      }

      final String contentRangeValue =
          String.format("bytes %s-%s/%s", range.start(), endAsString, contentSize);

      if (range.end() > contentSize || (range.end() == -1 && range.start() > contentSize)) {

        builder =
            status(REQUESTED_RANGE_NOT_SATISFIABLE).header("Content-Range", contentRangeValue);
      } else {
        final RangeRequestInputStream rangeInputStream =
            new RangeRequestInputStream(binary.getContent(), range.start(), range.size());

        builder =
            status(PARTIAL_CONTENT)
                .entity(rangeInputStream)
                .header("Content-Range", contentRangeValue);
      }

    } else {
      final InputStream content = binary.getContent();
      builder = ok(content);
    }

    // we set the content-type explicitly to avoid content-negotiation from getting in the way
    return builder.type(binary.getMimeType()).cacheControl(cc).build();
  }
コード例 #8
0
  private static void evaluateRequestPreconditions(
      final Request request,
      final HttpServletResponse servletResponse,
      final FedoraResource resource,
      final Session session,
      final boolean cacheControl) {

    final String txId = TransactionServiceImpl.getCurrentTransactionId(session);
    if (txId != null) {
      // Force cache revalidation if in a transaction
      servletResponse.addHeader(CACHE_CONTROL, "must-revalidate");
      servletResponse.addHeader(CACHE_CONTROL, "max-age=0");
      return;
    }

    final EntityTag etag = new EntityTag(resource.getEtagValue());
    final Date date = resource.getLastModifiedDate();
    final Date roundedDate = new Date();

    if (date != null) {
      roundedDate.setTime(date.getTime() - date.getTime() % 1000);
    }

    Response.ResponseBuilder builder = request.evaluatePreconditions(etag);
    if (builder != null) {
      builder = builder.entity("ETag mismatch");
    } else {
      builder = request.evaluatePreconditions(roundedDate);
      if (builder != null) {
        builder = builder.entity("Date mismatch");
      }
    }

    if (builder != null && cacheControl) {
      final CacheControl cc = new CacheControl();
      cc.setMaxAge(0);
      cc.setMustRevalidate(true);
      // here we are implicitly emitting a 304
      // the exception is not an error, it's genuinely
      // an exceptional condition
      builder = builder.cacheControl(cc).lastModified(date).tag(etag);
    }
    if (builder != null) {
      throw new WebApplicationException(builder.build());
    }
  }
コード例 #9
0
  @GET
  @Path("/")
  @ApiOperation(
      value = "List the available reports",
      responseClass = "String",
      multiValueResponse = true)
  @Produces({
    MediaType.TEXT_HTML,
    MediaType.APPLICATION_JSON,
    MediaType.APPLICATION_XML,
    "text/csv"
  })
  public Response listReports(@Context HttpHeaders headers, @Context UriInfo uriInfo) {

    List<Link> links = new ArrayList<Link>(reports.length);
    for (String report : reports) {
      UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
      uriBuilder.path("/reports/{report}");
      URI uri = uriBuilder.build(report);
      Link link = new Link(report, uri.toString());
      links.add(link);
    }

    MediaType mediaType = headers.getAcceptableMediaTypes().get(0);
    Response.ResponseBuilder builder = Response.ok();
    if (mediaType.getType().equals("text") && mediaType.getSubtype().equals("csv")) {
      StringBuilder stringBuilder = new StringBuilder();
      stringBuilder.append("Report,URL\n");
      for (Link link : links) {
        stringBuilder.append(link.getRel()).append(",").append(link.getHref());
        stringBuilder.append('\n');
      }
      builder.entity(stringBuilder.toString());
    } else if (mediaType.equals(MediaType.TEXT_HTML_TYPE)) {
      builder.entity(renderTemplate("reportIndex", links));
    } else {
      GenericEntity<List<Link>> list = new GenericEntity<List<Link>>(links) {};
      builder.entity(list);
    }
    CacheControl cacheControl = new CacheControl();
    cacheControl.setMaxAge(86400); // TODO 1 day or longer? What unit is this anyway?
    builder.cacheControl(cacheControl);
    return builder.build();
  }
コード例 #10
0
ファイル: FedoraContent.java プロジェクト: paluchas/fcrepo4
  /**
   * Get the binary content of a datastream
   *
   * @param pathList
   * @return Binary blob
   * @throws RepositoryException
   */
  @GET
  public Response getContent(
      @PathParam("path") List<PathSegment> pathList, @Context final Request request)
      throws RepositoryException {

    String path = toPath(pathList);
    final Datastream ds = datastreamService.getDatastream(path);

    final EntityTag etag = new EntityTag(ds.getContentDigest().toString());
    final Date date = ds.getLastModifiedDate();
    final Date roundedDate = new Date();
    roundedDate.setTime(date.getTime() - date.getTime() % 1000);
    ResponseBuilder builder = request.evaluatePreconditions(roundedDate, etag);

    final CacheControl cc = new CacheControl();
    cc.setMaxAge(0);
    cc.setMustRevalidate(true);

    if (builder == null) {
      builder = Response.ok(ds.getContent(), ds.getMimeType());
    }

    return builder.cacheControl(cc).lastModified(date).tag(etag).build();
  }
コード例 #11
0
 static {
   cache.setMaxAge(60); // 60 seconds
   cache.setPrivate(true); // no caching on the shared proxy, only the final client
   cache.setNoStore(true); // client cannot persist to disk, only in-memory.
 }