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

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

Introduction

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

Prototype

String ACCEPT_ENCODING

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

Click Source Link

Document

The HTTP Accept-Encoding header field name.

Usage

From source file:com.salesforce.ide.core.remote.AbstractHTTPTransport.java

public Builder constructBuilder() {
    Builder builder = getSessionEndpoint().request(getMediaType());
    builder.header("Authorization", "OAuth " + connection.getActiveSessionToken());
    builder.header("Content-Type", getMediaType());
    builder.header(HttpHeaders.ACCEPT_ENCODING, "gzip");
    return builder;
}

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;/* w w  w . ja v  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.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   www.  j ava2 s .  c o  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: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  v a2 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);/*from  w  w w.  ja  va2s.  c  o  m*/
    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 .  j a  v  a  2  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;
    }
}

From source file:de.fhg.igd.vaadin.util.servlets.OSGiResourcesServlet.java

/**
 * //from   ww  w  .  j  av  a  2 s  . c o m
 * @param resourcePath
 * @param req
 * @param resp
 * @return
 * @throws MalformedURLException 
 */
private URL lookupPrecompressedFileResource(String resourcePath, HttpServletRequest req,
        HttpServletResponse resp) throws MalformedURLException {

    final String acceptedEncodings = req.getHeader(HttpHeaders.ACCEPT_ENCODING);
    if (acceptedEncodings != null && acceptedEncodings.contains(GZIP_ENCODING)) {
        final URL precompressedResourceURL = lookupFileResource(resourcePath + ".gz", req, resp);
        if (precompressedResourceURL != null) {
            resp.setHeader(HttpHeaders.CONTENT_ENCODING, GZIP_ENCODING);
            log.trace("...using precompressed Resource from servlet context: {}", precompressedResourceURL);
            return precompressedResourceURL;
        }
    }
    // final URL resourcePath.
    return lookupFileResource(resourcePath, req, resp);
}

From source file:org.obm.push.handler.ItemOperationsHandler.java

@VisibleForTesting
static boolean isAcceptGZip(ActiveSyncRequest request) {
    String acceptEncoding = request.getHeader(HttpHeaders.ACCEPT_ENCODING);
    return acceptEncoding != null && acceptEncoding.contains("gzip");
}

From source file:com.nesscomputing.httpclient.factory.httpclient4.ApacheHttpClient4Factory.java

private <T> HttpClientRequest<T> contributeAcceptEncoding(HttpClientRequest<T> request) {
    if (defaultAcceptEncoding == null) {
        return request;
    }/*  ww w  .j a v  a 2s  .  co m*/

    for (HttpClientHeader h : request.getHeaders()) {
        if (StringUtils.equalsIgnoreCase(HttpHeaders.ACCEPT_ENCODING, h.getName())) {
            return request;
        }
    }

    return HttpClientRequest.Builder.fromRequest(request)
            .addHeader(HttpHeaders.ACCEPT_ENCODING, defaultAcceptEncoding).request();
}

From source file:com.google.gerrit.httpd.restapi.RestApiServlet.java

private static boolean acceptsGzip(HttpServletRequest req) {
    if (req != null) {
        String accepts = req.getHeader(HttpHeaders.ACCEPT_ENCODING);
        return accepts != null && accepts.indexOf("gzip") != -1;
    }/*  ww w .jav a 2s.com*/
    return false;
}