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.apache.marmotta.platform.core.webservices.resource.InspectionWebService.java

private Response inspectResource(RepositoryConnection conn, Resource rsc, long subjOffset, long propOffset,
        long objOffset, long ctxOffset, int limit) throws UnsupportedEncodingException, RepositoryException {
    if (rsc == null)
        return Response.status(Status.NOT_FOUND).entity("Not found").build();
    URI uri = null;/*  w w w.  ja  v a  2  s  .  c om*/
    if (rsc instanceof URI) {
        uri = (URI) rsc;
    }
    // Well, this is rather hacky...
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    PrintStream ps = new PrintStream(os);

    ps.println("<!DOCTYPE HTML><html><head>");

    ps.printf("<title>Inspect %s</title>%n", rsc.stringValue());
    ps.println("<style type='text/css'>");
    ps.println("table {border: 2px solid #006d8f;width: 100%;border-collapse: collapse;}"
            + "html, body{font-family: sans-serif;}" + "table th {background-color: #006d8f;color: white;}"
            + "table tr {}" + "table tr.even {background-color: #dff7ff;}"
            + "table tr.odd {background-color: lightBlue;}" + "table th, table td {padding: 2px;}"
            + "table tr:hover {background-color: white;}" + ".isDeleted { color: red; font-style: italic; }"
            + ".deleted {width: 20px; height: 20px; display: inline-block; border-radius: 10px; float: right}"
            + ".deleted.true {background-color: red;}" + ".deleted.false {background-color: darkGreen;}"
            + ".reasoned a { border-radius: 10px; display: inline-block; float: right; background-color: orange; width: 20px; height: 20px; color: white; text-decoration: none; margin-right: 5px; text-align: center; font-family: serif; font-weight: bolder;}"
            + ".info-dialog { border:1px solid black; width:50%; position:absolute; top:100px; left:25%; background-color:white; z-index:2; padding-top:10px; min-height:100px; overflow:auto; display:none;}"
            + ".info-dialog button.close-button { position:absolute; top:5px; right:5px; } "
            + ".info-dialog iframe { border:none; width:100%; }");

    ps.println("</style>");

    ps.println();
    ps.println("</head><body>");

    ps.printf("<h1>Inspect %s</h1>%n<div>ShortName: %s<span class='%s'>%<s</span></div>%n", rsc.stringValue(),
            getLabel(conn, rsc), "");
    Date created = ResourceUtils.getCreated(conn, rsc);
    if (created != null) {
        ps.printf("<div>Created: <span>%tF %<tT</span> by <span>%s</span></div>%n", created,
                createInspectLink(conn, null, null, ""));
    }
    ps.printf("<div>Last Modified: <span>%tF %<tT</span></div>%n", ResourceUtils.getLastModified(conn, rsc));

    // Outgoing
    printOutgoing(conn, rsc, ps, subjOffset, limit);

    // Incoming
    printIncoming(conn, rsc, ps, objOffset, limit);

    // Links
    printLinks(conn, uri, ps, propOffset, limit);

    // Context
    printContext(conn, uri, ps, ctxOffset, limit);

    ps.println();
    ps.println("</body></html>");
    return Response.ok().header(HttpHeaders.CONTENT_TYPE, "text/html;charset=" + CHARSET)
            .header(HttpHeaders.LAST_MODIFIED, ResourceUtils.getLastModified(conn, rsc))
            .entity(os.toString(CHARSET)).build();
}

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  ww.  j a  v  a  2 s.co 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:org.jclouds.openstack.swift.v1.blobstore.RegionScopedSwiftBlobStore.java

