下面列出了怎么用javax.ws.rs.core.EntityTag的API类实例代码及写法,或者点击链接到github查看源代码。
@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();
}
}
/**
* 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());
}
}
}
/**
* 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);
}
@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();
}
@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();
}
/** 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"));
}
/** 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"));
}
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;
}
@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());
}
}
}
}
/**
* 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;
}
@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);
}
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);
}
@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());
}
@Path("/{s:.+}")
@GET
@Consumes
public Response get(@Context UriInfo uriInfo, @Context Request request) throws IOException {
String path = uriInfo.getPath();
Optional<ConsoleBundle> consoleBundleOptional = console.findByScriptFile(path);
Resource resource;
if (consoleBundleOptional.isPresent()) {
ConsoleBundle consoleBundle = consoleBundleOptional.get();
resource = new CombinedResource(path, resourcePaths(consoleBundle), webRoot);
} else {
Optional<Resource> optional = webRoot.get(path);
if (!optional.isPresent()) {
throw new NotFoundException(String.format("missing resource, path=%s", path));
}
resource = optional.get();
}
EntityTag eTag = new EntityTag(resource.hash());
Response.ResponseBuilder builder = request.evaluatePreconditions(eTag);
if (builder != null) {
return builder.build();
}
builder = Response.ok(resource).type(MediaTypes.getMediaType(Files.getFileExtension(path)));
builder.tag(eTag);
CacheControl cacheControl = new CacheControl();
cacheControl.setMustRevalidate(true);
builder.cacheControl(cacheControl);
return builder.build();
}
@Override
public Response getDictCollectionDetail(HttpServletRequest request, HttpHeaders header, Company company,
Locale locale, User user, ServiceContext serviceContext, String code, Request requestCC) {
DictcollectionInterface dictItemDataUtil = new DictCollectionActions();
long groupId = GetterUtil.getLong(header.getHeaderString("groupId"));
DictCollection dictCollection = dictItemDataUtil.getDictCollectionDetail(code, groupId);
EntityTag etag = new EntityTag(Integer.toString(Long.valueOf(groupId).hashCode()));
ResponseBuilder builder = requestCC.evaluatePreconditions(etag);
if (Validator.isNotNull(dictCollection)) {
DictCollectionModel dictCollectionModel = DataManagementUtils.mapperDictCollectionModel(dictCollection);
if (OpenCPSConfigUtil.isHttpCacheEnable() && builder == null) {
builder = Response.status(200);
CacheControl cc = new CacheControl();
cc.setMaxAge(OpenCPSConfigUtil.getHttpCacheMaxAge());
cc.setPrivate(true);
// return json object after update
return builder.entity(dictCollectionModel).cacheControl(cc).build();
}
else {
return builder.entity(dictCollectionModel).build();
}
} else {
return null;
}
}
private ResponseBuilder getBuilder(String jsonEntity, Date lastMod, boolean includeEtag, 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);
if (lastMod != null) {
berg.lastModified(lastMod);
}
CacheControl cc = new CacheControl();
cc.setMustRevalidate(true);
cc.setPrivate(true);
cc.setMaxAge(86400);
cc.setNoTransform(true);
berg.cacheControl(cc);
}
return berg;
}
@Test
public void evaluatesPreconditionsResponseByETagAs_NOT_MODIFIED_When_GET_RequestAndIfNoneMatchHeaderIsWeak() {
containerRequest.setMethod("GET");
headers.putSingle(IF_NONE_MATCH, "W/\"1234567\"");
Response response = containerRequest.evaluatePreconditions(new EntityTag("1234567")).build();
assertEquals(NOT_MODIFIED, response.getStatusInfo());
}
@Test
public void parsesStringWeak() {
EntityTag entityTag = entityTagHeaderDelegate.fromString("W/\"test\"");
assertTrue(entityTag.isWeak());
assertEquals("test", entityTag.getValue());
}
@Test
public void testEtagsIfNotMatch() {
metadata.putSingle(HttpHeaders.IF_NONE_MATCH, "\"123\"");
ResponseBuilder rb =
new RequestImpl(m).evaluatePreconditions(new EntityTag("123"));
assertEquals("Precondition must not be met",
304, rb.build().getStatus());
}
@Test
void testGetLdprs() {
when(mockTrellisRequest.getBaseUrl()).thenReturn("http://example.org");
final GetConfiguration config = new GetConfiguration(false, true, true, null, null);
final GetHandler handler = new GetHandler(mockTrellisRequest, mockBundler, extensions, config);
try (final Response res = handler.getRepresentation(handler.standardHeaders(handler.initialize(mockResource)))
.toCompletableFuture().join().build()) {
assertEquals(OK, res.getStatusInfo(), ERR_RESPONSE_CODE);
assertEquals(APPLICATION_SPARQL_UPDATE, res.getHeaderString(ACCEPT_PATCH), ERR_ACCEPT_PATCH);
assertEquals(from(time), res.getLastModified(), ERR_LAST_MODIFIED);
assertTrue(TEXT_TURTLE_TYPE.isCompatible(res.getMediaType()), ERR_CONTENT_TYPE);
assertTrue(res.getMediaType().isCompatible(TEXT_TURTLE_TYPE), ERR_CONTENT_TYPE);
assertNull(res.getHeaderString(PREFERENCE_APPLIED), ERR_PREFERENCE_APPLIED);
assertNull(res.getHeaderString(ACCEPT_RANGES), ERR_ACCEPT_RANGES);
assertNull(res.getHeaderString(ACCEPT_POST), ERR_ACCEPT_POST);
assertAll(CHECK_LINK_TYPES, checkLdpType(res, LDP.RDFSource));
assertAll(CHECK_ALLOW, checkAllowHeader(res, asList(GET, HEAD, OPTIONS, PUT, DELETE, PATCH)));
final EntityTag etag = res.getEntityTag();
assertTrue(etag.isWeak(), "ETag isn't weak for an RDF document!");
assertEquals(sha256Hex(mockResource.getRevision()), etag.getValue(), "Unexpected ETag value!");
final List<String> varies = getVaryHeaders(res);
assertFalse(varies.contains(RANGE), ERR_VARY_RANGE);
assertTrue(varies.contains(ACCEPT_DATETIME), ERR_VARY_ACCEPT_DATETIME);
assertTrue(varies.contains(PREFER), ERR_VARY_PREFER);
}
}
@Test
void testGetVersionedLdprs() {
final GetConfiguration config = new GetConfiguration(true, true, true, null, null);
final GetHandler handler = new GetHandler(mockTrellisRequest, mockBundler, extensions, config);
try (final Response res = handler.getRepresentation(handler.standardHeaders(handler.initialize(mockResource)))
.toCompletableFuture().join().build()) {
assertEquals(OK, res.getStatusInfo(), ERR_RESPONSE_CODE);
assertEquals(from(time), res.getLastModified(), ERR_LAST_MODIFIED);
assertEquals(ofInstant(time, UTC).format(RFC_1123_DATE_TIME), res.getHeaderString(MEMENTO_DATETIME),
"Incorrect Memento-Datetime header!");
assertTrue(TEXT_TURTLE_TYPE.isCompatible(res.getMediaType()), "Incompatible Content-Type header!");
assertTrue(res.getMediaType().isCompatible(TEXT_TURTLE_TYPE), "Incompatible Content-Type header!");
assertNull(res.getHeaderString(ACCEPT_POST), ERR_ACCEPT_POST);
assertNull(res.getHeaderString(ACCEPT_PATCH), "Unexpected Accept-Patch header!");
assertNull(res.getHeaderString(PREFERENCE_APPLIED), ERR_PREFERENCE_APPLIED);
assertNull(res.getHeaderString(ACCEPT_RANGES), ERR_ACCEPT_RANGES);
assertAll("Check LDP type headers", checkLdpType(res, LDP.RDFSource));
assertAll(CHECK_ALLOW, checkAllowHeader(res, asList(GET, HEAD, OPTIONS)));
final EntityTag etag = res.getEntityTag();
assertTrue(etag.isWeak(), "ETag header is not weak for an RDF resource!");
assertEquals(sha256Hex(mockResource.getRevision()), etag.getValue(), "Unexpected ETag value!");
final List<String> varies = getVaryHeaders(res);
assertTrue(varies.contains(PREFER), "Missing Vary: prefer header!");
assertFalse(varies.contains(RANGE), ERR_VARY_RANGE);
assertFalse(varies.contains(ACCEPT_DATETIME), ERR_VARY_ACCEPT_DATETIME);
}
}
private ResponseBuilder evaluateAll(EntityTag eTag, Date lastModified) {
// http://tools.ietf.org/search/draft-ietf-httpbis-p4-conditional-25#section-5
// Check If-Match. If it is not available proceed to checking If-Not-Modified-Since
// if it is available and the preconditions are not met - return, otherwise:
// Check If-Not-Match. If it is not available proceed to checking If-Modified-Since
// otherwise return the evaluation result
ResponseBuilder rb = evaluateIfMatch(eTag, lastModified);
if (rb == null) {
rb = evaluateIfNonMatch(eTag, lastModified);
}
return rb;
}
@Test
public void testEntityTag() {
ResponseImpl ri = new ResponseImpl(200);
MetadataMap<String, Object> meta = new MetadataMap<>();
meta.add(HttpHeaders.ETAG, "1234");
ri.addMetadata(meta);
assertEquals(EntityTag.valueOf("\"1234\""), ri.getEntityTag());
}
/**
* Test creating a basic container via POST.
* @throws Exception when the RDF resource does not close cleanly
*/
default void testCreateContainerViaPost() throws Exception {
final RDF rdf = RDFFactory.getInstance();
final String containerContent = getResourceAsString(BASIC_CONTAINER);
final String child3;
// First fetch the container headers to get the initial ETag
final EntityTag initialETag = getETag(getContainerLocation());
// POST an LDP-BC
try (final Response res = target(getContainerLocation()).request()
.header(LINK, fromUri(LDP.BasicContainer.getIRIString()).rel(TYPE).build())
.post(entity(containerContent, TEXT_TURTLE))) {
assertAll("Check the LDP-BC response", checkRdfResponse(res, LDP.BasicContainer, null));
child3 = res.getLocation().toString();
assertTrue(child3.startsWith(getContainerLocation()), "Check the Location header");
assertTrue(child3.length() > getContainerLocation().length(), "Check the Location header again");
}
await().until(() -> !initialETag.equals(getETag(getContainerLocation())));
// Now fetch the container
try (final Response res = target(getContainerLocation()).request().get();
final Graph g = readEntityAsGraph(res.getEntity(), getBaseURL(), TURTLE)) {
assertAll("Check the LDP-BC again", checkRdfResponse(res, LDP.BasicContainer, TEXT_TURTLE_TYPE));
final IRI identifier = rdf.createIRI(getContainerLocation());
final EntityTag etag = res.getEntityTag();
assertAll("Check the LDP-BC graph", checkRdfGraph(g, identifier));
assertTrue(g.contains(identifier, LDP.contains, rdf.createIRI(child3)));
assertTrue(etag.isWeak(), "Verify that the ETag is weak");
assertNotEquals(initialETag, etag, "Check that the ETag has been changed");
}
}
/**
* Test creating a child resource via PUT.
* @throws Exception when the RDF resource does not close cleanly
*/
default void testCreateContainerViaPut() throws Exception {
final RDF rdf = RDFFactory.getInstance();
final String containerContent = getResourceAsString(BASIC_CONTAINER);
final boolean createUncontained = getConfig().getOptionalValue(CONFIG_HTTP_PUT_UNCONTAINED, Boolean.class)
.orElse(Boolean.FALSE);
// First fetch the container headers to get the initial ETag
final EntityTag initialETag = getETag(getContainerLocation());
final String child4 = getContainerLocation() + "child4/";
try (final Response res = target(getContainerLocation() + "child4").request()
.header(LINK, fromUri(LDP.BasicContainer.getIRIString()).rel(TYPE).build())
.put(entity(containerContent, TEXT_TURTLE))) {
assertAll("Check PUTting an LDP-BC", checkRdfResponse(res, LDP.BasicContainer, null));
}
// Now fetch the resource
try (final Response res = target(getContainerLocation()).request().get();
final Graph g = readEntityAsGraph(res.getEntity(), getBaseURL(), TURTLE)) {
assertAll("Check an LDP-BC after PUT", checkRdfResponse(res, LDP.BasicContainer, TEXT_TURTLE_TYPE));
final IRI identifier = rdf.createIRI(getContainerLocation());
final EntityTag etag = res.getEntityTag();
assertAll("Check the resulting graph", checkRdfGraph(g, identifier));
if (createUncontained) {
assertFalse(g.contains(identifier, LDP.contains, rdf.createIRI(child4)),
"Check for the absense of an ldp:contains triple");
assertEquals(initialETag, etag, "Check ETags");
} else {
assertTrue(g.contains(identifier, LDP.contains, rdf.createIRI(child4)),
"Check for the presence of an ldp:contains triple");
assertNotEquals(initialETag, etag, "Check ETags");
}
assertTrue(etag.isWeak(), "Check for a weak ETag");
}
}
/**
* Test creating a child resource with a Slug header.
* @throws Exception when the RDF resource does not close cleanly
*/
@DisplayName("Test create container with slug")
default void testCreateContainerWithSlug() throws Exception {
final RDF rdf = RDFFactory.getInstance();
final String containerContent = getResourceAsString(BASIC_CONTAINER);
// First fetch the container headers to get the initial ETag
final EntityTag initialETag = getETag(getContainerLocation());
final String child5;
// POST an LDP-BC
try (final Response res = target(getContainerLocation()).request().header("Slug", "child5")
.header(LINK, fromUri(LDP.BasicContainer.getIRIString()).rel(TYPE).build())
.post(entity(containerContent, TEXT_TURTLE))) {
assertAll("Check POSTing an LDP-BC", checkRdfResponse(res, LDP.BasicContainer, null));
child5 = res.getLocation().toString();
}
await().until(() -> !initialETag.equals(getETag(getContainerLocation())));
// Now fetch the resource
try (final Response res = target(getContainerLocation()).request().get();
final Graph g = readEntityAsGraph(res.getEntity(), getBaseURL(), TURTLE)) {
assertAll("Check GETting the new resource", checkRdfResponse(res, LDP.BasicContainer, TEXT_TURTLE_TYPE));
final IRI identifier = rdf.createIRI(getContainerLocation());
final EntityTag etag = res.getEntityTag();
assertAll("Check the resulting Graph", checkRdfGraph(g, identifier));
assertTrue(g.contains(identifier, LDP.contains, rdf.createIRI(child5)), "Check for an ldp:contains triple");
assertTrue(etag.isWeak(), "Check for a weak ETag");
assertNotEquals(initialETag, etag, "Compare ETags 1 and 4");
}
}
@Test
public void testStarEtagsIfNotMatch() {
metadata.putSingle(HttpHeaders.IF_NONE_MATCH, "*");
ResponseBuilder rb =
new RequestImpl(m).evaluatePreconditions(new EntityTag("123"));
assertEquals("Precondition must not be met",
304, rb.build().getStatus());
}
@GET
@Path("{fileName:.+}")
@Produces("text/css")
public Response getCSS(@PathParam("fileName") String name, @Context Request request) {
try {
MCRServletContextResourceImporter importer = new MCRServletContextResourceImporter(context);
Optional<String> cssFile = MCRSassCompilerManager.getInstance()
.getCSSFile(name, Stream.of(importer).collect(Collectors.toList()));
if (cssFile.isPresent()) {
CacheControl cc = new CacheControl();
cc.setMaxAge(SECONDS_OF_ONE_DAY);
String etagString = MCRSassCompilerManager.getInstance().getLastMD5(name).get();
EntityTag etag = new EntityTag(etagString);
Response.ResponseBuilder builder = request.evaluatePreconditions(etag);
if (builder != null) {
return builder.cacheControl(cc).tag(etag).build();
}
return Response.ok().status(Response.Status.OK)
.cacheControl(cc)
.tag(etag)
.entity(cssFile.get())
.build();
} else {
return Response.status(Response.Status.NOT_FOUND)
.build();
}
} catch (IOException | CompilationException e) {
StreamingOutput so = (OutputStream os) -> e.printStackTrace(new PrintStream(os, true,
StandardCharsets.UTF_8));
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(so).build();
}
}
@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();
}
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()));
}