javax.ws.rs.core.EntityTag Java Examples

The following examples show how to use javax.ws.rs.core.EntityTag. 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: RequestImpl.java    From cxf with Apache License 2.0 6 votes vote down vote up
private ResponseBuilder evaluateIfMatch(EntityTag eTag, Date date) {
    List<String> ifMatch = headers.getRequestHeader(HttpHeaders.IF_MATCH);

    if (ifMatch == null || ifMatch.isEmpty()) {
        return date == null ? null : evaluateIfNotModifiedSince(date);
    }

    try {
        for (String value : ifMatch) {
            if ("*".equals(value)) {
                return null;
            }
            EntityTag requestTag = EntityTag.valueOf(value);
            // must be a strong comparison
            if (!requestTag.isWeak() && !eTag.isWeak() && requestTag.equals(eTag)) {
                return null;
            }
        }
    } catch (IllegalArgumentException ex) {
        // ignore
    }
    return Response.status(Response.Status.PRECONDITION_FAILED).tag(eTag);
}
 
Example #2
Source File: TestClass22.java    From jaxrs-analyzer with Apache License 2.0 6 votes vote down vote up
@javax.ws.rs.GET public Response method() {
    Response.ResponseBuilder responseBuilder = Response.ok();
    responseBuilder.header("X-Test", "Hello");
    responseBuilder.cacheControl(CacheControl.valueOf(""));
    responseBuilder.contentLocation(URI.create(""));
    responseBuilder.cookie();
    responseBuilder.entity(12d);
    responseBuilder.expires(new Date());
    responseBuilder.language(Locale.ENGLISH);
    responseBuilder.encoding("UTF-8");
    responseBuilder.lastModified(new Date());
    responseBuilder.link(URI.create(""), "rel");
    responseBuilder.location(URI.create(""));
    responseBuilder.status(433);
    responseBuilder.tag(new EntityTag(""));
    responseBuilder.type(MediaType.APPLICATION_JSON_TYPE);
    responseBuilder.variants(new LinkedList<>());

    return responseBuilder.build();
}
 
Example #3
Source File: ETagResponseFilterTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
/** Check if ETag is generated for a list of JSON */
@Test
public void filterListEntityTest() throws Exception {

  final ContainerResponse response =
      resourceLauncher.service(
          HttpMethod.GET, SERVICE_PATH + "/list", BASE_URI, null, null, null);
  assertEquals(response.getStatus(), OK.getStatusCode());
  // check entity
  Assert.assertEquals(response.getEntity(), Arrays.asList("a", "b", "c"));
  // Check etag
  List<Object> headerTags = response.getHttpHeaders().get("ETag");
  Assert.assertNotNull(headerTags);
  Assert.assertEquals(headerTags.size(), 1);
  Assert.assertEquals(headerTags.get(0), new EntityTag("900150983cd24fb0d6963f7d28e17f72"));
}
 
Example #4
Source File: ETagResponseFilterTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
/** Check if ETag is generated for a simple entity of JSON */
@Test
public void filterSingleEntityTest() throws Exception {

  final ContainerResponse response =
      resourceLauncher.service(
          HttpMethod.GET, SERVICE_PATH + "/single", BASE_URI, null, null, null);
  assertEquals(response.getStatus(), OK.getStatusCode());
  // check entity
  Assert.assertEquals(response.getEntity(), "hello");
  // Check etag
  List<Object> headerTags = response.getHttpHeaders().get("ETag");
  Assert.assertNotNull(headerTags);
  Assert.assertEquals(headerTags.size(), 1);
  Assert.assertEquals(headerTags.get(0), new EntityTag("5d41402abc4b2a76b9719d911017c592"));
}
 
