Example usage for org.apache.http.entity ContentProducer ContentProducer

List of usage examples for org.apache.http.entity ContentProducer ContentProducer

Introduction

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

Prototype

ContentProducer

Source Link

Usage

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// www  . ja  v  a2  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:org.apache.jena.web.DatasetGraphAccessorHTTP.java

/** Create an HttpEntity for the graph */
protected HttpEntity graphToHttpEntity(final Graph graph) {

    final RDFFormat syntax = getOutboundSyntax();
    ContentProducer producer = new ContentProducer() {
        @Override//from  w w w  .  j a  v  a 2 s .c o m
        public void writeTo(OutputStream out) {
            RDFDataMgr.write(out, graph, syntax);
        }
    };

    EntityTemplate entity = new EntityTemplate(producer);
    String ct = syntax.getLang().getContentType().getContentType();
    entity.setContentType(ct);
    return entity;
}

From source file:com.caucho.hessian.client.HessianProxy.java

/**
 * Sends the HTTP request to the Hessian connection.
 *///www . j av a2 s  .  c o m
protected HessianConnection sendRequest(final String methodName, final Object[] args) throws IOException {
    HessianConnection conn = null;

    boolean isValid = false;
    try {
        conn = _factory.getConnectionFactory().open(_url);
        addRequestHeaders(conn);

        ContentProducer contentProducer = new ContentProducer() {
            public void writeTo(OutputStream outstream) throws IOException {
                try {
                    AbstractHessianOutput out = _factory.getHessianOutput(outstream);

                    out.call(methodName, args);
                    out.flush();
                } catch (Exception e) {
                    throw new HessianRuntimeException(e);
                }
            }
        };

        conn.setContentProducer(contentProducer);
        conn.sendRequest();

        isValid = true;

    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        if (!isValid && conn != null)
            conn.destroy();
    }
    return conn;
}

From source file:org.apache.marmotta.client.clients.ResourceClient.java

/**
 * Update (overwrite) the metadata of the resource identified by the given uri. The metadata will be serialised to
 * application/json and sent to the Apache Marmotta server. The given metadata will override any metadata
 * for the resource already existing on the server. The resource has to exist or be created before updating, otherwise
 * the method will throw a NotFoundException.
 *
 * @param uri        the URI of the resource to update
 * @param metadata   the metadata to upload to the resource
 * @throws IOException/*from ww  w.  j  ava  2s  .c om*/
 * @throws MarmottaClientException
 */
public void updateResourceMetadata(final String uri, final Metadata metadata)
        throws IOException, MarmottaClientException {
    HttpClient httpClient = HTTPUtil.createClient(config);

    HttpPut put = new HttpPut(getServiceUrl(uri));
    put.setHeader("Content-Type", "application/rdf+json; rel=meta");
    ContentProducer cp = new ContentProducer() {
        @Override
        public void writeTo(OutputStream outstream) throws IOException {
            RDFJSONParser.serializeRDFJSON(ImmutableMap.of(uri, metadata), outstream);
        }
    };
    put.setEntity(new EntityTemplate(cp));

    try {

        HttpResponse response = httpClient.execute(put);

        switch (response.getStatusLine().getStatusCode()) {
        case 200:
            log.debug("metadata for resource {} updated", uri);
            break;
        case 415:
            log.error("server does not support metadata type application/json for resource {}, cannot update",
                    uri);
            throw new ContentFormatException(
                    "server does not support metadata type application/json for resource " + uri);
        case 404:
            log.error("resource {} does not exist, cannot update", uri);
            throw new NotFoundException("resource " + uri + " does not exist, cannot update");
        default:
            log.error("error updating resource {}: {} {}", new Object[] { uri,
                    response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase() });
            throw new MarmottaClientException(
                    "error updating resource " + uri + ": " + response.getStatusLine().getStatusCode() + " "
                            + response.getStatusLine().getReasonPhrase());
        }

    } catch (UnsupportedEncodingException e) {
        log.error("could not encode URI parameter", e);
        throw new MarmottaClientException("could not encode URI parameter");
    } finally {
        put.releaseConnection();
    }
}

