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

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

Introduction

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

Prototype

String CONTENT_LENGTH

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

Click Source Link

Document

The HTTP Content-Length header field name.

Usage

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

protected String getContentLength(HttpRequest request) {
    Payload payload = request.getPayload();

    // Default Content Type
    String contentLength = request.getFirstHeaderOrNull(HttpHeaders.CONTENT_LENGTH);
    if (payload != null && payload.getContentMetadata() != null
            && payload.getContentMetadata().getContentType() != null) {
        Long length = payload.getContentMetadata().getContentLength();
        contentLength = length == null ? contentLength
                : String.valueOf(payload.getContentMetadata().getContentLength());
    }/*w w w . j  a  v  a 2  s  . co  m*/
    return contentLength;
}

From source file:com.bouncestorage.chaoshttpproxy.ChaosHttpProxyHandler.java

@Override
public void handle(String target, Request baseRequest, HttpServletRequest request,
        HttpServletResponse servletResponse) throws IOException {
    baseRequest.setHandled(true);//from   w ww  . j a v a2 s  .c  om

    // CONNECT is not supported pending implementation of MITM HTTPS
    if (request.getMethod().equals("CONNECT")) {
        logger.debug("CONNECT is not supported");
        servletResponse.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        return;
    }

    Failure failure = supplier.get();
    logger.debug("request: {}", request);
    logger.debug("Failure: {}", failure);
    try (InputStream is = request.getInputStream(); OutputStream os = servletResponse.getOutputStream()) {
        HostAndPort hostAndPort = HostAndPort.fromString(request.getHeader(HttpHeaders.HOST));
        String queryString = request.getQueryString();
        URI uri;
        try {
            uri = new URI(request.getScheme(), /*userInfo=*/ null, hostAndPort.getHostText(),
                    hostAndPort.hasPort() ? hostAndPort.getPort() : 80, request.getRequestURI(), queryString,
                    /*fragment=*/ null);
        } catch (URISyntaxException use) {
            throw new IOException(use);
        }
        logger.debug("uri: {}", uri);
        URI redirectedUri = redirects.get(uri);
        if (redirectedUri != null) {
            // TODO: parameters
            uri = redirectedUri;
            logger.debug("redirected uri: {}", uri);
        }

        switch (failure) {
        case HTTP_301:
        case HTTP_302:
        case HTTP_303:
        case HTTP_307:
        case HTTP_308:
            servletResponse.setStatus(failure.getResponseCode());
            URI redirectUri;
            try {
                redirectUri = new URI(request.getScheme(), /*userInfo=*/ null, hostAndPort.getHostText(),
                        hostAndPort.hasPort() ? hostAndPort.getPort() : 80, "/" + UUID.randomUUID().toString(),
                        /*query=*/ null, /*fragment=*/ null);
            } catch (URISyntaxException use) {
                throw new IOException(use);
            }
            redirects.put(redirectUri, uri);
            servletResponse.addHeader(HttpHeaders.LOCATION, redirectUri.toString());
            return;
        case HTTP_408:
        case HTTP_500:
        case HTTP_503:
        case HTTP_504:
            servletResponse.setStatus(failure.getResponseCode());
            return;
        case TIMEOUT:
            Uninterruptibles.sleepUninterruptibly(Long.MAX_VALUE, TimeUnit.DAYS);
            return;
        default:
            break;
        }

        InputStreamResponseListener listener = new InputStreamResponseListener();
        InputStream iss = failure == Failure.PARTIAL_REQUEST ?
        // TODO: random limit
                ByteStreams.limit(is, 1024) : is;
        org.eclipse.jetty.client.api.Request clientRequest = client.newRequest(uri.toString())
                .method(request.getMethod());
        long userContentLength = -1;
        for (String headerName : Collections.list(request.getHeaderNames())) {
            if (headerName.equalsIgnoreCase(HttpHeaders.EXPECT)
                    || headerName.equalsIgnoreCase("Proxy-Connection")) {
                continue;
            }
            String headerValue = request.getHeader(headerName);
            logger.trace("{}: {}", headerName, headerValue);

            if (headerName.equalsIgnoreCase(HttpHeaders.CONTENT_MD5)
                    && failure == Failure.CORRUPT_REQUEST_CONTENT_MD5) {
                headerValue = headerValue.toUpperCase();
            }
            if (headerName.equalsIgnoreCase(HttpHeaders.CONTENT_LENGTH)) {
                userContentLength = Long.parseLong(headerValue);
            }
            clientRequest.header(headerName, headerValue);
        }

        // Work around Jetty bug that strips Content-Length
        // https://bugs.eclipse.org/bugs/show_bug.cgi?id=475613.
        final long length = userContentLength;
        clientRequest.content(new InputStreamContentProvider(iss) {
            @Override
            public long getLength() {
                return length != -1 ? length : super.getLength();
            }
        });
        clientRequest.send(listener);
        if (failure == Failure.PARTIAL_REQUEST) {
            return;
        }

        Response response;
        try {
            response = listener.get(Long.MAX_VALUE, TimeUnit.SECONDS);
        } catch (ExecutionException | InterruptedException | TimeoutException e) {
            throw new IOException(e);
        }
        int status = response.getStatus();
        logger.trace("status: {}", status);
        servletResponse.setStatus(status);
        List<HttpField> headers = Lists.newArrayList(response.getHeaders());
        if (failure == Failure.REORDER_HEADERS) {
            Collections.shuffle(headers);
        }
        for (HttpField field : headers) {
            String header = field.getName();
            String value = field.getValue();
            logger.trace("header: {}: {}", header, value);
            switch (failure) {
            case CHANGE_HEADER_CASE:
                // TODO: randomly change between upper- and lower-case
                header = header.toUpperCase();
                break;
            case CORRUPT_RESPONSE_CONTENT_MD5:
                if (header.equals(HttpHeaders.CONTENT_MD5)) {
                    value = BaseEncoding.base64().encode(new byte[Hashing.md5().bits() / 8]);
                }
                break;
            default:
                break;
            }
            servletResponse.addHeader(header, value);
        }
        try (InputStream responseContent = listener.getInputStream()) {
            switch (failure) {
            case PARTIAL_RESPONSE:
                byte[] array = new byte[1024];
                int count = responseContent.read(array);
                if (count != -1) {
                    // TODO: randomly read n - 1 bytes
                    os.write(array, 0, count / 2);
                    os.flush();
                }
                return;
            case SLOW_RESPONSE:
                for (int i = 0; i < 10; ++i) {
                    int ch = responseContent.read();
                    if (ch == -1) {
                        break;
                    }
                    os.write(ch);
                    os.flush();
                    Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
                }
                break;
            default:
                break;
            }
            ByteStreams.copy(responseContent, os);
        }
    }
}