Example #5
Source File: Item.java    From Processor with Apache License 2.0 6 votes vote down vote up
@Override
public Response put(Dataset dataset)
{
    Model existing = getService().getDatasetAccessor().getModel(getURI().toString());

    if (!existing.isEmpty()) // remove existing representation
    {
        EntityTag entityTag = new EntityTag(Long.toHexString(ModelUtils.hashModel(dataset.getDefaultModel())));
        ResponseBuilder rb = getRequest().evaluatePreconditions(entityTag);
        if (rb != null)
        {
            if (log.isDebugEnabled()) log.debug("PUT preconditions were not met for resource: {} with entity tag: {}", this, entityTag);
            return rb.build();
        }
    }
    
    if (log.isDebugEnabled()) log.debug("PUT GRAPH {} to GraphStore", getURI());
    getService().getDatasetAccessor().putModel(getURI().toString(), dataset.getDefaultModel());
    
    if (existing.isEmpty()) return Response.created(getURI()).build();
    else return Response.ok(dataset).build();
}
 
Example #6
Source File: BinaryResourceDownloadResponseBuilder.java    From eplmp with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Apply cache policy to a response.
 *
 * @param response     The response builder.
 * @param eTag         The ETag of the resource.
 * @param lastModified The last modified date of the resource.
 * @param isToBeCached     Boolean to set whether we should define maxage of cache control
 * @return The response builder with the cache policy.
 */
private static Response.ResponseBuilder applyCachePolicyToResponse(Response.ResponseBuilder response, EntityTag eTag, Date lastModified, boolean isToBeCached) {

    if (isToBeCached) {
        CacheControl cc = new CacheControl();
        cc.setMaxAge(CACHE_SECOND);
        cc.setNoTransform(false);
        cc.setPrivate(false);

        Calendar expirationDate = Calendar.getInstance();
        expirationDate.add(Calendar.SECOND, CACHE_SECOND);
        response.cacheControl(cc)
                .expires(expirationDate.getTime());

    }

    return response.lastModified(lastModified)
            .tag(eTag);
}
 
Example #7
Source File: FramedResource.java    From org.openntf.domino with Apache License 2.0 6 votes vote down vote up
private ResponseBuilder getBuilder(final String jsonEntity, final Date lastMod, final boolean includeEtag, final Request request) {
	String etagSource = DominoUtils.md5(jsonEntity);
	EntityTag etag = new EntityTag(etagSource);
	ResponseBuilder berg = null;
	if (request != null) {
		berg = request.evaluatePreconditions(etag);
	}
	if (berg == null) {
		// System.out.println("TEMP DEBUG creating a new builder");
		berg = Response.ok();
		if (includeEtag) {
			berg.tag(etag);
		}
		berg.type(MediaType.APPLICATION_JSON_TYPE);
		berg.entity(jsonEntity);
		berg.lastModified(lastMod);
		CacheControl cc = new CacheControl();
		cc.setMustRevalidate(true);
		cc.setPrivate(true);
		cc.setMaxAge(86400);
		cc.setNoTransform(true);
		berg.cacheControl(cc);
	}
	return berg;
}
 
Example #8
Source File: AddETagFilter.java    From syncope with Apache License 2.0 6 votes vote down vote up
@Override
public void filter(final ContainerRequestContext reqCtx, final ContainerResponseContext resCtx) throws IOException {
    if (resCtx.getEntityTag() == null) {
        AnyTO annotated = null;
        if (resCtx.getEntity() instanceof AnyTO) {
            annotated = (AnyTO) resCtx.getEntity();
        } else if (resCtx.getEntity() instanceof ProvisioningResult) {
            EntityTO entity = ((ProvisioningResult<?>) resCtx.getEntity()).getEntity();
            if (entity instanceof AnyTO) {
                annotated = (AnyTO) entity;
            }
        }
        if (annotated != null) {
            String etagValue = annotated.getETagValue();
            if (StringUtils.isNotBlank(etagValue)) {
                resCtx.getHeaders().add(HttpHeaders.ETAG, new EntityTag(etagValue).toString());
            }
        }
    }
}
 