@Override
public String copyBlob(String fromContainer, String fromName, String toContainer, String toName,
        CopyOptions options) {/*from  w w  w. j  ava2 s .c om*/
    ObjectApi objectApi = api.getObjectApi(regionId, toContainer);

    org.jclouds.openstack.swift.v1.options.CopyOptions swiftOptions = new org.jclouds.openstack.swift.v1.options.CopyOptions();

    if (options.ifMatch() != null) {
        swiftOptions.ifMatch(options.ifMatch());
    }
    if (options.ifNoneMatch() != null) {
        throw new UnsupportedOperationException("Swift does not support ifNoneMatch");
    }
    if (options.ifModifiedSince() != null) {
        swiftOptions.ifModifiedSince(options.ifModifiedSince());
    }
    if (options.ifUnmodifiedSince() != null) {
        swiftOptions.ifUnmodifiedSince(options.ifUnmodifiedSince());
    }

    Map<String, String> systemMetadata = Maps.newHashMap();
    ContentMetadata contentMetadata = options.contentMetadata();
    Map<String, String> userMetadata = options.userMetadata();

    if (contentMetadata != null || userMetadata != null) {
        if (contentMetadata != null) {
            String contentDisposition = contentMetadata.getContentDisposition();
            if (contentDisposition != null) {
                systemMetadata.put(HttpHeaders.CONTENT_DISPOSITION, contentDisposition);
            }

            String contentEncoding = contentMetadata.getContentEncoding();
            if (contentEncoding != null) {
                systemMetadata.put(HttpHeaders.CONTENT_ENCODING, contentEncoding);
            }

            String contentLanguage = contentMetadata.getContentLanguage();
            if (contentLanguage != null) {
                systemMetadata.put(HttpHeaders.CONTENT_LANGUAGE, contentLanguage);
            }

            String contentType = contentMetadata.getContentType();
            if (contentType != null) {
                systemMetadata.put(HttpHeaders.CONTENT_TYPE, contentType);
            }
        }
        if (userMetadata == null) {
            userMetadata = Maps.newHashMap();
        }
    } else {
        SwiftObject metadata = api.getObjectApi(regionId, fromContainer).getWithoutBody(fromName);
        if (metadata == null) {
            throw new KeyNotFoundException(fromContainer, fromName,
                    "Swift could not find the specified source key");
        }
        contentMetadata = metadata.getPayload().getContentMetadata();
        String contentDisposition = contentMetadata.getContentDisposition();
        if (contentDisposition != null) {
            systemMetadata.put(HttpHeaders.CONTENT_DISPOSITION, contentDisposition);
        }
        String contentEncoding = contentMetadata.getContentEncoding();
        if (contentEncoding != null) {
            systemMetadata.put(HttpHeaders.CONTENT_ENCODING, contentEncoding);
        }
        String contentLanguage = contentMetadata.getContentLanguage();
        if (contentLanguage != null) {
            systemMetadata.put(HttpHeaders.CONTENT_LANGUAGE, contentLanguage);
        }
        String contentType = contentMetadata.getContentType();
        if (contentType != null) {
            systemMetadata.put(HttpHeaders.CONTENT_TYPE, contentType);
        }
        userMetadata = metadata.getMetadata();
    }

    objectApi.copy(toName, fromContainer, fromName, userMetadata, systemMetadata, swiftOptions);

    // TODO: Swift copy object *appends* user metadata, does not overwrite
    return objectApi.getWithoutBody(toName).getETag();
}

From source file:co.cask.cdap.messaging.client.ClientMessagingService.java

/**
 * Verifies the content-type in the header matches with the required type.
 *///www.  jav  a  2 s  . com
private void verifyContentType(Map<String, ? extends Collection<String>> headers, String requiredContentType) {
    Collection<String> values = headers.get(HttpHeaders.CONTENT_TYPE);
    if (values == null || !requiredContentType.equals(Iterables.getFirst(values, null))) {
        throw new IllegalArgumentException("Only " + requiredContentType + " content type is support.");
    }
}

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

protected MediaType requestContentType() {
    String contentType = DEFAULT_REQUEST_CONTENT_TYPE;
    if (options.get(HEADERS) != null) {
        Map headers = (Map) options.get(HEADERS);
        for (Object key : headers.keySet()) {
            if (key instanceof String
                    && ((String) key).toLowerCase().equals(HttpHeaders.CONTENT_TYPE.toLowerCase())) {
                contentType = (String) headers.get(key);
                break;
            }//ww w .  j a  v  a 2 s.c  om
        }
    }
    return MediaType.parseMediaType(contentType);
}

From source file:com.facebook.presto.server.HttpRemoteTask.java