From source file:org.haiku.haikudepotserver.pkg.controller.PkgIconController.java

/**
 * @param isAsFallback is true if the request was originally for a package, but fell back to this generic.
 *///ww  w  . ja va  2 s. c o  m

private void handleGenericHeadOrGet(RequestMethod requestMethod, HttpServletResponse response, Integer size,
        boolean isAsFallback) throws IOException {

    if (null == size) {
        size = 64; // largest natural size
    }

    size = normalizeSize(size);
    byte[] data = renderedPkgIconRepository.renderGeneric(size);
    response.setHeader(HttpHeaders.CONTENT_LENGTH, Integer.toString(data.length));
    response.setContentType(MediaType.PNG.toString());

    if (isAsFallback) {
        response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate");
        response.setHeader(HttpHeaders.PRAGMA, "no-cache");
        response.setHeader(HttpHeaders.EXPIRES, "0");
    } else {
        response.setDateHeader(HttpHeaders.LAST_MODIFIED, startupMillis);
    }

    if (requestMethod == RequestMethod.GET) {
        response.getOutputStream().write(data);
    }
}

From source file:com.google.zxing.web.DecodeServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String imageURIString = request.getParameter("u");
    if (imageURIString == null || imageURIString.isEmpty()) {
        log.info("URI was empty");
        errorResponse(request, response, "badurl");
        return;/* w ww .ja  va  2 s. c  o  m*/
    }

    imageURIString = imageURIString.trim();
    for (CharSequence substring : blockedURLSubstrings) {
        if (imageURIString.contains(substring)) {
            log.info("Disallowed URI " + imageURIString);
            errorResponse(request, response, "badurl");
            return;
        }
    }

    URI imageURI;
    try {
        imageURI = new URI(imageURIString);
        // Assume http: if not specified
        if (imageURI.getScheme() == null) {
            imageURI = new URI("http://" + imageURIString);
        }
    } catch (URISyntaxException urise) {
        log.info("URI " + imageURIString + " was not valid: " + urise);
        errorResponse(request, response, "badurl");
        return;
    }

    // Shortcut for data URI
    if ("data".equals(imageURI.getScheme())) {
        try {
            BufferedImage image = ImageReader.readDataURIImage(imageURI);
            processImage(image, request, response);
        } catch (IOException ioe) {
            log.info(ioe.toString());
            errorResponse(request, response, "badurl");
        }
        return;
    }

    URL imageURL;
    try {
        imageURL = imageURI.toURL();
    } catch (MalformedURLException ignored) {
        log.info("URI was not valid: " + imageURIString);
        errorResponse(request, response, "badurl");
        return;
    }

    String protocol = imageURL.getProtocol();
    if (!"http".equalsIgnoreCase(protocol) && !"https".equalsIgnoreCase(protocol)) {
        log.info("URI was not valid: " + imageURIString);
        errorResponse(request, response, "badurl");
        return;
    }

    HttpURLConnection connection;
    try {
        connection = (HttpURLConnection) imageURL.openConnection();
    } catch (IllegalArgumentException ignored) {
        log.info("URI could not be opened: " + imageURL);
        errorResponse(request, response, "badurl");
        return;
    }

    connection.setAllowUserInteraction(false);
    connection.setReadTimeout(5000);
    connection.setConnectTimeout(5000);
    connection.setRequestProperty(HttpHeaders.USER_AGENT, "zxing.org");
    connection.setRequestProperty(HttpHeaders.CONNECTION, "close");

    try {
        connection.connect();
    } catch (IOException | IllegalArgumentException e) {
        // Encompasses lots of stuff, including
        //  java.net.SocketException, java.net.UnknownHostException,
        //  javax.net.ssl.SSLPeerUnverifiedException,
        //  org.apache.http.NoHttpResponseException,
        //  org.apache.http.client.ClientProtocolException,
        log.info(e.toString());
        errorResponse(request, response, "badurl");
        return;
    }

    try (InputStream is = connection.getInputStream()) {
        try {
            if (connection.getResponseCode() != HttpServletResponse.SC_OK) {
                log.info("Unsuccessful return code: " + connection.getResponseCode());
                errorResponse(request, response, "badurl");
                return;
            }
            if (connection.getHeaderFieldInt(HttpHeaders.CONTENT_LENGTH, 0) > MAX_IMAGE_SIZE) {
                log.info("Too large");
                errorResponse(request, response, "badimage");
                return;
            }

            log.info("Decoding " + imageURL);
            processStream(is, request, response);
        } finally {
            consumeRemainder(is);
        }
    } catch (IOException ioe) {
        log.info(ioe.toString());
        errorResponse(request, response, "badurl");
    } finally {
        connection.disconnect();
    }

}

