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:org.glassfish.jersey.server.RequestContextBuilder.java

public RequestContextBuilder type(MediaType contentType) {
    result.getHeaders().putSingle(HttpHeaders.CONTENT_TYPE, HeadersFactory.asString(contentType, rd));
    return this;
}

From source file:org.openqa.selenium.remote.server.DriverServlet.java

private void handleCrossDomainRpc(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ServletException, IOException {
    CrossDomainRpc rpc;/*from  w w  w .  j a  va2 s. co  m*/

    try {
        rpc = new CrossDomainRpcLoader().loadRpc(servletRequest);
    } catch (IllegalArgumentException e) {
        servletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        servletResponse.getOutputStream().println(e.getMessage());
        servletResponse.getOutputStream().flush();
        return;
    }

    HttpRequest request = new HttpRequest(HttpMethod.valueOf(rpc.getMethod()), rpc.getPath());
    request.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.JSON_UTF_8.toString());
    request.setContent(rpc.getContent());

    HttpResponse response = commandHandler.handleRequest(request);
    sendResponse(response, servletResponse);
}

From source file:org.haiku.haikudepotserver.job.controller.JobController.java

/**
 * <p>This URL can be used to supply data that can be used with a job to be run as an input to the
 * job.  A GUID is returned in the header {@link #HEADER_DATAGUID} that can be later used to refer
 * to this uploaded data.</p>// w w  w.  j a v  a  2  s  . co m
 */

@RequestMapping(value = "/" + SEGMENT_JOBDATA, method = RequestMethod.POST)
@ResponseBody
public void supplyData(final HttpServletRequest request, final HttpServletResponse response,
        @RequestHeader(value = HttpHeaders.CONTENT_TYPE, required = false) String contentType,
        @RequestParam(value = KEY_USECODE, required = false) String useCode) throws IOException {

    Preconditions.checkArgument(null != request, "the request must be provided");

    int length = request.getContentLength();

    if (-1 != length && length > MAX_SUPPLY_DATA_LENGTH) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    }

    ObjectContext context = serverRuntime.newContext();

    tryObtainAuthenticatedUser(context).orElseThrow(() -> {
        LOGGER.warn("attempt to supply job data with no authenticated user");
        return new JobDataAuthorizationFailure();
    });

    JobData data = jobService.storeSuppliedData(useCode,
            !Strings.isNullOrEmpty(contentType) ? contentType : MediaType.OCTET_STREAM.toString(),
            new ByteSource() {
                @Override
                public InputStream openStream() throws IOException {
                    return request.getInputStream();
                }
            });

    response.setStatus(HttpServletResponse.SC_OK);
    response.setHeader(HEADER_DATAGUID, data.getGuid());
}

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;
    }//from   w w w.j  av  a 2  s . c o m
    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:be.solidx.hot.shows.RestRequest.java

private String extractContentTypeHttpHeader() {
    for (Entry<?, ?> entry : headers.entrySet()) {
        if (entry.getKey().equals(HttpHeaders.CONTENT_TYPE)) {
            return (String) ((List<?>) entry.getValue()).get(0);
        }// ww  w.java2 s .c  o  m
    }
    return "text/plain; charset=utf-8";
}

From source file:org.killbill.billing.plugin.util.http.HttpClient.java

protected AsyncHttpClient.BoundRequestBuilder getBuilderWithHeaderAndQuery(final String verb, final String url,
        final Map<String, String> immutableOptions) {
    final AsyncHttpClient.BoundRequestBuilder builder;

    if (GET.equals(verb)) {
        builder = httpClient.prepareGet(url);
    } else if (POST.equals(verb)) {
        builder = httpClient.preparePost(url);
    } else if (PUT.equals(verb)) {
        builder = httpClient.preparePut(url);
    } else if (DELETE.equals(verb)) {
        builder = httpClient.prepareDelete(url);
    } else if (HEAD.equals(verb)) {
        builder = httpClient.prepareHead(url);
    } else if (OPTIONS.equals(verb)) {
        builder = httpClient.prepareOptions(url);
    } else {/*  w  w  w.  ja v a  2 s.c om*/
        throw new IllegalArgumentException("Unrecognized verb: " + verb);
    }

    if (username != null || password != null) {
        final Realm.RealmBuilder realm = new Realm.RealmBuilder();
        if (username != null) {
            realm.setPrincipal(username);
        }
        if (password != null) {
            realm.setPassword(password);
        }
        // Unclear why it's now needed
        realm.setUsePreemptiveAuth(true);
        realm.setScheme(Realm.AuthScheme.BASIC);
        builder.setRealm(realm.build());
    }

    final Map<String, String> options = new HashMap<String, String>(immutableOptions);

    if (options.get(HttpHeaders.ACCEPT) != null) {
        builder.addHeader(HttpHeaders.ACCEPT, options.remove(HttpHeaders.ACCEPT));
    }
    if (options.get(HttpHeaders.CONTENT_TYPE) != null) {
        builder.addHeader(HttpHeaders.CONTENT_TYPE, options.remove(HttpHeaders.CONTENT_TYPE));
    }

    for (final String key : options.keySet()) {
        if (options.get(key) != null) {
            builder.addQueryParam(key, options.get(key));
        }
    }

    if (proxyHost != null && proxyPort != null) {
        final ProxyServer proxyServer = new ProxyServer(proxyHost, proxyPort);
        builder.setProxyServer(proxyServer);
    }

    return builder;
}

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

