Example usage for org.apache.http.entity EntityTemplate setContentType

List of usage examples for org.apache.http.entity EntityTemplate setContentType

Introduction

In this page you can find the example usage for org.apache.http.entity EntityTemplate setContentType.

Prototype

public void setContentType(Header header) 

Source Link

Usage

From source file:org.apache.jena.rdfconnection.RDFConnectionRemote.java

/** Create an HttpEntity for the dataset */
protected HttpEntity datasetToHttpEntity(DatasetGraph dataset, RDFFormat syntax) {
    EntityTemplate entity = new EntityTemplate((out) -> RDFDataMgr.write(out, dataset, syntax));
    String ct = syntax.getLang().getContentType().getContentType();
    entity.setContentType(ct);
    return entity;
}

From source file:com.ngdata.hbaseindexer.indexer.FusionPipelineClient.java

public void postJsonToPipeline(String endpoint, List docs, int requestId) throws Exception {

    FusionSession fusionSession = null;//from w  w  w  . ja v a  2s.co m

    long currTime = System.nanoTime();
    synchronized (this) {
        fusionSession = sessions.get(endpoint);

        // ensure last request within the session timeout period, else reset the session
        if (fusionSession == null || (currTime - fusionSession.sessionEstablishedAt) > maxNanosOfInactivity) {
            log.info("Fusion session is likely expired (or soon will be) for endpoint " + endpoint + ", "
                    + "pre-emptively re-setting this session before processing request " + requestId);
            fusionSession = resetSession(endpoint);
            if (fusionSession == null)
                throw new IllegalStateException("Failed to re-connect to " + endpoint
                        + " after session loss when processing request " + requestId);
        }
    }

    HttpEntity entity = null;
    try {
        HttpPost postRequest = new HttpPost(endpoint);

        // stream the json directly to the HTTP output
        EntityTemplate et = new EntityTemplate(new JacksonContentProducer(jsonObjectMapper, docs));
        et.setContentType("application/json");
        et.setContentEncoding(StandardCharsets.UTF_8.name());
        postRequest.setEntity(et); // new BufferedHttpEntity(et));

        HttpResponse response = null;
        HttpClientContext context = null;
        if (isKerberos) {
            httpClient = FusionKrb5HttpClientConfigurer.createClient(fusionUser);
            response = httpClient.execute(postRequest);
        } else {
            context = HttpClientContext.create();
            if (cookieStore != null) {
                context.setCookieStore(cookieStore);
            }
            response = httpClient.execute(postRequest, context);
        }

        entity = response.getEntity();
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == 401) {
            // unauth'd - session probably expired? retry to establish
            log.warn("Unauthorized error (401) when trying to send request " + requestId + " to Fusion at "
                    + endpoint + ", will re-try to establish session");

            // re-establish the session and re-try the request
            try {
                EntityUtils.consume(entity);
            } catch (Exception ignore) {
                log.warn("Failed to consume entity due to: " + ignore);
            } finally {
                entity = null;
            }

            synchronized (this) {
                fusionSession = resetSession(endpoint);
                if (fusionSession == null)
                    throw new IllegalStateException(
                            "After re-establishing session when processing request " + requestId + ", endpoint "
                                    + endpoint + " is no longer active! Try another endpoint.");
            }

            log.info("Going to re-try request " + requestId + " after session re-established with " + endpoint);
            if (isKerberos) {
                httpClient = FusionKrb5HttpClientConfigurer.createClient(fusionUser);
                response = httpClient.execute(postRequest);
            } else {
                response = httpClient.execute(postRequest, context);
            }

            entity = response.getEntity();
            statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200 || statusCode == 204) {
                log.info("Re-try request " + requestId + " after session timeout succeeded for: " + endpoint);
            } else {
                raiseFusionServerException(endpoint, entity, statusCode, response, requestId);
            }
        } else if (statusCode != 200 && statusCode != 204) {
            raiseFusionServerException(endpoint, entity, statusCode, response, requestId);
        } else {
            // OK!
            if (fusionSession != null && fusionSession.docsSentMeter != null)
                fusionSession.docsSentMeter.mark(docs.size());
        }
    } finally {

        if (entity != null) {
            try {
                EntityUtils.consume(entity);
            } catch (Exception ignore) {
                log.warn("Failed to consume entity due to: " + ignore);
            } finally {
                entity = null;
            }
        }
    }
}

From source file:com.cellbots.logger.localServer.LocalHttpServer.java

public void handle(final HttpServerConnection conn, final HttpContext context)
        throws HttpException, IOException {
    HttpRequest request = conn.receiveRequestHeader();
    HttpResponse response = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), HttpStatus.SC_OK, "OK");

    String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
    if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST") && !method.equals("PUT")) {
        throw new MethodNotSupportedException(method + " method not supported");
    }/*from ww  w .jav a  2  s  .co m*/

    // Get the requested target. This is the string after the domain name in
    // the URL. If the full URL was http://mydomain.com/test.html, target
    // will be /test.html.
    String target = request.getRequestLine().getUri();
    // Log.w(TAG, "*** Request target: " + target);

    // Gets the requested resource name. For example, if the full URL was
    // http://mydomain.com/test.html?x=1&y=2, resource name will be
    // test.html
    final String resName = getResourceNameFromTarget(target);
    UrlParams params = new UrlParams(target);
    // Log.w(TAG, "*** Request LINE: " +
    // request.getRequestLine().toString());
    // Log.w(TAG, "*** Request resource: " + resName);
    if (method.equals("POST") || method.equals("PUT")) {
        byte[] entityContent = null;
        // Gets the content if the request has an entity.
        if (request instanceof HttpEntityEnclosingRequest) {
            conn.receiveRequestEntity((HttpEntityEnclosingRequest) request);
            HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
            if (entity != null) {
                entityContent = EntityUtils.toByteArray(entity);
            }
        }
        response.setStatusCode(HttpStatus.SC_OK);
        if (serverListener != null) {
            serverListener.onRequest(resName, params.keys, params.values, entityContent);
        }
    } else if (dataMap.containsKey(resName)) { // The requested resource is
                                               // a byte array
        response.setStatusCode(HttpStatus.SC_OK);
        response.setHeader("Content-Type", dataMap.get(resName).contentType);
        response.setEntity(new ByteArrayEntity(dataMap.get(resName).resource));
    } else { // Return sensor readings
        String contentType = resourceMap.containsKey(resName) ? resourceMap.get(resName).contentType
                : "text/html";
        response.setStatusCode(HttpStatus.SC_OK);
        EntityTemplate body = new EntityTemplate(new ContentProducer() {
            @Override
            public void writeTo(final OutputStream outstream) throws IOException {
                OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
                writer.write(serverListener.getLoggerStatus());
                writer.flush();
            }
        });
        body.setContentType(contentType);
        response.setEntity(body);
    }
    conn.sendResponseHeader(response);
    conn.sendResponseEntity(response);
    conn.flush();
    conn.shutdown();
}