From source file:org.haiku.haikudepotserver.pkg.controller.PkgIconController.java

private void handleHeadOrGetPkgIcon(RequestMethod requestMethod, HttpServletResponse response, Integer size,
        String format, String pkgName, Boolean fallback) throws IOException {

    if (null == format) {
        throw new MissingOrBadFormat();
    }/*w  w  w  .jav  a2 s .c  om*/

    if (Strings.isNullOrEmpty(pkgName) || !Pkg.PATTERN_NAME.matcher(pkgName).matches()) {
        throw new MissingPkgName();
    }

    ObjectContext context = serverRuntime.newContext();
    Optional<Pkg> pkg = Pkg.tryGetByName(context, pkgName); // cached

    if (!pkg.isPresent()) {
        LOGGER.debug("request for icon for package '{}', but no such package was able to be found", pkgName);
        throw new PkgNotFound();
    }

    switch (format) {

    case org.haiku.haikudepotserver.dataobjects.MediaType.EXTENSION_HAIKUVECTORICONFILE:
        Optional<PkgIcon> hvifPkgIcon = pkg.get().getPkgIcon(
                org.haiku.haikudepotserver.dataobjects.MediaType.getByExtension(context, format).get(), null);

        if (hvifPkgIcon.isPresent()) {
            byte[] data = hvifPkgIcon.get().getPkgIconImage().getData();
            response.setHeader(HttpHeaders.CONTENT_LENGTH, Integer.toString(data.length));
            response.setContentType(
                    org.haiku.haikudepotserver.dataobjects.MediaType.MEDIATYPE_HAIKUVECTORICONFILE);
            response.setDateHeader(HttpHeaders.LAST_MODIFIED,
                    pkg.get().getModifyTimestampSecondAccuracy().getTime());

            if (requestMethod == RequestMethod.GET) {
                OutputStream outputStream = response.getOutputStream();
                outputStream.write(data);
                outputStream.flush();
            }
        } else {
            throw new PkgIconNotFound();
        }
        break;

    case org.haiku.haikudepotserver.dataobjects.MediaType.EXTENSION_PNG:

        if (null == size) {
            throw new IllegalArgumentException("the size must be provided when requesting a PNG");
        }

        size = normalizeSize(size);
        Optional<byte[]> pngImageData = renderedPkgIconRepository.render(size, context, pkg.get());

        if (!pngImageData.isPresent()) {
            if ((null == fallback) || !fallback) {
                throw new PkgIconNotFound();
            }

            handleGenericHeadOrGet(requestMethod, response, size, true);
        } else {
            byte[] data = pngImageData.get();
            response.setHeader(HttpHeaders.CONTENT_LENGTH, Integer.toString(data.length));
            response.setContentType(MediaType.PNG.toString());
            response.setDateHeader(HttpHeaders.LAST_MODIFIED,
                    pkg.get().getModifyTimestampSecondAccuracy().getTime());

            if (requestMethod == RequestMethod.GET) {
                OutputStream outputStream = response.getOutputStream();
                outputStream.write(data);
                outputStream.flush();
            }
        }
        break;

    default:
        throw new IllegalStateException("unexpected format; " + format);

    }

}

