javax.ws.rs.core.Request Java Examples

The following examples show how to use javax.ws.rs.core.Request. 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: ServerFrontend.java    From ldp4j with Apache License 2.0 6 votes vote down vote up
@POST
@Path(ENDPOINT_PATH)
public Response post(
	@Context UriInfo uriInfo,
	@PathParam(ENDPOINT_PATH_PARAM) String path,
	@Context HttpHeaders headers,
	@Context Request request,
	String entity) {
	OperationContext context =
		newOperationBuilder(HttpMethod.POST).
			withEndpointPath(path).
			withUriInfo(uriInfo).
			withHeaders(headers).
			withRequest(request).
			withEntity(entity).
			build();
	return
		EndpointControllerFactory.
			newController().
				createResource(context);
}
 
Example #2
Source File: TrellisWebDAV.java    From trellis with Apache License 2.0 6 votes vote down vote up
/**
 * Get properties for a resource.
 * @param response the response
 * @param request the request
 * @param uriInfo the URI info
 * @param headers the headers
 * @param propfind the propfind
 * @throws ParserConfigurationException if the XML parser is not properly configured
 */
@PROPFIND
@Consumes({APPLICATION_XML})
@Produces({APPLICATION_XML})
@Timed
public void getProperties(@Suspended final AsyncResponse response, @Context final Request request,
        @Context final UriInfo uriInfo, @Context final HttpHeaders headers, final DavPropFind propfind)
        throws ParserConfigurationException {
    final TrellisRequest req = new TrellisRequest(request, uriInfo, headers);
    final IRI identifier = rdf.createIRI(TRELLIS_DATA_PREFIX + req.getPath());
    final String location = fromUri(getBaseUrl(req)).path(req.getPath()).build().toString();
    final Document doc = getDocument();
    services.getResourceService().get(identifier)
        .thenApply(this::checkResource)
        .thenApply(propertiesToMultiStatus(doc, location, propfind))
        .thenApply(multistatus -> status(MULTI_STATUS).entity(multistatus).build())
        .exceptionally(this::handleException).thenApply(response::resume);
}
 
Example #3
Source File: SPARQLQuery.java    From neo4j-sparql-extension with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Query via GET.
 *
 * @see <a href="http://www.w3.org/TR/sparql11-protocol/#query-operation">
 * SPARQL 1.1 Protocol
 * </a>
 * @param req JAX-RS {@link Request} object
 * @param uriInfo JAX-RS {@link UriInfo} object
 * @param queryString the "query" query parameter
 * @param defgraphs the "default-graph-uri" query parameter
 * @param namedgraphs the "named-graph-uri" query parameter
 * @param inference the "inference" query parameter
 * @return the result of the SPARQL query
 */
@GET
@Produces({
	RDFMediaType.SPARQL_RESULTS_JSON,
	RDFMediaType.SPARQL_RESULTS_XML,
	RDFMediaType.SPARQL_RESULTS_CSV,
	RDFMediaType.SPARQL_RESULTS_TSV,
	RDFMediaType.RDF_TURTLE,
	RDFMediaType.RDF_NTRIPLES,
	RDFMediaType.RDF_XML,
	RDFMediaType.RDF_JSON
})
public Response query(
		@Context Request req,
		@Context UriInfo uriInfo,
		@QueryParam("query") String queryString,
		@QueryParam("default-graph-uri") List<String> defgraphs,
		@QueryParam("named-graph-uri") List<String> namedgraphs,
		@QueryParam("inference") String inference) {
	return handleQuery(
			req, uriInfo, queryString, defgraphs, namedgraphs, inference);
}
 
Example #4
Source File: RestResource.java    From development with Apache License 2.0 6 votes vote down vote up
/**
 * Wrapper for backend GET commands. Prepares, validates and revises data
 * for commands and assembles responses.
 * 
 * @param request
 *            the request context
 * @param backend
 *            the backend command
 * @param params
 *            the request parameters
 * @param id
 *            true if id needs to be validated
 * @return the response with representation or -collection
 */
protected <R extends Representation, P extends RequestParameters> Response get(
        Request request, RestBackend.Get<R, P> backend, P params,
        boolean id) throws Exception {

    int version = getVersion(request);

    prepareData(version, params, id, null, false);

    Representation item = backend.get(params);

    reviseData(version, item);

    String tag = "";
    if (item.getETag() != null) {
        tag = item.getETag().toString();
    }

    return Response.ok(item).tag(tag).build();
}
 
