com.sun.jersey.api.core.HttpRequestContext Java Examples
The following examples show how to use
com.sun.jersey.api.core.HttpRequestContext.
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: RequestDecoder.java From jersey-hmac-auth with Apache License 2.0 | 6 votes |
/** * Under normal circumstances, the body of the request can only be read once, because it is * backed by an {@code InputStream}, and thus is not easily consumed multiple times. This * method gets the request content and resets it so it can be read again later if necessary. */ private byte[] safelyGetContent(HttpRequestContext request) { ContainerRequest containerRequest = (ContainerRequest) request; ByteArrayOutputStream out = new ByteArrayOutputStream(); InputStream in = containerRequest.getEntityInputStream(); try { ReaderWriter.writeTo(in, out); byte[] content = out.toByteArray(); // Reset the input stream so that it can be read again by another filter or resource containerRequest.setEntityInputStream(new ByteArrayInputStream(content)); return content; } catch (IOException ex) { throw new ContainerException(ex); } }
Example #2
Source File: AuthResourceFilterFactory.java From emodb with Apache License 2.0 | 6 votes |
/** * Creates a substitution function for query param values, such as * <code>@RequiresPermission("resource|update|{?id}")</code> */ private Function<HttpRequestContext, String> createQuerySubstitution(final String param) { return new Function<HttpRequestContext, String>() { @Override public String apply(HttpRequestContext request) { MultivaluedMap<String, String> params = request.getQueryParameters(); if (!params.containsKey(param)) { throw new IllegalStateException("Parameter required for authentication is missing: " + param); } List<String> values = params.get(param); if (values.size() != 1) { throw new IllegalStateException("Exactly one parameter expected for authentication: " + param); } return values.get(0); } }; }
Example #3
Source File: BulkExtractTest.java From secure-data-service with Apache License 2.0 | 6 votes |
@Test public void testFailedEvaluatePreconditions() throws Exception { injector.setOauthAuthenticationWithEducationRole(); mockApplicationEntity(); mockBulkExtractEntity(null); HttpRequestContext context = new HttpRequestContextAdapter() { @Override public ResponseBuilder evaluatePreconditions(Date lastModified, EntityTag eTag) { return Responses.preconditionFailed(); } }; Response res = bulkExtract.getEdOrgExtractResponse(context, null, null); assertEquals(412, res.getStatus()); }
Example #4
Source File: AuthorizationResourceFilter.java From emodb with Apache License 2.0 | 6 votes |
/** * Resolves permissions based on the request. For example, if the annotation's permission is * "get|{thing}" and the method's @Path annotation is "/resources/{thing}" then a request to * "/resources/table" will resolve to the permission "get|table". */ private String[] resolvePermissions(ContainerRequest request) { String[] values = _permissions; if (_substitutions.isEmpty()) { return values; } String[] permissions = new String[values.length]; System.arraycopy(values, 0, permissions, 0, values.length); for (Map.Entry<String, Function<HttpRequestContext, String>> entry : _substitutions.entrySet()) { String key = Pattern.quote(entry.getKey()); String substitution = Matcher.quoteReplacement(MatchingPermission.escape(entry.getValue().apply(request))); for (int i=0; i < values.length; i++) { permissions[i] = permissions[i].replaceAll(key, substitution); } } return permissions; }
Example #5
Source File: RequestDecoder.java From jersey-hmac-auth with Apache License 2.0 | 6 votes |
public Credentials decode(HttpRequestContext request) { Version version = getVersion(request); Credentials.CredentialsBuilder builder = Credentials.builder() .withApiKey(getApiKey(request)) .withSignature(getSignature(request)) .withPath(getPath(request)) .withTimestamp(getTimestamp(request)) .withMethod(getMethod(request)) .withVersion(version); if (requestConfiguration.isDataInSignature(version)) { builder.withContent(getContent(request)); } return builder.build(); }
Example #6
Source File: DefaultRequestHandlerTest.java From jersey-hmac-auth with Apache License 2.0 | 5 votes |
@Test(expected = NotAuthorizedException.class) public void testHandleWithInvalidCredentials() { HttpRequestContext request = mock(HttpRequestContext.class); when(decoder.decode(any(HttpRequestContext.class))).thenReturn(credentials); when(authenticator.authenticate(any(Credentials.class))).thenReturn(null); handler.handle(request); fail(); }
Example #7
Source File: DefaultRequestHandlerTest.java From jersey-hmac-auth with Apache License 2.0 | 5 votes |
@Test public void testHandleWithValidCredentials() { HttpRequestContext request = mock(HttpRequestContext.class); when(decoder.decode(any(HttpRequestContext.class))).thenReturn(credentials); when(authenticator.authenticate(any(Credentials.class))).thenReturn(principal); String value = handler.handle(request); assertNotNull(value); assertEquals(principal, value); }
Example #8
Source File: DefaultRequestHandlerTest.java From jersey-hmac-auth with Apache License 2.0 | 5 votes |
@Test(expected = InternalServerException.class) public void testHandleWithInternalError() { HttpRequestContext request = mock(HttpRequestContext.class); when(decoder.decode(any(HttpRequestContext.class))).thenReturn(credentials); when(authenticator.authenticate(any(Credentials.class))).thenThrow(new NullPointerException()); handler.handle(request); fail(); }
Example #9
Source File: InstrumentedRequestDispatcher.java From titus-control-plane with Apache License 2.0 | 5 votes |
private String generateRequestResponseErrorMessage(HttpContext context, Exception e) { StringBuilder result = new StringBuilder(); HttpRequestContext request = context.getRequest(); HttpResponseContext response = context.getResponse(); result.append("An error occurred during an HTTP request:\r\n"); if (request != null) { String bodyLengthString = request.getHeaderValue("Content-Length"); result.append("Request Path: " + request.getMethod().toUpperCase() + " " + request.getRequestUri().toString() + "\r\n"); result.append("Request Content-Length: " + bodyLengthString + "\r\n"); result.append("Request Headers:\r\n" + request.getRequestHeaders() .entrySet() .stream() .map(entry -> "\t" + entry.getKey() + ": " + entry.getValue() + "\r\n") .collect(Collectors.joining()) ); long bodyLength = Strings.isNullOrEmpty(bodyLengthString) ? 0 : Long.parseLong(bodyLengthString); if (bodyLength > 0 && ((ContainerRequest) request).getEntityInputStream().markSupported()) { try { ((ContainerRequest) request).getEntityInputStream().reset(); result.append("Request Body:\r\n" + request.getEntity(String.class) + "\r\n"); } catch (Exception ignore) { } } } result.append("Error response http code: " + response.getStatus() + "\r\n"); result.append("Error message: " + e.getMessage() + "\r\n"); result.append("Error stack trace :\r\n" + Throwables.getStackTraceAsString(e) + "\r\n"); return result.toString(); }
Example #10
Source File: OptionalRequestHandlerTest.java From jersey-hmac-auth with Apache License 2.0 | 5 votes |
@Test public void testHandleWithValidCredentials() { HttpRequestContext request = mock(HttpRequestContext.class); when(decoder.decode(any(HttpRequestContext.class))).thenReturn(credentials); when(authenticator.authenticate(any(Credentials.class))).thenReturn(principal); String value = handler.handle(request); assertNotNull(value); assertEquals(principal, value); }
Example #11
Source File: OptionalRequestHandlerTest.java From jersey-hmac-auth with Apache License 2.0 | 5 votes |
@Test(expected = NotAuthorizedException.class) public void testHandleWithInvalidCredentials() { HttpRequestContext request = mock(HttpRequestContext.class); when(decoder.decode(any(HttpRequestContext.class))).thenReturn(credentials); when(authenticator.authenticate(any(Credentials.class))).thenReturn(null); handler.handle(request); fail(); }
Example #12
Source File: OptionalRequestHandlerTest.java From jersey-hmac-auth with Apache License 2.0 | 5 votes |
@Test(expected = InternalServerException.class) public void testHandleWithInternalError() { HttpRequestContext request = mock(HttpRequestContext.class); when(decoder.decode(any(HttpRequestContext.class))).thenReturn(credentials); when(authenticator.authenticate(any(Credentials.class))).thenThrow(new NullPointerException()); handler.handle(request); fail(); }
Example #13
Source File: BulkExtract.java From secure-data-service with Apache License 2.0 | 5 votes |
/** * Get the bulk extract response * * @param req the http request context * @param deltaDate the date of the delta, or null to get the full extract * @param edOrgId the Ed Org id (if private extract) * @param isPublicData indicates if the extract is for public data * @return the jax-rs response to send back. */ Response getEdOrgExtractResponse(final HttpRequestContext req, final String edOrgId, final String deltaDate) { ExtractFile ef = getEdOrgExtractFile(edOrgId, deltaDate); if (ef == null) { return Response.status(Status.NOT_FOUND).build(); } return fileResource.getFileResponse(req, ef, ef.getLastModified()); }
Example #14
Source File: BulkExtract.java From secure-data-service with Apache License 2.0 | 5 votes |
/** * Get the bulk extract response * * @param req the http request context * @param deltaDate the date of the delta, or null to get the full extract * @param edOrgId the Ed Org id (if private extract) * @param isPublicData indicates if the extract is for public data * @return the jax-rs response to send back. */ Response getPublicExtractResponse(final HttpRequestContext req, final String deltaDate) { ExtractFile ef = getPublicExtractFile(deltaDate); if (ef == null) { return Response.status(Status.NOT_FOUND).build(); } return fileResource.getFileResponse(req, ef, ef.getLastModified()); }
Example #15
Source File: BulkExtractTest.java From secure-data-service with Apache License 2.0 | 5 votes |
@Test public void testGetExtractResponse() throws Exception { injector.setOauthAuthenticationWithEducationRole(); mockApplicationEntity(); mockBulkExtractEntity(null); HttpRequestContext context = new HttpRequestContextAdapter() { @Override public String getMethod() { return "GET"; } }; Response res = bulkExtract.getEdOrgExtractResponse(context, null, null); assertEquals(200, res.getStatus()); MultivaluedMap<String, Object> headers = res.getMetadata(); assertNotNull(headers); assertTrue(headers.containsKey("content-disposition")); assertTrue(headers.containsKey("last-modified")); String header = (String) headers.getFirst("content-disposition"); assertNotNull(header); assertTrue(header.startsWith("attachment")); assertTrue(header.indexOf(INPUT_FILE_NAME) > 0); Object entity = res.getEntity(); assertNotNull(entity); StreamingOutput out = (StreamingOutput) entity; ByteArrayOutputStream os = new ByteArrayOutputStream(); out.write(os); os.flush(); byte[] responseData = os.toByteArray(); String s = new String(responseData); assertEquals(BULK_DATA, s); }
Example #16
Source File: JerseyRequestModuleProvidesTest.java From dagger-servlet with Apache License 2.0 | 5 votes |
@Inject public RequestProvidesResource(HttpContext httpContext, UriInfo uriInfo, ExtendedUriInfo extendedUriInfo, HttpRequestContext httpRequestContext, HttpHeaders httpHeaders, Request request, SecurityContext securityContext, HttpResponseContext httpResponseContext) { assertNotNull(httpContext); assertNotNull(uriInfo); assertNotNull(extendedUriInfo); assertNotNull(httpRequestContext); assertNotNull(httpHeaders); assertNotNull(request); assertNotNull(securityContext); assertNotNull(httpResponseContext); }
Example #17
Source File: BulkExtractTest.java From secure-data-service with Apache License 2.0 | 5 votes |
@Test public void testHeadTenant() throws Exception { injector.setOauthAuthenticationWithEducationRole(); mockApplicationEntity(); mockBulkExtractEntity(null); HttpRequestContext context = new HttpRequestContextAdapter() { @Override public String getMethod() { return "HEAD"; } }; Response res = bulkExtract.getEdOrgExtractResponse(context, null, null); assertEquals(200, res.getStatus()); MultivaluedMap<String, Object> headers = res.getMetadata(); assertNotNull(headers); assertTrue(headers.containsKey("content-disposition")); assertTrue(headers.containsKey("last-modified")); String header = (String) headers.getFirst("content-disposition"); assertNotNull(header); assertTrue(header.startsWith("attachment")); assertTrue(header.indexOf(INPUT_FILE_NAME) > 0); Object entity = res.getEntity(); assertNull(entity); }
Example #18
Source File: ApiKeyAuthenticationTokenGenerator.java From emodb with Apache License 2.0 | 5 votes |
@Override public ApiKeyAuthenticationToken createToken(HttpRequestContext context) { String apiKey = context.getHeaderValue(ApiKeyRequest.AUTHENTICATION_HEADER); if (Strings.isNullOrEmpty(apiKey)) { apiKey = context.getQueryParameters().getFirst(ApiKeyRequest.AUTHENTICATION_PARAM); if (Strings.isNullOrEmpty(apiKey)) { return null; } } return new ApiKeyAuthenticationToken(apiKey); }
Example #19
Source File: BulkExtractTest.java From secure-data-service with Apache License 2.0 | 5 votes |
@Test public void testRange() throws Exception { injector.setOauthAuthenticationWithEducationRole(); mockApplicationEntity(); mockBulkExtractEntity(null); HttpRequestContext failureContext = Mockito.mock(HttpRequestContext.class); Mockito.when(failureContext.getMethod()).thenReturn("HEAD"); Mockito.when(failureContext.getHeaderValue("Range")).thenReturn("bytes=0"); Response failureRes = bulkExtract.getEdOrgExtractResponse(failureContext, null, null); assertEquals(416, failureRes.getStatus()); HttpRequestContext validContext = Mockito.mock(HttpRequestContext.class); Mockito.when(validContext.getMethod()).thenReturn("HEAD"); Mockito.when(validContext.getHeaderValue("Range")).thenReturn("bytes=0-5"); Response validRes = bulkExtract.getEdOrgExtractResponse(validContext, null, null); assertEquals(200, validRes.getStatus()); HttpRequestContext multiRangeContext = Mockito.mock(HttpRequestContext.class); Mockito.when(multiRangeContext.getMethod()).thenReturn("HEAD"); Mockito.when(multiRangeContext.getHeaderValue("Range")).thenReturn("bytes=0-5,6-10"); Response multiRangeRes = bulkExtract.getEdOrgExtractResponse(validContext, null, null); assertEquals(200, multiRangeRes.getStatus()); }
Example #20
Source File: AuthResourceFilterFactory.java From emodb with Apache License 2.0 | 5 votes |
/** * Creates a substitution function for path values, such as * <code>@RequiresPermission("resource|update|{id}")</code> */ private Function<HttpRequestContext, String> createPathSubstitution(final String param, final AbstractMethod am) { int from = 0; int segment = -1; // Get the path from resource then from the method Path[] annotations = new Path[] { am.getResource().getAnnotation(Path.class), am.getAnnotation(Path.class) }; for (Path annotation : annotations) { if (annotation == null) { continue; } int index = getSubstitutionIndex(param, annotation.value()); if (index >= 0) { segment = from + index; } else { from += -index; } } if (segment == -1) { throw new IllegalArgumentException("Param not found in path: " + param); } final int validatedSegment = segment; return new Function<HttpRequestContext, String>() { @Override public String apply(HttpRequestContext request) { return request.getPathSegments().get(validatedSegment).getPath(); } }; }
Example #21
Source File: AuthResourceFilterFactory.java From emodb with Apache License 2.0 | 5 votes |
/** * Returns a mapping from permissions found in the annotations to functions which can perform any necessary * substitutions based on actual values in the request. */ private Map<String,Function<HttpRequestContext, String>> createSubstitutionMap(String[] permissions, AbstractMethod am) { Map<String, Function<HttpRequestContext, String>> map = Maps.newLinkedHashMap(); for (String permission : permissions) { Matcher matcher = SUBSTITUTION_MATCHER.matcher(permission); while (matcher.find()) { String match = matcher.group(); if (map.containsKey(match)) { continue; } String param = matcher.group("param"); Function<HttpRequestContext, String> substitution; if (param.startsWith("?")) { substitution = createQuerySubstitution(param.substring(1)); } else { substitution = createPathSubstitution(param, am); } map.put(match, substitution); } } return map; }
Example #22
Source File: BulkExtractTest.java From secure-data-service with Apache License 2.0 | 5 votes |
@Override public HttpRequestContext getRequest() { return new HttpRequestContextAdapter() { @Override public String getMethod() { return "GET"; } }; }
Example #23
Source File: FileResource.java From secure-data-service with Apache License 2.0 | 4 votes |
/** * Validate and process range request. * * @param req * The http request context * @param full * The full range of the requested file * @param ranges * The list where the processed ranges are stored * @param fileLength * The length of the requested file * @param lastModifiedTime * The last modified time of the file * @param eTag an ETag for the current state of the resource * @return null if the range request is valid or a ResponseBuilder set with * the status of 416 if the range request cannot be processed. A returned * ResponseBuilder will include a Content-Range set to the file length. */ private ResponseBuilder processRangeHeader(final HttpRequestContext req, final Range full, final List<Range> ranges, final long fileLength, final long lastModifiedTime, final String eTag) { String range = req.getHeaderValue("Range"); if (range != null && range.length() > 0) { // Range header should match format "bytes=n-n,n-n,n-n...". If not, then return 416. if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*$")) { logSecurityEvent(req.getRequestUri(), "Range header doesn't match format"); return Response.status(416).header("Content-Range", "bytes */" + fileLength);// Required in 416. } // If-Range header should either match ETag or be greater then LastModified. If not, // then return full file. String ifRange = req.getHeaderValue("If-Range"); if (ifRange != null && !ifRange.equals(eTag)) { try { long ifRangeTime = HttpHeaderReader.readDate(ifRange).getTime(); if (ifRangeTime > 0 && ifRangeTime + 1000 < lastModifiedTime) { ranges.add(full); } } catch (ParseException ignore) { ranges.add(full); } } // If any valid If-Range header, then process each part of byte range. if (ranges.isEmpty()) { for (String part : range.substring(6).split(",")) { // Assuming a file with fileLength of 100, the following examples returns bytes at: // 50-80 (50 to 80), 40- (40 to fileLength=100), -20 (fileLength-20=80 to fileLength=100). long start = sublong(part, 0, part.indexOf("-")); long end = sublong(part, part.indexOf("-") + 1, part.length()); if (start == -1) { start = Math.max(0, fileLength - end); end = fileLength - 1; } else if (end == -1 || end > fileLength - 1) { end = fileLength - 1; } // Check if Range is syntactically valid. If not, then return 416. if (start > end) { logSecurityEvent(req.getRequestUri(), "If Range is not syntactically valid"); return Response.status(416).header("Content-Range", "bytes */" + fileLength); // Required in 416. } // Add range. ranges.add(new Range(start, end, fileLength)); } } } return null; }
Example #24
Source File: FileResource.java From secure-data-service with Apache License 2.0 | 4 votes |
/** * Get the file request response. * * @param req * The HTTP request context * @param requestedFile * The requested file to return * @param lastModified * The last modified date * @return * Response with the requested file * @throws ParseException */ public Response getFileResponse(final HttpRequestContext req, final File requestedFile, final Date lastModified) { LOG.info("Retrieving bulk extract with method {}", req.getMethod()); String fileName = requestedFile.getName(); long fileLength = requestedFile.length(); String eTag = fileName + "_" + fileLength + "_" + lastModified; /* * Validate request headers for caching and resume */ ResponseBuilder builder = req.evaluatePreconditions(lastModified, new EntityTag(eTag)); if (builder != null) { // evaluate fails logSecurityEvent(req.getRequestUri(), "Bulk Extract request header preconditions failed"); return builder.build(); } /* * Validate and process range */ // Prepare some variables. The full Range represents the complete file. final Range full = new Range(0, fileLength - 1, fileLength); final List<Range> ranges = new ArrayList<Range>(); builder = processRangeHeader(req, full, ranges, fileLength, lastModified.getTime(), eTag); if (builder != null) { // validation fails return builder.build(); } /* * Combine overlapped ranges */ if (ranges.size() > 1) { combineOverlapped(ranges); } /* * Prepare and initialize response */ boolean fullContent = ranges.isEmpty() || ranges.get(0) == full || ranges.get(0).equals(full); boolean headMethod = req.getMethod().equals("HEAD"); builder = fullContent ? Response.ok() : Response.status(206); builder.header("content-disposition", "attachment; filename = " + fileName) .header("Accept-Ranges", "bytes") .header("ETag", eTag) .header(HttpHeaders.LAST_MODIFIED, lastModified); Response r = null; if (fullContent || ranges.size() == 1) { r = singlePartFileResponse(builder, requestedFile, (fullContent ? full : ranges.get(0)), headMethod); logSecurityEvent(req.getRequestUri(), "Successful request for singlePartFileResponse"); } else { if (headMethod) { r = Responses.methodNotAllowed().header("Allow", "GET").build(); } else { r = multiPartsFileResponse(builder, requestedFile, ranges); logSecurityEvent(req.getRequestUri(), "Successful request for multiPartsFileResponse"); } } return r; }
Example #25
Source File: OptionalRequestHandlerTest.java From jersey-hmac-auth with Apache License 2.0 | 4 votes |
@Test public void testHandleWithoutCredentials() { when(decoder.decode(any(HttpRequestContext.class))).thenThrow(new IllegalArgumentException()); String value = handler.handle(request); assertNull(value); }
Example #26
Source File: RequestDecoder.java From jersey-hmac-auth with Apache License 2.0 | 4 votes |
private byte[] getContent(HttpRequestContext request) { return safelyGetContent(request); }
Example #27
Source File: DefaultRequestHandlerTest.java From jersey-hmac-auth with Apache License 2.0 | 4 votes |
@Test(expected = NotAuthorizedException.class) public void testHandleWithoutCredentials() { when(decoder.decode(any(HttpRequestContext.class))).thenThrow(new IllegalArgumentException()); handler.handle(request); fail(); }
Example #28
Source File: RequestDecoder.java From jersey-hmac-auth with Apache License 2.0 | 4 votes |
private String getRequiredHeaderField(HttpRequestContext request, String name) { String value = request.getHeaderValue(name); checkArgument(!isNullOrEmpty(value), "Missing required HTTP header: " + name); return value; }
Example #29
Source File: RequestDecoder.java From jersey-hmac-auth with Apache License 2.0 | 4 votes |
private String getMethod(HttpRequestContext request) { return request.getMethod(); }
Example #30
Source File: RequestDecoder.java From jersey-hmac-auth with Apache License 2.0 | 4 votes |
private Version getVersion(HttpRequestContext request) { return Version.fromValue(getRequiredHeaderField(request, this.requestConfiguration.getVersionHttpHeader())); }