From source file:io.github.mike10004.vhs.testsupport.MakeFileUploadHar.java

private static NanoHTTPD.Response processUpload(NanoHTTPD.IHTTPSession session,
        Map<String, TypedContent> storage) {
    if (NanoHTTPD.Method.POST != session.getMethod()) {
        return NanoHTTPD.newFixedLengthResponse(NanoHTTPD.Response.Status.METHOD_NOT_ALLOWED, "text/plain",
                "Not allowed: " + session.getMethod());
    }/*w  ww  .j  a v a2  s.c  o  m*/
    Long contentLength = getHeaderValueAsLong(session.getHeaders(), HttpHeaders.CONTENT_LENGTH);
    if (contentLength == null) {
        return NanoHTTPD.newFixedLengthResponse(NanoHTTPD.Response.Status.BAD_REQUEST, "text/plain",
                "Bad Request: must contain content-length header");
    }
    byte[] bytes;
    InputStream in = session.getInputStream(); // do not close: that would close the socket, which needs to remain open to send a response
    try {
        bytes = readFully(in, contentLength);
    } catch (IOException e) {
        System.out.format("%s %s error: %s%n", session.getMethod(), session.getUri(), e);
        return NanoHTTPD.newFixedLengthResponse(NanoHTTPD.Response.Status.INTERNAL_ERROR, "text/plain",
                e.toString());
    }
    return parseBody(getContentType(session.getHeaders()), bytes, storage);
}

From source file:be.solidx.hot.nio.http.Request.java

private HttpRequest prepareRequest(URL url) {
    HttpRequest httpRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, (HttpMethod) options.get(TYPE),
            url.getPath());/*from w  w  w .  ja v a  2  s . co  m*/

    // Set request http headers
    boolean hostnameHeader = false;
    if (Request.this.options.get(HEADERS) != null) {
        for (Entry<String, String> entry : ((Map<String, String>) Request.this.options.get(HEADERS))
                .entrySet()) {
            if (entry.getValue() == null) {
                LOGGER.error("null value for header [" + entry.getKey() + "]");
                continue;
            }
            httpRequest.headers().set(entry.getKey(), entry.getValue());
            if (entry.getKey().equals("Host")) {
                hostnameHeader = true;
            }
        }
    }
    if (!hostnameHeader) {
        httpRequest.headers().set("Host", url.getHost());
    }

    // Set request payload
    if (options.get(DATA) != null) {
        Charset urlDataCharset = requestContentType().getCharSet();
        if (urlDataCharset == null)
            urlDataCharset = Charset.forName("utf-8");
        if (httpRequest.getMethod().equals(HttpMethod.GET)) {
            httpRequest.setUri(httpRequest.getUri() + "?"
                    + new String(processRequestData(MediaType.APPLICATION_FORM_URLENCODED), urlDataCharset));
        } else {
            if ((boolean) options.get(PROCESS_DATA)) {
                byte[] processedData = processRequestData();
                if (processedData != null)
                    httpRequest.setContent(ChannelBuffers.wrappedBuffer(processedData));
                httpRequest.headers().set(HttpHeaders.CONTENT_LENGTH, processedData.length);
            } else {
                byte[] payload;
                if (options.get(DATA) instanceof String) {
                    payload = ((String) options.get(DATA)).getBytes(urlDataCharset);
                } else {
                    payload = (options.get(DATA).toString().getBytes(urlDataCharset));
                }
                httpRequest.headers().set(HttpHeaders.CONTENT_LENGTH, payload.length);
                httpRequest.setContent(ChannelBuffers.wrappedBuffer(payload));
            }
        }
    }
    return httpRequest;
}