Example #5
Source File: CourseWebService.java    From olat with Apache License 2.0 6 votes vote down vote up
/**
 * Get the editor tree model of the course by id
 * 
 * @response.representation.200.mediaType application/xml
 * @response.representation.200.doc The editor tree model of the course
 * @response.representation.401.doc The roles of the authenticated user are not sufficient
 * @response.representation.404.doc The course not found
 * @param courseId
 *            The course resourceable's id
 * @param httpRequest
 *            The HTTP request
 * @param request
 *            The REST request
 * @return It returns the XML representation of the <code>Editor model</code> object representing the course.
 */
@GET
@Path("editortreemodel")
@Produces(MediaType.APPLICATION_XML)
public Response findEditorTreeModelById(@PathParam("courseId") final Long courseId, @Context final HttpServletRequest httpRequest, @Context final Request request) {
    if (!isAuthor(httpRequest)) {
        return Response.serverError().status(Status.UNAUTHORIZED).build();
    }

    final ICourse course = loadCourse(courseId);
    if (course == null) {
        return Response.serverError().status(Status.NOT_FOUND).build();
    } else if (!isAuthorEditor(course, httpRequest)) {
        return Response.serverError().status(Status.UNAUTHORIZED).build();
    }
    final VFSItem editorModelItem = course.getCourseBaseContainer().resolve("editortreemodel.xml");
    final Date lastModified = new Date(editorModelItem.getLastModified());

    final Response.ResponseBuilder response = request.evaluatePreconditions(lastModified);
    if (response == null) {
        return Response.ok(myXStream.toXML(course.getEditorTreeModel())).build();
    }
    return response.build();
}
 
Example #6
Source File: ServerFrontend.java    From ldp4j with Apache License 2.0 6 votes vote down vote up
@DELETE
@Path(ENDPOINT_PATH)
public Response delete(
	@Context UriInfo uriInfo,
	@PathParam(ENDPOINT_PATH_PARAM) String path,
	@Context HttpHeaders headers,
	@Context Request request) {
	OperationContext context =
		newOperationBuilder(HttpMethod.DELETE).
			withEndpointPath(path).
			withUriInfo(uriInfo).
			withHeaders(headers).
			withRequest(request).
			build();
	return
		EndpointControllerFactory.
			newController().
				deleteResource(context);
}
 
Example #7
Source File: TaskReportResourceImpl.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
public Response getTaskCountByCandidateGroupReport(Request request) {
  Variant variant = request.selectVariant(VARIANTS);
  if (variant != null) {
    MediaType mediaType = variant.getMediaType();

    if (MediaType.APPLICATION_JSON_TYPE.equals(mediaType)) {
      List<TaskCountByCandidateGroupResultDto> result = getTaskCountByCandidateGroupResultAsJson();
      return Response.ok(result, mediaType).build();
    }
    else if (APPLICATION_CSV_TYPE.equals(mediaType) || TEXT_CSV_TYPE.equals(mediaType)) {
      String csv = getReportResultAsCsv();
      return Response
        .ok(csv, mediaType)
        .header("Content-Disposition", "attachment; filename=\"task-count-by-candidate-group.csv\"")
        .build();
    }
  }
  throw new InvalidRequestException(Status.NOT_ACCEPTABLE, "No acceptable content-type found");
}
 
Example #8
Source File: TrellisHttpResource.java    From trellis with Apache License 2.0 6 votes vote down vote up
/**
 * Perform a POST operation on a LDP Resource.
 *
 * @param uriInfo the URI info
 * @param secContext the security context
 * @param headers the HTTP headers
 * @param request the request
 * @param body the body
 * @return the async response
 */
@POST
@Timed
@Operation(summary = "Create a linked data resource")
public CompletionStage<Response> createResource(@Context final Request request, @Context final UriInfo uriInfo,
        @Context final HttpHeaders headers, @Context final SecurityContext secContext,
        @RequestBody(description = "The new resource") final InputStream body) {
    final TrellisRequest req = new TrellisRequest(request, uriInfo, headers, secContext);
    final String urlBase = getBaseUrl(req);
    final String path = req.getPath();
    final String identifier = getIdentifier(req);
    final String separator = path.isEmpty() ? "" : "/";

    final IRI parent = buildTrellisIdentifier(path);
    final IRI child = buildTrellisIdentifier(path + separator + identifier);
    final PostHandler postHandler = new PostHandler(req, parent, identifier, body, trellis, extensions, urlBase);

    return trellis.getResourceService().get(parent)
        .thenCombine(trellis.getResourceService().get(child), postHandler::initialize)
        .thenCompose(postHandler::createResource).thenCompose(postHandler::updateMemento)
        .thenApply(ResponseBuilder::build).exceptionally(this::handleException);
}
 
