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

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

Introduction

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

Prototype

public void setContentEncoding(Header header) 

Source Link

Usage

From source file:org.eclipse.koneki.protocols.omadm.client.http.internal.DMHttpClient.java

@Override
protected void sendAndReceiveMessage(final URI server, final String encoding, final DMMessenger messenger)
        throws IOException, DMClientException {
    try {/*  ww w. j  a va  2s .c  om*/
        final HttpPost post = new HttpPost(server);

        final EntityTemplate entity = new EntityTemplate(new ContentProducer() {

            @Override
            public void writeTo(final OutputStream out) throws IOException {
                try {
                    messenger.writeMessage(out);
                } catch (final DMClientException e) {
                    throw new IOException(e);
                }
            }

        });
        entity.setChunked(false);
        entity.setContentEncoding(encoding);
        entity.setContentType("application/vnd.syncml.dm+xml"); //$NON-NLS-1$
        post.setEntity(entity);

        final HttpResponse response = this.httpClient.execute(post);

        if (response.getStatusLine().getStatusCode() < 200 || response.getStatusLine().getStatusCode() > 299) {
            throw new DMClientException(response.getStatusLine().toString());
        }

        messenger.readMessage(response.getEntity().getContent());

        EntityUtils.consume(response.getEntity());
    } catch (final IOException e) {
        if (e.getCause() != null && e.getCause() instanceof DMClientException) {
            throw (DMClientException) e.getCause();
        } else {
            throw e;
        }
    }
}

From source file:org.wso2.esb.integration.common.utils.clients.SimpleHttpClient.java

/**
 * Send a HTTP POST request to the specified URL
 *
 * @param url         Target endpoint URL
 * @param headers     Any HTTP headers that should be added to the request
 * @param payload     Content payload that should be sent
 * @param contentType Content-type of the request
 * @return Returned HTTP response// www.  ja  v  a2 s . co  m
 * @throws IOException If an error occurs while making the invocation
 */
public HttpResponse doPost(String url, final Map<String, String> headers, final String payload,
        String contentType) throws IOException {
    HttpUriRequest request = new HttpPost(url);
    setHeaders(headers, request);
    HttpEntityEnclosingRequest entityEncReq = (HttpEntityEnclosingRequest) request;
    final boolean zip = headers != null && "gzip".equals(headers.get(HttpHeaders.CONTENT_ENCODING));

    EntityTemplate ent = new EntityTemplate(new ContentProducer() {
        public void writeTo(OutputStream outputStream) throws IOException {
            OutputStream out = outputStream;
            if (zip) {
                out = new GZIPOutputStream(outputStream);
            }
            out.write(payload.getBytes());
            out.flush();
            out.close();
        }
    });
    ent.setContentType(contentType);
    if (zip) {
        ent.setContentEncoding("gzip");
    }
    entityEncReq.setEntity(ent);
    return client.execute(request);
}

From source file:org.wso2.esb.integration.common.utils.clients.SimpleHttpClient.java

/**
 * Send a HTTP PATCH request to the specified URL
 *
 * @param url         Target endpoint URL
 * @param headers     Any HTTP headers that should be added to the request
 * @param payload     Content payload that should be sent
 * @param contentType Content-type of the request
 * @return Returned HTTP response//from   w  w w .  j a  va  2s.co m
 * @throws IOException If an error occurs while making the invocation
 */
public HttpResponse doPatch(String url, final Map<String, String> headers, final String payload,
        String contentType) throws IOException {
    HttpUriRequest request = new HttpPatch(url);
    setHeaders(headers, request);
    HttpEntityEnclosingRequest entityEncReq = (HttpEntityEnclosingRequest) request;
    final boolean zip = headers != null && "gzip".equals(headers.get(HttpHeaders.CONTENT_ENCODING));

    EntityTemplate ent = new EntityTemplate(new ContentProducer() {
        public void writeTo(OutputStream outputStream) throws IOException {
            OutputStream out = outputStream;
            if (zip) {
                out = new GZIPOutputStream(outputStream);
            }
            out.write(payload.getBytes());
            out.flush();
            out.close();
        }
    });
    ent.setContentType(contentType);
    if (zip) {
        ent.setContentEncoding("gzip");
    }
    entityEncReq.setEntity(ent);
    return client.execute(request);
}

From source file:org.wso2.esb.integration.common.utils.clients.SimpleHttpClient.java

/**
 * Send a HTTP PUT request to the specified URL
 *
 * @param url         Target endpoint URL
 * @param headers     Any HTTP headers that should be added to the request
 * @param payload     Content payload that should be sent
 * @param contentType Content-type of the request
 * @return Returned HTTP response/* ww  w .  ja  va  2s .c  o  m*/
 * @throws IOException If an error occurs while making the invocation
 */
