Example usage for com.google.common.net HttpHeaders CONTENT_ENCODING

List of usage examples for com.google.common.net HttpHeaders CONTENT_ENCODING

Introduction

In this page you can find the example usage for com.google.common.net HttpHeaders CONTENT_ENCODING.

Prototype

String CONTENT_ENCODING

To view the source code for com.google.common.net HttpHeaders CONTENT_ENCODING.

Click Source Link

Document

The HTTP Content-Encoding header field name.

Usage

From source file:org.graylog.plugins.usagestatistics.okhttp.GzipRequestInterceptor.java

@Override
public Response intercept(Chain chain) throws IOException {
    Request originalRequest = chain.request();
    if (originalRequest.body() == null || originalRequest.header(HttpHeaders.CONTENT_ENCODING) != null) {
        return chain.proceed(originalRequest);
    }//  w ww  .  j a va 2s  .  c  o m

    Request compressedRequest = originalRequest.newBuilder().header(HttpHeaders.CONTENT_ENCODING, "gzip")
            .method(originalRequest.method(), gzip(originalRequest.body())).build();
    return chain.proceed(compressedRequest);
}

From source file:uk.org.iay.mdq.server.ResultRawView.java

@Override
public void render(final Map<String, ?> model, final HttpServletRequest request,
        final HttpServletResponse response) throws Exception {
    final Result result = (Result) model.get("result");
    log.debug("rendering as {}", getContentType());

    if (result.isNotFound()) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;/*from  www.  j av  a2 s  .  c o m*/
    }

    // select the representation to provide
    Representation rep = null;
    final String acceptEncoding = request.getHeader(HttpHeaders.ACCEPT_ENCODING);
    if (acceptEncoding != null) {
        if (acceptEncoding.contains("gzip")) {
            rep = result.getGZIPRepresentation();
        } else if (acceptEncoding.contains("compress")) {
            rep = result.getDeflateRepresentation();
        }
    }

    // default to the normal representation
    if (rep == null) {
        rep = result.getRepresentation();
    }

    // Set response headers
    String contentEncoding = rep.getContentEncoding();
    if (contentEncoding != null) {
        response.setHeader(HttpHeaders.CONTENT_ENCODING, contentEncoding);
    } else {
        // for logging only
        contentEncoding = "normal";
    }
    response.setContentType(getContentType());
    response.setContentLength(rep.getBytes().length);
    response.setHeader(HttpHeaders.ETAG, rep.getETag());

    log.debug("selected ({}) representation is {} bytes", contentEncoding, rep.getBytes().length);

    response.getOutputStream().write(rep.getBytes());
}

From source file:com.cloudera.oryx.als.serving.web.IngestServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    OryxRecommender recommender = getRecommender();

    boolean fromBrowserUpload = request.getContentType().startsWith("multipart/form-data");

    Reader reader;//from  w ww  .j  a  v  a  2 s. c o m
    if (fromBrowserUpload) {

        Collection<Part> parts = request.getParts();
        if (parts == null || parts.isEmpty()) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No form data");
            return;
        }
        Part part = parts.iterator().next();
        String partContentType = part.getContentType();
        InputStream in = part.getInputStream();
        if ("application/zip".equals(partContentType)) {
            in = new ZipInputStream(in);
        } else if ("application/gzip".equals(partContentType)) {
            in = new GZIPInputStream(in);
        } else if ("application/x-gzip".equals(partContentType)) {
            in = new GZIPInputStream(in);
        }
        reader = new InputStreamReader(in, Charsets.UTF_8);

    } else {

        String charEncodingName = request.getCharacterEncoding();
        Charset charEncoding = charEncodingName == null ? Charsets.UTF_8 : Charset.forName(charEncodingName);
        String contentEncoding = request.getHeader(HttpHeaders.CONTENT_ENCODING);
        if (contentEncoding == null) {
            reader = request.getReader();
        } else if ("gzip".equals(contentEncoding)) {
            reader = new InputStreamReader(new GZIPInputStream(request.getInputStream()), charEncoding);
        } else if ("zip".equals(contentEncoding)) {
            reader = new InputStreamReader(new ZipInputStream(request.getInputStream()), charEncoding);
        } else {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Unsupported Content-Encoding");
            return;
        }

    }

    try {
        recommender.ingest(reader);
    } catch (IllegalArgumentException iae) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, iae.toString());
        return;
    } catch (NoSuchElementException nsee) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, nsee.toString());
        return;
    }

    String referer = request.getHeader(HttpHeaders.REFERER);
    if (fromBrowserUpload && referer != null) {
        // Parsing avoids response splitting
        response.sendRedirect(new URL(referer).toString());
    }

}