Example #9
Source File: DocumentBinaryResourceTest.java    From eplmp with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Test to download a document file as a regular user who has no read access on it
 *
 * @throws Exception
 */
@Test
public void downloadDocumentFileAsUserWithNoAccessRights() throws Exception {

    //Given
    Request request = Mockito.mock(Request.class);
    String fullName = ResourceUtil.WORKSPACE_ID + "/documents/" + ResourceUtil.DOCUMENT_ID + "/" + ResourceUtil.VERSION + "/" + ResourceUtil.ITERATION + "/" + ResourceUtil.FILENAME1;

    BinaryResource binaryResource = new BinaryResource(ResourceUtil.FILENAME1, ResourceUtil.DOCUMENT_SIZE, new Date());
    Mockito.when(documentService.canAccess(new DocumentIterationKey(ResourceUtil.WORKSPACE_ID, ResourceUtil.DOCUMENT_ID, ResourceUtil.VERSION, ResourceUtil.ITERATION))).thenReturn(false);
    Mockito.when(documentService.getBinaryResource(fullName)).thenReturn(binaryResource);
    Mockito.when(storageManager.getBinaryResourceInputStream(binaryResource)).thenReturn(new FileInputStream(new File(ResourceUtil.getFilePath(ResourceUtil.SOURCE_FILE_STORAGE + ResourceUtil.FILENAME1))));
    Mockito.when(publicEntityManager.getBinaryResourceForSharedEntity(fullName)).thenReturn(binaryResource);
    Mockito.when(contextManager.isCallerInRole(UserGroupMapping.REGULAR_USER_ROLE_ID)).thenReturn(true);
    Mockito.when(publicEntityManager.canAccess(Matchers.any(DocumentIterationKey.class))).thenReturn(false);

    //When
    try {
        Response response = documentBinaryResource.downloadDocumentFile(request, ResourceUtil.WORKSPACE_ID, ResourceUtil.DOCUMENT_ID, ResourceUtil.VERSION, ResourceUtil.ITERATION, ResourceUtil.FILENAME1, ResourceUtil.FILE_TYPE, null, ResourceUtil.RANGE, null, null, null);
        assertTrue(false);
    } catch (NotAllowedException e) {
        assertTrue(true);
    }

}
 
Example #10
Source File: PartBinaryResourceTest.java    From eplmp with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Test to download a part file as a guest and the part is public
 *
 * @throws Exception
 */
@Test
public void downloadPartFileAsGuestPartPublic() throws Exception {

    //Given
    Request request = Mockito.mock(Request.class);
    BinaryResource binaryResource = Mockito.spy(new BinaryResource(ResourceUtil.FILENAME1, ResourceUtil.PART_SIZE, new Date()));
    Mockito.when(storageManager.getBinaryResourceInputStream(binaryResource)).thenReturn(new FileInputStream(new File(ResourceUtil.getFilePath(ResourceUtil.SOURCE_FILE_STORAGE + ResourceUtil.FILENAME1))));
    Mockito.when(contextManager.isCallerInRole(UserGroupMapping.REGULAR_USER_ROLE_ID)).thenReturn(false);
    Mockito.when(publicEntityManager.canAccess(Mockito.any(PartIterationKey.class))).thenReturn(true);
    Mockito.when(productService.canAccess(Matchers.any(PartIterationKey.class))).thenReturn(false);
    Mockito.when(storageManager.getBinaryResourceInputStream(binaryResource)).thenReturn(new FileInputStream(new File(ResourceUtil.getFilePath(ResourceUtil.SOURCE_PART_STORAGE + ResourceUtil.TEST_PART_FILENAME1))));
    Mockito.when(productService.getPartRevision(Matchers.any(PartRevisionKey.class))).thenReturn(new PartRevision());

    //When
    Mockito.when(publicEntityManager.getPublicBinaryResourceForPart(Matchers.anyString())).thenReturn(binaryResource);
    Response response = partBinaryResource.downloadPartFile(request, ResourceUtil.WORKSPACE_ID,
            ResourceUtil.PART_NUMBER, ResourceUtil.VERSION, ResourceUtil.ITERATION, "attached-files",
            ResourceUtil.TEST_PART_FILENAME1, ResourceUtil.FILE_TYPE, null, ResourceUtil.RANGE, null, null, null);
    //Then
    assertNotNull(response);
    assertEquals(response.getStatus(), 206);
    assertNotNull(response.getEntity());
    assertTrue(response.getEntity() instanceof BinaryResourceBinaryStreamingOutput);
}
 
