Java Code Examples for javax.ws.rs.ext.WriterInterceptorContext#getOutputStream()

The following examples show how to use javax.ws.rs.ext.WriterInterceptorContext#getOutputStream() . 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: SnappyWriterInterceptor.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example 2
Source File: GZIPWriterInterceptor.java    From wings with Apache License 2.0 5 votes vote down vote up
@Override
public void aroundWriteTo(WriterInterceptorContext context)
    throws IOException, WebApplicationException {

  boolean compress = false;
  String ae = request.getHeader("accept-encoding");
  if (ae != null && ae.indexOf("gzip") >= 0) {
    compress = true;
  }
  if(compress) {
    MultivaluedMap<String, Object> headers = context.getHeaders(); 
    for(Object type : headers.get("content-type")) {
      String ctype = type.toString();
      if(ctype.contains("zip") || 
          ctype.contains("compress") ||
          ctype.contains("image")) {
        compress = false;
        break;
      }
    }
    if(compress) {
      headers.add("Content-Encoding", "gzip");
      final OutputStream outputStream = context.getOutputStream();
      context.setOutputStream(new GZIPOutputStream(outputStream));
    }      
  }
  context.proceed();
}
 
Example 3
Source File: CreateSignatureInterceptor.java    From cxf with Apache License 2.0 5 votes vote down vote up
private void addDigest(WriterInterceptorContext context) throws IOException {
    // make sure we have all content
    OutputStream originalOutputStream = context.getOutputStream();
    CachedOutputStream cachedOutputStream = new CachedOutputStream();
    context.setOutputStream(cachedOutputStream);

    context.proceed();
    cachedOutputStream.flush();

    // then digest using requested encoding
    String encoding = context.getMediaType().getParameters()
        .getOrDefault(MediaType.CHARSET_PARAMETER, StandardCharsets.UTF_8.toString());

    String digestAlgorithm = digestAlgorithmName;
    if (digestAlgorithm == null) {
        Message m = PhaseInterceptorChain.getCurrentMessage();
        digestAlgorithm =
            (String)m.getContextualProperty(HTTPSignatureConstants.RSSEC_HTTP_SIGNATURE_DIGEST_ALGORITHM);
        if (digestAlgorithm == null) {
            digestAlgorithm = DefaultSignatureConstants.DIGEST_ALGORITHM;
        }
    }

    // not so nice - would be better to have a stream
    String digest = SignatureHeaderUtils.createDigestHeader(
        new String(cachedOutputStream.getBytes(), encoding), digestAlgorithm);

    // add header
    context.getHeaders().add(DIGEST_HEADER_NAME, digest);
    sign(context);

    // write the contents
    context.setOutputStream(originalOutputStream);
    IOUtils.copy(cachedOutputStream.getInputStream(), originalOutputStream);
}
 