From source file:net.myrrix.web.servlets.IngestServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    MyrrixRecommender recommender = getRecommender();

    boolean fromBrowserUpload = request.getContentType().startsWith("multipart/form-data");

    Reader reader;/*  w w  w.  j a  va2  s. c o m*/
    if (fromBrowserUpload) {

        Collection<Part> parts = request.getParts();
        if (parts == null || parts.isEmpty()) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No form data");
            return;
        }
        Part part = parts.iterator().next();
        String partContentType = part.getContentType();
        InputStream in = part.getInputStream();
        if ("application/zip".equals(partContentType)) {
            in = new ZipInputStream(in);
        } else if ("application/gzip".equals(partContentType)) {
            in = new GZIPInputStream(in);
        } else if ("application/x-gzip".equals(partContentType)) {
            in = new GZIPInputStream(in);
        } else if ("application/bzip2".equals(partContentType)) {
            in = new BZip2CompressorInputStream(in);
        } else if ("application/x-bzip2".equals(partContentType)) {
            in = new BZip2CompressorInputStream(in);
        }
        reader = new InputStreamReader(in, Charsets.UTF_8);

    } else {

        String charEncodingName = request.getCharacterEncoding();
        Charset charEncoding = charEncodingName == null ? Charsets.UTF_8 : Charset.forName(charEncodingName);
        String contentEncoding = request.getHeader(HttpHeaders.CONTENT_ENCODING);
        if (contentEncoding == null) {
            reader = request.getReader();
        } else if ("gzip".equals(contentEncoding)) {
            reader = new InputStreamReader(new GZIPInputStream(request.getInputStream()), charEncoding);
        } else if ("zip".equals(contentEncoding)) {
            reader = new InputStreamReader(new ZipInputStream(request.getInputStream()), charEncoding);
        } else if ("bzip2".equals(contentEncoding)) {
            reader = new InputStreamReader(new BZip2CompressorInputStream(request.getInputStream()),
                    charEncoding);
        } else {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Unsupported Content-Encoding");
            return;
        }

    }

    try {
        recommender.ingest(reader);
    } catch (IllegalArgumentException iae) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, iae.toString());
        return;
    } catch (NoSuchElementException nsee) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, nsee.toString());
        return;
    } catch (TasteException te) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, te.toString());
        getServletContext().log("Unexpected error in " + getClass().getSimpleName(), te);
        return;
    }

    String referer = request.getHeader(HttpHeaders.REFERER);
    if (fromBrowserUpload && referer != null) {
        // Parsing avoids response splitting
        response.sendRedirect(new URL(referer).toString());
    }

}

From source file:com.linkedin.flashback.netty.builder.RecordedHttpMessageBuilder.java

/**
 * Get content encoding from headers/*from   ww w .  j a v  a  2s  .c om*/
 *
 * */
protected String getContentEncoding() {
    String header = getHeader(HttpHeaders.CONTENT_ENCODING);
    if (Strings.isNullOrEmpty(header)) {
        return DEFAULT_CONTENT_ENCODING;
    } else {
        return header;
    }
}

From source file:com.sector91.wit.responders.Page.java

@Override
public final void respond(Zero params, Request request, Response response) throws IOException {
    boolean gzipSupported = request.getValue(HttpHeaders.ACCEPT_ENCODING).contains("gzip");
    byte[] data = gzipSupported ? compressed : uncompressed;

    response.setValue(HttpHeaders.ETAG, etag);
    response.setDate(HttpHeaders.LAST_MODIFIED, timestamp);

    long ifModifiedSince = request.getDate(HttpHeaders.IF_MODIFIED_SINCE);
    if (ifModifiedSince >= timestamp || etag.equals(request.getValue(HttpHeaders.IF_NONE_MATCH))) {
        response.setStatus(Status.NOT_MODIFIED);
        response.getOutputStream().close();
        return;//from   w w  w  .ja va  2s .  co  m
    }

    try (OutputStream stream = response.getOutputStream()) {
        response.setContentType(contentType);
        response.setContentLength(data.length);
        if (gzipSupported)
            response.setValue(HttpHeaders.CONTENT_ENCODING, "gzip");
        if (!request.getMethod().equals("HEAD"))
            stream.write(data);
    }
}