Example #11
Source File: PartBinaryResourceTest.java    From eplmp with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Test to download a part file as a regular user who has read access
 *
 * @throws Exception
 */
@Test
public void downloadPartFileAsRegularUserReadAccess() throws Exception {
    //Given
    Request request = Mockito.mock(Request.class);
    BinaryResource binaryResource = Mockito.spy(new BinaryResource(ResourceUtil.FILENAME1, ResourceUtil.PART_SIZE, new Date()));
    Mockito.when(storageManager.getBinaryResourceInputStream(binaryResource)).thenReturn(new FileInputStream(new File(ResourceUtil.getFilePath(ResourceUtil.SOURCE_FILE_STORAGE + ResourceUtil.FILENAME1))));
    Mockito.when(contextManager.isCallerInRole(UserGroupMapping.REGULAR_USER_ROLE_ID)).thenReturn(true);
    Mockito.when(productService.getBinaryResource(Matchers.anyString())).thenReturn(binaryResource);
    Mockito.when(productService.canAccess(Matchers.any(PartIterationKey.class))).thenReturn(true);
    Mockito.when(productService.getPartRevision(Matchers.any(PartRevisionKey.class))).thenReturn(new PartRevision());
    Mockito.when(storageManager.getBinaryResourceInputStream(binaryResource)).thenReturn(new FileInputStream(new File(ResourceUtil.getFilePath(ResourceUtil.SOURCE_PART_STORAGE + ResourceUtil.TEST_PART_FILENAME1))));
    Mockito.when(publicEntityManager.getPublicBinaryResourceForPart(Matchers.anyString())).thenReturn(binaryResource);
    //When
    Response response = partBinaryResource.downloadPartFile(request, ResourceUtil.WORKSPACE_ID,
            ResourceUtil.PART_NUMBER, ResourceUtil.VERSION, ResourceUtil.ITERATION, "attached-files",
            ResourceUtil.TEST_PART_FILENAME1, ResourceUtil.FILE_TYPE, null, ResourceUtil.RANGE, null, null, null);
    //Then
    assertNotNull(response);
    assertEquals(response.getStatus(), 206);
    assertNotNull(response.getEntity());
    assertTrue(response.getEntity() instanceof BinaryResourceBinaryStreamingOutput);

}
 
Example #12
Source File: RenderImageService.java    From render with GNU General Public License v2.0 6 votes vote down vote up
@Path("v1/owner/{owner}/project/{project}/stack/{stack}/largeDataTileSource/{width}/{height}/small/{z}.png")
@GET
@Produces(RenderServiceUtil.IMAGE_PNG_MIME_TYPE)
@ApiOperation(
        tags = "Bounding Box Image APIs",
        value = "Render PNG image for the specified large data (type 5) section overview")
public Response renderLargeDataOverviewPng(@PathParam("owner") final String owner,
                                           @PathParam("project") final String project,
                                           @PathParam("stack") final String stack,
                                           @PathParam("width") final Integer width,
                                           @PathParam("height") final Integer height,
                                           @PathParam("z") final Double z,
                                           @QueryParam("maxOverviewWidthAndHeight") final Integer maxOverviewWidthAndHeight,
                                           @BeanParam final RenderQueryParameters renderQueryParameters,
                                           @QueryParam("maxTileSpecsToRender") final Integer maxTileSpecsToRender,
                                           @QueryParam("translateOrigin") final Boolean translateOrigin,
                                           @Context final Request request) {

    return renderLargeDataOverview(owner, project, stack, width, height, z,
                                   Utils.PNG_FORMAT, RenderServiceUtil.IMAGE_PNG_MIME_TYPE,
                                   maxOverviewWidthAndHeight, renderQueryParameters,
                                   maxTileSpecsToRender, translateOrigin, request);
}
 