public HttpResponse doPut(String url, final Map<String, String> headers, final String payload,
        String contentType) throws IOException {
    HttpUriRequest request = new HttpPut(url);
    setHeaders(headers, request);
    HttpEntityEnclosingRequest entityEncReq = (HttpEntityEnclosingRequest) request;
    final boolean zip = headers != null && "gzip".equals(headers.get(HttpHeaders.CONTENT_ENCODING));

    EntityTemplate ent = new EntityTemplate(new ContentProducer() {
        public void writeTo(OutputStream outputStream) throws IOException {
            OutputStream out = outputStream;
            if (zip) {
                out = new GZIPOutputStream(outputStream);
            }
            out.write(payload.getBytes());
            out.flush();
            out.close();
        }
    });
    ent.setContentType(contentType);
    if (zip) {
        ent.setContentEncoding("gzip");
    }
    entityEncReq.setEntity(ent);
    return client.execute(request);
}

From source file:org.wso2.carbon.automation.extensions.servers.httpserver.SimpleHttpClient.java

/**
 * Send a HTTP POST request to the specified URL
 *
 * @param url         Target endpoint URL
 * @param headers     Any HTTP headers that should be added to the request
 * @param payload     Content payload that should be sent
 * @param contentType Content-type of the request
 * @return Returned HTTP response/*from   w ww .  j  a va2  s  . c  om*/
 * @throws IOException If an error occurs while making the invocation
 */
public HttpResponse doPost(String url, final Map<String, String> headers, final String payload,
        String contentType) throws IOException {
    HttpUriRequest request = new HttpPost(url);
    setHeaders(headers, request);
    HttpEntityEnclosingRequest entityEncReq = (HttpEntityEnclosingRequest) request;
    final boolean zip = headers != null && "gzip".equals(headers.get(HttpHeaders.CONTENT_ENCODING));

    EntityTemplate ent = new EntityTemplate(new ContentProducer() {
        public void writeTo(OutputStream outputStream) throws IOException {
            OutputStream out = outputStream;
            if (zip) {
                out = new GZIPOutputStream(outputStream);
            }
            out.write(payload.getBytes(Charset.defaultCharset()));
            out.flush();
            out.close();
        }
    });
    ent.setContentType(contentType);
    if (zip) {
        ent.setContentEncoding("gzip");
    }
    entityEncReq.setEntity(ent);
    return client.execute(request);
}

From source file:org.wso2.carbon.automation.extensions.servers.httpserver.SimpleHttpClient.java

/**
 * Send a HTTP PUT request to the specified URL
 *
 * @param url         Target endpoint URL
 * @param headers     Any HTTP headers that should be added to the request
 * @param payload     Content payload that should be sent
 * @param contentType Content-type of the request
 * @return Returned HTTP response//from  w w w . j a va 2 s .  com
 * @throws IOException If an error occurs while making the invocation
 */
public HttpResponse doPut(String url, final Map<String, String> headers, final String payload,
        String contentType) throws IOException {
    HttpUriRequest request = new HttpPut(url);
    setHeaders(headers, request);
    HttpEntityEnclosingRequest entityEncReq = (HttpEntityEnclosingRequest) request;
    final boolean zip = headers != null && "gzip".equals(headers.get(HttpHeaders.CONTENT_ENCODING));

    EntityTemplate ent = new EntityTemplate(new ContentProducer() {
        public void writeTo(OutputStream outputStream) throws IOException {
            OutputStream out = outputStream;
            if (zip) {
                out = new GZIPOutputStream(outputStream);
            }
            out.write(payload.getBytes(Charset.defaultCharset()));
            out.flush();
            out.close();
        }
    });
    ent.setContentType(contentType);
    if (zip) {
        ent.setContentEncoding("gzip");
    }
    entityEncReq.setEntity(ent);
    return client.execute(request);
}

From source file:org.wso2.esb.integration.common.utils.clients.SimpleHttpClient.java

/**
 * Send a HTTP OPTIONS request to the specified URL
 *
 * @param url         Target endpoint URL
 * @param headers     Any HTTP headers that should be added to the request
 * @param payload     Content payload that should be sent
 * @param contentType Content-type of the request
 * @return Returned HTTP response/*from w w w  .ja v  a 2  s . c o  m*/
 * @throws IOException If an error occurs while making the invocation
 */
public HttpResponse doOptions(String url, final Map<String, String> headers, final String payload,
        String contentType) throws IOException {
    HttpUriRequest request = new HttpOptions(url);
    setHeaders(headers, request);
    if (payload != null) {
        HttpEntityEnclosingRequest entityEncReq = (HttpEntityEnclosingRequest) request;
        final boolean zip = headers != null && "gzip".equals(headers.get(HttpHeaders.CONTENT_ENCODING));

        EntityTemplate ent = new EntityTemplate(new ContentProducer() {
            public void writeTo(OutputStream outputStream) throws IOException {
                OutputStream out = outputStream;
                if (zip) {
                    out = new GZIPOutputStream(outputStream);
                }
                out.write(payload.getBytes());
                out.flush();
                out.close();
            }
        });
        ent.setContentType(contentType);
        if (zip) {
            ent.setContentEncoding("gzip");
        }
        entityEncReq.setEntity(ent);
    }
    return client.execute(request);
}

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 . j  av a  2 s  . c om*/

    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;
            }
        }
    }
}