Example 4
Source File: JAXRSHTTPSignatureTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private void addDigest(WriterInterceptorContext context) throws IOException {
    // make sure we have all content
    OutputStream originalOutputStream = context.getOutputStream();
    CachedOutputStream cachedOutputStream = new CachedOutputStream();
    context.setOutputStream(cachedOutputStream);

    context.proceed();
    cachedOutputStream.flush();

    // then digest using requested encoding
    String encoding = context.getMediaType().getParameters()
        .getOrDefault(MediaType.CHARSET_PARAMETER, StandardCharsets.UTF_8.toString());
    // not so nice - would be better to have a stream

    String digest = digestAlgorithmName + "=";
    try {
        MessageDigest messageDigest = MessageDigest.getInstance(digestAlgorithmName);
        messageDigest.update(new String(cachedOutputStream.getBytes(), encoding).getBytes());
        if (!emptyDigestValue) {
            if (changeDigestValue) {
                byte[] bytes = messageDigest.digest();
                bytes[0] += 1;
                digest += Base64.getEncoder().encodeToString(bytes);
            } else {
                digest += Base64.getEncoder().encodeToString(messageDigest.digest());
            }
        }
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // add header
    context.getHeaders().add(DIGEST_HEADER_NAME, digest);
    sign(context);

    // write the contents
    context.setOutputStream(originalOutputStream);
    IOUtils.copy(cachedOutputStream.getInputStream(), originalOutputStream);
}
 
Example 5
Source File: GZIPWriterInterceptor.java    From demo-rest-jersey-spring with MIT License 5 votes vote down vote up
@Override
public void aroundWriteTo(WriterInterceptorContext context)
                throws IOException, WebApplicationException {
	
	MultivaluedMap<String,Object> headers = context.getHeaders();
	headers.add("Content-Encoding", "gzip");
	
    final OutputStream outputStream = context.getOutputStream();
    context.setOutputStream(new GZIPOutputStream(outputStream));
    context.proceed();
}
 
Example 6
Source File: LoggingFilter.java    From dubbo-2.6.5 with Apache License 2.0 5 votes vote down vote up
@Override
public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException {
    OutputStreamWrapper wrapper = new OutputStreamWrapper(context.getOutputStream());
    context.setOutputStream(wrapper);
    context.proceed();
    logger.info("The contents of response body is: \n" + new String(wrapper.getBytes(), "UTF-8") + "\n");
}
 
Example 7
Source File: ContentMD5Writer.java    From resteasy-examples with Apache License 2.0 5 votes vote down vote up
@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.getEncoder().encodeToString(hash);
      context.getHeaders().putSingle("Content-MD5", encodedHash);

      byte[] content = buffer.toByteArray();
      old.write(content);
   }
   finally
   {
      context.setOutputStream(old);
   }
}
 
Example 8
Source File: GZIPWriterInterceptor.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException {
    MultivaluedMap<String,Object> headers = context.getHeaders();
    headers.add("Content-Encoding", "gzip");

    final OutputStream outputStream = context.getOutputStream();
    context.setOutputStream(new GZIPOutputStream(outputStream));
    context.proceed();
}
 
Example 9
Source File: GZIPWriterInterceptor.java    From eplmp with Eclipse Public License 1.0 5 votes vote down vote up
@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();
        }
    }
}
 
Example 10
Source File: GZipInterceptor.java    From Alpine with Apache License 2.0 5 votes vote down vote up
@Override
public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException {
    final List<String> requestHeader = httpHeaders.getRequestHeader(HttpHeaders.ACCEPT_ENCODING);
    if (requestHeader != null && requestHeader.contains("gzip")) {
        // DO NOT CLOSE STREAMS
        final OutputStream contextOutputStream = context.getOutputStream();
        final GZIPOutputStream gzipOutputStream = new GZIPOutputStream(contextOutputStream);
        context.setOutputStream(gzipOutputStream);
        context.getHeaders().add(HttpHeaders.CONTENT_ENCODING, "gzip");
    }
    context.proceed();
}
 
Example 11
Source File: BaseMethodStatsInterceptor.java    From datawave with Apache License 2.0 5 votes vote down vote up
protected ResponseMethodStats doWrite(WriterInterceptorContext context) throws IOException, WebApplicationException {
    ResponseMethodStats stats;
    long start = System.nanoTime();
    OutputStream originalOutputStream = context.getOutputStream();
    CountingOutputStream countingStream = new CountingOutputStream(originalOutputStream);
    context.setOutputStream(countingStream);
    try {
        context.proceed();
    } finally {
        long stop = System.nanoTime();
        long time = TimeUnit.NANOSECONDS.toMillis(stop - start);
        
        context.setOutputStream(originalOutputStream);
        
        stats = (ResponseMethodStats) context.getProperty(RESPONSE_STATS_NAME);
        if (stats == null) {
            log.warn("No response stats found for " + getClass() + ". Using default.");
            stats = new ResponseMethodStats();
        }
        
        RequestMethodStats requestStats = (RequestMethodStats) context.getProperty(REQUEST_STATS_NAME);
        if (requestStats == null) {
            log.warn("No request method stats found for " + getClass() + ". Using default.");
            requestStats = new RequestMethodStats();
            requestStats.callStartTime = stop + TimeUnit.MILLISECONDS.toNanos(1);
        }
        
        stats.serializationTime = time;
        stats.loginTime = requestStats.getLoginTime();
        stats.callTime = TimeUnit.NANOSECONDS.toMillis(stop - requestStats.getCallStartTime());
        stats.bytesWritten = countingStream.getCount();
        // Merge in the headers we saved in the postProcess call, if any.
        putNew(stats.responseHeaders, context.getHeaders());
    }
    
    return stats;
}
 
