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.apache.hadoop.hdfs.ByteRangeInputStream.java

@VisibleForTesting
protected InputStream openInputStream() throws IOException {
    // Use the original url if no resolved url exists, eg. if
    // it's the first time a request is made.
    final boolean resolved = resolvedURL.getURL() != null;
    final URLOpener opener = resolved ? resolvedURL : originalURL;

    final HttpURLConnection connection = opener.connect(startPos, resolved);
    resolvedURL.setURL(getResolvedUrl(connection));

    InputStream in = connection.getInputStream();
    final Map<String, List<String>> headers = connection.getHeaderFields();
    if (isChunkedTransferEncoding(headers)) {
        // file length is not known
        fileLength = null;//w  w  w.j  ava2  s  .c  o  m
    } else {
        // for non-chunked transfer-encoding, get content-length
        final String cl = connection.getHeaderField(HttpHeaders.CONTENT_LENGTH);
        if (cl == null) {
            throw new IOException(HttpHeaders.CONTENT_LENGTH + " is missing: " + headers);
        }
        final long streamlength = Long.parseLong(cl);
        fileLength = startPos + streamlength;

        // Java has a bug with >2GB request streams.  It won't bounds check
        // the reads so the transfer blocks until the server times out
        in = new BoundedInputStream(in, streamlength);
    }

    return in;
}

From source file:com.google.gerrit.util.http.testutil.FakeHttpServletResponse.java

@Override
public void setContentLengthLong(long length) {
    headers.removeAll(HttpHeaders.CONTENT_LENGTH);
    addHeader(HttpHeaders.CONTENT_LENGTH, Long.toString(length));
}

From source file:com.ibm.og.http.AuthenticatedHttpRequest.java

/**
 * Sets the content length for the content stream of this request
 * //from   w  ww .j a  va2  s.c om
 * @param length content stream length
 */
public void setContentLength(final long length) {
    checkArgument(length >= 0, "length must be >= 0 [%s]", length);
    this.addHeader(HttpHeaders.CONTENT_LENGTH, Long.toString(length));
}

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

private void handleHeadOrGet(RequestMethod requestMethod, HttpServletResponse response, Integer targetWidth,
        Integer targetHeight, String format, String screenshotCode) throws IOException {

    if (targetWidth <= 0 || targetWidth > SCREENSHOT_SIDE_LIMIT) {
        throw new BadSize();
    }// w  w  w .  java2  s .  c om

    if (targetHeight <= 0 || targetHeight > SCREENSHOT_SIDE_LIMIT) {
        throw new BadSize();
    }

    if (Strings.isNullOrEmpty(screenshotCode)) {
        throw new MissingScreenshotCode();
    }

    if (Strings.isNullOrEmpty(format) || !"png".equals(format)) {
        throw new MissingOrBadFormat();
    }

    ObjectContext context = serverRuntime.newContext();
    PkgScreenshot screenshot = PkgScreenshot.tryGetByCode(context, screenshotCode)
            .orElseThrow(ScreenshotNotFound::new);

    response.setContentType(MediaType.PNG.toString());
    response.setHeader(HttpHeaders.CACHE_CONTROL, "max-age=3600");

    response.setDateHeader(HttpHeaders.LAST_MODIFIED,
            screenshot.getPkg().getModifyTimestampSecondAccuracy().getTime());

    switch (requestMethod) {
    case HEAD:
        ByteCounterOutputStream byteCounter = new ByteCounterOutputStream(ByteStreams.nullOutputStream());
        pkgScreenshotService.writePkgScreenshotImage(byteCounter, context, screenshot, targetWidth,
                targetHeight);
        response.setHeader(HttpHeaders.CONTENT_LENGTH, Long.toString(byteCounter.getCounter()));

        break;

    case GET:
        pkgScreenshotService.writePkgScreenshotImage(response.getOutputStream(), context, screenshot,
                targetWidth, targetHeight);
        break;

    default:
        throw new IllegalStateException("unhandled request method; " + requestMethod);
    }

}

