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

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

Introduction

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

Prototype

String CONTENT_TYPE

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

Click Source Link

Document

The HTTP Content-Type header field name.

Usage

From source file:com.seleniumtests.connectors.selenium.SeleniumRobotGridConnector.java

/**
 * In case an app is required on the node running the test, upload it to the grid hub
 * This will then be made available through HTTP GET URL to the node (appium will receive an url instead of a file)
 * /*w  ww . j av a  2s.  co m*/
 */
@Override
public void uploadMobileApp(Capabilities caps) {

    String appPath = (String) caps.getCapability(MobileCapabilityType.APP);

    // check whether app is given and app path is a local file
    if (appPath != null && new File(appPath).isFile()) {

        try (CloseableHttpClient client = HttpClients.createDefault();) {
            // zip file
            List<File> appFiles = new ArrayList<>();
            appFiles.add(new File(appPath));
            File zipFile = FileUtility.createZipArchiveFromFiles(appFiles);

            HttpHost serverHost = new HttpHost(hubUrl.getHost(), hubUrl.getPort());
            URIBuilder builder = new URIBuilder();
            builder.setPath("/grid/admin/FileServlet/");
            builder.addParameter("output", "app");
            HttpPost httpPost = new HttpPost(builder.build());
            httpPost.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.OCTET_STREAM.toString());
            FileInputStream fileInputStream = new FileInputStream(zipFile);
            InputStreamEntity entity = new InputStreamEntity(fileInputStream);
            httpPost.setEntity(entity);

            CloseableHttpResponse response = client.execute(serverHost, httpPost);
            if (response.getStatusLine().getStatusCode() != 200) {
                throw new SeleniumGridException(
                        "could not upload application file: " + response.getStatusLine().getReasonPhrase());
            } else {
                // set path to the mobile application as an URL on the grid hub
                ((DesiredCapabilities) caps).setCapability(MobileCapabilityType.APP,
                        IOUtils.toString(response.getEntity().getContent()) + "/" + appFiles.get(0).getName());
            }

        } catch (IOException | URISyntaxException e) {
            throw new SeleniumGridException("could not upload application file", e);
        }
    }
}

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

/**
 * Get char set from headers/* w  w  w  . j a v a 2 s  .  c om*/
 *
 * */
protected String getCharset() {
    String header = getHeader(HttpHeaders.CONTENT_TYPE);
    if (Strings.isNullOrEmpty(header)) {
        return DEFAULT_CHARSET;
    } else {
        return MediaType.parse(header).charset().or(Charsets.UTF_8).toString();
    }
}

From source file:net.bobah.mail.Searcher.java

private static final String contentType(final Headers reqHeaders) {
    final String reqContentType = reqHeaders.getFirst(HttpHeaders.CONTENT_TYPE);
    String encoding = "utf-8";
    if (!Strings.isNullOrEmpty(reqContentType)) {
        final Iterable<String> params = headerValueSplitter.split(reqContentType);
        final String param = Iterables.find(params, new Predicate<String>() {
            @Override//ww w .  j  a v  a  2s .c  o m
            public boolean apply(String param) {
                return param.startsWith("encoding=");
            }
        }, "encoding=utf-8");
        encoding = param.substring("encoding=".length());
    }
    return encoding;
}

From source file:org.jclouds.googlecloudstorage.blobstore.GoogleCloudStorageBlobRequestSigner.java