Example #9
Source File: ContainerRequest.java    From everrest with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Comparison for If-None-Match header and ETag.
 *
 * @param etag
 *         the ETag
 * @return ResponseBuilder with status 412 (precondition failed) if If-None-Match header is MATCH to ETag and HTTP method is not GET or
 * HEAD. If method is GET or HEAD and If-None-Match is MATCH to ETag then ResponseBuilder with status 304 (not modified) will be
 * returned.
 */
private ResponseBuilder evaluateIfNoneMatch(EntityTag etag) {
    String ifNoneMatch = getRequestHeaders().getFirst(IF_NONE_MATCH);

    if (Strings.isNullOrEmpty(ifNoneMatch)) {
        return null;
    }

    EntityTag otherEtag = EntityTag.valueOf(ifNoneMatch);
    String httpMethod = getMethod();
    if (httpMethod.equals(GET) || httpMethod.equals(HEAD)) {
        if (eTagsWeakEqual(etag, otherEtag)) {
            return Response.notModified(etag);
        }
    } else {
        if (eTagsStrongEqual(etag, otherEtag)) {
            return Response.status(PRECONDITION_FAILED);
        }
    }
    return null;
}
 
Example #10
Source File: HttpUtils.java    From trellis with Apache License 2.0 6 votes vote down vote up
/**
 * Check for a conditional operation.
 * @param method the HTTP method
 * @param ifNoneMatch the If-None-Match header
 * @param etag the resource etag
 */
public static void checkIfNoneMatch(final String method, final String ifNoneMatch, final EntityTag etag) {
    if (ifNoneMatch == null) {
        return;
    }

    final Set<String> items = stream(ifNoneMatch.split(",")).map(String::trim).collect(toSet());
    if (isGetOrHead(method)) {
        if ("*".equals(ifNoneMatch) || items.stream().map(EntityTag::valueOf)
                .anyMatch(e -> e.equals(etag) || e.equals(new EntityTag(etag.getValue(), !etag.isWeak())))) {
            throw new RedirectionException(notModified().build());
        }
    } else {
        if ("*".equals(ifNoneMatch) || items.stream().map(EntityTag::valueOf).anyMatch(isEqual(etag))) {
            throw new ClientErrorException(status(PRECONDITION_FAILED).build());
        }
    }
 }
 
Example #11
Source File: ContainerRequest.java    From everrest with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public ResponseBuilder evaluatePreconditions(Date lastModified, EntityTag etag) {
    checkArgument(lastModified != null, "Null last modification date is not supported");
    checkArgument(etag != null, "Null ETag is not supported");

    ResponseBuilder responseBuilder = evaluateIfMatch(etag);
    if (responseBuilder != null) {
        return responseBuilder;
    }

    long lastModifiedTime = lastModified.getTime();
    responseBuilder = evaluateIfModified(lastModifiedTime);
    if (responseBuilder != null) {
        return responseBuilder;
    }

    responseBuilder = evaluateIfNoneMatch(etag);
    if (responseBuilder != null) {
        return responseBuilder;
    }

    return evaluateIfUnmodified(lastModifiedTime);
}
 
Example #12
Source File: BookStore.java    From cxf with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/books/response3/{bookId}/")
@Produces("application/xml")
public Response getBookAsResponse3(@PathParam("bookId") String id,
                                   @HeaderParam("If-Modified-Since") String modifiedSince
) throws BookNotFoundFault {
    Book entity = doGetBook(id);

    EntityTag etag = new EntityTag(Integer.toString(entity.hashCode()));

    CacheControl cacheControl = new CacheControl();
    cacheControl.setMaxAge(1);
    cacheControl.setPrivate(true);

    if (modifiedSince != null) {
        return Response.status(304).tag(etag)
            .cacheControl(cacheControl).lastModified(new Date()).build();
    } else {
        return Response.ok().tag(etag).entity(entity)
            .cacheControl(cacheControl).lastModified(new Date()).build();
    }
}
 