From source file:org.jclouds.s3.filters.Aws4SignerForChunkedUpload.java

protected HttpRequest sign(HttpRequest request) throws HttpException {
    checkNotNull(request, "request is not ready to sign");
    checkNotNull(request.getEndpoint(), "request is not ready to sign, request.endpoint not present.");

    Payload payload = request.getPayload();
    // chunked upload required content-length.
    Long contentLength = payload.getContentMetadata().getContentLength();

    // check contentLength not null
    checkNotNull(contentLength, "request is not ready to sign, payload contentLength not present.");

    // get host from request endpoint.
    String host = request.getEndpoint().getHost();

    Date date = timestampProvider.get();
    String timestamp = timestampFormat.format(date);
    String datestamp = dateFormat.format(date);

    String service = serviceAndRegion.service();
    String region = serviceAndRegion.region(host);
    String credentialScope = Joiner.on('/').join(datestamp, region, service, "aws4_request");

    HttpRequest.Builder<?> requestBuilder = request.toBuilder() //
            .removeHeader(AUTHORIZATION) // remove Authorization
            .removeHeader(DATE) // remove Date
            .removeHeader(CONTENT_LENGTH); // remove Content-Length

    ImmutableMap.Builder<String, String> signedHeadersBuilder = ImmutableSortedMap
            .<String, String>naturalOrder();

    // content-encoding
    String contentEncoding = CONTENT_ENCODING_HEADER_AWS_CHUNKED;
    String originalContentEncoding = payload.getContentMetadata().getContentEncoding();
    if (originalContentEncoding != null) {
        contentEncoding += "," + originalContentEncoding;
    }/* w w  w.  ja  va 2  s . c om*/
    requestBuilder.replaceHeader(HttpHeaders.CONTENT_ENCODING, contentEncoding);
    signedHeadersBuilder.put(HttpHeaders.CONTENT_ENCODING.toLowerCase(), contentEncoding);

    // x-amz-decoded-content-length
    requestBuilder.replaceHeader(AMZ_DECODED_CONTENT_LENGTH_HEADER, contentLength.toString());
    signedHeadersBuilder.put(AMZ_DECODED_CONTENT_LENGTH_HEADER.toLowerCase(), contentLength.toString());

    // how big is the overall request stream going to be once we add the signature
    // 'headers' to each chunk?
    long totalLength = calculateChunkedContentLength(contentLength, userDataBlockSize);
    requestBuilder.replaceHeader(CONTENT_LENGTH, Long.toString(totalLength));
    signedHeadersBuilder.put(CONTENT_LENGTH.toLowerCase(), Long.toString(totalLength));

    // Content MD5
    String contentMD5 = request.getFirstHeaderOrNull(CONTENT_MD5);
    if (payload != null) {
        HashCode md5 = payload.getContentMetadata().getContentMD5AsHashCode();
        if (md5 != null) {
            contentMD5 = BaseEncoding.base64().encode(md5.asBytes());
        }
    }
    if (contentMD5 != null) {
        requestBuilder.replaceHeader(CONTENT_MD5, contentMD5);
        signedHeadersBuilder.put(CONTENT_MD5.toLowerCase(), contentMD5);
    }

    // Content Type
    // content-type is not a required signing param. However, examples use this, so we include it to ease testing.
    String contentType = getContentType(request);
    if (!Strings.isNullOrEmpty(contentType)) {
        requestBuilder.replaceHeader(HttpHeaders.CONTENT_TYPE, contentType);
        signedHeadersBuilder.put(HttpHeaders.CONTENT_TYPE.toLowerCase(), contentType);
    } else {
        requestBuilder.removeHeader(HttpHeaders.CONTENT_TYPE);
    }

    // host
    requestBuilder.replaceHeader(HttpHeaders.HOST, host);
    signedHeadersBuilder.put(HttpHeaders.HOST.toLowerCase(), host);

    // user-agent, not a required signing param
    if (request.getHeaders().containsKey(HttpHeaders.USER_AGENT)) {
        signedHeadersBuilder.put(HttpHeaders.USER_AGENT.toLowerCase(),
                request.getFirstHeaderOrNull(HttpHeaders.USER_AGENT));
    }

    // all x-amz-* headers
    appendAmzHeaders(request, signedHeadersBuilder);

    // x-amz-security-token
    Credentials credentials = creds.get();
    if (credentials instanceof SessionCredentials) {
        String token = SessionCredentials.class.cast(credentials).getSessionToken();
        requestBuilder.replaceHeader(AMZ_SECURITY_TOKEN_HEADER, token);
        signedHeadersBuilder.put(AMZ_SECURITY_TOKEN_HEADER.toLowerCase(), token);
    }

    // x-amz-content-sha256
    String contentSha256 = getPayloadHash();
    requestBuilder.replaceHeader(AMZ_CONTENT_SHA256_HEADER, contentSha256);
    signedHeadersBuilder.put(AMZ_CONTENT_SHA256_HEADER.toLowerCase(), contentSha256);

    // put x-amz-date
    requestBuilder.replaceHeader(AMZ_DATE_HEADER, timestamp);
    signedHeadersBuilder.put(AMZ_DATE_HEADER.toLowerCase(), timestamp);

    ImmutableMap<String, String> signedHeaders = signedHeadersBuilder.build();

    String stringToSign = createStringToSign(request.getMethod(), request.getEndpoint(), signedHeaders,
            timestamp, credentialScope, contentSha256);
    signatureWire.getWireLog().debug("<< " + stringToSign);

    byte[] signatureKey = signatureKey(credentials.credential, datestamp, region, service);

    // init hmacSHA256 processor for seed signature and chunked block signature
    ByteProcessor<byte[]> hmacSHA256;
    try {
        hmacSHA256 = hmacSHA256(crypto, signatureKey);
    } catch (InvalidKeyException e) {
        throw new ChunkedUploadException("invalid key", e);
    }

    // Calculating the Seed Signature
    String signature;
    try {
        signature = hex(readBytes(toInputStream(stringToSign), hmacSHA256));
    } catch (IOException e) {
        throw new ChunkedUploadException("hmac sha256 seed signature error", e);
    }

    StringBuilder authorization = new StringBuilder(AMZ_ALGORITHM_HMAC_SHA256).append(" ");
    authorization.append("Credential=").append(Joiner.on("/").join(credentials.identity, credentialScope))
            .append(", ");
    authorization.append("SignedHeaders=").append(Joiner.on(";").join(signedHeaders.keySet())).append(", ");
    authorization.append("Signature=").append(signature);

    // replace request payload with chunked upload payload
    ChunkedUploadPayload chunkedPayload = new ChunkedUploadPayload(payload, userDataBlockSize, timestamp,
            credentialScope, hmacSHA256, signature);
    chunkedPayload.getContentMetadata().setContentEncoding(null);

    return requestBuilder.replaceHeader(HttpHeaders.AUTHORIZATION, authorization.toString())
            .payload(chunkedPayload).build();

}

