@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
  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();
  }
예제 #3
0
 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);
   }
 }
예제 #4
0
  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();
  }
예제 #5
0
 /**
  * Edit the response headers to indicating no caching.
  *
  * @param response response
  * @return builder
  */
 protected ResponseBuilder noCache(final ResponseBuilder response) {
   final CacheControl cacheControl = new CacheControl();
   cacheControl.setPrivate(true);
   cacheControl.setNoCache(true);
   cacheControl.setNoStore(true);
   return response.cacheControl(cacheControl);
 }
예제 #6
0
  @GET
  @Path("/all")
  @AnonymousAllowed
  public Response getLinks(@QueryParam("gadgetId") Long gadgetId) {
    final ApplicationUser applicationUser = authenticationContext.getUser();
    final User user = applicationUser.getDirectoryUser();

    if (this.justStarted) {
      Map<String, String> userPrefs =
          portletConfigurationManager.getByPortletId(gadgetId).getUserPrefs();
      // TODO: pass in the name of used UserPref as ajax parameter
      String allLinks = userPrefs.get("allLinks");
      if (customlinks.isEmpty() && allLinks != null && allLinks != "") userPrefProcess(allLinks);

      this.justStarted = false;
    }

    if (customlinks.isEmpty()) {
      CacheControl cc = new CacheControl();
      cc.setNoCache(true);
      return Response.ok(new Warning()).cacheControl(cc).build();
    }
    CacheControl cc = new CacheControl();
    cc.setNoCache(true);
    return Response.ok(customlinks).cacheControl(cc).build();
  }
 @Test
 public void testMultiplePrivateFields() {
   CacheControl cc = new CacheControl();
   cc.setPrivate(true);
   cc.getPrivateFields().add("a");
   cc.getPrivateFields().add("b");
   assertTrue(cc.toString().contains("private=\"a,b\""));
 }
예제 #8
0
 @GET
 @Path("/validate")
 public Response validateConfig() {
   // TODO: manipulate changed userPrefs here
   CacheControl cc = new CacheControl();
   cc.setNoCache(true);
   return Response.ok("No input validation errors found.").cacheControl(cc).build();
 }
예제 #9
0
  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);
  }
 @Test
 public void testMultipleNoCacheFields() {
   CacheControl cc = new CacheControl();
   cc.setNoCache(true);
   cc.getNoCacheFields().add("c");
   cc.getNoCacheFields().add("d");
   assertTrue(cc.toString().contains("no-cache=\"c,d\""));
 }
 @Test
 public void testFromSimpleString() {
   CacheControl c = CacheControl.valueOf("public,must-revalidate");
   assertTrue(!c.isPrivate() && !c.isNoStore() && c.isMustRevalidate() && !c.isProxyRevalidate());
   assertTrue(
       !c.isNoCache()
           && !c.isNoTransform()
           && c.getNoCacheFields().size() == 0
           && c.getPrivateFields().size() == 0);
 }