From source file:org.eclipse.hawkbit.rest.util.RestResourceConversionHelper.java

private static void handleStandardRangeRequest(final Artifact artifact, final HttpServletResponse response,
        final DbArtifact file, final ControllerManagement controllerManagement, final Long statusId,
        final List<ByteRange> ranges) {
    final ByteRange r = ranges.get(0);
    response.setHeader(HttpHeaders.CONTENT_RANGE,
            "bytes " + r.getStart() + "-" + r.getEnd() + "/" + r.getTotal());
    response.setHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(r.getLength()));
    response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);

    try (InputStream inputStream = file.getFileInputStream()) {
        copyStreams(inputStream, response.getOutputStream(), controllerManagement, statusId, r.getStart(),
                r.getLength());// w  w  w.j  a v a2s  .co m
    } catch (final IOException e) {
        LOG.error("standardRangeRequest of file ({}) failed!", artifact.getFilename(), e);
        throw new FileSteamingFailedException(artifact.getFilename());
    }
}

From source file:net.myrrix.client.ClientRecommender.java

private void doSetOrRemove(String path, long unnormalizedID, float value, boolean set) throws TasteException {
    boolean sendValue = value != 1.0f;
    Map<String, String> requestProperties;
    byte[] bytes;
    if (sendValue) {
        requestProperties = Maps.newHashMapWithExpectedSize(2);
        bytes = Float.toString(value).getBytes(Charsets.UTF_8);
        requestProperties.put(HttpHeaders.CONTENT_TYPE, MediaType.PLAIN_TEXT_UTF_8.toString());
        requestProperties.put(HttpHeaders.CONTENT_LENGTH, Integer.toString(bytes.length));
    } else {/*  w w  w  .j  a v  a  2 s  . c o  m*/
        requestProperties = null;
        bytes = null;
    }

    TasteException savedException = null;
    for (HostAndPort replica : choosePartitionAndReplicas(unnormalizedID)) {
        HttpURLConnection connection = null;
        try {
            connection = buildConnectionToReplica(replica, path, set ? "POST" : "DELETE", sendValue, false,
                    requestProperties);
            if (sendValue) {
                OutputStream out = connection.getOutputStream();
                out.write(bytes);
                out.close();
            }
            // Should not be able to return Not Available status
            if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                throw new TasteException(connection.getResponseCode() + " " + connection.getResponseMessage());
            }
            return;
        } catch (TasteException te) {
            log.info("Can't access {} at {}: ({})", path, replica, te.toString());
            savedException = te;
        } catch (IOException ioe) {
            log.info("Can't access {} at {}: ({})", path, replica, ioe.toString());
            savedException = new TasteException(ioe);
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }
    throw savedException;
}

From source file:com.tinspx.util.net.Headers.java

/**
 * Returns the value of the {@code Content-Length} header, or 0 if the
 * header is missing or invalid. Will not throw a
 * {@code NumberFormatException}./*from   w  w  w .  ja va 2s .c o  m*/
 * 
 * @see #parseContentLength()
 */
public long contentLength() {
    final String header = last(HttpHeaders.CONTENT_LENGTH).trim();
    if (header.isEmpty()) {
        return 0;
    } else {
        final Long len = Longs.tryParse(header);
        return len != null ? Math.max(0, len) : 0;
    }
}