@Override public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException { MessageDigest digest = null; try { digest = getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new IllegalArgumentException(e); } ByteArrayOutputStream buffer = new ByteArrayOutputStream(); DigestOutputStream digestStream = new DigestOutputStream(buffer, digest); OutputStream old = context.getOutputStream(); context.setOutputStream(digestStream); try { context.proceed(); byte[] hash = digest.digest(); String encodedHash = getEncoder().encodeToString(hash); context.getHeaders().putSingle(CONTENT_MD5_STRING, encodedHash); byte[] content = buffer.toByteArray(); old.write(content); } finally { context.setOutputStream(old); } }
public void testWrapsInputStream(String contentType) throws WebApplicationException, IOException { WriterInterceptorContext context = mockContext(contentType); OutputStream os = mock(OutputStream.class); when(context.getOutputStream()).thenReturn(os); writeInterceptor.aroundWriteTo(context); verifyZeroInteractions(os); ArgumentCaptor<OutputStream> updatedOsCapture = ArgumentCaptor.forClass(OutputStream.class); verify(context).setOutputStream(updatedOsCapture.capture()); verify(context).getMediaType(); verify(context).getOutputStream(); verify(context).proceed(); verifyNoMoreInteractions(context); OutputStream updatedOs = updatedOsCapture.getValue(); // just make sure we have some wrapper assertNotSame(os, updatedOs); updatedOs.close(); verify(os).close(); }
@Test public void testWrapsOutputStreamAlways() throws IOException { WriterInterceptorContext context = mock(WriterInterceptorContext.class); OutputStream os = mock(OutputStream.class); when(context.getOutputStream()).thenReturn(os); ArgumentCaptor<OutputStream> updatedOsCapture = ArgumentCaptor.forClass(OutputStream.class); alwaysBase64WriteInterceptor.aroundWriteTo(context); verify(alwaysBase64WriteInterceptor).isBase64(context); verifyZeroInteractions(os); verify(context).setOutputStream(updatedOsCapture.capture()); verify(context).proceed(); verify(context).getOutputStream(); verifyNoMoreInteractions(context); OutputStream updatedOs = updatedOsCapture.getValue(); // just make sure we have some wrapper assertNotSame(os, updatedOs); updatedOs.close(); verify(os).close(); }
private void testBase64Encoding(byte[] bytes, String expectedBase64) throws IOException { WriterInterceptorContext context = mock(WriterInterceptorContext.class); ByteArrayOutputStream baos = new ByteArrayOutputStream(); when(context.getOutputStream()).thenReturn(baos); ArgumentCaptor<OutputStream> updatesOsCapture = ArgumentCaptor.forClass(OutputStream.class); alwaysBase64WriteInterceptor.aroundWriteTo(context); verify(context).setOutputStream(updatesOsCapture.capture()); OutputStream updatedOs = updatesOsCapture.getValue(); updatedOs.write(bytes); updatedOs.close(); assertEquals(expectedBase64, baos.toString()); }
@Override public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException { if (!isVersioningSupported(context)) { context.proceed(); return; } String targetVersion = Version.get(context); Object source = context.getEntity(); if (source instanceof Collection) { context.setEntity(convertCollectionToLowerVersion(targetVersion, (Collection<?>)source)); } else { mapper.map(source); context.setEntity(converter.convertToLowerVersion(targetVersion, source)); } Type targetType = getVersionType(context.getGenericType(), targetVersion); context.setType(toClass(targetType)); context.setGenericType(targetType); context.proceed(); Version.unset(context); }
@Test public void simpleWriterInterceptors() { Response response = client .target(mockServer.url("/writerInterceptor").uri()) .register( new WriterInterceptor() { @Override public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException { context.getHeaders().putSingle(HEADER_NAME, HEADER_VALUE); context.proceed(); } }) .request() .post(Entity.json(PAYLOAD)); assertThat(response.getStatusInfo()).isEqualTo(Response.Status.OK); assertThat(response.readEntity(String.class)).isEqualTo(HEADER_VALUE); }
@Test public void testSnappyWriterInterceptor() throws IOException { SnappyWriterInterceptor writerInterceptor = new SnappyWriterInterceptor(); MultivaluedMap<String, Object> headers = new MultivaluedHashMap<>(); WriterInterceptorContext mockInterceptorContext = Mockito.mock(WriterInterceptorContext.class); Mockito.when(mockInterceptorContext.getHeaders()).thenReturn(headers); Mockito.when(mockInterceptorContext.getOutputStream()).thenReturn(new ByteArrayOutputStream()); Mockito.doNothing().when(mockInterceptorContext).setOutputStream(Mockito.any(OutputStream.class)); // call aroundWriteTo on mock writerInterceptor.aroundWriteTo(mockInterceptorContext); // verify that setOutputStream method was called once with argument which is an instance of SnappyFramedOutputStream Mockito.verify(mockInterceptorContext, Mockito.times(1)) .setOutputStream(Mockito.any(SnappyFramedOutputStream.class)); }
@Override public void aroundWriteTo(WriterInterceptorContext wic) throws IOException, WebApplicationException { System.out.println("MyServerWriterInterceptor"); wic.setOutputStream(new FilterOutputStream(wic.getOutputStream()) { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); @Override public void write(int b) throws IOException { baos.write(b); super.write(b); } @Override public void close() throws IOException { System.out.println("MyServerWriterInterceptor --> " + baos.toString()); super.close(); } }); wic.proceed(); }
/** * <p>applyStreaming.</p> * * @param requestContext a {@link javax.ws.rs.container.ContainerRequestContext} object. * @param context a {@link javax.ws.rs.ext.WriterInterceptorContext} object. * @throws java.io.IOException if any. */ protected void applyStreaming(ContainerRequestContext requestContext, WriterInterceptorContext context) throws IOException { Object entity = context.getEntity(); StreamingProcess<Object> process = MessageHelper.getStreamingProcess(context.getEntity(), manager); if (process != null) { ContainerResponseContext responseContext = (ContainerResponseContext) requestContext.getProperty(RESP_PROP_N); responseContext.setStatusInfo(Response.Status.PARTIAL_CONTENT); context.getHeaders().putSingle(ACCEPT_RANGES, BYTES_RANGE); context.setType(StreamingOutput.class); context.setEntity(new MediaStreaming( entity, requestContext.getHeaderString(MediaStreaming.RANGE), process, context.getMediaType(), context.getHeaders() ) ); } }
/** * {@inheritDoc} */ @Override public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException { if (!context.getHeaders().containsKey(HttpHeaders.CONTENT_LENGTH)) { Object entity = context.getEntity(); StreamingProcess<Object> process = MessageHelper.getStreamingProcess(entity, manager); if (process != null) { long length = process.length(entity); if (length != -1) context.getHeaders().putSingle(HttpHeaders.CONTENT_LENGTH, length); } } context.proceed(); }
/** * {@inheritDoc} */ @Override public void aroundWriteTo(final WriterInterceptorContext writerInterceptorContext) throws IOException, WebApplicationException { final LoggingStream stream = (LoggingStream) writerInterceptorContext.getProperty(ENTITY_LOGGER_PROPERTY); writerInterceptorContext.proceed(); final Object requestId = Requests.getProperty(LOGGING_ID_PROPERTY); final long id = requestId != null ? (Long) requestId : _id.incrementAndGet(); StringBuilder b = (StringBuilder) writerInterceptorContext.getProperty(LOGGER_BUFFER_PROPERTY); if (b == null) { b = new StringBuilder(); writerInterceptorContext.setProperty(LOGGER_BUFFER_PROPERTY, b); } printPrefixedHeaders(b, id, RESPONSE_PREFIX, HeaderUtils.asStringHeaders(writerInterceptorContext.getHeaders())); if (stream != null) { log(stream.getStringBuilder(MessageUtils.getCharset(writerInterceptorContext.getMediaType()))); } else { log(b); } }
@Override public void aroundWriteTo(final WriterInterceptorContext context) throws IOException, WebApplicationException { final Object entity = context.getEntity(); if (entity instanceof Viewable) { User user = (User) securityContext.getUserPrincipal(); if ( ((Viewable) entity).getModel() instanceof ViewData) { ViewData model = ((ViewData) ((Viewable) entity).getModel()); model.set("authUser", user); String templateName = ((Viewable) entity).getTemplateName(); context.setEntity(new Viewable(templateName, model.getData())); } } context.proceed(); }
@Override public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException { final List<String> requestHeader = httpHeaders.getRequestHeader(HttpHeaders.ACCEPT_ENCODING); if (requestHeader != null && requestHeader.contains("gzip")) { context.setOutputStream(new GZIPOutputStream(context.getOutputStream())); context.getHeaders().add(HttpHeaders.CONTENT_ENCODING, "gzip"); } context.proceed(); }
@Override public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException { final LoggingStream stream = (LoggingStream) context.getProperty("client.LoggingStream"); context.proceed(); if (stream != null) { System.out.printf("Body: %s\n", stream.getString(StandardCharsets.UTF_8)); } System.out.printf("-----------\n"); }
@Override public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException { context.proceed(); if (logger.isTraceEnabled()) { logRequestBody(context); } }
private void logRequestBody(WriterInterceptorContext context) { LoggingOutputStream loggingOutputStream = (LoggingOutputStream) context.getProperty(LOGGING_OUTPUT_STREAM_PROPERTY); if (loggingOutputStream != null) { Charset charset = MessageUtils.getCharset(context.getMediaType()); byte[] bytes = loggingOutputStream.getBytes(); logger.trace("Message body: " + new String(bytes, charset)); } }
@Override public void aroundWriteTo(WriterInterceptorContext context) throws IOException { MultivaluedMap<String, Object> headers = context.getHeaders(); headers.add("Content-Encoding", "gzip"); final OutputStream outputStream = context.getOutputStream(); context.setOutputStream(new GZIPOutputStream(outputStream)); context.proceed(); }
@Override public void aroundWriteTo(WriterInterceptorContext context) throws IOException { MultivaluedMap<String, Object> responseHeaders = context.getHeaders(); Object rangeHeader = responseHeaders.getFirst("Content-Range"); // Use a custom header here // Some clients needs to know the content length in response headers in order to display a loading state // Browsers don't let programmers to change the default "Accept-Encoding" header, then we use a custom one. String acceptEncoding = requestHeaders.getHeaderString("x-accept-encoding"); GZIPOutputStream gzipOutputStream = null; if (acceptEncoding != null && acceptEncoding.equals("identity")) { responseHeaders.add("Content-Encoding", "identity"); } else if (rangeHeader == null) { responseHeaders.add("Content-Encoding", "gzip"); responseHeaders.remove("Content-Length"); gzipOutputStream = new GZIPOutputStream(context.getOutputStream(), DEFAULT_BUFFER_SIZE); context.setOutputStream(gzipOutputStream); } try { context.proceed(); } finally { if (gzipOutputStream != null) { gzipOutputStream.finish(); } } }
public void testDoesNotWrapInputStream(String contentType) throws WebApplicationException, IOException { WriterInterceptorContext context = mockContext(contentType); OutputStream os = mock(OutputStream.class); when(context.getOutputStream()).thenReturn(os); writeInterceptor.aroundWriteTo(context); verifyZeroInteractions(os); verify(context).getMediaType(); verify(context).proceed(); verifyNoMoreInteractions(context); }
private static WriterInterceptorContext mockContext(String contentType) { WriterInterceptorContext context = mock(WriterInterceptorContext.class); if (contentType != null) { when(context.getMediaType()).thenReturn(MediaType.valueOf(contentType)); } return context; }
@Override public final void aroundWriteTo(WriterInterceptorContext context) throws IOException { if (isBase64(context)) { context.setOutputStream(Base64.getEncoder().wrap(context.getOutputStream())); } context.proceed(); }
@Test public void testWrapsOutputStreamNever() throws IOException { WriterInterceptorContext context = mock(WriterInterceptorContext.class); OutputStream os = mock(OutputStream.class); when(context.getOutputStream()).thenReturn(os); neverBase64WriteInterceptor.aroundWriteTo(context); verify(neverBase64WriteInterceptor).isBase64(context); verify(context).proceed(); verifyNoMoreInteractions(context); }
@Override public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException { try (ActiveSpan activeSpan = decorateWrite(context, buildSpan(context, "serialize"))) { try { context.proceed(); } catch (Exception e) { Tags.ERROR.set(activeSpan, true); throw e; } } }
public void aroundWriteTo(WriterInterceptorContext ctx) throws IOException, WebApplicationException { ByteArrayInterceptingOutputStream interceptOS = new ByteArrayInterceptingOutputStream(ctx.getOutputStream()); ctx.setOutputStream(interceptOS); ctx.proceed(); if (!ctx.getHeaders().containsKey(header)) { String xhubHeaderValue = XHub.generateHeaderXHubToken(getEncoder(), getHash(), Objects.requireNonNull(token, "cannot encode with a null token"), interceptOS.interceptedContent()); ctx.getHeaders().putSingle(header, xhubHeaderValue); } return; }
@Override public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException { MessageDigest digest = null; try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new IllegalArgumentException(e); } ByteArrayOutputStream buffer = new ByteArrayOutputStream(); DigestOutputStream digestStream = new DigestOutputStream(buffer, digest); OutputStream old = context.getOutputStream(); context.setOutputStream(digestStream); try { context.proceed(); byte[] hash = digest.digest(); String encodedHash = Base64.encodeBytes(hash); context.getHeaders().putSingle("Content-MD5", encodedHash); byte[] content = buffer.toByteArray(); old.write(content); } finally { context.setOutputStream(old); } }
public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException { TraceContext traceContext = tracer.startSpan("MessageBodyWriter#writeTo"); try { context.proceed(); } finally { tracer.endSpan(traceContext); } }
@Override public void aroundWriteTo (WriterInterceptorContext context) throws IOException, WebApplicationException { final OutputStream outputStream = context.getOutputStream(); context.setOutputStream(new GZIPOutputStream(outputStream)); context.proceed(); }
@Override public void aroundWriteTo(final WriterInterceptorContext writerInterceptorContext) throws IOException, WebApplicationException { final LoggingStream stream = (LoggingStream) writerInterceptorContext.getProperty(ENTITY_LOGGER_PROPERTY); writerInterceptorContext.proceed(); if (stream != null) { JaxRsExchangeMessage msg = stream.getMsg(); msg.setPayload(stream.getStringBuilder(MessageUtils.getCharset(writerInterceptorContext.getMediaType())).toString()); stream.collect(); } }
@Override public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException { try { context.proceed(); } catch (Throwable e) { String path = (String) context.getProperty("metrics.path"); String name = name("REST", "WRITE", e.getClass().getSimpleName(), path); JerseyMetricsPlugin.getMetricRegistry().meter(name).mark(); throw e; } }
@Override public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException { List<Statistics> pipelines = statistics.get(); MultivaluedMap<String, Object> headers = context.getHeaders(); pipelines.forEach(s -> headers.add("x-porcupine-statistics-" + s.getPipelineName(), serializeStatistics(s))); context.proceed(); }
@Override public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException { String acceptEncodings = getAcceptEncodingHeader(context.getHeaders()); if (acceptEncodings.contains("gzip")) { final OutputStream outputStream = context.getOutputStream(); context.setOutputStream(new GZIPOutputStream(outputStream)); } context.proceed(); }
@Override public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException { context.getHeaders().add(CONTENT_ENCODING, SNAPPY); final OutputStream outputStream = context.getOutputStream(); context.setOutputStream(new SnappyFramedOutputStream(outputStream)); context.proceed(); }
@Override public void aroundWriteTo(WriterInterceptorContext writerInterceptorContext) throws IOException, WebApplicationException { logger.info("Enters RestSkolWriterInterceptor.aroundWriterTo()"); final OutputStream outputStream = writerInterceptorContext.getOutputStream(); writerInterceptorContext.setOutputStream(new GZIPOutputStream(outputStream)); writerInterceptorContext.proceed(); }
@Override public void aroundWriteTo(final WriterInterceptorContext writerInterceptorContext) throws IOException, WebApplicationException { final LoggingStream stream = (LoggingStream) writerInterceptorContext.getProperty(ENTITY_LOGGER_PROPERTY); writerInterceptorContext.proceed(); if (stream != null) { if (log.isDebugEnabled()) log.debug(stream.getStringBuilder(MessageUtils.getCharset(writerInterceptorContext.getMediaType())).toString()); } }
@SuppressWarnings({ "unchecked", "rawtypes" }) @Override public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException { if (context.getEntity() != null && context.getEntity() instanceof Viewable) { final Viewable viewable = (Viewable) context.getEntity(); Object model = viewable.getModel(); if (!(model instanceof Map)) { model = new HashMap<String, Object>() { private static final long serialVersionUID = 1L; { put("model", viewable.getModel()); } }; } ((Map) model).put("context", getContextMap()); ((Map) model).put("session", getSessionMap()); if (servletRequest.getAttribute(RepositoryContext.ATTR_NAME) != null) { RepositoryContext repoContext = (RepositoryContext) servletRequest.getAttribute(RepositoryContext.ATTR_NAME); ((Map) model).put("repo", repoContext); } context.setEntity(new Viewable(viewable.getTemplateName(), model)); } context.proceed(); }
@Override public void aroundWriteTo(WriterInterceptorContext wic) throws IOException, WebApplicationException { System.out.println("MyClientWriterInterceptor"); wic.setOutputStream(new FilterOutputStream(wic.getOutputStream()) { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); @Override public void write(int b) throws IOException { baos.write(b); super.write(b); } @Override public void close() throws IOException { System.out.println("MyClientWriterInterceptor --> " + baos.toString()); super.close(); } }); // wic.setOutputStream(new FilterOutputStream(wic.getOutputStream()) { // // @Override // public void write(int b) throws IOException { // System.out.println("**** " + (char)b); // super.write(b); // } // // }); wic.proceed(); }