Example #13
Source File: RuntimeDelegateImpl.java    From cxf with Apache License 2.0 5 votes vote down vote up
public RuntimeDelegateImpl() {
    headerProviders.put(MediaType.class, new MediaTypeHeaderProvider());
    headerProviders.put(CacheControl.class, new CacheControlHeaderProvider());
    headerProviders.put(EntityTag.class, new EntityTagHeaderProvider());
    headerProviders.put(Cookie.class, new CookieHeaderProvider());
    headerProviders.put(NewCookie.class, new NewCookieHeaderProvider());
    headerProviders.put(Link.class, new LinkHeaderProvider());
    headerProviders.put(Date.class, new DateHeaderProvider());
}
 
Example #14
Source File: RequestImpl.java    From cxf with Apache License 2.0 5 votes vote down vote up
public ResponseBuilder evaluatePreconditions() {
    List<String> ifMatch = headers.getRequestHeader(HttpHeaders.IF_MATCH);
    if (ifMatch != null) {
        for (String value : ifMatch) {
            if (!"*".equals(value)) {
                return Response.status(Response.Status.PRECONDITION_FAILED).tag(EntityTag.valueOf(value));
            }
        }
    }
    return null;
}
 
Example #15
Source File: RequestImpl.java    From cxf with Apache License 2.0 5 votes vote down vote up
private ResponseBuilder evaluateIfNonMatch(EntityTag eTag, Date lastModified) {
    List<String> ifNonMatch = headers.getRequestHeader(HttpHeaders.IF_NONE_MATCH);

    if (ifNonMatch == null || ifNonMatch.isEmpty()) {
        return lastModified == null ? null : evaluateIfModifiedSince(lastModified);
    }

    String method = getMethod();
    boolean getOrHead = HttpMethod.GET.equals(method) || HttpMethod.HEAD.equals(method);
    try {
        for (String value : ifNonMatch) {
            boolean result = "*".equals(value);
            if (!result) {
                EntityTag requestTag = EntityTag.valueOf(value);
                result = getOrHead ? requestTag.equals(eTag)
                    : !requestTag.isWeak() && !eTag.isWeak() && requestTag.equals(eTag);
            }
            if (result) {
                Response.Status status = getOrHead ? Response.Status.NOT_MODIFIED
                    : Response.Status.PRECONDITION_FAILED;
                return Response.status(status).tag(eTag);
            }
        }
    } catch (IllegalArgumentException ex) {
        // ignore
    }
    return null;
}
 
Example #16
Source File: Meta.java    From syncope with Apache License 2.0 5 votes vote down vote up
@JsonCreator(mode = JsonCreator.Mode.PROPERTIES)
public Meta(
        @JsonProperty("resourceType") final Resource resourceType,
        @JsonProperty("created") final Date created,
        @JsonProperty("lastModified") final Date lastModified,
        @JsonProperty("version") final String version,
        @JsonProperty("location") final String location) {

    this.resourceType = resourceType;
    this.created = created;
    this.lastModified = lastModified;
    this.version = Optional.ofNullable(version).map(s -> new EntityTag(s, true)).orElse(null);
    this.location = location;
}
 
Example #17
Source File: SimpleService.java    From cxf with Apache License 2.0 5 votes vote down vote up
public Response perform(final Request request) {
    final Date lastModified = getLastModified();
    final EntityTag entityTag = getEntityTag();
    ResponseBuilder rb = request.evaluatePreconditions(lastModified, entityTag);
    if (rb == null) {
        rb = Response.ok();
    } else {
        // okay
    }
    return rb.build();
}
 
Example #18
Source File: EntityTagHeaderDelegateTest.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void parsesStringQuotedWeak() {
    EntityTag entityTag = entityTagHeaderDelegate.fromString("W/\"test \\\"test\\\"\"");

    assertTrue(entityTag.isWeak());
    assertEquals("test \"test\"", entityTag.getValue());
}
 
Example #19
Source File: ResponseBuilderImplTest.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void removesETagHeaderByNullEntityTag() {
    EntityTag tag = new EntityTag("foo");
    Response response = new ResponseBuilderImpl()
            .tag(tag)
            .tag((EntityTag)null)
            .build();
    assertNull(response.getHeaders().get("ETag"));
}
 