예제 #12
0
  public ClientResponse updateOnNotModified(
      ClientRequest request, BrowserCache.Entry old, BaseClientResponse response) throws Exception {
    old.getHeaders().remove(HttpHeaders.CACHE_CONTROL);
    old.getHeaders().remove(HttpHeaders.EXPIRES);
    old.getHeaders().remove(HttpHeaders.LAST_MODIFIED);
    String cc = (String) response.getResponseHeaders().getFirst(HttpHeaders.CACHE_CONTROL);
    String exp = (String) response.getResponseHeaders().getFirst(HttpHeaders.EXPIRES);
    int expires = -1;

    if (cc != null) {
      CacheControl cacheControl = CacheControl.valueOf(cc);
      if (cacheControl.isNoCache()) {
        return createClientResponse(request, old);
      }
      expires = cacheControl.getMaxAge();
    } else if (exp != null) {
      Date date = DateUtil.parseDate(exp);
      expires = (int) ((date.getTime() - System.currentTimeMillis()) / 1000);
    }

    if (cc != null) {
      old.getHeaders().putSingle(HttpHeaders.CACHE_CONTROL, cc);
    }
    if (exp != null) {
      old.getHeaders().putSingle(HttpHeaders.CACHE_CONTROL, exp);
    }

    String lastModified =
        (String) response.getResponseHeaders().getFirst(HttpHeaders.LAST_MODIFIED);
    String etag = (String) response.getResponseHeaders().getFirst(HttpHeaders.ETAG);

    if (etag == null) etag = old.getHeaders().getFirst(HttpHeaders.ETAG);
    else old.getHeaders().putSingle(HttpHeaders.ETAG, etag);

    if (lastModified != null) {
      old.getHeaders().putSingle(HttpHeaders.LAST_MODIFIED, lastModified);
    }

    if (etag == null && lastModified == null && cc == null && exp == null) // don't cache
    {
      return createClientResponse(request, old);
    }

    BrowserCache.Entry entry =
        cache.put(
            request.getUri(),
            old.getMediaType(),
            old.getHeaders(),
            old.getCached(),
            expires,
            etag,
            lastModified);
    return createClientResponse(request, entry);
  }
 @Test
 public void testCacheExtensionToString() {
   CacheControl cc = new CacheControl();
   cc.getCacheExtension().put("ext1", null);
   cc.getCacheExtension().put("ext2", "value2");
   cc.getCacheExtension().put("ext3", "value 3");
   String value = cc.toString();
   assertTrue(value.indexOf("ext1") != -1 && value.indexOf("ext1=") == -1);
   assertTrue(value.indexOf("ext2=value2") != -1);
   assertTrue(value.indexOf("ext3=\"value 3\"") != -1);
 }
 private Response response(String redirectUri, boolean asRequest)
     throws ProcessingException, ConfigurationException, IOException {
   URI uri = generateURI(redirectUri, asRequest);
   if (logger.isDebugEnabled()) logger.trace("redirect-binding uri: " + uri.toString());
   CacheControl cacheControl = new CacheControl();
   cacheControl.setNoCache(true);
   return Response.status(302)
       .location(uri)
       .header("Pragma", "no-cache")
       .header("Cache-Control", "no-cache, no-store")
       .build();
 }
  /**
   * 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();
  }
  @Test
  public void ok() throws Exception {
    // given
    final Response resp = resource.version();

    // when
    final RestfulResponse<VersionRepresentation> restfulResponse = RestfulResponse.ofT(resp);

    // then
    final CacheControl cacheControl = restfulResponse.getHeader(Header.CACHE_CONTROL);
    assertThat(cacheControl, hasMaxAge(24 * 60 * 60));
    assertThat(cacheControl.getMaxAge(), is(24 * 60 * 60));
  }
예제 #17
0
 /**
  * Builds the xml response.
  *
  * @param currentFolder The current folder.
  * @param language The language.
  * @param host The server address on which the gadget is deployed.
  * @return the response
  * @throws Exception the exception
  */
 public Response buildXMLResponse(String currentFolder, String language, String host)
     throws Exception {
   List<ApplicationCategory> applicationCategories = getGadgetCategories();
   Element rootElement = createRootElement(currentFolder, applicationCategories, language, host);
   Document document = rootElement.getOwnerDocument();
   CacheControl cacheControl = new CacheControl();
   cacheControl.setNoCache(true);
   cacheControl.setNoStore(true);
   DateFormat dateFormat = new SimpleDateFormat(IF_MODIFIED_SINCE_DATE_FORMAT);
   return Response.ok(new DOMSource(document), MediaType.TEXT_XML)
       .cacheControl(cacheControl)
       .header(LAST_MODIFIED_PROPERTY, dateFormat.format(new Date()))
       .build();
 }
예제 #18
0
  /**
   * Checks permission of the currently logged-in user on any test by the given test Id. The input
   * parameters will be in the URL of the test.
   *
   * @param username The given user's Id, or the currently logged-in user.
   * @param testid The given test Id on which the permission is checked.
   * @param type The test type: _private_, _public_ or _shared_.
   * @return The JSON data value will be returned.
   * @throws Exception
   * @anchor EStudyApplication.checkPermission @LevelAPI Experimental
   */
  @GET
  @RolesAllowed("users")
  @Path("/checkPermission/{username}/{testid}/{type}/")
  public Response checkPermission(
      @PathParam("username") String username,
      @PathParam("testid") String calendarId,
      @PathParam("type") String type)
      throws Exception {
    JSONData data = new JSONData();
    CacheControl cacheControl = new CacheControl();
    cacheControl.setNoCache(true);
    cacheControl.setNoStore(true);

    return Response.ok(data, MediaType.APPLICATION_JSON).cacheControl(cacheControl).build();
  }
 @Test
 public void testResource2() throws Exception {
   ClientRequest request = new ClientRequest(generateURL("/nocache"));
   try {
     ClientResponse<?> response = request.get();
     Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());
     String value = response.getResponseHeaders().getFirst("cache-control");
     Assert.assertEquals("no-cache", value);
     System.out.println("Cache-Control: " + value);
     CacheControl cc = CacheControl.valueOf(value);
     Assert.assertTrue(cc.isNoCache());
     response.releaseConnection();
   } catch (Exception e) {
     throw new RuntimeException(e);
   }
 }