From source file:org.apache.marmotta.client.clients.ConfigurationClient.java

/**
 * Update the configuration "key" with the given value. Value can be either a list of values or one of the
 * primitive types String, Boolean, Integer, Double
 * @param key// www .ja  v  a2 s  .  c o m
 * @param value
 * @throws IOException
 * @throws MarmottaClientException
 */
public void setConfiguration(String key, final Object value) throws IOException, MarmottaClientException {
    HttpClient httpClient = HTTPUtil.createClient(config);

    String serviceUrl = config.getMarmottaUri() + URL_CONFIG_SERVICE + "/data/"
            + URLEncoder.encode(key, "utf-8");

    HttpPost post = new HttpPost(serviceUrl);
    post.setHeader("Content-Type", "application/json");
    ContentProducer cp = new ContentProducer() {
        @Override
        public void writeTo(OutputStream outstream) throws IOException {
            ObjectMapper mapper = new ObjectMapper();
            if (value instanceof Collection) {
                mapper.writeValue(outstream, value);
            } else {
                mapper.writeValue(outstream, Collections.singletonList(value.toString()));
            }
        }
    };
    post.setEntity(new EntityTemplate(cp));

    try {

        HttpResponse response = httpClient.execute(post);

        switch (response.getStatusLine().getStatusCode()) {
        case 200:
            log.debug("configuration {} updated successfully", key);
            break;
        case 404:
            log.error("configuration with key {} does not exist", key);
            throw new NotFoundException("configuration with key " + key + " does not exist");
        default:
            log.error("error updating configuration {}: {} {}", new Object[] { key,
                    response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase() });
            throw new MarmottaClientException(
                    "error updating configuration " + key + ": " + response.getStatusLine().getStatusCode()
                            + " " + response.getStatusLine().getReasonPhrase());
        }

    } finally {
        post.releaseConnection();
    }
}

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/*w  w w  .  java2  s.  co  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(Charset.defaultCharset()));
            out.flush();
            out.close();
        }
    });
    ent.setContentType(contentType);
    if (zip) {
        ent.setContentEncoding("gzip");
    }
    entityEncReq.setEntity(ent);
    return client.execute(request);
}

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");
    }// ww w.j a v  a2  s  .  c o 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();
}

From source file:com.wills.clientproxy.HessianLBProxy.java

/**
 * Sends the HTTP request to the Hessian connection.
 *//*  www.  j  a va 2  s. co  m*/
protected HessianConnection sendRequest(final String methodName, final Object[] args, final URL currentUrl)
        throws IOException {
    HessianConnection conn = null;

    boolean isValid = false;
    try {
        conn = _factory.getConnectionFactory().open(currentUrl);
        addRequestHeaders(conn);

        ContentProducer contentProducer = new ContentProducer() {
            public void writeTo(OutputStream outstream) throws IOException {
                try {
                    AbstractHessianOutput out = _factory.getHessianOutput(outstream);

                    out.call(methodName, args);
                    out.flush();
                } catch (Exception e) {
                    throw new HessianRuntimeException(e);
                }
            }
        };

        conn.setContentProducer(contentProducer);
        conn.sendRequest();

        isValid = true;

    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        if (!isValid && conn != null)
            conn.destroy();
    }
    return conn;
}

From source file:org.apache.jena.fuseki.embedded.TestEmbeddedFuseki.java

/** Create an HttpEntity for the graph */
protected static HttpEntity graphToHttpEntity(final Graph graph) {
    final RDFFormat syntax = RDFFormat.TURTLE_BLOCKS;
    ContentProducer producer = new ContentProducer() {
        @Override/*www  .  j  a va  2 s.  c  o m*/
        public void writeTo(OutputStream out) {
            RDFDataMgr.write(out, graph, syntax);
        }
    };
    EntityTemplate entity = new EntityTemplate(producer);
    ContentType ct = syntax.getLang().getContentType();
    entity.setContentType(ct.getContentType());
    return entity;
}

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// www  . j  a v  a 2 s .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);
}