From source file:com.heliosapm.tsdblite.handlers.http.HttpRequestManager.java

/**
 * {@inheritDoc}//from  ww  w  . j a  v a2 s.  com
 * @see io.netty.channel.SimpleChannelInboundHandler#channelRead0(io.netty.channel.ChannelHandlerContext, java.lang.Object)
 */
@Override
protected void channelRead0(final ChannelHandlerContext ctx, final HttpRequest msg) throws Exception {
    try {
        final String uri = msg.uri();
        final Channel channel = ctx.channel();
        if (uri.endsWith("/favicon.ico")) {
            final DefaultFullHttpResponse resp = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                    HttpResponseStatus.OK, favicon);
            resp.headers().set(HttpHeaders.CONTENT_TYPE, "image/x-icon");
            resp.headers().setInt(HttpHeaders.CONTENT_LENGTH, favSize);
            ctx.writeAndFlush(resp);
            return;
        } else if (uri.equals("/api/put") || uri.equals("/api/metadata")) {
            final ChannelPipeline p = ctx.pipeline();
            //            p.addLast(loggingHandler, jsonAdapter, new JsonObjectDecoder(true), traceHandler);
            p.addLast(jsonAdapter, new JsonObjectDecoder(true), traceHandler);
            //            if(msg instanceof FullHttpRequest) {
            //               ByteBuf b = ((FullHttpRequest)msg).content().copy();
            //               ctx.fireChannelRead(b);
            //            }
            ctx.fireChannelRead(msg);
            p.remove("requestManager");
            log.info("Switched to JSON Trace Processor");
            return;
        }
        final TSDBHttpRequest r = new TSDBHttpRequest(msg, ctx.channel(), ctx);
        final HttpRequestHandler handler = requestHandlers.get(r.getRoute());
        if (handler == null) {
            r.send404().addListener(new GenericFutureListener<Future<? super Void>>() {
                public void operationComplete(Future<? super Void> f) throws Exception {
                    log.info("404 Not Found for {} Complete: success: {}", r.getRoute(), f.isSuccess());
                    if (!f.isSuccess()) {
                        log.error("Error sending 404", f.cause());
                    }
                };
            });
            return;
        }
        handler.process(r);
    } catch (Exception ex) {
        log.error("HttpRequest Routing Error", ex);
    }
}

From source file:org.jclouds.s3.filters.Aws4SignerForAuthorizationHeader.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();

    // 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

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

    // 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);
    }//from   w  ww  .  j av  a  2  s .  c o m

    // Content-Length for PUT or POST request http method
    String contentLength = getContentLength(request);
    if (!Strings.isNullOrEmpty(contentLength)) {
        requestBuilder.replaceHeader(HttpHeaders.CONTENT_LENGTH, contentLength);
        signedHeadersBuilder.put(HttpHeaders.CONTENT_LENGTH.toLowerCase(), contentLength);
    }

    // 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);
    }

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

    // user-agent
    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(request);
    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);
    String signature = base16().lowerCase().encode(hmacSHA256(stringToSign, signatureKey));

    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);
    return requestBuilder.replaceHeader(HttpHeaders.AUTHORIZATION, authorization.toString()).build();
}

From source file:com.google.cloud.runtimes.tomcat.trace.TraceValve.java

/**
 * Create labels for Stackdriver trace with basic response and request info.
 *//*from  w w  w . j av  a2s .  c  om*/