From source file:com.sector91.wit.responders.ResourceResponder.java

@Override
public void respond(One<String> param, Request request, Response response) throws IOException, HttpException {
    Log.debug(TAG, "Starting ResourceResponder for path " + basePath);

    // Read basic information from the request.
    final String path = param.first();
    Log.trace(TAG, "Responding with resource: " + path);
    final String mimetype = ContentTypes.forPath(path);
    final boolean gzipSupported = request.getValue(HttpHeaders.ACCEPT_ENCODING).contains("gzip");
    final boolean shouldCompressFile = gzipIf.apply(mimetype);

    // EDGE CASE: If we're caching a compressed version of the resource, but
    // the client doesn't support compression, then don't bother caching, and
    // just read the resource directly.
    if (!gzipSupported && shouldCompressFile) {
        Log.debug(TAG, "Resource '" + basePath + path + "' is cached in gzipped form, but client does"
                + " not support gzip. Skipping cache.");
        final InputStream stream = context.getResourceAsStream(basePath + path);
        if (stream == null)
            throw new HttpException(Status.NOT_FOUND);
        response.setContentType(mimetype);
        response.setDate(HttpHeaders.LAST_MODIFIED, timestamp);
        try (OutputStream out = response.getOutputStream()) {
            ByteStreams.copy(stream, out);
        }//w w  w .j a va 2  s.  c o m
        return;
    }

    // Retrieve the resource from the cache, loading it if necessary
    final byte[] data;
    try {
        data = loader.load(path);
    } catch (ResourceNotFoundException ex) {
        throw new HttpException(Status.NOT_FOUND);
    }

    // Return a 304 Not Modified if the client already has a cached copy.
    response.setDate(HttpHeaders.LAST_MODIFIED, timestamp);
    final long ifModifiedSince = request.getDate(HttpHeaders.IF_MODIFIED_SINCE);
    if (ifModifiedSince >= timestamp) {
        Log.trace(TAG, "Resource not modified: " + path);
        response.setStatus(Status.NOT_MODIFIED);
        response.getOutputStream().close();
        return;
    }

    // Otherwise, write the response headers and data.
    response.setContentType(mimetype);
    if (shouldCompressFile)
        response.setValue(HttpHeaders.CONTENT_ENCODING, "gzip");
    response.setContentLength(data.length);
    try (OutputStream out = response.getOutputStream()) {
        out.write(data);
    }
}

