Search in sources :

Example 31 with EntityTag

use of javax.ws.rs.core.EntityTag in project muikku by otavanopisto.

the class WorkspaceForumRESTService method findWorkspaceArea.

@GET
@Path("/workspaces/{WORKSPACEENTITYID}/forumAreas/{AREAID}")
@RESTPermit(handling = Handling.INLINE)
public Response findWorkspaceArea(@Context Request request, @PathParam("WORKSPACEENTITYID") Long workspaceEntityId, @PathParam("AREAID") Long areaId) {
    ForumArea forumArea = forumController.getForumArea(areaId);
    WorkspaceEntity workspaceEntity = workspaceEntityController.findWorkspaceEntityById(workspaceEntityId);
    if (workspaceEntity == null) {
        return Response.status(Status.NOT_FOUND).entity(String.format("Workspace entity %d not found", workspaceEntityId)).build();
    }
    if (forumArea != null) {
        if (!(forumArea instanceof WorkspaceForumArea)) {
            logger.severe(String.format("Trying to access forum %d via incorrect REST endpoint", forumArea.getId()));
            return Response.status(Status.NOT_FOUND).build();
        }
        if (!workspaceEntity.getId().equals(((WorkspaceForumArea) forumArea).getWorkspace())) {
            return Response.status(Status.NOT_FOUND).entity(String.format("WorkspaceForumArea %d does not belong to workspace entity %d", forumArea.getId(), workspaceEntity.getId())).build();
        }
        if (sessionController.hasWorkspacePermission(ForumResourcePermissionCollection.FORUM_ACCESSWORKSPACEFORUMS, workspaceEntity)) {
            Long numThreads = forumController.getThreadCount(forumArea);
            EntityTag tag = new EntityTag(DigestUtils.md5Hex(String.valueOf(forumArea.getVersion()) + String.valueOf(numThreads)));
            ResponseBuilder builder = request.evaluatePreconditions(tag);
            if (builder != null) {
                return builder.build();
            }
            CacheControl cacheControl = new CacheControl();
            cacheControl.setMustRevalidate(true);
            ForumAreaRESTModel result = new ForumAreaRESTModel(forumArea.getId(), forumArea.getName(), forumArea.getDescription(), forumArea.getGroup() != null ? forumArea.getGroup().getId() : null, numThreads);
            return Response.ok(result).cacheControl(cacheControl).tag(tag).build();
        } else {
            return Response.status(Status.FORBIDDEN).build();
        }
    } else {
        return Response.status(Status.NOT_FOUND).build();
    }
}
Also used : WorkspaceForumArea(fi.otavanopisto.muikku.plugins.forum.model.WorkspaceForumArea) WorkspaceEntity(fi.otavanopisto.muikku.model.workspace.WorkspaceEntity) EntityTag(javax.ws.rs.core.EntityTag) WorkspaceForumArea(fi.otavanopisto.muikku.plugins.forum.model.WorkspaceForumArea) ForumArea(fi.otavanopisto.muikku.plugins.forum.model.ForumArea) CacheControl(javax.ws.rs.core.CacheControl) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) Path(javax.ws.rs.Path) RESTPermit(fi.otavanopisto.security.rest.RESTPermit) GET(javax.ws.rs.GET)

Example 32 with EntityTag

use of javax.ws.rs.core.EntityTag in project muikku by otavanopisto.

the class UserEntityFileRESTService method getFileContent.

@GET
@Path("/user/{USERENTITYID}/identifier/{IDENTIFIER}")
@RESTPermit(handling = Handling.INLINE)
public Response getFileContent(@PathParam("USERENTITYID") Long userEntityId, @PathParam("IDENTIFIER") String identifier, @Context Request request) {
    // Check if the file exists
    UserEntity userEntity = userEntityController.findUserEntityById(userEntityId);
    if (userEntity == null) {
        return Response.status(Status.NOT_FOUND).build();
    }
    UserEntityFile userEntityFile = userEntityFileController.findByUserEntityAndIdentifier(userEntity, identifier);
    if (userEntityFile == null) {
        return Response.status(Status.NOT_FOUND).build();
    }
    if (userEntityFile.getVisibility() != UserEntityFileVisibility.PUBLIC) {
        UserEntity loggedUserEntity = sessionController.getLoggedUserEntity();
        if (loggedUserEntity == null) {
            return Response.status(Status.NOT_FOUND).build();
        } else if (!userEntityFile.getUserEntity().getId().equals(loggedUserEntity.getId())) {
            if (userEntityFile.getVisibility() == UserEntityFileVisibility.STAFF) {
                EnvironmentUser environmentUser = environmentUserController.findEnvironmentUserByUserEntity(loggedUserEntity);
                if (environmentUser == null || environmentUser.getRole() == null || environmentUser.getRole().getArchetype() == EnvironmentRoleArchetype.STUDENT) {
                    return Response.status(Status.NOT_FOUND).build();
                }
            } else {
                return Response.status(Status.NOT_FOUND).build();
            }
        }
    }
    // Serve the content
    String tagIdentifier = String.format("%d-%s-%d", userEntityFile.getUserEntity().getId(), userEntityFile.getIdentifier(), userEntityFile.getLastModified().getTime());
    EntityTag tag = new EntityTag(DigestUtils.md5Hex(String.valueOf(tagIdentifier)));
    ResponseBuilder builder = request.evaluatePreconditions(tag);
    if (builder != null) {
        return builder.build();
    }
    CacheControl cacheControl = new CacheControl();
    cacheControl.setMustRevalidate(true);
    byte[] data = userEntityFile.getData();
    return Response.ok(data).cacheControl(cacheControl).tag(tag).header("Content-Length", data.length).header("Content-Disposition", String.format("attachment; filename=\"%s\"", userEntityFile.getName())).type(userEntityFile.getContentType()).build();
}
Also used : EnvironmentUser(fi.otavanopisto.muikku.model.users.EnvironmentUser) EntityTag(javax.ws.rs.core.EntityTag) CacheControl(javax.ws.rs.core.CacheControl) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) UserEntity(fi.otavanopisto.muikku.model.users.UserEntity) UserEntityFile(fi.otavanopisto.muikku.model.users.UserEntityFile) Path(javax.ws.rs.Path) RESTPermit(fi.otavanopisto.security.rest.RESTPermit) GET(javax.ws.rs.GET)