private Labels createLabels(Request request, Response response) {
    Labels.Builder labels = Labels.builder();
    this.annotateIfNotEmpty(labels, HttpLabels.HTTP_METHOD.getValue(), request.getMethod());
    this.annotateIfNotEmpty(labels, HttpLabels.HTTP_URL.getValue(), request.getRequestURI());
    this.annotateIfNotEmpty(labels, HttpLabels.HTTP_CLIENT_PROTOCOL.getValue(), request.getProtocol());
    this.annotateIfNotEmpty(labels, HttpLabels.HTTP_USER_AGENT.getValue(),
            request.getHeader(HttpHeaders.USER_AGENT));
    this.annotateIfNotEmpty(labels, HttpLabels.HTTP_REQUEST_SIZE.getValue(),
            request.getHeader(HttpHeaders.CONTENT_LENGTH));
    this.annotateIfNotEmpty(labels, HttpLabels.HTTP_RESPONSE_SIZE.getValue(),
            response.getHeader(HttpHeaders.CONTENT_LENGTH));
    labels.add(HttpLabels.HTTP_STATUS_CODE.getValue(), Integer.toString(response.getStatus()));
    return labels.build();
}

From source file:org.hashes.CollisionInjector.java

protected void addRequestHeaders(final int contentLength, final StringBuilder payloadBuilder) {

    // http://www.ietf.org/rfc/rfc2616.txt
    // Each header field consists of a name followed by a colon (":") and the field value. Field names are
    // case-insensitive.
    final Locale locale = Locale.ENGLISH;
    final Map<String, String> defaultHeaders = new LinkedHashMap<String, String>();
    defaultHeaders.put(HttpHeaders.HOST.toLowerCase(locale), this.configuration.getTarget().getHost());
    defaultHeaders.put(HttpHeaders.CONTENT_TYPE.toLowerCase(locale), "application/x-www-form-urlencoded");
    defaultHeaders.put(HttpHeaders.ACCEPT_CHARSET.toLowerCase(locale), this.configuration.getCharset().name());
    defaultHeaders.put(HttpHeaders.CONTENT_LENGTH.toLowerCase(locale), String.valueOf(contentLength));
    defaultHeaders.put(HttpHeaders.USER_AGENT.toLowerCase(locale), "hashes");
    defaultHeaders.put(HttpHeaders.ACCEPT.toLowerCase(locale), "*/*");

    for (final Entry<String, String> externalHeaders : this.configuration.getHeaders().entrySet()) {
        defaultHeaders.put(externalHeaders.getKey().toLowerCase(locale), externalHeaders.getValue());
    }// w  w w .j av  a2  s.c  om

    for (final Entry<String, String> header : defaultHeaders.entrySet()) {
        payloadBuilder.append(header.getKey());
        payloadBuilder.append(": ");
        payloadBuilder.append(header.getValue());
        payloadBuilder.append("\r\n");
    }

    payloadBuilder.append("\r\n");
}

From source file:com.heliosapm.tsdblite.handlers.http.TSDBHttpRequest.java

private static HttpResponse response(final HttpResponseStatus status, final String... msgs) {
    final ByteBuf buf = join(msgs);
    if (buf.readableBytes() == 0) {
        return new DefaultHttpResponse(HttpVersion.HTTP_1_1, status);
    }/*  ww w . j  a  va  2  s.c  o m*/
    final DefaultFullHttpResponse resp = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, buf);
    resp.headers().setInt(HttpHeaders.CONTENT_LENGTH, buf.readableBytes());
    resp.headers().set(HttpHeaders.CONTENT_TYPE, "text/plain");
    return resp;
}

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

private static void handleFullFileRequest(final Artifact artifact, final HttpServletResponse response,
        final DbArtifact file, final ControllerManagement controllerManagement, final Long statusId,
        final ByteRange full) {
    final ByteRange r = full;
    response.setHeader(HttpHeaders.CONTENT_RANGE,
            "bytes " + r.getStart() + "-" + r.getEnd() + "/" + r.getTotal());
    response.setHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(r.getLength()));

    try (InputStream inputStream = file.getFileInputStream()) {
        copyStreams(inputStream, response.getOutputStream(), controllerManagement, statusId, r.getStart(),
                r.getLength());// ww  w .j  a  va2  s . c om
    } catch (final IOException e) {
        LOG.error("fullfileRequest of file ({}) failed!", artifact.getFilename(), e);
        throw new FileSteamingFailedException(artifact.getFilename());
    }
}