Search in sources :

Example 11 with EntityTag

use of javax.ws.rs.core.EntityTag in project che by eclipse.

the class ETagResponseFilter method doFilter.

/**
     * Filter the given container response
     *
     * @param containerResponse
     *         the response to use
     */
public void doFilter(GenericContainerResponse containerResponse) {
    // get entity of the response
    Object entity = containerResponse.getEntity();
    // no entity, skip
    if (entity == null) {
        return;
    }
    // Only handle JSON content
    if (!MediaType.APPLICATION_JSON_TYPE.equals(containerResponse.getContentType())) {
        return;
    }
    // Get the request
    ApplicationContext applicationContext = ApplicationContext.getCurrent();
    Request request = applicationContext.getRequest();
    // manage only GET requests
    if (!HttpMethod.GET.equals(request.getMethod())) {
        return;
    }
    // calculate hash with MD5
    HashFunction hashFunction = Hashing.md5();
    Hasher hasher = hashFunction.newHasher();
    boolean hashingSuccess = true;
    // Manage a list
    if (entity instanceof List) {
        List<?> entities = (List) entity;
        for (Object simpleEntity : entities) {
            hashingSuccess = addHash(simpleEntity, hasher);
            if (!hashingSuccess) {
                break;
            }
        }
    } else {
        hashingSuccess = addHash(entity, hasher);
    }
    // if we're able to handle the hash
    if (hashingSuccess) {
        // get result of the hash
        HashCode hashCode = hasher.hash();
        // Create the entity tag
        EntityTag entityTag = new EntityTag(hashCode.toString());
        // Check the etag
        Response.ResponseBuilder builder = request.evaluatePreconditions(entityTag);
        // not modified ?
        if (builder != null) {
            containerResponse.setResponse(builder.tag(entityTag).build());
        } else {
            // it has been changed, so send response with new ETag and entity
            Response.ResponseBuilder responseBuilder = Response.fromResponse(containerResponse.getResponse()).tag(entityTag);
            containerResponse.setResponse(responseBuilder.build());
        }
    }
}
Also used : GenericContainerResponse(org.everrest.core.GenericContainerResponse) Response(javax.ws.rs.core.Response) ApplicationContext(org.everrest.core.ApplicationContext) Hasher(com.google.common.hash.Hasher) HashCode(com.google.common.hash.HashCode) HashFunction(com.google.common.hash.HashFunction) Request(javax.ws.rs.core.Request) List(java.util.List) EntityTag(javax.ws.rs.core.EntityTag)

Example 12 with EntityTag

use of javax.ws.rs.core.EntityTag in project che by eclipse.

the class ETagResponseFilterTest method filterSingleEntityTest.

/**
     * 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"));
}
Also used : ContainerResponse(org.everrest.core.impl.ContainerResponse) EntityTag(javax.ws.rs.core.EntityTag) Test(org.testng.annotations.Test)

Example 13 with EntityTag

use of javax.ws.rs.core.EntityTag in project che by eclipse.

the class ETagResponseFilterTest method useExistingHeaders.

/**
     * Check if ETag is added in response if we're also using a custom header
     */
@Test
public void useExistingHeaders() throws Exception {
    final ContainerResponse response = resourceLauncher.service(HttpMethod.GET, SERVICE_PATH + "/modify", BASE_URI, null, null, null);
    assertEquals(response.getStatus(), OK.getStatusCode());
    // check entity
    Assert.assertEquals(response.getEntity(), "helloContent");
    // headers = 2
    Assert.assertEquals(response.getHttpHeaders().keySet().size(), 3);
    // Check custom header
    List<Object> customTags = response.getHttpHeaders().get(HttpHeaders.CONTENT_DISPOSITION);
    Assert.assertNotNull(customTags);
    Assert.assertEquals(customTags.size(), 1);
    Assert.assertEquals(customTags.get(0), "attachment; filename=my.json");
    // Check etag
    List<Object> headerTags = response.getHttpHeaders().get("ETag");
    Assert.assertNotNull(headerTags);
    Assert.assertEquals(headerTags.get(0), new EntityTag("77e671575d94cfd400ed26c5ef08e0fd"));
}
Also used : ContainerResponse(org.everrest.core.impl.ContainerResponse) EntityTag(javax.ws.rs.core.EntityTag) Test(org.testng.annotations.Test)

Example 14 with EntityTag

use of javax.ws.rs.core.EntityTag in project jersey by jersey.

the class ContainerRequestTest method testPreconditionsNoneMatch.

@Test
public void testPreconditionsNoneMatch() {
    ContainerRequest r = new ContainerRequest(URI.create("http://example.org/app"), URI.create("http://example.org/app/resource"), "GET", SECURITY_CONTEXT, new MapPropertiesDelegate());
    r.header(HttpHeaders.IF_NONE_MATCH, "\"686897696a7c876b7e\"");
    assertEquals(r.evaluatePreconditions(new EntityTag("686897696a7c876b7e")).build().getStatus(), Response.Status.NOT_MODIFIED.getStatusCode());
    assertNull(r.evaluatePreconditions(new EntityTag("000000000000000000")));
}
Also used : MapPropertiesDelegate(org.glassfish.jersey.internal.MapPropertiesDelegate) EntityTag(javax.ws.rs.core.EntityTag) Test(org.junit.Test)

Example 15 with EntityTag

use of javax.ws.rs.core.EntityTag in project exhibitor by soabase.

the class ConfigResource method getSystemState.