private synchronized void scheduleUpdate() {
    // don't update if the task hasn't been started yet or if it is already finished
    if (!needsUpdate.get() || taskInfo.get().getState().isDone()) {
        return;/*from   w w  w. java 2  s .  c om*/
    }

    // if we have an old request outstanding, cancel it
    if (currentRequest != null
            && Duration.nanosSince(currentRequestStartNanos).compareTo(requestTimeout) >= 0) {
        needsUpdate.set(true);
        currentRequest.cancel(true);
        currentRequest = null;
        currentRequestStartNanos = 0;
    }

    // if there is a request already running, wait for it to complete
    if (this.currentRequest != null && !this.currentRequest.isDone()) {
        return;
    }

    // if throttled due to error, asynchronously wait for timeout and try again
    ListenableFuture<?> errorRateLimit = updateErrorTracker.acquireRequestPermit();
    if (!errorRateLimit.isDone()) {
        errorRateLimit.addListener(this::scheduleUpdate, executor);
        return;
    }

    List<TaskSource> sources = getSources();
    TaskUpdateRequest updateRequest = new TaskUpdateRequest(session.toSessionRepresentation(), planFragment,
            sources, outputBuffers.get());

    Request request = preparePost()
            .setUri(uriBuilderFrom(taskInfo.get().getSelf()).addParameter("summarize").build())
            .setHeader(HttpHeaders.CONTENT_TYPE, MediaType.JSON_UTF_8.toString())
            .setBodyGenerator(jsonBodyGenerator(taskUpdateRequestCodec, updateRequest)).build();

    updateErrorTracker.startRequest();

    ListenableFuture<JsonResponse<TaskInfo>> future = httpClient.executeAsync(request,
            createFullJsonResponseHandler(taskInfoCodec));
    currentRequest = future;
    currentRequestStartNanos = System.nanoTime();

    // The needsUpdate flag needs to be set to false BEFORE adding the Future callback since callback might change the flag value
    // and does so without grabbing the instance lock.
    needsUpdate.set(false);

    Futures.addCallback(future,
            new SimpleHttpResponseHandler<>(new UpdateResponseHandler(sources), request.getUri()), executor);
}

From source file:com.facebook.presto.server.remotetask.HttpRemoteTask.java

private synchronized void sendUpdate() {
    TaskStatus taskStatus = getTaskStatus();
    // don't update if the task hasn't been started yet or if it is already finished
    if (!needsUpdate.get() || taskStatus.getState().isDone()) {
        return;//from  w ww.  ja  v  a  2s  . c  o  m
    }

    // if we have an old request outstanding, cancel it
    if (currentRequest != null
            && Duration.nanosSince(currentRequestStartNanos).compareTo(requestTimeout) >= 0) {
        needsUpdate.set(true);
        currentRequest.cancel(true);
        currentRequest = null;
        currentRequestStartNanos = 0;
    }

    // if there is a request already running, wait for it to complete
    if (this.currentRequest != null && !this.currentRequest.isDone()) {
        return;
    }

    // if throttled due to error, asynchronously wait for timeout and try again
    ListenableFuture<?> errorRateLimit = updateErrorTracker.acquireRequestPermit();
    if (!errorRateLimit.isDone()) {
        errorRateLimit.addListener(this::sendUpdate, executor);
        return;
    }

    List<TaskSource> sources = getSources();

    Optional<PlanFragment> fragment = Optional.empty();
    if (sendPlan.get()) {
        fragment = Optional.of(planFragment);
    }
    TaskUpdateRequest updateRequest = new TaskUpdateRequest(session.toSessionRepresentation(), fragment,
            sources, outputBuffers.get());

    HttpUriBuilder uriBuilder = getHttpUriBuilder(taskStatus);
    Request request = preparePost().setUri(uriBuilder.build())
            .setHeader(HttpHeaders.CONTENT_TYPE, MediaType.JSON_UTF_8.toString())
            .setBodyGenerator(jsonBodyGenerator(taskUpdateRequestCodec, updateRequest)).build();

    updateErrorTracker.startRequest();

    ListenableFuture<JsonResponse<TaskInfo>> future = httpClient.executeAsync(request,
            createFullJsonResponseHandler(taskInfoCodec));
    currentRequest = future;
    currentRequestStartNanos = System.nanoTime();

    // The needsUpdate flag needs to be set to false BEFORE adding the Future callback since callback might change the flag value
    // and does so without grabbing the instance lock.
    needsUpdate.set(false);

    Futures.addCallback(future,
            new SimpleHttpResponseHandler<>(new UpdateResponseHandler(sources), request.getUri(), stats),
            executor);
}