Example 12
Source File: LoggingFilter.java    From dubbox with Apache License 2.0 4 votes vote down vote up
public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException {
    OutputStreamWrapper wrapper = new OutputStreamWrapper(context.getOutputStream());
    context.setOutputStream(wrapper);
    context.proceed();
    logger.info("The contents of response body is: \n" + new String(wrapper.getBytes(), "UTF-8") + "\n");
}
 
Example 13
Source File: LoggingFilter.java    From dubbox with Apache License 2.0 4 votes vote down vote up
public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException {
    OutputStreamWrapper wrapper = new OutputStreamWrapper(context.getOutputStream());
    context.setOutputStream(wrapper);
    context.proceed();
    logger.info("The contents of response body is: \n" + new String(wrapper.getBytes(), "UTF-8") + "\n");
}
 
Example 14
Source File: LoggingFilter.java    From dubbox-hystrix with Apache License 2.0 4 votes vote down vote up
public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException {
    OutputStreamWrapper wrapper = new OutputStreamWrapper(context.getOutputStream());
    context.setOutputStream(wrapper);
    context.proceed();
    logger.info("The contents of response body is: \n" + new String(wrapper.getBytes(), "UTF-8") + "\n");
}
 
Example 15
Source File: LoggingFilter.java    From dubbox with Apache License 2.0 4 votes vote down vote up
public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException {
    OutputStreamWrapper wrapper = new OutputStreamWrapper(context.getOutputStream());
    context.setOutputStream(wrapper);
    context.proceed();
    logger.info("The contents of response body is: \n" + new String(wrapper.getBytes(), "UTF-8") + "\n");
}
 
Example 16
Source File: JweWriterInterceptor.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Override
public void aroundWriteTo(WriterInterceptorContext ctx) throws IOException, WebApplicationException {
    if (ctx.getEntity() == null) {
        ctx.proceed();
        return;
    }
    OutputStream actualOs = ctx.getOutputStream();
    JweHeaders jweHeaders = new JweHeaders();
    JweEncryptionProvider theEncryptionProvider = getInitializedEncryptionProvider(jweHeaders);

    String ctString = null;
    MediaType contentMediaType = ctx.getMediaType();
    if (contentTypeRequired && contentMediaType != null) {
        if ("application".equals(contentMediaType.getType())) {
            ctString = contentMediaType.getSubtype();
        } else {
            ctString = JAXRSUtils.mediaTypeToString(contentMediaType);
        }
    }
    if (ctString != null) {
        jweHeaders.setContentType(ctString);
    }
    protectHttpHeadersIfNeeded(ctx, jweHeaders);
    if (useJweOutputStream) {
        JweEncryptionOutput encryption =
            theEncryptionProvider.getEncryptionOutput(new JweEncryptionInput(jweHeaders));
        JoseUtils.traceHeaders(encryption.getHeaders());
        try {
            JweCompactBuilder.startJweContent(actualOs,
                                               encryption.getHeaders(),
                                               encryption.getEncryptedContentEncryptionKey(),
                                               encryption.getIv());
        } catch (IOException ex) {
            LOG.warning("JWE encryption error");
            throw new JweException(JweException.Error.CONTENT_ENCRYPTION_FAILURE, ex);
        }
        OutputStream wrappedStream = null;
        JweOutputStream jweOutputStream = new JweOutputStream(actualOs, encryption.getCipher(),
                                                     encryption.getAuthTagProducer());
        wrappedStream = jweOutputStream;
        if (encryption.isCompressionSupported()) {
            wrappedStream = new DeflaterOutputStream(jweOutputStream);
        }

        ctx.setOutputStream(wrappedStream);
        ctx.proceed();
        setJoseMediaType(ctx);
        jweOutputStream.finalFlush();
    } else {
        CachedOutputStream cos = new CachedOutputStream();
        ctx.setOutputStream(cos);
        ctx.proceed();
        String jweContent = theEncryptionProvider.encrypt(cos.getBytes(), jweHeaders);
        JoseUtils.traceHeaders(jweHeaders);
        setJoseMediaType(ctx);
        IOUtils.copy(new ByteArrayInputStream(StringUtils.toBytesUTF8(jweContent)),
                     actualOs);
        actualOs.flush();
    }
}
 