From source file:com.sector91.wit.responders.FileResponder.java

@Override
public void respond(One<String> param, Request request, Response response) throws IOException, HttpException {

    // Read basic information from the request.
    String pathstr = param.first();
    if (pathstr.startsWith("/"))
        pathstr = pathstr.substring(1);/*  w  ww. j  ava  2s. c  om*/
    final Path path = root.resolve(pathstr);
    Log.debug(TAG, "Responding with file: " + path);
    final boolean gzipSupported = request.getValue(HttpHeaders.ACCEPT_ENCODING).contains("gzip");

    // Get the file from the cache, loading it if necessary.
    FileEntry entry;
    while (true) {
        try {
            entry = cache.get(path, new FileLoader(path));
        } catch (ExecutionException wrapper) {
            try {
                throw wrapper.getCause();
            } catch (FileTooLargeForCacheException ex) {
                Log.debug(TAG, "File too large for cache: " + path);
                entry = ex.file;
                break;
            } catch (HttpException ex) {
                throw ex;
            } catch (Throwable ex) {
                throw new HttpException(Status.INTERNAL_SERVER_ERROR, ex);
            }
        }

        // Reload the cached file if it has been modified since it was cached.
        if (entry.data.length <= maxSize && Files.getLastModifiedTime(path).toMillis() > entry.timestamp) {
            Log.debug(TAG, "Reloading file " + path + " from cache.");
            cache.invalidate(path);
        } else {
            break;
        }
    }

    // Return a 304 Not Modified if the client already has a cached copy.
    response.setDate(HttpHeaders.LAST_MODIFIED, entry.timestamp);
    final long ifModifiedSince = request.getDate(HttpHeaders.IF_MODIFIED_SINCE);
    if (ifModifiedSince >= (entry.timestamp * 1000) / 1000) {
        Log.trace(TAG, "File not modified: " + path);
        response.setStatus(Status.NOT_MODIFIED);
        response.getOutputStream().close();
        return;
    }

    // Set the HTTP headers.
    response.setDate(HttpHeaders.DATE, System.currentTimeMillis());
    response.setContentType(entry.mimetype);

    // EDGE CASE: If we're caching a compressed version of the file, but the
    // client doesn't support compression, then don't bother caching, and just
    // read the file directly.
    if (!gzipSupported && entry.gzipped) {
        Log.debug(TAG, "File " + path + " is cached in gzipped form, but client does not support"
                + " gzip. Skipping cache.");
        checkPathValidity(path);
        try (final InputStream in = Files.newInputStream(path);
                final OutputStream out = response.getOutputStream()) {
            ByteStreams.copy(in, out);
            return;
        }
    }

    // Otherwise, write the response headers and data.
    if (entry.gzipped)
        response.setValue(HttpHeaders.CONTENT_ENCODING, "gzip");
    response.setContentLength(entry.data.length);
    try (OutputStream out = response.getOutputStream()) {
        out.write(entry.data);
    }
}

From source file:org.obm.push.impl.ResponderImpl.java

private OutputStream getOutputStream(boolean gzip) throws IOException {
    OutputStream out = null;/*from  w ww.jav  a2 s  .  c  om*/
    try {
        out = resp.getOutputStream();
        if (gzip) {
            resp.addHeader(HttpHeaders.VARY, HttpHeaders.ACCEPT_ENCODING);
            resp.addHeader(HttpHeaders.CONTENT_ENCODING, "gzip");
            return new GZIPOutputStream(out);
        } else {
            return out;
        }
    } catch (IOException t) {
        IOUtils.closeQuietly(out);
        throw t;
    } catch (RuntimeException e) {
        IOUtils.closeQuietly(out);
        throw e;
    }
}