Example #20
Source File: BookStore.java    From cxf with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/books/response/{bookId}/")
@Produces("application/xml")
public Response getBookAsResponse(@PathParam("bookId") String id) throws BookNotFoundFault {
    Book entity = doGetBook(id);
    EntityTag etag = new EntityTag(Integer.toString(entity.hashCode()));

    CacheControl cacheControl = new CacheControl();
    cacheControl.setMaxAge(100000);
    cacheControl.setPrivate(true);

    return Response.ok().tag(etag).entity(entity).cacheControl(cacheControl).build();
}
 
Example #21
Source File: AbstractService.java    From syncope with Apache License 2.0 5 votes vote down vote up
protected ResponseBuilder checkETag(final Resource resource, final String key) {
    Date lastChange = anyDAO(resource).findLastChange(key);
    if (lastChange == null) {
        throw new NotFoundException("Resource" + key + " not found");
    }

    return messageContext.getRequest().
            evaluatePreconditions(new EntityTag(String.valueOf(lastChange.getTime()), true));
}
 
Example #22
Source File: ContainerRequest.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public ResponseBuilder evaluatePreconditions(EntityTag etag) {
    checkArgument(etag != null, "Null ETag is not supported");
    ResponseBuilder responseBuilder = evaluateIfMatch(etag);
    if (responseBuilder == null) {
        responseBuilder = evaluateIfNoneMatch(etag);
    }
    return responseBuilder;
}
 
Example #23
Source File: CustomerResource.java    From resteasy-examples with Apache License 2.0 5 votes vote down vote up
@GET
@Path("{id}")
@Produces("application/xml")
public Response getCustomer(@PathParam("id") int id,
                            @HeaderParam("If-None-Match") String sent,
                            @Context Request request)
{
   Customer cust = customerDB.get(id);
   if (cust == null)
   {
      throw new WebApplicationException(Response.Status.NOT_FOUND);
   }

   if (sent == null) System.out.println("No If-None-Match sent by client");

   EntityTag tag = new EntityTag(Integer.toString(cust.hashCode()));

   CacheControl cc = new CacheControl();
   cc.setMaxAge(5);


   Response.ResponseBuilder builder = request.evaluatePreconditions(tag);
   if (builder != null)
   {
      System.out.println("** revalidation on the server was successful");
      builder.cacheControl(cc);
      return builder.build();
   }


   // Preconditions not met!

   cust.setLastViewed(new Date().toString());
   builder = Response.ok(cust, "application/xml");
   builder.cacheControl(cc);
   builder.tag(tag);
   return builder.build();
}
 
Example #24
Source File: ResponseImpl.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public EntityTag getEntityTag() {
    Object value = getMetadata().getFirst(ETAG);
    if (value == null) {
        return null;
    }
    if (value instanceof EntityTag) {
        return (EntityTag)value;
    }
    return EntityTag.valueOf(value instanceof String ? (String)value : getHeaderAsString(value));
}
 
Example #25
Source File: ExceptionMapperBase.java    From Processor with Apache License 2.0 5 votes vote down vote up
public Response.ResponseBuilder getResponseBuilder(Dataset dataset)
{
    Variant variant = getRequest().selectVariant(getVariants(Dataset.class));
    if (variant == null) return getResponseBuilder(dataset.getDefaultModel()); // if quads are not acceptable, fallback to responding with the default graph
    
    Response.ResponseBuilder builder = new com.atomgraph.core.model.impl.Response(getRequest(),
            dataset,
            null,
            new EntityTag(Long.toHexString(com.atomgraph.core.model.impl.Response.hashDataset(dataset))),
            variant).
            getResponseBuilder().
        header("Link", new Link(getUriInfo().getBaseUri(), LDT.base.getURI(), null));
    if (getTemplateCall() != null) builder.header("Link", new Link(URI.create(getTemplateCall().getTemplate().getURI()), LDT.template.getURI(), null));

    if (getOntology() != null)
    {
        builder.header("Link", new Link(URI.create(getOntology().getURI()), LDT.ontology.getURI(), null));

        Reasoner reasoner = getOntology().getOntModel().getSpecification().getReasoner();
        if (reasoner instanceof GenericRuleReasoner)
        {
            List<Rule> rules = ((GenericRuleReasoner)reasoner).getRules();
            builder.header("Rules", RulePrinter.print(rules));
        }
    }
    
    return builder;
}
 