Example 17
Source File: JweJsonWriterInterceptor.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Override
public void aroundWriteTo(WriterInterceptorContext ctx) throws IOException, WebApplicationException {
    if (ctx.getEntity() == null) {
        ctx.proceed();
        return;
    }
    OutputStream actualOs = ctx.getOutputStream();
    JweHeaders sharedProtectedHeaders = new JweHeaders();
    List<String> propLocs = getPropertyLocations();
    List<JweHeaders> perRecipientUnprotectedHeaders = new ArrayList<>(propLocs.size());
    for (int i = 0; i < propLocs.size(); i++) {
        perRecipientUnprotectedHeaders.add(new JweHeaders());
    }
    List<JweEncryptionProvider> providers = getInitializedEncryptionProviders(propLocs,
                                                                              sharedProtectedHeaders,
                                                                              perRecipientUnprotectedHeaders);

    String ctString = null;
    MediaType contentMediaType = ctx.getMediaType();
    if (contentTypeRequired && contentMediaType != null) {
        if ("application".equals(contentMediaType.getType())) {
            ctString = contentMediaType.getSubtype();
        } else {
            ctString = JAXRSUtils.mediaTypeToString(contentMediaType);
        }
    }
    if (ctString != null) {
        sharedProtectedHeaders.setContentType(ctString);
    }
    protectHttpHeadersIfNeeded(ctx, sharedProtectedHeaders);
    if (useJweOutputStream) {
        //TODO
    } else {
        CachedOutputStream cos = new CachedOutputStream();
        ctx.setOutputStream(cos);
        ctx.proceed();



        JweJsonProducer producer = new JweJsonProducer(sharedProtectedHeaders, cos.getBytes());
        String jweContent = producer.encryptWith(providers, perRecipientUnprotectedHeaders);

        setJoseMediaType(ctx);
        IOUtils.copy(new ByteArrayInputStream(StringUtils.toBytesUTF8(jweContent)),
                     actualOs);
        actualOs.flush();
    }
}
 
Example 18
Source File: JwsWriterInterceptor.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Override
public void aroundWriteTo(WriterInterceptorContext ctx) throws IOException, WebApplicationException {
    if (ctx.getEntity() == null) {
        ctx.proceed();
        return;
    }
    JwsHeaders headers = new JwsHeaders();
    JwsSignatureProvider sigProvider = getInitializedSigProvider(headers);
    setContentTypeIfNeeded(headers, ctx);
    if (!encodePayload) {
        headers.setPayloadEncodingStatus(false);
    }
    protectHttpHeadersIfNeeded(ctx, headers);
    OutputStream actualOs = ctx.getOutputStream();
    if (useJwsOutputStream) {
        JwsSignature jwsSignature = sigProvider.createJwsSignature(headers);
        JoseUtils.traceHeaders(headers);
        JwsOutputStream jwsStream = new JwsOutputStream(actualOs, jwsSignature, true);
        byte[] headerBytes = StringUtils.toBytesUTF8(writer.toJson(headers));
        Base64UrlUtility.encodeAndStream(headerBytes, 0, headerBytes.length, jwsStream);
        jwsStream.write(new byte[]{'.'});

        Base64UrlOutputStream base64Stream = null;
        if (encodePayload) {
            base64Stream = new Base64UrlOutputStream(jwsStream);
            ctx.setOutputStream(base64Stream);
        } else {
            ctx.setOutputStream(jwsStream);
        }
        ctx.proceed();
        setJoseMediaType(ctx);
        if (base64Stream != null) {
            base64Stream.flush();
        }
        jwsStream.flush();
    } else {
        CachedOutputStream cos = new CachedOutputStream();
        ctx.setOutputStream(cos);
        ctx.proceed();
        JwsCompactProducer p = new JwsCompactProducer(headers, new String(cos.getBytes(), StandardCharsets.UTF_8));
        setJoseMediaType(ctx);
        writeJws(p, sigProvider, actualOs);
    }
}