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.linkedin.flashback.serializable.RecordedHttpMessage.java

public String getCharset() {
    String header = _headers.get(HttpHeaders.CONTENT_TYPE);
    if (Strings.isNullOrEmpty(header)) {
        return DEFAULT_CHARSET;
    } else {//  w  w  w. ja v a2 s . c  o  m
        return MediaType.parse(header).charset().or(Charsets.UTF_8).toString();
    }
}

From source file:be.solidx.hot.shows.spring.RequestMappingMvcRequestMappingAdapter.java

RequestMappingInfo getRequestMappingInfo(final ClosureRequestMapping requestMapping) {

    List<String> consumeConditions = new ArrayList<>();
    List<String> produceConditions = new ArrayList<>();

    List<String> nameValueHeaders = new ArrayList<>();

    for (String header : requestMapping.getHeaders()) {
        nameValueHeaders.add(header.replaceFirst(":", "="));
        if (header.contains(HttpHeaders.CONTENT_TYPE)) {
            //            consumeConditions.add(HttpHeaders.CONTENT_TYPE+":"+ header.split(":")[1]);
            consumeConditions.add(header.split(":")[1].trim());
        }/* w  w w. j av a2 s.  c o  m*/
        if (header.contains(HttpHeaders.ACCEPT)) {
            produceConditions.add(header.split(":")[1].trim());
            //            produceConditions.add(HttpHeaders.ACCEPT+":"+ header.split(":")[1]);
        }
    }

    String[] headers = requestMapping.getHeaders().toArray(new String[] {});

    return new RequestMappingInfo(
            new PatternsRequestCondition(requestMapping.getPaths().toArray(new String[] {})),
            new RequestMethodsRequestCondition(requestMapping.getRequestMethod()),
            new ParamsRequestCondition(requestMapping.getParams().toArray(new String[] {})),
            new HeadersRequestCondition(nameValueHeaders.toArray(new String[] {})),
            new ConsumesRequestCondition(consumeConditions.toArray(new String[] {}), headers),
            new ProducesRequestCondition(produceConditions.toArray(new String[] {}), headers), null);
}

From source file:com.palantir.atlasdb.http.TextDelegateDecoder.java

@Override
public Object decode(Response response, Type type) throws IOException, DecodeException, FeignException {
    Collection<String> contentTypes = response.headers().get(HttpHeaders.CONTENT_TYPE);
    // In the case of multiple content types, or an unknown content type, we'll use the delegate instead.
    if (contentTypes != null && contentTypes.size() == 1
            && Iterables.getOnlyElement(contentTypes, "").equals(MediaType.TEXT_PLAIN)) {
        return stringDecoder.decode(response, type);
    }/*from   w  w  w.j ava  2 s  .  com*/

    return delegate.decode(response, type);
}

From source file:com.calclab.emite.base.util.Platform.java

/**
 * Send a BOSH HTTP request to a server.
 * //from w  w w  . j  a  va 2s  .  c om
 * @param httpBase the base URL to send the request
 * @param request the request contents
 * @param callback a callback to process the response
 */