예제 #20
0
  @Autowired
  public IncogitoResource(IncogitoApplication incogito) {
    this.incogito = incogito;

    cacheForOneHourCacheControl = new CacheControl();
    cacheForOneHourCacheControl.setMaxAge(3600);
  }
  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());
    }
  }
 @Test
 public void testToString() {
   String s =
       "private=\"foo\",no-cache=\"bar\",no-store,no-transform,"
           + "must-revalidate,proxy-revalidate,max-age=2,s-maxage=3";
   String parsed = CacheControl.valueOf(s).toString();
   assertEquals(s, parsed);
 }
 @Test
 public void testResource() throws Exception {
   ClientRequest request = new ClientRequest(generateURL("/maxage"));
   try {
     ClientResponse<?> response = request.get();
     Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatus());
     System.out.println(
         "Cache-Control: " + response.getResponseHeaders().getFirst("cache-control"));
     CacheControl cc =
         CacheControl.valueOf(response.getResponseHeaders().getFirst("cache-control"));
     Assert.assertFalse(cc.isPrivate());
     Assert.assertEquals(3600, cc.getMaxAge());
     response.releaseConnection();
   } catch (Exception e) {
     throw new RuntimeException(e);
   }
 }
 private void setHttpHeaders(Exchange exchange, Response.ResponseBuilder responseBuilder) {
   final String contentType = (String) exchange.getIn().getHeader(Exchange.CONTENT_TYPE);
   if (contentType != null) {
     responseBuilder.header(HttpHeaders.CONTENT_TYPE, contentType);
   }
   final String fileName = (String) exchange.getIn().getHeader(Exchange.FILE_NAME);
   if (fileName != null) {
     responseBuilder.header(
         HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + fileName + "\"");
   }
   final Boolean cache =
       exchange.getIn().getHeader(Exchange.DISABLE_HTTP_STREAM_CACHE, Boolean.class);
   if (cache == null || cache) {
     final CacheControl cacheControl = new CacheControl();
     cacheControl.setNoCache(true);
     responseBuilder.cacheControl(cacheControl);
   }
 }
예제 #25
0
  @DELETE
  @Path("/{value}")
  public Response delete(@PathParam("value") final String value) {
    // TODO: should use this for deleting items from restful table
    int v = Integer.valueOf(value);
    boolean flag = false;
    for (CustomlinksResourceModel.Link link : customlinks)
      if (link.getLinkNum() == v) {
        customlinks.remove(link);
        flag = true;
        break;
      }
    CacheControl cc = new CacheControl();
    cc.setNoCache(true);
    if (flag) return Response.ok(customlinks).cacheControl(cc).build();

    return Response.status(204).cacheControl(cc).build();
  }
예제 #26
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();
  }
예제 #27
0
  public ClientResponse cacheIfPossible(ClientRequest request, BaseClientResponse response)
      throws Exception {
    String cc = (String) response.getResponseHeaders().getFirst(HttpHeaders.CACHE_CONTROL);
    String exp = (String) response.getResponseHeaders().getFirst(HttpHeaders.EXPIRES);
    int expires = -1;

    if (cc != null) {
      CacheControl cacheControl = CacheControl.valueOf(cc);
      if (cacheControl.isNoCache()) return response;
      expires = cacheControl.getMaxAge();
    } else if (exp != null) {
      Date date = DateUtil.parseDate(exp);
      expires = (int) ((date.getTime() - System.currentTimeMillis()) / 1000);
    }

    String lastModified =
        (String) response.getResponseHeaders().getFirst(HttpHeaders.LAST_MODIFIED);
    String etag = (String) response.getResponseHeaders().getFirst(HttpHeaders.ETAG);

    String contentType = (String) response.getResponseHeaders().getFirst(HttpHeaders.CONTENT_TYPE);

    byte[] cached =
        ReadFromStream.readFromStream(1024, response.getStreamFactory().getInputStream());
    response.getStreamFactory().performReleaseConnection();

    MediaType mediaType = MediaType.valueOf(contentType);
    final BrowserCache.Entry entry =
        cache.put(
            request.getUri(),
            mediaType,
            response.getResponseHeaders(),
            cached,
            expires,
            etag,
            lastModified);

    response.setStreamFactory(new CachedStreamFactory(entry));

    return response;
  }
예제 #28
0
  @POST
  @Path("/update")
  // TODO: modify data consumed later
  public Response update(
      @FormParam("value") String value,
      @FormParam("label") String label,
      @FormParam("url") String url,
      @FormParam("text") String text) {
    boolean flag = false;
    for (CustomlinksResourceModel.Link link : customlinks)
      if (link.getLinkNum() == Integer.valueOf(value)) {
        link.setLabel(label);
        link.setUrl(url);
        link.setText(text);
        flag = true;
      }

    CacheControl cc = new CacheControl();
    cc.setNoCache(true);
    if (flag) return Response.ok(customlinks).cacheControl(cc).build();

    return Response.status(204).cacheControl(cc).build();
  }
예제 #29
0
  /**
   * 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();
  }
예제 #30
0
 @POST
 @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
 public Response createVersion(
     @FormParam("label") String label,
     @FormParam("url") String url,
     @FormParam("text") String text) {
   // if there is no duplicate, the new link will add to the link collections and a response will
   // be sent back
   if (!duplicateCheck(label)) {
     CustomlinksResourceModel.Link reply =
         new CustomlinksResourceModel.Link(getNextLinkNum(), label, url, text);
     customlinks.add(reply);
     // TODO: add new link to UP_allLinks as well, this is now be done in jQuery
     CacheControl cc = new CacheControl();
     cc.setNoCache(true);
     return Response.ok(reply).cacheControl(cc).build();
   }
   // if there is duplicate, 204 will be sent and no other response
   else {
     CacheControl cc = new CacheControl();
     cc.setNoCache(true);
     return Response.status(204).cacheControl(cc).build();
   }
 }