Example 33 with EntityTag

use of javax.ws.rs.core.EntityTag in project graylog2-server by Graylog2.

the class ConfigurationResource method renderConfiguration.

@GET
@Timed
@Path("/render/{sidecarId}/{configurationId}")
@Produces(MediaType.APPLICATION_JSON)
@RequiresPermissions(SidecarRestPermissions.CONFIGURATIONS_READ)
@ApiOperation(value = "Render configuration template")
public Response renderConfiguration(@Context HttpHeaders httpHeaders, @ApiParam(name = "sidecarId", required = true) @PathParam("sidecarId") String sidecarId, @ApiParam(name = "configurationId", required = true) @PathParam("configurationId") String configurationId) throws RenderTemplateException {
    String ifNoneMatch = httpHeaders.getHeaderString("If-None-Match");
    Boolean etagCached = false;
    Response.ResponseBuilder builder = Response.noContent();
    // check if client is up to date with a known valid etag
    if (ifNoneMatch != null) {
        EntityTag etag = new EntityTag(ifNoneMatch.replaceAll("\"", ""));
        if (etagService.isPresent(etag.toString())) {
            etagCached = true;
            builder = Response.notModified();
            builder.tag(etag);
        }
    }
    // fetch configuration from database if client is outdated
    if (!etagCached) {
        Sidecar sidecar = sidecarService.findByNodeId(sidecarId);
        if (sidecar == null) {
            throw new NotFoundException("Couldn't find Sidecar by ID: " + sidecarId);
        }
        Configuration configuration = configurationService.find(configurationId);
        if (configuration == null) {
            throw new NotFoundException("Couldn't find configuration by ID: " + configurationId);
        }
        Configuration collectorConfiguration = this.configurationService.renderConfigurationForCollector(sidecar, configuration);
        // add new etag to cache
        String etagString = configurationToEtag(collectorConfiguration);
        EntityTag collectorConfigurationEtag = new EntityTag(etagString);
        builder = Response.ok(collectorConfiguration);
        builder.tag(collectorConfigurationEtag);
        etagService.put(collectorConfigurationEtag.toString());
    }
    // set cache control
    CacheControl cacheControl = new CacheControl();
    cacheControl.setNoTransform(true);
    cacheControl.setPrivate(true);
    builder.cacheControl(cacheControl);
    return builder.build();
}
Also used : ConfigurationSidecarsResponse(org.graylog.plugins.sidecar.rest.responses.ConfigurationSidecarsResponse) Response(javax.ws.rs.core.Response) ConfigurationPreviewRenderResponse(org.graylog.plugins.sidecar.rest.responses.ConfigurationPreviewRenderResponse) CollectorUploadListResponse(org.graylog.plugins.sidecar.rest.responses.CollectorUploadListResponse) ConfigurationListResponse(org.graylog.plugins.sidecar.rest.responses.ConfigurationListResponse) Configuration(org.graylog.plugins.sidecar.rest.models.Configuration) NotFoundException(javax.ws.rs.NotFoundException) EntityTag(javax.ws.rs.core.EntityTag) CacheControl(javax.ws.rs.core.CacheControl) Sidecar(org.graylog.plugins.sidecar.rest.models.Sidecar) Path(javax.ws.rs.Path) RequiresPermissions(org.apache.shiro.authz.annotation.RequiresPermissions) Produces(javax.ws.rs.Produces) Timed(com.codahale.metrics.annotation.Timed) GET(javax.ws.rs.GET) ApiOperation(io.swagger.annotations.ApiOperation)

Example 34 with EntityTag

use of javax.ws.rs.core.EntityTag in project graylog2-server by Graylog2.

the class WebInterfaceAssetsResource method getResponse.