public static final void sendXML(final String httpBase, final XMLPacket request,
        final AsyncResult<XMLPacket> callback) {
    final RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, httpBase);
    builder.setHeader(HttpHeaders.CONTENT_TYPE, "text/xml; charset=utf-8");
    //builder.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache");
    //builder.setHeader(HttpHeaders.PRAGMA, "no-cache");
    // TODO : Hard coded timeout to 6s, but we should set it to the wait + a delta
    // builder.setTimeoutMillis(6000);
    try {
        final Request req = builder.sendRequest(request.toString(), new RequestCallback() {
            @Override
            public void onResponseReceived(@Nullable final Request req, @Nullable final Response res) {
                requests.remove(req);
                if (res.getStatusCode() != Response.SC_OK) {
                    callback.onError(new RequestException(
                            "Invalid status " + res.getStatusCode() + ": " + res.getStatusText()));
                    return;
                }

                final XMLPacket response = XMLBuilder.fromXML(res.getText());
                if (response == null || !"body".equals(response.getTagName())) {
                    callback.onError(new RequestException("Bad response: " + res.getText()));
                    return;
                }

                callback.onSuccess(response);
            }

            @Override
            public void onError(@Nullable final Request req, @Nullable final Throwable throwable) {
                logger.severe("GWT CONNECTOR ERROR: " + throwable.getMessage());
                requests.remove(req);
                callback.onError(throwable);
            }
        });
        requests.add(req);
    } catch (final RequestException e) {
        callback.onError(e);
    } catch (final Exception e) {
        logger.severe("Some GWT connector exception: " + e.getMessage());
        callback.onError(e);
    }
}

From source file:com.linkedin.flashback.serializable.RecordedHttpMessage.java

public String getContentType() {
    String header = _headers.get(HttpHeaders.CONTENT_TYPE);
    if (Strings.isNullOrEmpty(header)) {
        return DEFAULT_CONTENT_TYPE;
    } else {/*from   w ww  . j  a  va2  s .  co  m*/
        return MediaType.parse(header).withoutParameters().toString();
    }
}

From source file:gmusic.api.api.comm.FormBuilder.java

public final void addFile(final String name, final String fileName, final byte[] file) throws IOException {
    final StringBuilder sb = new StringBuilder();

    sb.append(String.format("\r\n--%1$s\r\n", boundary));
    sb.append(/*from   w w  w.ja  v a 2  s  . c om*/
            String.format(HttpHeaders.CONTENT_DISPOSITION + ": form-data; name=\"%1$s\"; filename=\"%2$s\"\r\n",
                    name, fileName));

    sb.append(String.format(HttpHeaders.CONTENT_TYPE + ": %1$s\r\n\r\n", ContentType.APPLICATION_OCTET_STREAM));

    outputStream.write(sb.toString().getBytes());
    outputStream.write(file, 0, file.length);
}

From source file:org.graylog2.radio.cluster.InputService.java

public List<PersistedInputsResponse> getPersistedInputs() throws IOException {
    final URI uri = UriBuilder.fromUri(serverUrl).path("/system/radios/{radioId}/inputs")
            .build(nodeId.toString());/*www  .j a va2  s  .c  om*/

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

    final Response r = httpclient.newCall(request).execute();
    if (!r.isSuccessful()) {
        throw new RuntimeException(
                "Expected successful HTTP response [2xx] for list of persisted input but got [" + r.code()
                        + "].");
    }

    final PersistedInputsSummaryResponse persistedInputsResponse = mapper.readValue(r.body().byteStream(),
            PersistedInputsSummaryResponse.class);

    return persistedInputsResponse.inputs();
}

From source file:org.haiku.haikudepotserver.operations.controller.MaintenanceController.java

/**
 * <p>This triggers daily tasks.</p>
 *///from  w ww.j  av  a2  s  .co  m

@RequestMapping(value = "/daily", method = RequestMethod.GET)
public void daily(HttpServletResponse response) throws IOException {

    // go through all of the repositories and fetch them.  This is essentially a mop-up
    // task for those repositories that are unable to trigger a refresh.

    {
        ObjectContext context = serverRuntime.newContext();

        for (Repository repository : Repository.getAllActive(context)) {
            jobService.submit(new RepositoryHpkrIngressJobSpecification(repository.getCode()),
                    JobSnapshot.COALESCE_STATUSES_QUEUED);
        }
    }

    LOGGER.info("did trigger daily maintenance");

    response.setStatus(HttpServletResponse.SC_OK);
    response.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.PLAIN_TEXT_UTF_8.toString());
    response.getWriter().print("accepted request for daily maintenance");

}

From source file:org.gaul.s3proxy.AwsSignature.java

