Java Code Examples for javax.ws.rs.container.ContainerRequestContext#setEntityStream()
The following examples show how to use
javax.ws.rs.container.ContainerRequestContext#setEntityStream() .
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: DefaultFormEntityProvider.java From krazo with Apache License 2.0 | 6 votes |
@Override public Form getForm(ContainerRequestContext context) throws IOException { final InputStream is = context.getEntityStream(); // Ensure stream can be restored for next interceptor InputStream bufferedStream; if (is.markSupported()) { bufferedStream = is; } else { bufferedStream = new BufferedInputStream(is); } bufferedStream.mark(Integer.MAX_VALUE); final MediaType contentType = context.getMediaType(); final String charset = contentType.getParameters().get("charset"); final String entity = toString(bufferedStream, charset != null ? charset : DEFAULT_CHARSET); final Form form = parseForm(entity); bufferedStream.reset(); context.setEntityStream(bufferedStream); return form; }
Example 2
Source File: AuditFilter.java From onos with Apache License 2.0 | 6 votes |
@Override public void filter(ContainerRequestContext requestContext) throws IOException { if (auditService() != null) { String requestBody = (requestContext.hasEntity() ? (readTreeFromStream(mapper, requestContext.getEntityStream()).toString()) : ""); requestContext.setProperty("requestBody", requestBody); // FIXME: audit message should be better structured requestContext.setProperty("auditMessage", "{\"Path" + logCompSeperator + requestContext.getUriInfo().getPath() + separator + "Method" + logCompSeperator + requestContext.getMethod() + separator + (requestContext.getMethod().equals("PUT") ? // FIXME: is there really a need to differentiate based on method? ("Path_Parameters" + logCompSeperator + requestContext.getUriInfo().getPathParameters().toString() + separator + "Query_Parameters" + logCompSeperator + requestContext.getUriInfo().getQueryParameters().toString() + separator + "Request_Body" + logCompSeperator + requestBody) : "")); requestContext.setEntityStream(IOUtils.toInputStream(requestBody)); } }
Example 3
Source File: JweContainerRequestFilter.java From cxf with Apache License 2.0 | 6 votes |
@Override public void filter(ContainerRequestContext context) throws IOException { if (isMethodWithNoContent(context.getMethod()) || isCheckEmptyStream() && !context.hasEntity()) { return; } final byte[] encryptedContent = IOUtils.readBytesFromStream(context.getEntityStream()); if (encryptedContent.length == 0) { return; } JweDecryptionOutput out = decrypt(encryptedContent); byte[] bytes = out.getContent(); context.setEntityStream(new ByteArrayInputStream(bytes)); context.getHeaders().putSingle("Content-Length", Integer.toString(bytes.length)); String ct = JoseUtils.checkContentType(out.getHeaders().getContentType(), getDefaultMediaType()); if (ct != null) { context.getHeaders().putSingle("Content-Type", ct); } if (super.isValidateHttpHeaders()) { super.validateHttpHeadersIfNeeded(context.getHeaders(), out.getHeaders()); } }
Example 4
Source File: AuditLogFilter.java From helix with Apache License 2.0 | 6 votes |
@Override public void filter(ContainerRequestContext request) throws IOException { AuditLog.Builder auditLogBuilder = new AuditLog.Builder(); auditLogBuilder.namespace(getNamespace()) .requestPath(request.getUriInfo().getPath()) .httpMethod(request.getMethod()) .startTime(new Date()) .requestHeaders(getHeaders(request.getHeaders())) .principal(_servletRequest.getUserPrincipal()) .clientIP(_servletRequest.getRemoteAddr()) .clientHostPort(_servletRequest.getRemoteHost() + ":" + _servletRequest.getRemotePort()); String entity = getEntity(request.getEntityStream()); auditLogBuilder.requestEntity(entity); InputStream stream = new ByteArrayInputStream(entity.getBytes(StandardCharsets.UTF_8)); request.setEntityStream(stream); request.setProperty(AuditLog.ATTRIBUTE_NAME, auditLogBuilder); }
Example 5
Source File: RequestLoggingFilter.java From pnc with Apache License 2.0 | 6 votes |
private String getEntityBody(ContainerRequestContext requestContext) { ByteArrayOutputStream out = new ByteArrayOutputStream(); InputStream in = requestContext.getEntityStream(); final StringBuilder b = new StringBuilder(); try { IOUtils.copy(in, out); byte[] requestEntity = out.toByteArray(); if (requestEntity.length == 0) { b.append("\n"); } else { b.append(new String(requestEntity)).append("\n"); } requestContext.setEntityStream(new ByteArrayInputStream(requestEntity)); } catch (IOException e) { logger.error("Error logging REST request.", e); } return b.toString(); }
Example 6
Source File: LogFilter.java From container with Apache License 2.0 | 6 votes |
@Override public void filter(final ContainerRequestContext request) throws IOException { if (logger.isDebugEnabled()) { logger.debug("=== LogFilter BEGIN ==="); logger.debug("Method: {}", request.getMethod()); logger.debug("URL: {}", UriUtil.encode(request.getUriInfo().getAbsolutePath())); for (final String key : request.getHeaders().keySet()) { logger.debug(key + " : " + request.getHeaders().get(key)); } final List<MediaType> mediaTypes = Lists.newArrayList(MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_XML_TYPE, MediaType.TEXT_PLAIN_TYPE, MediaType.TEXT_XML_TYPE, MediaType.TEXT_HTML_TYPE); if (request.getMediaType() != null && mediaTypes.contains(request.getMediaType())) { if (request.hasEntity()) { final String body = IOUtils.toString(request.getEntityStream()); request.setEntityStream(IOUtils.toInputStream(body)); logger.debug("Body: {}", body); } } logger.debug("=== LogFilter END ==="); } }
Example 7
Source File: VerifySignatureFilter.java From cxf with Apache License 2.0 | 5 votes |
@Override public void filter(ContainerRequestContext requestCtx) { byte[] messageBody = verifyDigest(requestCtx.getHeaders(), requestCtx.getEntityStream()); if (messageBody != null) { requestCtx.setEntityStream(new ByteArrayInputStream(messageBody)); } verifySignature(requestCtx.getHeaders(), requestCtx.getUriInfo().getAbsolutePath().getPath(), requestCtx.getMethod()); }
Example 8
Source File: JweJsonContainerRequestFilter.java From cxf with Apache License 2.0 | 5 votes |
@Override public void filter(ContainerRequestContext context) throws IOException { if (isMethodWithNoContent(context.getMethod()) || isCheckEmptyStream() && !context.hasEntity()) { return; } final byte[] encryptedContent = IOUtils.readBytesFromStream(context.getEntityStream()); if (encryptedContent.length == 0) { return; } try { JweDecryptionOutput out = decrypt(encryptedContent); byte[] bytes = out.getContent(); context.setEntityStream(new ByteArrayInputStream(bytes)); context.getHeaders().putSingle("Content-Length", Integer.toString(bytes.length)); String ct = JoseUtils.checkContentType(out.getHeaders().getContentType(), getDefaultMediaType()); if (ct != null) { context.getHeaders().putSingle("Content-Type", ct); } if (super.isValidateHttpHeaders()) { super.validateHttpHeadersIfNeeded(context.getHeaders(), out.getHeaders()); } } catch (JweException ex) { context.abortWith(JAXRSUtils.toResponse(400)); return; } }
Example 9
Source File: JwsJsonContainerRequestFilter.java From cxf with Apache License 2.0 | 5 votes |
@Override public void filter(ContainerRequestContext context) throws IOException { if (isMethodWithNoContent(context.getMethod()) || isCheckEmptyStream() && !context.hasEntity()) { return; } final String content = IOUtils.readStringFromStream(context.getEntityStream()); if (StringUtils.isEmpty(content)) { return; } JwsSignatureVerifier theSigVerifier = getInitializedSigVerifier(); JwsJsonConsumer c = new JwsJsonConsumer(content); try { validate(c, theSigVerifier); } catch (JwsException ex) { context.abortWith(JAXRSUtils.toResponse(400)); return; } byte[] bytes = c.getDecodedJwsPayloadBytes(); context.setEntityStream(new ByteArrayInputStream(bytes)); context.getHeaders().putSingle("Content-Length", Integer.toString(bytes.length)); // the list is guaranteed to be non-empty JwsJsonSignatureEntry sigEntry = c.getSignatureEntries().get(0); String ct = JoseUtils.checkContentType(sigEntry.getUnionHeader().getContentType(), getDefaultMediaType()); if (ct != null) { context.getHeaders().putSingle("Content-Type", ct); } if (super.isValidateHttpHeaders()) { super.validateHttpHeadersIfNeeded(context.getHeaders(), sigEntry.getProtectedHeader()); } }
Example 10
Source File: JwsContainerRequestFilter.java From cxf with Apache License 2.0 | 5 votes |
@Override public void filter(ContainerRequestContext context) throws IOException { if (isMethodWithNoContent(context.getMethod()) || isCheckEmptyStream() && !context.hasEntity()) { return; } final String content = IOUtils.readStringFromStream(context.getEntityStream()); if (StringUtils.isEmpty(content)) { return; } JwsCompactConsumer p = new JwsCompactConsumer(content); JwsSignatureVerifier theSigVerifier = getInitializedSigVerifier(p.getJwsHeaders()); if (!p.verifySignatureWith(theSigVerifier)) { context.abortWith(JAXRSUtils.toResponse(400)); return; } JoseUtils.validateRequestContextProperty(p.getJwsHeaders()); byte[] bytes = p.getDecodedJwsPayloadBytes(); context.setEntityStream(new ByteArrayInputStream(bytes)); context.getHeaders().putSingle("Content-Length", Integer.toString(bytes.length)); String ct = JoseUtils.checkContentType(p.getJwsHeaders().getContentType(), getDefaultMediaType()); if (ct != null) { context.getHeaders().putSingle("Content-Type", ct); } if (super.isValidateHttpHeaders()) { super.validateHttpHeadersIfNeeded(context.getHeaders(), p.getJwsHeaders()); } Principal currentPrincipal = context.getSecurityContext().getUserPrincipal(); if (currentPrincipal == null || currentPrincipal.getName() == null) { SecurityContext securityContext = configureSecurityContext(theSigVerifier); if (securityContext != null) { JAXRSUtils.getCurrentMessage().put(SecurityContext.class, securityContext); } } }
Example 11
Source File: LoggingFilter.java From docker-java with Apache License 2.0 | 5 votes |
@Override public void filter(final ContainerRequestContext context) throws IOException { final long id = aid.incrementAndGet(); final StringBuilder b = new StringBuilder(); printRequestLine(b, "Server has received a request", id, context.getMethod(), context.getUriInfo() .getRequestUri()); printPrefixedHeaders(b, id, REQUEST_PREFIX, context.getHeaders()); if (printEntity && context.hasEntity()) { context.setEntityStream(logInboundEntity(b, context.getEntityStream())); } log(b); }
Example 12
Source File: RemoteRequest.java From logbook with MIT License | 5 votes |
@Override public State buffer( final ContainerRequestContext context) throws IOException { final byte[] body = toByteArray(context.getEntityStream()); context.setEntityStream(new ByteArrayInputStream(body)); return new Buffering(body); }
Example 13
Source File: OidcRpAuthenticationFilter.java From cxf with Apache License 2.0 | 5 votes |
private MultivaluedMap<String, String> toRequestState(ContainerRequestContext rc) { MultivaluedMap<String, String> requestState = new MetadataMap<>(); requestState.putAll(rc.getUriInfo().getQueryParameters(true)); if (MediaType.APPLICATION_FORM_URLENCODED_TYPE.isCompatible(rc.getMediaType())) { String body = FormUtils.readBody(rc.getEntityStream(), StandardCharsets.UTF_8.name()); FormUtils.populateMapFromString(requestState, JAXRSUtils.getCurrentMessage(), body, StandardCharsets.UTF_8.name(), true); rc.setEntityStream(new ByteArrayInputStream(StringUtils.toBytesUTF8(body))); } return requestState; }
Example 14
Source File: AbstractFilterInterceptorTest.java From servicetalk with Apache License 2.0 | 5 votes |
@Override public void filter(final ContainerRequestContext requestCtx) { // Simulate an ill-behaved filter that consumes the all request content beforehand // instead of modifying it in a streaming fashion (as done in super) try { Collection<byte[]> collection = fromInputStream(new UpperCaseInputStream( requestCtx.getEntityStream())).toFuture().get(); requestCtx.setEntityStream(fromIterable(collection).toInputStream(identity())); } catch (Exception e) { throw new RuntimeException(e); } }
Example 15
Source File: RequestUtils.java From jeesuite-libs with Apache License 2.0 | 4 votes |
/** * 获取请求参数 * @param request * @param inputStream * @return * @throws IOException */ public static Map<String, Object> getParametersMap(ContainerRequestContext requestContext,HttpServletRequest request) throws IOException { if(isMultipartContent(request)){ return buildQueryParamsMap(request); } Map<String, Object> parameters = buildQueryParamsMap(request); if (RestConst.GET_METHOD.equals(request.getMethod())) { return parameters; }else if (RestConst.POST_METHOD.equals(request.getMethod())) { byte[] byteArray = IOUtils.toByteArray(requestContext.getEntityStream()); //reset InputStream requestContext.setEntityStream(new ByteArrayInputStream(byteArray)); if(byteArray == null || byteArray.length == 0)return parameters; String content = new String(byteArray); //JSON // try { // return JsonUtils.toObject(content, Map.class); // } catch (Exception e) {} if(content.contains("{")){ content = StringUtils.left(content, 2048).trim(); if(!content.endsWith("}"))content = content + "...\n}"; parameters.put("data", content); return parameters; } String[] split = content.split("\\&"); for (String s : split) { String[] split2 = s.split("="); if (split2.length == 2 && StringUtils.isNotBlank(split2[1])) { parameters.put(split2[0], split2[1]); } } return parameters; } return null; }
Example 16
Source File: BookServer20.java From cxf with Apache License 2.0 | 4 votes |
@Override public void filter(ContainerRequestContext context) throws IOException { UriInfo ui = context.getUriInfo(); String path = ui.getPath(false); if ("POST".equals(context.getMethod()) && "bookstore/bookheaders/simple".equals(path) && !context.hasEntity()) { byte[] bytes = StringUtils.toBytesUTF8("<Book><name>Book</name><id>126</id></Book>"); context.getHeaders().putSingle(HttpHeaders.CONTENT_LENGTH, Integer.toString(bytes.length)); context.getHeaders().putSingle("Content-Type", "application/xml"); context.getHeaders().putSingle("EmptyRequestStreamDetected", "true"); context.setEntityStream(new ByteArrayInputStream(bytes)); } if ("true".equals(context.getProperty("DynamicPrematchingFilter"))) { throw new RuntimeException(); } context.setProperty("FirstPrematchingFilter", "true"); if ("wrongpath".equals(path)) { context.setRequestUri(URI.create("/bookstore/bookheaders/simple")); } else if ("throwException".equals(path)) { context.setProperty("filterexception", "prematch"); throw new InternalServerErrorException( Response.status(500).type("text/plain") .entity("Prematch filter error").build()); } else if ("throwExceptionIO".equals(path)) { context.setProperty("filterexception", "prematch"); throw new IOException(); } MediaType mt = context.getMediaType(); if (mt != null && "text/xml".equals(mt.toString())) { String method = context.getMethod(); if ("PUT".equals(method)) { context.setMethod("POST"); } context.getHeaders().putSingle("Content-Type", "application/xml"); } else { String newMt = context.getHeaderString("newmediatype"); if (newMt != null) { context.getHeaders().putSingle("Content-Type", newMt); } } List<MediaType> acceptTypes = context.getAcceptableMediaTypes(); if (acceptTypes.size() == 1 && "text/mistypedxml".equals(acceptTypes.get(0).toString())) { context.getHeaders().putSingle("Accept", "text/xml"); } }
Example 17
Source File: BookServer20.java From cxf with Apache License 2.0 | 4 votes |
private void replaceStream(ContainerRequestContext context) { InputStream is = new ByteArrayInputStream("123".getBytes()); context.setEntityStream(is); }
Example 18
Source File: RequestUtils.java From azeroth with Apache License 2.0 | 4 votes |
/** * 获取请求参数 * @param request * @param inputStream * @return * @throws IOException */ public static Map<String, Object> getParametersMap(ContainerRequestContext requestContext, HttpServletRequest request) throws IOException { if (isMultipartContent(request)) { return buildQueryParamsMap(request); } Map<String, Object> parameters = buildQueryParamsMap(request); if (RestConst.GET_METHOD.equals(request.getMethod())) { return parameters; } else if (RestConst.POST_METHOD.equals(request.getMethod())) { byte[] byteArray = IOUtils.toByteArray(request.getInputStream()); //reset InputStream requestContext.setEntityStream(new ByteArrayInputStream(byteArray)); if (byteArray == null || byteArray.length == 0) return parameters; String content = new String(byteArray); //JSON // try { // return JsonUtils.toObject(content, Map.class); // } catch (Exception e) {} if (content.contains("{")) { content = StringUtils.left(content, 2048).trim(); if (!content.endsWith("}")) content = content + "...\n}"; parameters.put("data", content); return parameters; } String[] split = content.split("\\&"); for (String s : split) { String[] split2 = s.split("="); if (split2.length == 2 && StringUtils.isNotBlank(split2[1])) { parameters.put(split2[0], split2[1]); } } return parameters; } return null; }
Example 19
Source File: AbstractFilterInterceptorTest.java From servicetalk with Apache License 2.0 | 4 votes |
@Override public void filter(final ContainerRequestContext requestCtx) { requestCtx.setEntityStream(new UpperCaseInputStream(requestCtx.getEntityStream())); }
Example 20
Source File: FilterStreamingJsonTest.java From servicetalk with Apache License 2.0 | 4 votes |
@Override public void filter(final ContainerRequestContext requestCtx) { requestCtx.setEntityStream(new UpperCaseInputStream(requestCtx.getEntityStream())); }