/**
 * Returns a modifiable view of the headers. Any header (except
 * {@code Content-Length}) may be added, including overwriting the
 * {@code Content-Type} (which defaults to
 * {@code application/x-www-form-urlencoded}).
 *//*ww w. jav a 2 s .  c  o  m*/
@Override
public ListMultimap<String, String> headers() {
    if (headers == null) {
        headers = LinkedListMultimap.create();
        headers.put(HttpHeaders.CONTENT_TYPE, X_WWW_FORM_URLENCODED);
    }
    if (headersView == null) {
        headersView = Predicated.listMultimap(headers, Requests.HKEY_NO_LEN, Predicates.notNull());
    }
    return headersView;
}

From source file:brooklyn.entity.nosql.couchbase.CouchbaseNodeImpl.java

protected void renameServerToPublicHostname() {
    // http://docs.couchbase.com/couchbase-manual-2.5/cb-install/#couchbase-getting-started-hostnames
    URI apiUri = null;//from   w w  w.  j a va  2s  . com
    try {
        HostAndPort accessible = BrooklynAccessUtils.getBrooklynAccessibleAddress(this,
                getAttribute(COUCHBASE_WEB_ADMIN_PORT));
        apiUri = URI.create(String.format("http://%s:%d/node/controller/rename", accessible.getHostText(),
                accessible.getPort()));
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(
                getConfig(COUCHBASE_ADMIN_USERNAME), getConfig(COUCHBASE_ADMIN_PASSWORD));
        HttpToolResponse response = HttpTool.httpPost(
                // the uri is required by the HttpClientBuilder in order to set the AuthScope of the credentials
                HttpTool.httpClientBuilder().uri(apiUri).credentials(credentials).build(), apiUri,
                MutableMap.of(HttpHeaders.CONTENT_TYPE, MediaType.FORM_DATA.toString(), HttpHeaders.ACCEPT,
                        "*/*",
                        // this appears needed; without it we get org.apache.http.NoHttpResponseException !?
                        HttpHeaders.AUTHORIZATION, HttpTool.toBasicAuthorizationValue(credentials)),
                Charsets.UTF_8.encode("hostname=" + Urls.encode(accessible.getHostText())).array());
        log.debug("Renamed Couchbase server " + this + " via " + apiUri + ": " + response);
        if (!HttpTool.isStatusCodeHealthy(response.getResponseCode())) {
            log.warn("Invalid response code, renaming " + apiUri + ": " + response);
        }
    } catch (Exception e) {
        Exceptions.propagateIfFatal(e);
        log.warn("Error renaming server, using " + apiUri + ": " + e, e);
    }
}

From source file:org.openqa.selenium.remote.server.WebDriverServlet.java

private void handleCrossDomainRpc(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ServletException, IOException {
    CrossDomainRpc rpc;//from  w  w w. j  a v  a2s.c  o m

    try {
        rpc = new CrossDomainRpcLoader().loadRpc(servletRequest);
    } catch (IllegalArgumentException e) {
        servletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        servletResponse.getOutputStream().println(e.getMessage());
        servletResponse.getOutputStream().flush();
        return;
    }

    servletRequest.setAttribute(HttpHeaders.CONTENT_TYPE, MediaType.JSON_UTF_8.toString());
    HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(servletRequest) {
        @Override
        public String getMethod() {
            return rpc.getMethod();
        }

        @Override
        public String getPathInfo() {
            return rpc.getPath();
        }

        @Override
        public ServletInputStream getInputStream() throws IOException {
            return new InputStreamWrappingServletInputStream(new ByteArrayInputStream(rpc.getContent()));
        }
    };

    handle(wrapper, servletResponse);
}

From source file:org.apache.brooklyn.entity.nosql.couchbase.CouchbaseNodeImpl.java

protected void renameServerToPublicHostname() {
    // http://docs.couchbase.com/couchbase-manual-2.5/cb-install/#couchbase-getting-started-hostnames
    URI apiUri = null;/*from w w  w  .  j av  a2 s. com*/
    try {
        HostAndPort accessible = BrooklynAccessUtils.getBrooklynAccessibleAddress(this,
                getAttribute(COUCHBASE_WEB_ADMIN_PORT));
        apiUri = URI.create(String.format("http://%s:%d/node/controller/rename", accessible.getHostText(),
                accessible.getPort()));
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(
                getConfig(COUCHBASE_ADMIN_USERNAME), getConfig(COUCHBASE_ADMIN_PASSWORD));
        HttpToolResponse response = HttpTool.httpPost(
                // the uri is required by the HttpClientBuilder in order to set the AuthScope of the credentials
                HttpTool.httpClientBuilder().uri(apiUri).credentials(credentials).build(), apiUri,
                MutableMap.of(HttpHeaders.CONTENT_TYPE, MediaType.FORM_DATA.toString(), HttpHeaders.ACCEPT,
                        "*/*",
                        // this appears needed; without it we get org.apache.http.NoHttpResponseException !?
                        HttpHeaders.AUTHORIZATION, HttpTool.toBasicAuthorizationValue(credentials)),
                Charsets.UTF_8.encode("hostname=" + Urls.encode(accessible.getHostText())).array());
        log.debug("Renamed Couchbase server " + this + " via " + apiUri + ": " + response);
        if (!HttpTool.isStatusCodeHealthy(response.getResponseCode())) {
            log.warn("Invalid response code, renaming {} ({}): {}",
                    new Object[] { apiUri, response.getResponseCode(), response.getContentAsString() });
        }
    } catch (Exception e) {
        Exceptions.propagateIfFatal(e);
        log.warn("Error renaming server, using " + apiUri + ": " + e, e);
    }
}