private Response getResponse(Request request, String filename, URL resourceUrl, boolean fromPlugin) throws IOException, URISyntaxException {
    final URI uri = resourceUrl.toURI();
    final java.nio.file.Path path;
    final byte[] fileContents;
    switch(resourceUrl.getProtocol()) {
        case "file":
            {
                path = Paths.get(uri);
                fileContents = Files.readAllBytes(path);
                break;
            }
        case "jar":
            {
                final FileSystem fileSystem = fileSystemCache.getUnchecked(uri);
                path = fileSystem.getPath(pluginPrefixFilename(fromPlugin, filename));
                fileContents = Resources.toByteArray(resourceUrl);
                break;
            }
        default:
            throw new IllegalArgumentException("Not a JAR or local file: " + resourceUrl);
    }
    final FileTime lastModifiedTime = Files.getLastModifiedTime(path);
    final Date lastModified = Date.from(lastModifiedTime.toInstant());
    final HashCode hashCode = Hashing.sha256().hashBytes(fileContents);
    final EntityTag entityTag = new EntityTag(hashCode.toString());
    final Response.ResponseBuilder response = request.evaluatePreconditions(lastModified, entityTag);
    if (response != null) {
        return response.build();
    }
    final String contentType = firstNonNull(mimeTypes.getContentType(filename), MediaType.APPLICATION_OCTET_STREAM);
    final CacheControl cacheControl = new CacheControl();
    cacheControl.setMaxAge((int) TimeUnit.DAYS.toSeconds(365));
    cacheControl.setNoCache(false);
    cacheControl.setPrivate(false);
    return Response.ok(fileContents, contentType).tag(entityTag).cacheControl(cacheControl).lastModified(lastModified).build();
}
Also used : FileTime(java.nio.file.attribute.FileTime) URI(java.net.URI) Date(java.util.Date) Response(javax.ws.rs.core.Response) HashCode(com.google.common.hash.HashCode) FileSystem(java.nio.file.FileSystem) EntityTag(javax.ws.rs.core.EntityTag) CacheControl(javax.ws.rs.core.CacheControl)

Example 35 with EntityTag

use of javax.ws.rs.core.EntityTag in project openolat by klemens.

the class RepositoryEntryResource method getById.

/**
 * get a resource in the repository
 * @response.representation.200.qname {http://www.example.com}repositoryEntryVO
 * @response.representation.200.mediaType application/xml, application/json
 * @response.representation.200.doc Get the repository resource
 * @response.representation.200.example {@link org.olat.restapi.support.vo.Examples#SAMPLE_REPOENTRYVO}
 * @response.representation.404.doc The repository entry not found
 * @param repoEntryKey The key or soft key of the repository entry
 * @param request The REST request
 * @return
 */
@GET
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Response getById(@PathParam("repoEntryKey") String repoEntryKey, @Context Request request) {
    RepositoryEntry re = lookupRepositoryEntry(repoEntryKey);
    if (re == null) {
        return Response.serverError().status(Status.NOT_FOUND).build();
    }
    Date lastModified = re.getLastModified();
    Response.ResponseBuilder response;
    if (lastModified == null) {
        EntityTag eTag = ObjectFactory.computeEtag(re);
        response = request.evaluatePreconditions(eTag);
        if (response == null) {
            RepositoryEntryVO vo = ObjectFactory.get(re);
            response = Response.ok(vo).tag(eTag).lastModified(lastModified);
        }
    } else {
        EntityTag eTag = ObjectFactory.computeEtag(re);
        response = request.evaluatePreconditions(lastModified, eTag);
        if (response == null) {
            RepositoryEntryVO vo = ObjectFactory.get(re);
            response = Response.ok(vo).tag(eTag).lastModified(lastModified);
        }
    }
    return response.build();
}
Also used : Response(javax.ws.rs.core.Response) RepositoryEntryVO(org.olat.restapi.support.vo.RepositoryEntryVO) EntityTag(javax.ws.rs.core.EntityTag) RepositoryEntry(org.olat.repository.RepositoryEntry) Date(java.util.Date) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Aggregations

EntityTag (javax.ws.rs.core.EntityTag)77 Response (javax.ws.rs.core.Response)28 GET (javax.ws.rs.GET)27 ResponseBuilder (javax.ws.rs.core.Response.ResponseBuilder)25 Path (javax.ws.rs.Path)24 CacheControl (javax.ws.rs.core.CacheControl)20 Test (org.junit.Test)18 Produces (javax.ws.rs.Produces)16 Date (java.util.Date)10 Test (org.testng.annotations.Test)9 RESTPermit (fi.otavanopisto.security.rest.RESTPermit)8 Timestamp (com.yahoo.rdl.Timestamp)5 UserEntity (fi.otavanopisto.muikku.model.users.UserEntity)5 RESTPermitUnimplemented (fi.otavanopisto.muikku.rest.RESTPermitUnimplemented)5 ArrayList (java.util.ArrayList)5 HashMap (java.util.HashMap)5 List (java.util.List)5 HttpServletResponse (javax.servlet.http.HttpServletResponse)5 ContainerResponse (org.everrest.core.impl.ContainerResponse)5 Principal (com.yahoo.athenz.auth.Principal)4