private HttpRequest sign(String method, String container, String name, GetOptions options, long expires,
        String contentType) {//from   ww w .j  av  a  2 s  .  c  o  m
    checkNotNull(container, "container");
    checkNotNull(name, "name");

    HttpRequest.Builder request = HttpRequest.builder().method(method)
            .endpoint(Uris.uriBuilder(STORAGE_URL).appendPath(container).appendPath(name).build());
    if (contentType != null) {
        request.replaceHeader(HttpHeaders.CONTENT_TYPE, contentType);
    }

    String stringToSign = createStringToSign(request.build(), expires);
    byte[] rawSignature;
    try {
        Signature signer = Signature.getInstance("SHA256withRSA");
        signer.initSign(privateKey.get());
        signer.update(stringToSign.getBytes(Charsets.UTF_8));
        rawSignature = signer.sign();
    } catch (InvalidKeyException ike) {
        throw new RuntimeException(ike);
    } catch (NoSuchAlgorithmException nsae) {
        throw new RuntimeException(nsae);
    } catch (SignatureException se) {
        throw new RuntimeException(se);
    }
    String signature = BaseEncoding.base64().encode(rawSignature);

    for (Map.Entry<String, String> entry : options.buildRequestHeaders().entries()) {
        request.addHeader(entry.getKey(), entry.getValue());
    }

    return (HttpRequest) request.addQueryParam("Expires", String.valueOf(expires))
            .addQueryParam("GoogleAccessId", creds.get().identity).addQueryParam("Signature", signature)
            .build();
}

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

@Override
public void setContentType(String type) {
    headers.removeAll(HttpHeaders.CONTENT_TYPE);
    addHeader(HttpHeaders.CONTENT_TYPE, type);
}

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);
    }/* www  . j a  v a2s.com*/

    // 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:org.ambraproject.wombat.controller.ExternalResourceController.java

private void serve(HttpServletResponse responseToClient, HttpServletRequest requestFromClient, ContentKey key)
        throws IOException {
    CacheKey cacheKey = key.asCacheKey("indirect");
    Map<String, Object> fileMetadata;

    try {/*from   ww w. ja va  2 s. c  om*/
        fileMetadata = editorialContentApi.requestMetadata(cacheKey, key);
    } catch (EntityNotFoundException e) {
        String message = String.format("Not found in repo: %s", key.toString());
        throw new NotFoundException(message, e);
    }

    String contentType = (String) fileMetadata.get("contentType");
    if (contentType != null) {
        responseToClient.setHeader(HttpHeaders.CONTENT_TYPE, contentType);
    }

    String downloadName = (String) fileMetadata.get("downloadName");
    if (downloadName != null) {
        responseToClient.setHeader(HttpHeaders.CONTENT_DISPOSITION, "filename=" + downloadName);
    }

    List<String> reproxyUrls = (List<String>) fileMetadata.get("reproxyURL");
    if (ReproxyUtil.applyReproxy(requestFromClient, responseToClient, reproxyUrls, REPROXY_CACHE_FOR)) {
        return;
    }

    Collection<Header> assetHeaders = HttpMessageUtil.getRequestHeaders(requestFromClient,
            ASSET_REQUEST_HEADER_WHITELIST);
    try (CloseableHttpResponse repoResponse = editorialContentApi.request(key, assetHeaders)) {
        forwardAssetResponse(repoResponse, responseToClient, false);
    } catch (EntityNotFoundException e) {
        throw new NotFoundException("File not found in repo: " + key, e);
    }
}

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

/**
 * {@inheritDoc}// w  ww .  j av  a2s . c o m
 * @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.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.ja  v  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:org.graylog2.radio.cluster.InputService.java

public void unregisterInCluster(MessageInput input)
        throws ExecutionException, InterruptedException, IOException {
    final URI uri = UriBuilder.fromUri(serverUrl).path("/system/radios/{radioId}/inputs/{inputId}")
            .build(nodeId.toString(), input.getPersistId());

    final Request request = new Request.Builder().header(HttpHeaders.CONTENT_TYPE, APPLICATION_JSON).delete()
            .url(uri.toString()).build();

    final Response r = httpclient.newCall(request).execute();
    if (!r.isSuccessful()) {
        throw new RuntimeException(
                "Expected HTTP response [2xx] for input unregistration but got [" + r.code() + "].");
    }// w  w w  . ja  va  2 s. c  om
}