Example #13
Source File: TermsResource.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) {
		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 #14
Source File: SPARQLQuery.java    From neo4j-sparql-extension with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Query via GET (with inference).
 *
 * @see <a href="http://www.w3.org/TR/sparql11-protocol/#query-operation">
 * SPARQL 1.1 Protocol
 * </a>
 * @param req JAX-RS {@link Request} object
 * @param uriInfo JAX-RS {@link UriInfo} object
 * @param queryString the "query" query parameter
 * @param defgraphs the "default-graph-uri" query parameter
 * @param namedgraphs the "named-graph-uri" query parameter
 * @return the result of the SPARQL query
 */
@GET
@Path("/inference")
@Produces({
	RDFMediaType.SPARQL_RESULTS_JSON,
	RDFMediaType.SPARQL_RESULTS_XML,
	RDFMediaType.SPARQL_RESULTS_CSV,
	RDFMediaType.SPARQL_RESULTS_TSV,
	RDFMediaType.RDF_TURTLE,
	RDFMediaType.RDF_NTRIPLES,
	RDFMediaType.RDF_XML,
	RDFMediaType.RDF_JSON
})
public Response queryInference(
		@Context Request req,
		@Context UriInfo uriInfo,
		@QueryParam("query") String queryString,
		@QueryParam("default-graph-uri") List<String> defgraphs,
		@QueryParam("named-graph-uri") List<String> namedgraphs) {
	return handleQuery(
			req, uriInfo, queryString, defgraphs, namedgraphs, "true");
}
 
Example #15
Source File: LearningGroupWebService.java    From olat with Apache License 2.0 6 votes vote down vote up
/**
 * Return the group specified by the key of the group.
 * 
 * @response.representation.200.qname {http://www.example.com}groupVO
 * @response.representation.200.mediaType application/xml, application/json
 * @response.representation.200.doc A business group in the OLAT system
 * @response.representation.200.example {@link org.olat.connectors.rest.support.vo.Examples#SAMPLE_GROUPVO}
 * @param groupKey
 *            The key of the group
 * @param request
 *            The REST request
 * @param httpRequest
 *            The HTTP request
 * @return
 */
@GET
@Path("{groupKey}")
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Response findById(@PathParam("groupKey") final Long groupKey, @Context final Request request, @Context final HttpServletRequest httpRequest) {
    final BusinessGroup bg = businessGroupService.loadBusinessGroup(groupKey, false);
    if (bg == null) {
        return Response.serverError().status(Status.NOT_FOUND).build();
    }
    final Identity identity = RestSecurityHelper.getIdentity(httpRequest);
    if (!isGroupManager(httpRequest) && !businessGroupService.isIdentityInBusinessGroup(identity, bg)) {
        return Response.serverError().status(Status.UNAUTHORIZED).build();
    }

    final Date lastModified = bg.getLastModified();
    Response.ResponseBuilder response = request.evaluatePreconditions(lastModified);
    if (response == null) {
        final GroupVO vo = ObjectFactory.get(bg);
        response = Response.ok(vo);
    }
    return response.build();
}
 
Example #16
Source File: TrellisHttpResource.java    From trellis with Apache License 2.0 6 votes vote down vote up
/**
 * Perform a PATCH operation on an LDP Resource.
 *
 * @param uriInfo the URI info
 * @param secContext the security context
 * @param headers the HTTP headers
 * @param request the request
 * @param body the body
 * @return the async response
 */
@PATCH
@Timed
@Operation(summary = "Update a linked data resource")
public CompletionStage<Response> updateResource(@Context final Request request, @Context final UriInfo uriInfo,
        @Context final HttpHeaders headers, @Context final SecurityContext secContext,
        @RequestBody(description = "The update request for RDF resources, typically as SPARQL-Update",
                     required = true,
                     content = @Content(mediaType = "application/sparql-update")) final String body) {
    final TrellisRequest req = new TrellisRequest(request, uriInfo, headers, secContext);
    final String urlBase = getBaseUrl(req);
    final IRI identifier = buildTrellisIdentifier(req.getPath());
    final PatchHandler patchHandler = new PatchHandler(req, body, trellis, extensions, supportsCreateOnPatch,
            defaultJsonLdProfile, urlBase);

    return getParent(identifier).thenCombine(trellis.getResourceService().get(identifier), patchHandler::initialize)
        .thenCompose(patchHandler::updateResource).thenCompose(patchHandler::updateMemento)
        .thenApply(ResponseBuilder::build).exceptionally(this::handleException);
}
 
Example #17
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 #18
Source File: TileImageService.java    From render with GNU General Public License v2.0 5 votes vote down vote up
@Path("v1/owner/{owner}/project/{project}/stack/{stack}/tile/{tileId}/source/png-image")
@GET
@Produces(RenderServiceUtil.IMAGE_PNG_MIME_TYPE)
@ApiOperation(value = "Render tile's source image without transformations in PNG format")
@ApiResponses(value = {
        @ApiResponse(code = 404, message = "Tile not found")
})
public Response renderPngSourceImageForTile(@PathParam("owner") final String owner,
                                            @PathParam("project") final String project,
                                            @PathParam("stack") final String stack,
                                            @PathParam("tileId") final String tileId,
                                            @BeanParam final RenderQueryParameters renderQueryParameters,
                                            @Context final Request request) {

    LOG.info("renderPngSourceImageForTile: entry, owner={}, project={}, stack={}, tileId={}",
             owner, project, stack, tileId);

    final ResponseHelper responseHelper = new ResponseHelper(request, getStackMetaData(owner, project, stack));
    if (responseHelper.isModified()) {
        final RenderParameters renderParameters =
                tileDataService.getTileSourceRenderParameters(owner, project, stack, tileId, null,
                                                              renderQueryParameters);
        return RenderServiceUtil.renderPngImage(renderParameters, null, responseHelper);
    } else {
        return responseHelper.getNotModifiedResponse();
    }
}
 
Example #19
Source File: DocumentBinaryResourceTest.java    From eplmp with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Test to download a document file as a guest but the document is private
 *
 * @throws Exception
 */
@Test
public void downloadDocumentFileAsGuestDocumentIsPrivate() throws Exception {
    //Given
    Request request = Mockito.mock(Request.class);
    //Workspace workspace, User author, Date expireDate, String password, DocumentRevision documentRevision
    Account account = Mockito.spy(new Account("user2", "user2", "[email protected]", "en", new Date(), null));
    Workspace workspace = new Workspace(ResourceUtil.WORKSPACE_ID, account, "pDescription", false);
    User user = new User(workspace, new Account("user1", "user1", "[email protected]", "en", new Date(), null));
    DocumentMaster documentMaster = new DocumentMaster(workspace, ResourceUtil.DOCUMENT_ID, user);
    DocumentRevision documentRevision = new DocumentRevision(documentMaster, ResourceUtil.VERSION, user);
    List<DocumentIteration> iterations = new ArrayList<>();
    DocumentIteration documentIteration = new DocumentIteration(documentRevision, user);
    iterations.add(documentIteration);
    documentRevision.setDocumentIterations(iterations);

    SharedDocument sharedEntity = new SharedDocument(workspace, user, ResourceUtil.getFutureDate(), "password", documentRevision);

    String fullName = ResourceUtil.WORKSPACE_ID + "/documents/" + ResourceUtil.DOCUMENT_ID + "/" + ResourceUtil.VERSION + "/" + ResourceUtil.ITERATION + "/" + ResourceUtil.FILENAME1;

    BinaryResource binaryResource = new BinaryResource(ResourceUtil.FILENAME1, ResourceUtil.DOCUMENT_SIZE, new Date());
    Mockito.when(documentService.getBinaryResource(fullName)).thenReturn(binaryResource);
    Mockito.when(storageManager.getBinaryResourceInputStream(binaryResource)).thenReturn(new FileInputStream(new File(ResourceUtil.getFilePath(ResourceUtil.SOURCE_FILE_STORAGE + ResourceUtil.FILENAME1))));
    Mockito.when(publicEntityManager.getBinaryResourceForSharedEntity(fullName)).thenReturn(binaryResource);
    Mockito.when(contextManager.isCallerInRole(UserGroupMapping.REGULAR_USER_ROLE_ID)).thenReturn(false);
    String uuid = ResourceUtil.SHARED_DOC_ENTITY_UUID.split("/")[2];
    Mockito.when(shareService.findSharedEntityForGivenUUID(uuid)).thenReturn(sharedEntity);
    //When
    Response response = documentBinaryResource.downloadDocumentFile(request, ResourceUtil.WORKSPACE_ID, ResourceUtil.DOCUMENT_ID, ResourceUtil.VERSION, ResourceUtil.ITERATION, ResourceUtil.FILENAME1, ResourceUtil.FILE_TYPE, null, ResourceUtil.RANGE, uuid, "password", null);

    //Then
    assertNotNull(response);
    assertEquals(response.getStatus(), 206);
    assertEquals(response.getStatusInfo(), Response.Status.PARTIAL_CONTENT);


}
 
Example #20
Source File: ApiResource.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
@GET
@Path("picture")
@Produces({ MediaType.WILDCARD, MediaType.APPLICATION_JSON })
public Response getPictureByApiId(@Context Request request, @PathParam("apiId") String apiId) {
    Collection<ApiEntity> userApis = apiService.findPublishedByUser(getAuthenticatedUserOrNull());
    if (userApis.stream().anyMatch(a -> a.getId().equals(apiId))) {

        InlinePictureEntity image = apiService.getPicture(apiId);

        return createPictureResponse(request, image);
    }
    throw new ApiNotFoundException(apiId);
}
 
Example #21
Source File: CourseAssessmentWebService.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the results of the course.
 * 
 * @response.representation.200.qname {http://www.example.com}assessableResultsVO
 * @response.representation.200.mediaType application/xml, application/json
 * @response.representation.200.doc The result of the course
 * @response.representation.200.example {@link org.olat.connectors.rest.support.vo.Examples#SAMPLE_ASSESSABLERESULTSVO}
 * @response.representation.401.doc The roles of the authenticated user are not sufficient
 * @response.representation.404.doc The identity or the course not found
 * @param courseId
 *            The course resourceable's id
 * @param identityKey
 *            The id of the user
 * @param httpRequest
 *            The HTTP request
 * @param request
 *            The REST request
 * @return
 */
@GET
@Path("users/{identityKey}")
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Response getCourseResultsOf(@PathParam("courseId") final Long courseId, @PathParam("identityKey") final Long identityKey,
        @Context final HttpServletRequest httpRequest, @Context final Request request) {
    if (!RestSecurityHelper.isAuthor(httpRequest)) {
        return Response.serverError().status(Status.UNAUTHORIZED).build();
    }

    try {
        final Identity userIdentity = getBaseSecurity().loadIdentityByKey(identityKey, false);
        if (userIdentity == null) {
            return Response.serverError().status(Status.NOT_FOUND).build();
        }

        final Date lastModified = userIdentity.getLastLogin();
        Response.ResponseBuilder response = request.evaluatePreconditions(lastModified);
        if (response == null) {
            final ICourse course = CourseFactory.loadCourse(courseId);
            if (course == null) {
                return Response.serverError().status(Status.NOT_FOUND).build();
            }

            final AssessableResultsVO results = getRootResult(userIdentity, course);
            response = Response.ok(results).lastModified(lastModified).cacheControl(cc);
        }
        return response.build();
    } catch (final Throwable e) {
        throw new WebApplicationException(e);
    }
}
 
Example #22
Source File: CourseResourceFolderWebService.java    From olat with Apache License 2.0 5 votes vote down vote up
@GET
@Path("sharedfolder/{path:.*}")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_HTML, MediaType.APPLICATION_OCTET_STREAM })
public Response getSharedFiles(@PathParam("courseId") final Long courseId, @PathParam("path") final List<PathSegment> path, @Context final UriInfo uriInfo,
        @Context final HttpServletRequest httpRequest, @Context final Request request) {
    return getFiles(courseId, path, FolderType.COURSE_FOLDER, uriInfo, httpRequest, request);
}
 
Example #23
Source File: PeopleRestService.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
@Produces({ MediaType.APPLICATION_JSON })
@Path("/options")
@OPTIONS
public Response getOptions(@Context HttpHeaders headers, @Context Request request) {
    return Response.ok().header(CorsHeaderConstants.HEADER_AC_ALLOW_METHODS, "GET POST DELETE PUT OPTIONS")
            .header(CorsHeaderConstants.HEADER_AC_ALLOW_CREDENTIALS, "false")
            .header(CorsHeaderConstants.HEADER_AC_REQUEST_HEADERS, MediaType.APPLICATION_JSON).build();
}
 
Example #24
Source File: RestTriggerResource.java    From development with Apache License 2.0 5 votes vote down vote up
/**
 * Gets all available trigger actions
 */
@Since(CommonParams.VERSION_1)
@GET
@Produces(MediaType.APPLICATION_JSON)
@Override
public Response getCollection(@Context Request request,
                              @BeanParam TriggerParameters params) throws Exception {

    RestBackend.Get<RepresentationCollection<ActionRepresentation>, TriggerParameters> backend;
    backend = new RestBackend.Get<RepresentationCollection<ActionRepresentation>, TriggerParameters>() {

        @Override
        public RepresentationCollection<ActionRepresentation> get(
                TriggerParameters params)
                throws WebApplicationException {

            Collection<ActionRepresentation> col = new ArrayList<>();
            col.add(new ActionRepresentation(null,
                    ActionRepresentation.Action.SUBSCRIBE_TO_SERVICE));
            col.add(new ActionRepresentation(null,
                    ActionRepresentation.Action.UNSUBSCRIBE_FROM_SERVICE));
            col.add(new ActionRepresentation(null,
                    ActionRepresentation.Action.MODIFY_SUBSCRIPTION));

            return new RepresentationCollection<>(col);
        }
    };

    return get(request, backend, params, false);
}
 
Example #25
Source File: TileImageService.java    From render with GNU General Public License v2.0 5 votes vote down vote up
@Path("v1/owner/{owner}/project/{project}/stack/{stack}/tile/{tileId}/jpeg-image")
@GET
@Produces(RenderServiceUtil.IMAGE_JPEG_MIME_TYPE)
@ApiOperation(value = "Render JPEG image for a tile")
@ApiResponses(value = {
        @ApiResponse(code = 404, message = "Tile not found")
})
public Response renderJpegImageForTile(@PathParam("owner") final String owner,
                                       @PathParam("project") final String project,
                                       @PathParam("stack") final String stack,
                                       @PathParam("tileId") final String tileId,
                                       @BeanParam final RenderQueryParameters renderQueryParameters,
                                       @QueryParam("width") final Integer width,
                                       @QueryParam("height") final Integer height,
                                       @QueryParam("normalizeForMatching") final Boolean normalizeForMatching,
                                       @QueryParam("excludeTransformsAfterLast") final Set<String> excludeAfterLastLabels,
                                       @QueryParam("excludeFirstTransformAndAllAfter") final Set<String> excludeFirstAndAllAfterLabels,
                                       @QueryParam("excludeAllTransforms") final Boolean excludeAllTransforms,
                                       @Context final Request request) {

    LOG.info("renderJpegImageForTile: entry, owner={}, project={}, stack={}, tileId={}",
             owner, project, stack, tileId);

    final ResponseHelper responseHelper = new ResponseHelper(request, getStackMetaData(owner, project, stack));
    if (responseHelper.isModified()) {
        final RenderParameters renderParameters =
                tileDataService.getRenderParameters(owner, project, stack, tileId, renderQueryParameters,
                                                    width, height, normalizeForMatching,
                                                    excludeAfterLastLabels, excludeFirstAndAllAfterLabels,
                                                    excludeAllTransforms);
        return RenderServiceUtil.renderJpegImage(renderParameters, null, responseHelper);
    } else {
        return responseHelper.getNotModifiedResponse();
    }
}
 
Example #26
Source File: CellResource.java    From io with Apache License 2.0 5 votes vote down vote up
/**
 * 次のパスをBoxResourceへ渡すメソッド.
 * @param request HTPPサーブレットリクエスト
 * @param boxName Boxパス名
 * @param jaxRsRequest JAX-RS用HTTPリクエスト
 * @return BoxResource BoxResource Object
 */
@Path("{box: [^\\/]+}")
public BoxResource box(
        @Context final HttpServletRequest request,
        @PathParam("box") final String boxName,
        @Context final Request jaxRsRequest) {
    return new BoxResource(this.cell, boxName, this.accessContext, this.cellRsCmp, request, jaxRsRequest);
}
 
Example #27
Source File: MyResource.java    From resteasy-examples with Apache License 2.0 5 votes vote down vote up
@Path("multi")
@GET
@Produces({"application/json", "application/xml"})
public Test getMulti(@Context Request request)
{
	return new Test("foo");
}
 
Example #28
Source File: EvaluatePreconditionsTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected Request getRequest(final String... headers) {
    final MessageImpl message = new MessageImpl();
    final Map<String, List<String>> map = new HashMap<>();
    message.put(Message.PROTOCOL_HEADERS, map);
    for (int i = 0; i < headers.length; i += 2) {
        final List<String> l = new ArrayList<>(1);
        l.add(headers[i + 1]);
        map.put(headers[i], l);
    }
    message.put(Message.HTTP_REQUEST_METHOD, "GET");
    return new RequestImpl(message);
}
 
Example #29
Source File: ReferenceResource.java    From org.openntf.domino with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #30
Source File: UsersResource.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/{userId}/avatar")
public Response getUserAvatar(@Context Request request, @PathParam("userId") String userId) {
    PictureEntity picture = userService.getPicture(userId);

    if (picture == null) {
        return Response.ok().build();
    }

    if (picture instanceof UrlPictureEntity) {
        return Response.temporaryRedirect(URI.create(((UrlPictureEntity) picture).getUrl())).build();
    }

    return createPictureResponse(request, (InlinePictureEntity) picture);
}