@Path("get-state")
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getSystemState(@Context Request request) throws Exception {
    InstanceConfig config = context.getExhibitor().getConfigManager().getConfig();
    String response = new FourLetterWord(FourLetterWord.Word.RUOK, config, context.getExhibitor().getConnectionTimeOutMs()).getResponse();
    ServerList serverList = new ServerList(config.getString(StringConfigs.SERVERS_SPEC));
    ServerSpec us = UsState.findUs(context.getExhibitor(), serverList.getSpecs());
    ObjectNode mainNode = JsonNodeFactory.instance.objectNode();
    ObjectNode configNode = JsonNodeFactory.instance.objectNode();
    ObjectNode controlPanelNode = JsonNodeFactory.instance.objectNode();
    mainNode.put("version", context.getExhibitor().getVersion());
    mainNode.put("running", "imok".equals(response));
    mainNode.put("backupActive", context.getExhibitor().getBackupManager().isActive());
    mainNode.put("standaloneMode", context.getExhibitor().getConfigManager().isStandaloneMode());
    mainNode.put("extraHeadingText", context.getExhibitor().getExtraHeadingText());
    mainNode.put("nodeMutationsAllowed", context.getExhibitor().nodeMutationsAllowed());
    configNode.put("rollInProgress", context.getExhibitor().getConfigManager().isRolling());
    configNode.put("rollStatus", context.getExhibitor().getConfigManager().getRollingConfigState().getRollingStatus());
    configNode.put("rollPercentDone", context.getExhibitor().getConfigManager().getRollingConfigState().getRollingPercentDone());
    configNode.put("hostname", context.getExhibitor().getThisJVMHostname());
    configNode.put("serverId", (us != null) ? us.getServerId() : -1);
    for (StringConfigs c : StringConfigs.values()) {
        configNode.put(fixName(c), config.getString(c));
    }
    for (IntConfigs c : IntConfigs.values()) {
        String fixedName = fixName(c);
        int value = config.getInt(c);
        configNode.put(fixedName, value);
    }
    EncodedConfigParser zooCfgParser = new EncodedConfigParser(config.getString(StringConfigs.ZOO_CFG_EXTRA));
    ObjectNode zooCfgNode = JsonNodeFactory.instance.objectNode();
    for (EncodedConfigParser.FieldValue fv : zooCfgParser.getFieldValues()) {
        zooCfgNode.put(fv.getField(), fv.getValue());
    }
    configNode.put("zooCfgExtra", zooCfgNode);
    if (context.getExhibitor().getBackupManager().isActive()) {
        ObjectNode backupExtraNode = JsonNodeFactory.instance.objectNode();
        EncodedConfigParser parser = context.getExhibitor().getBackupManager().getBackupConfigParser();
        List<BackupConfigSpec> configs = context.getExhibitor().getBackupManager().getConfigSpecs();
        for (BackupConfigSpec c : configs) {
            String value = parser.getValue(c.getKey());
            backupExtraNode.put(c.getKey(), (value != null) ? value : "");
        }
        configNode.put("backupExtra", backupExtraNode);
    }
    configNode.put("controlPanel", controlPanelNode);
    mainNode.put("config", configNode);
    String json = JsonUtil.writeValueAsString(mainNode);
    EntityTag tag = new EntityTag(Hashing.sha1().hashString(json, Charsets.UTF_8).toString());
    Response.ResponseBuilder builder = request.evaluatePreconditions(tag);
    if (builder == null) {
        builder = Response.ok(json).tag(tag);
    }
    return builder.build();
}
Also used : ServerSpec(com.netflix.exhibitor.core.state.ServerSpec) ObjectNode(org.codehaus.jackson.node.ObjectNode) IntConfigs(com.netflix.exhibitor.core.config.IntConfigs) Response(javax.ws.rs.core.Response) InstanceConfig(com.netflix.exhibitor.core.config.InstanceConfig) EncodedConfigParser(com.netflix.exhibitor.core.config.EncodedConfigParser) FourLetterWord(com.netflix.exhibitor.core.state.FourLetterWord) BackupConfigSpec(com.netflix.exhibitor.core.backup.BackupConfigSpec) ServerList(com.netflix.exhibitor.core.state.ServerList) EntityTag(javax.ws.rs.core.EntityTag) StringConfigs(com.netflix.exhibitor.core.config.StringConfigs) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Aggregations

EntityTag (javax.ws.rs.core.EntityTag)15 ContainerResponse (org.everrest.core.impl.ContainerResponse)5 Test (org.testng.annotations.Test)5 Response (javax.ws.rs.core.Response)4 Test (org.junit.Test)4 List (java.util.List)3 HashCode (com.google.common.hash.HashCode)2 URI (java.net.URI)2 HashMap (java.util.HashMap)2 Produces (javax.ws.rs.Produces)2 MapPropertiesDelegate (org.glassfish.jersey.internal.MapPropertiesDelegate)2 CoreMatchers.containsString (org.hamcrest.CoreMatchers.containsString)2 HashFunction (com.google.common.hash.HashFunction)1 Hasher (com.google.common.hash.Hasher)1 BackupConfigSpec (com.netflix.exhibitor.core.backup.BackupConfigSpec)1 EncodedConfigParser (com.netflix.exhibitor.core.config.EncodedConfigParser)1 InstanceConfig (com.netflix.exhibitor.core.config.InstanceConfig)1 IntConfigs (com.netflix.exhibitor.core.config.IntConfigs)1 StringConfigs (com.netflix.exhibitor.core.config.StringConfigs)1 FourLetterWord (com.netflix.exhibitor.core.state.FourLetterWord)1