Example #26
Source File: ContainerRequest.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
private boolean eTagsStrongEqual(EntityTag etag, EntityTag otherEtag) {
    // Strong comparison is required.
    // From specification:
    // The strong comparison function: in order to be considered equal,
    // both validators MUST be identical in every way, and both MUST NOT be weak.
    return !etag.isWeak() && !otherEtag.isWeak()
           && ("*".equals(otherEtag.getValue()) || etag.getValue().equals(otherEtag.getValue()));
}
 
Example #27
Source File: AbstractClient.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Client match(EntityTag tag, boolean ifNot) {
    String hName = ifNot ? HttpHeaders.IF_NONE_MATCH : HttpHeaders.IF_MATCH;
    state.getRequestHeaders().putSingle(hName, tag.toString());
    return this;
}
 
Example #28
Source File: PictureManagementTest.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
@Test
public void testPictureResponse() throws IOException, URISyntaxException {
    Request request = Mockito.mock(Request.class);
    doReturn(null).when(request).evaluatePreconditions(any(EntityTag.class));

    InlinePictureEntity mockImage = new InlinePictureEntity();
    byte[] imageContent = Files.readAllBytes(Paths.get(this.getClass().getClassLoader().getResource("media/logo.svg").toURI()));
    mockImage.setContent(imageContent);
    mockImage.setType("image/svg");

    Response response = pictureResourceForTest.createPictureResponse(request, mockImage);

    assertEquals(OK_200, response.getStatus());

    MultivaluedMap<String, Object> headers = response.getHeaders();
    MediaType mediaType = (MediaType) headers.getFirst(HttpHeader.CONTENT_TYPE.asString());
    String etag = ((EntityTag) headers.getFirst("ETag")).getValue();

    assertEquals(mockImage.getType(), mediaType.toString());

    ByteArrayOutputStream baos = (ByteArrayOutputStream)response.getEntity();
    byte[] fileContent = baos.toByteArray();
    assertTrue(Arrays.equals(fileContent, imageContent));

    String expectedTag = Integer.toString(new String(fileContent).hashCode());
    assertEquals(expectedTag, etag);


    // test Cache
    ResponseBuilder responseBuilder = Response.notModified();
    doReturn(responseBuilder).when(request).evaluatePreconditions(any(EntityTag.class));

    final Response cachedResponse = pictureResourceForTest.createPictureResponse(request, mockImage);
    assertEquals(NOT_MODIFIED_304, cachedResponse.getStatus());
}
 
Example #29
Source File: ContainerRequestTest.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void evaluatesPreconditionsResponseByETgaAndLastModificationDateAs_NOT_MODIFIED_WhenLastModificationDateIsNotAfterIfModifiedSinceHeader() {
    Date now = new Date();
    Date before = new Date(now.getTime() - 10000);
    headers.putSingle(IF_MODIFIED_SINCE, formatDateInRfc1123DateFormat(now));
    Response response = containerRequest.evaluatePreconditions(before, new EntityTag("1234567")).build();
    assertEquals(NOT_MODIFIED, response.getStatusInfo());
}
 
Example #30
Source File: RequestImplTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testStrictEtagsPreconditionNotMet() {
    metadata.putSingle("If-Match", new EntityTag("123", true).toString());


    ResponseBuilder rb =
        new RequestImpl(m).evaluatePreconditions(new EntityTag("123"));
    assertEquals("Precondition must not be met, strict comparison is required",
                 412, rb.build().getStatus());
}