From source file:eu.seaclouds.policy.SeaCloudsManagementPolicy.java

private HttpToolResponse delete(String url, String mediaType, String username, String password) {
    URI apiEndpoint = URI.create(url);
    // the uri is required by the HttpClientBuilder in order to set the AuthScope of the credentials

    if (username == null || password == null) {
        return HttpTool.httpDelete(HttpTool.httpClientBuilder().build(), apiEndpoint,
                MutableMap.of(HttpHeaders.CONTENT_TYPE, mediaType, HttpHeaders.ACCEPT, mediaType));
    } else {//ww w  .jav a2 s .co m
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);

        // the uri is required by the HttpClientBuilder in order to set the AuthScope of the credentials
        return HttpTool.httpDelete(
                HttpTool.httpClientBuilder().uri(apiEndpoint).credentials(credentials).build(), apiEndpoint,
                MutableMap.of(HttpHeaders.CONTENT_TYPE, mediaType, HttpHeaders.ACCEPT, mediaType,
                        HttpHeaders.AUTHORIZATION, HttpTool.toBasicAuthorizationValue(credentials)));
    }
}

From source file:io.prestosql.server.remotetask.HttpRemoteTask.java

private synchronized void sendUpdate() {
    TaskStatus taskStatus = getTaskStatus();
    // don't update if the task hasn't been started yet or if it is already finished
    if (!needsUpdate.get() || taskStatus.getState().isDone()) {
        return;//from  ww w .ja v a 2  s. c  o  m
    }

    // if there is a request already running, wait for it to complete
    if (this.currentRequest != null && !this.currentRequest.isDone()) {
        return;
    }

    // if throttled due to error, asynchronously wait for timeout and try again
    ListenableFuture<?> errorRateLimit = updateErrorTracker.acquireRequestPermit();
    if (!errorRateLimit.isDone()) {
        errorRateLimit.addListener(this::sendUpdate, executor);
        return;
    }

    List<TaskSource> sources = getSources();

    Optional<PlanFragment> fragment = sendPlan.get() ? Optional.of(planFragment) : Optional.empty();
    TaskUpdateRequest updateRequest = new TaskUpdateRequest(session.toSessionRepresentation(),
            session.getIdentity().getExtraCredentials(), fragment, sources, outputBuffers.get(),
            totalPartitions);
    byte[] taskUpdateRequestJson = taskUpdateRequestCodec.toJsonBytes(updateRequest);
    if (fragment.isPresent()) {
        stats.updateWithPlanBytes(taskUpdateRequestJson.length);
    }

    HttpUriBuilder uriBuilder = getHttpUriBuilder(taskStatus);
    Request request = preparePost().setUri(uriBuilder.build())
            .setHeader(HttpHeaders.CONTENT_TYPE, MediaType.JSON_UTF_8.toString())
            .setBodyGenerator(createStaticBodyGenerator(taskUpdateRequestJson)).build();

    updateErrorTracker.startRequest();

    ListenableFuture<JsonResponse<TaskInfo>> future = httpClient.executeAsync(request,
            createFullJsonResponseHandler(taskInfoCodec));
    currentRequest = future;
    currentRequestStartNanos = System.nanoTime();

    // The needsUpdate flag needs to be set to false BEFORE adding the Future callback since callback might change the flag value
    // and does so without grabbing the instance lock.
    needsUpdate.set(false);

    Futures.addCallback(future,
            new SimpleHttpResponseHandler<>(new UpdateResponseHandler(sources), request.getUri(), stats),
            executor);
}

From source file:com.rapid7.conqueso.client.ConquesoClient.java

private void post(String message) throws IOException {
    HttpURLConnection connection = (HttpURLConnection) conquesoUrl.openConnection();
    connection.setDoOutput(true);//from   ww w .  ja  va  2 s .  c o  m
    connection.setRequestProperty(HttpHeaders.CONTENT_TYPE, "application/json");
    connection.setRequestMethod("POST");

    Writer writer = null;
    try {
        writer = new OutputStreamWriter(connection.getOutputStream(), Charsets.UTF_8);
        writer.write(message);
    } finally {
        if (writer != null) {
            writer.close();
        }
        // Need to call this to send data
        connection.getInputStream().close();
    }
}