@Override public void writeTo(final Template template, final Viewable viewable, final MediaType mediaType, final MultivaluedMap<String, Object> httpHeaders, final OutputStream out) throws IOException { try { Object model = viewable.getModel(); if (!(model instanceof Map)) { model = new HashMap<String, Object>() {{ put("model", viewable.getModel()); }}; } Charset encoding = setContentType(mediaType, httpHeaders); template.process(model, new OutputStreamWriter(out, encoding)); } catch (TemplateException te) { throw new ContainerException(te); } }
private void stripResponse(ClientResponseContext responseContext) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); InputStream in = responseContext.getEntityStream(); final StringBuilder b = new StringBuilder(); try { if (in.available() > 0) { ReaderWriter.writeTo(in, out); StringBuffer sbuf = new StringBuffer(new String(out.toByteArray())); if (sbuf.indexOf(ALLOW_ILLEGAL_RESOURCE_CALL_PREFIX) == 0) { if (log.isDebugEnabled()) { log.debug("Stripping "+ALLOW_ILLEGAL_RESOURCE_CALL_PREFIX); } responseContext.setEntityStream(new ByteArrayInputStream(sbuf.substring(ALLOW_ILLEGAL_RESOURCE_CALL_PREFIX.length()).getBytes())); } else { responseContext.setEntityStream(new ByteArrayInputStream(out.toByteArray())); } // end if } // end if } catch (IOException ex) { throw new ContainerException(ex); } // end try/catch }
private void logResponse(ClientResponseContext responseContext) throws IOException { String responseBody = null; ByteArrayOutputStream out = new ByteArrayOutputStream(); InputStream in = responseContext.getEntityStream(); final StringBuilder b = new StringBuilder(); try { if (in.available() > 0) { ReaderWriter.writeTo(in, out); responseContext.setEntityStream(new ByteArrayInputStream(out.toByteArray())); responseBody = new String(out.toByteArray()); } // end if } catch (IOException ex) { throw new ContainerException(ex); } // end try/catch responseBody = (responseBody == null) ? "" : "\n"+responseBody; log.debug("\nClient Response:\nStatus: "+responseContext.getStatus()+ responseBody); }
@Override public void filter(ContainerRequestContext request) { if (predicate == null || predicate.apply(request)) { ByteArrayOutputStream out = new ByteArrayOutputStream(); InputStream in = request.getEntityStream(); try { if(in.available() > 0) { ReaderWriter.writeTo(in, out); byte[] requestEntity = out.toByteArray(); request.setEntityStream(new ByteArrayInputStream(requestEntity)); request.setProperty(REQUEST_ENTITY, requestEntity); } } catch (IOException ex) { throw new ContainerException(ex); } } }
/** * Writes the response status code and headers, returns an OutputStream that the Jersey application can write to. * @param contentLength The content length for the body * @param containerResponse The response object from the Jersey app * @return An OutputStream for Jersey to write the response body to * @throws ContainerException default Jersey declaration */ public OutputStream writeResponseStatusAndHeaders(long contentLength, ContainerResponse containerResponse) throws ContainerException { statusCode = containerResponse.getStatusInfo().getStatusCode(); if (headers == null) { headers = new HashMap<>(); } for (final Map.Entry<String, List<String>> e : containerResponse.getStringHeaders().entrySet()) { for (final String value : e.getValue()) { // special case for set cookies // RFC 2109 allows for a comma separated list of cookies in one Set-Cookie header: https://tools.ietf.org/html/rfc2109 if (e.getKey().equals(HttpHeaders.SET_COOKIE)) { if (headers.containsKey(e.getKey()) && LambdaContainerHandler.getContainerConfig().isConsolidateSetCookieHeaders()) { headers.put(e.getKey(), headers.get(e.getKey()) + ", " + value); } else { headers.put(e.getKey(), containerResponse.getStringHeaders().getFirst(e.getKey())); break; } } else { headers.put(e.getKey(), value); } } } responseBody = new ByteArrayOutputStream(); return responseBody; }
public void close() { if (closed.compareAndSet(false, true)) { try { responseWriter.writeResponse(statusType, headers, entityOutputStream); } catch (IOException e) { LOG.error("failed to write response", e); throw new ContainerException(e); } } else { LOG.warn("request has already been closed"); } }
@Override @SuppressWarnings("unchecked") public void writeTo(final Template template, final Viewable viewable, final MediaType mediaType, final MultivaluedMap<String, Object> httpHeaders, final OutputStream out) throws IOException { try { Object model = viewable.getModel(); if (!(model instanceof Map)) { model = new HashMap<String, Object>() {{ put("model", viewable.getModel()); }}; } VelocityContext velocityContext = new VelocityContext(); for (String key : ((Map<String, Object>) model).keySet()) { velocityContext.put(key, ((Map<String, Object>) model).get(key)); } Charset encoding = setContentType(mediaType, httpHeaders); VelocityWriter writer = new VelocityWriter(new OutputStreamWriter(out, encoding)); template.merge(velocityContext, writer); writer.flush(); } catch (VelocityException te) { throw new ContainerException(te); } }
protected String getJsonBody(ContainerRequestContext containerRequestContext) { String body = null; ByteArrayOutputStream out = new ByteArrayOutputStream(); InputStream in = containerRequestContext.getEntityStream(); final StringBuilder b = new StringBuilder(); try { //REMOVED THE in.available() CHECK AS THIS DOESNT WORK IN TOMCAT WITH JERSEY //SEE: https://java.net/jira/browse/JERSEY-749 if (log.isTraceEnabled()) { log.trace("Data Available..."); } ReaderWriter.writeTo(in, out); containerRequestContext.setEntityStream(new ByteArrayInputStream(out.toByteArray())); body = new String(out.toByteArray()); if (log.isTraceEnabled()) { log.trace("Data Read:\n["+body+"]"); } } catch (IOException ex) { log.error("Error while reading JSON body",ex); throw new ContainerException(ex); } // end try/catch if (log.isDebugEnabled()) { if (MediaType.APPLICATION_JSON.equals(containerRequestContext.getHeaderString(HttpHeaders.CONTENT_TYPE))) { log.debug("\n["+containerRequestContext.getMethod()+"] : "+containerRequestContext.getUriInfo().getPath()+"\n"+ JiveSDKUtils.getJson(body)); } else { log.debug("\n["+containerRequestContext.getMethod()+"] : "+containerRequestContext.getUriInfo().getPath()+"\n"+body); } // end if } // end if return body; }
@Override public OutputStream writeResponseStatusAndHeaders(long contentLength, ContainerResponse jerseyResponse) throws ContainerException { int status = jerseyResponse.getStatus(); LOGGER.debug("{}: [{}] write status and headers st:{} cl:{}", Channels.getHexText(ctx), requestId, status, contentLength); meterStatus(status); // create the netty response HttpResponse nettyResponse = new DefaultHttpResponse(httpVersion, HttpResponseStatus.valueOf(status)); copyHeaders(jerseyResponse, nettyResponse); // add the request id to the header nettyResponse.headers().add(Headers.REQUEST_TRACING_HEADER, requestId); // add a Connection: Close header if required if (!keepAlive) { nettyResponse.headers().add(Names.CONNECTION, Values.CLOSE); } // create the content buffer if necessary if (contentLength < 0) { LOGGER.trace("{}: [{}] chunked", Channels.getHexText(ctx), requestId); nettyResponse.headers().add(Names.TRANSFER_ENCODING, Values.CHUNKED); ctx.writeAndFlush(nettyResponse); entityOutputStream = new EntityOutputStream(ctx, CONTENT_LENGTH_HISTOGRAM); } else if (contentLength == 0) { LOGGER.trace("{}: [{}] no content", Channels.getHexText(ctx), requestId); nettyResponse.headers().add(Names.CONTENT_LENGTH, 0); ctx.write(nettyResponse); entityOutputStream = new EmptyEntityOutputStream(ctx); } else { LOGGER.trace("{}: [{}] non-empty body", Channels.getHexText(ctx), requestId); nettyResponse.headers().add(Names.CONTENT_LENGTH, contentLength); ctx.write(nettyResponse); // don't flush now - only do so when all the content is written entityOutputStream = new EntityOutputStream(ctx, CONTENT_LENGTH_HISTOGRAM); } return entityOutputStream; }
@Override public OutputStream writeResponseStatusAndHeaders(long contentLength, ContainerResponse responseContext) throws ContainerException { response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(responseContext.getStatus())); for (Map.Entry<String, List<Object>> header : responseContext.getHeaders().entrySet()) { } return new ByteBufOutputStream(response.content()); }
private Class<? extends MustacheFactory> getFactoryClass() { if (factoryClass == null) { return DefaultMustacheFactory.class; } else { try { return Class.forName(factoryClass).asSubclass(MustacheFactory.class); } catch (ClassNotFoundException ex) { throw new ContainerException("Mustache factory not found", ex); } } }
private MustacheFactory createMustacheFactory(final Class<? extends MustacheFactory> clazz) { try { if (resourceRoot != null) { return clazz.getConstructor(String.class).newInstance(resourceRoot); } if (fileRoot != null) { return clazz.getConstructor(File.class).newInstance(fileRoot); } return clazz.getConstructor().newInstance(); } catch (Exception ex) { throw new ContainerException("Failed to create mustache factory", ex); } }
@Override public Response toResponse(ContainerException exception) { if (TenacityExceptionMapper.isTenacityException(exception.getCause())) { return Response.status(statusCode).build(); } else { return Response.serverError().build(); } }
@Test(expected = ContainerException.class) public void testCreateDefinedMustacheFactoryWithInvalidConstructor() { MustacheFactoryHelper helper = new MustacheFactoryHelper(CustomMustacheFactory.class.getName(), null, null, null); helper.createMustacheFactory(); }
@Test(expected = ContainerException.class) public void testCreateDefinedMustacheFactoryWithInvalidClass() { MustacheFactoryHelper helper = new MustacheFactoryHelper("this.factory.is.missing.Factory", null, null, null); helper.createMustacheFactory(); }