/**
 * Create Amazon V2 signature.  Reference:
 * http://docs.aws.amazon.com/general/latest/gr/signature-version-2.html
 */// w w  w .  j  ava  2s. co m
static String createAuthorizationSignature(HttpServletRequest request, String uri, String credential) {
    // sort Amazon headers
    SortedSetMultimap<String, String> canonicalizedHeaders = TreeMultimap.create();
    for (String headerName : Collections.list(request.getHeaderNames())) {
        Collection<String> headerValues = Collections.list(request.getHeaders(headerName));
        headerName = headerName.toLowerCase();
        if (!headerName.startsWith("x-amz-")) {
            continue;
        }
        if (headerValues.isEmpty()) {
            canonicalizedHeaders.put(headerName, "");
        }
        for (String headerValue : headerValues) {
            canonicalizedHeaders.put(headerName, Strings.nullToEmpty(headerValue));
        }
    }

    // build string to sign
    StringBuilder builder = new StringBuilder().append(request.getMethod()).append('\n')
            .append(Strings.nullToEmpty(request.getHeader(HttpHeaders.CONTENT_MD5))).append('\n')
            .append(Strings.nullToEmpty(request.getHeader(HttpHeaders.CONTENT_TYPE))).append('\n');
    String expires = request.getParameter("Expires");
    if (expires != null) {
        builder.append(expires);
    } else if (!canonicalizedHeaders.containsKey("x-amz-date")) {
        builder.append(request.getHeader(HttpHeaders.DATE));
    }
    builder.append('\n');
    for (Map.Entry<String, String> entry : canonicalizedHeaders.entries()) {
        builder.append(entry.getKey()).append(':').append(entry.getValue()).append('\n');
    }
    builder.append(uri);

    char separator = '?';
    List<String> subresources = Collections.list(request.getParameterNames());
    Collections.sort(subresources);
    for (String subresource : subresources) {
        if (SIGNED_SUBRESOURCES.contains(subresource)) {
            builder.append(separator).append(subresource);

            String value = request.getParameter(subresource);
            if (!"".equals(value)) {
                builder.append('=').append(value);
            }
            separator = '&';
        }
    }

    String stringToSign = builder.toString();
    logger.trace("stringToSign: {}", stringToSign);

    // sign string
    Mac mac;
    try {
        mac = Mac.getInstance("HmacSHA1");
        mac.init(new SecretKeySpec(credential.getBytes(StandardCharsets.UTF_8), "HmacSHA1"));
    } catch (InvalidKeyException | NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
    return BaseEncoding.base64().encode(mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8)));
}

From source file:clocker.mesos.entity.MesosUtils.java

public static final Optional<String> httpPost(Entity framework, String subUrl, String dataUrl,
        Map<String, Object> substitutions) {
    String targetUrl = Urls.mergePaths(framework.sensors().get(MesosFramework.FRAMEWORK_URL), subUrl);
    String templateContents = ResourceUtils.create().getResourceAsString(dataUrl);
    String processedJson = TemplateProcessor.processTemplateContents(templateContents, substitutions);
    LOG.debug("Posting JSON to {}: {}", targetUrl, processedJson);
    URI postUri = URI.create(targetUrl);
    HttpToolResponse response = HttpTool
            .httpPost(MesosUtils.buildClient(framework), postUri,
                    MutableMap.of(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType(),
                            HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.getMimeType()),
                    processedJson.getBytes());
    LOG.debug("Response: " + response.getContentAsString());
    if (!HttpTool.isStatusCodeHealthy(response.getResponseCode())) {
        LOG.warn("Invalid response code {}: {}", response.getResponseCode(), response.getReasonPhrase());
        return Optional.absent();
    } else {/*from   w  w  w . ja va2  s. c  om*/
        LOG.debug("Successfull call to {}: {}", targetUrl);
        return Optional.of(response.getContentAsString());
    }
}