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.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  .ja  v  a2s . com*/
 * @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.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//from   w w w  .  j  a v  a2s .  com
 * @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:com.baqr.baqrcam.http.ModInternationalization.java

public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context)
        throws HttpException, IOException {

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

    final EntityTemplate body = new EntityTemplate(new ContentProducer() {
        public void writeTo(final OutputStream outstream) throws IOException {
            OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
            writer.write(mJSON);
            writer.flush();
        }
    });

    response.setStatusCode(HttpStatus.SC_OK);
    body.setContentType("text/json; charset=UTF-8");
    response.setEntity(body);

}

From source file:net.facework.core.http.ModInternationalization.java

@Override
public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context)
        throws HttpException, IOException {

    final String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
    if (!method.equals("GET") && !method.equals("HEAD")) {
        throw new MethodNotSupportedException(method + " method not supported");
    }// ww w  . j a va  2  s.c o  m

    final EntityTemplate body = new EntityTemplate(new ContentProducer() {
        @Override
        public void writeTo(final OutputStream outstream) throws IOException {
            OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
            writer.write(mJSON);
            writer.flush();
        }
    });

    response.setStatusCode(HttpStatus.SC_OK);
    body.setContentType("text/json; charset=UTF-8");
    response.setEntity(body);

}

From source file:com.joshdrummond.webpasswordsafe.android.GetCurrentPassword.java

private void doSubmit() {
    TextView status = (TextView) findViewById(R.id.status);
    String url = ((EditText) findViewById(R.id.url)).getText().toString();
    String authnUsername = ((EditText) findViewById(R.id.authnUsername)).getText().toString();
    String authnPassword = ((EditText) findViewById(R.id.authnPassword)).getText().toString();
    String passwordName = ((EditText) findViewById(R.id.passwordName)).getText().toString();

    final String requestSOAP = new StringBuffer().append(
            "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:wps=\"http://www.joshdrummond.com/webpasswordsafe/schemas\">")
            .append("<soapenv:Header/>").append("<soapenv:Body>").append("<wps:GetCurrentPasswordRequest>")
            .append("<wps:authnUsername>").append(authnUsername).append("</wps:authnUsername>")
            .append("<wps:authnPassword>").append(authnPassword).append("</wps:authnPassword>")
            .append("<wps:passwordName>").append(passwordName).append("</wps:passwordName>")
            .append("</wps:GetCurrentPasswordRequest>").append("</soapenv:Body>").append("</soapenv:Envelope>")
            .toString();//w  w  w.  j  a v  a2  s .  c o m
    try {
        HttpClient httpClient = new DefaultHttpClient();
        HttpContext localContext = new BasicHttpContext();
        ContentProducer cp = new ContentProducer() {
            public void writeTo(OutputStream outstream) throws IOException {
                Writer writer = new OutputStreamWriter(outstream, "UTF-8");
                writer.write(requestSOAP);
                writer.flush();
            }
        };
        HttpEntity entity = new EntityTemplate(cp);
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(entity);
        HttpResponse httpResponse = httpClient.execute(httpPost, localContext);
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(httpResponse.getEntity().getContent()));
        StringBuffer responseSOAP = new StringBuffer();
        String line = reader.readLine();
        while (line != null) {
            responseSOAP.append(line);
            line = reader.readLine();
        }
        status.setText(parseResponse(responseSOAP.toString()));
    } catch (Exception e) {
        e.printStackTrace();
        status.setText("ERROR: " + e.getMessage());
    }
}

From source file:org.apache.tuscany.sca.binding.jsonrpc.provider.JsonRpcInvoker.java

public Message invoke(Message msg) {
    HttpPost post = null;/*from w w  w.  j a  v a 2s  . c  o  m*/
    HttpResponse response = null;
    try {
        String requestId = UUID.randomUUID().toString();
        post = new HttpPost(uri);
        HttpEntity entity = null;
        Object[] args = msg.getBody();
        final String db = msg.getOperation().getInputWrapper().getDataBinding();

        if (!db.equals(JSONDataBinding.NAME)) {
            Object[] params = new Object[0];
            // Extract the arguments
            args = msg.getBody();

            if (args instanceof Object[]) {
                params = (Object[]) args;
            }

            JsonRpcRequest req = null;
            if (JSONRPCBinding.VERSION_20
                    .equals(((JSONRPCBinding) endpointReference.getBinding()).getVersion())) {
                req = new JsonRpc20Request(requestId, msg.getOperation().getName(), params);
            } else {
                req = new JsonRpc10Request(requestId, msg.getOperation().getName(), params);
            }
            final JsonRpcRequest json = req;

            // Create content producer so that we can stream the json result out
            ContentProducer cp = new ContentProducer() {
                public void writeTo(OutputStream outstream) throws IOException {
                    // mapper.writeValue(outstream, req.toJSONObject().toString());
                    try {
                        json.write(outstream);
                    } catch (Exception e) {
                        throw new IOException(e);
                    }
                }
            };
            entity = new EntityTemplate(cp);
        } else {
            // Single string argument
            entity = new StringEntity((String) args[0], "UTF-8");
        }

        post.setEntity(entity);

        response = httpClient.execute(post);

        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            //success 

            entity = response.getEntity();
            String entityResponse = EntityUtils.toString(entity);
            entity.consumeContent();
            if (!db.equals(JSONDataBinding.NAME)) {
                ObjectNode jsonResponse = (ObjectNode) JacksonHelper.MAPPER.readTree(entityResponse);

                if (jsonResponse.has("error") && jsonResponse.get("error") != NullNode.instance) {
                    processException(jsonResponse);
                }
                DataType<List<DataType>> outputType = operation.getOutputType();
                DataType returnType = (outputType != null && !outputType.getLogical().isEmpty())
                        ? outputType.getLogical().get(0)
                        : null;

                if (returnType == null) {
                    msg.setBody(null);
                    return msg;
                }

                //check requestId
                if (!requestId.equalsIgnoreCase(jsonResponse.get("id").getTextValue())) {
                    throw new ServiceRuntimeException("Invalid response id:" + requestId);
                }

                JsonNode rawResult = jsonResponse.get("result");

                Class<?> returnClass = returnType.getPhysical();
                Type genericReturnType = returnType.getGenericType();

                ObjectMapper mapper = createObjectMapper(returnClass);
                String json = mapper.writeValueAsString(rawResult);

                Object body = mapper.readValue(json, TypeFactory.type(genericReturnType));

                msg.setBody(body);
            } else {
                msg.setBody(entityResponse);
            }

        } else {
            // Consume the content so the connection can be released
            response.getEntity().consumeContent();
            throw new ServiceRuntimeException("Abnormal HTTP response: " + response.getStatusLine().toString());
        }
    } catch (RuntimeException e) {
        throw e;
    } catch (Error e) {
        throw e;
    } catch (Exception e) {
        // e.printStackTrace();
        msg.setFaultBody(e);
    } catch (Throwable e) {
        throw new ServiceRuntimeException(e);
    }

    return msg;
}

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

/**
 * Upload/Import a dataset in the Marmotta Server. The dataset is given as an Inputstream that contains data of the
 * mime type passed as argument. The mime type must be one of the acceptable types of the server.
 *
 * @param in InputStream to read the dataset from; will be consumed by this method
 * @param mimeType mime type of the input data
 * @throws IOException//from   www  . j  a va 2s .co  m
 * @throws MarmottaClientException
 */
public void uploadDataset(final InputStream in, final String mimeType)
        throws IOException, MarmottaClientException {
    //Preconditions.checkArgument(acceptableTypes.contains(mimeType));

    HttpClient httpClient = HTTPUtil.createClient(config);

    HttpPost post = HTTPUtil.createPost(URL_UPLOAD_SERVICE, config);
    post.setHeader("Content-Type", mimeType);

    ContentProducer cp = new ContentProducer() {
        @Override
        public void writeTo(OutputStream outstream) throws IOException {
            ByteStreams.copy(in, outstream);
        }
    };
    post.setEntity(new EntityTemplate(cp));

    ResponseHandler<Boolean> handler = new ResponseHandler<Boolean>() {
        @Override
        public Boolean handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
            EntityUtils.consume(response.getEntity());
            switch (response.getStatusLine().getStatusCode()) {
            case 200:
                log.debug("dataset uploaded updated successfully");
                return true;
            case 412:
                log.error("mime type {} not acceptable by import service", mimeType);
                return false;
            default:
                log.error("error uploading dataset: {} {}", new Object[] {
                        response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase() });
                return false;
            }
        }
    };

    try {
        httpClient.execute(post, handler);
    } catch (IOException ex) {
        post.abort();
        throw ex;
    } finally {
        post.releaseConnection();
    }

}

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 ava2  s .  com
 * @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:net.facework.core.http.ModAssetServer.java

@Override
public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context)
        throws HttpException, IOException {
    AbstractHttpEntity body = null;//from   ww  w . j ava  2  s . c om

    final String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
    if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST")) {
        throw new MethodNotSupportedException(method + " method not supported");
    }

    final String url = URLDecoder.decode(request.getRequestLine().getUri());
    if (request instanceof HttpEntityEnclosingRequest) {
        HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
        byte[] entityContent = EntityUtils.toByteArray(entity);
        Log.d(TAG, "Incoming entity content (bytes): " + entityContent.length);
    }

    final String location = "www" + (url.equals("/") ? "/index.htm" : url);
    response.setStatusCode(HttpStatus.SC_OK);

    try {
        Log.i(TAG, "Requested: \"" + url + "\"");

        // Compares the Last-Modified date header (if present) with the If-Modified-Since date
        if (request.containsHeader("If-Modified-Since")) {
            try {
                Date date = DateUtils.parseDate(request.getHeaders("If-Modified-Since")[0].getValue());
                if (date.compareTo(mServer.mLastModified) <= 0) {
                    // The file has not been modified
                    response.setStatusCode(HttpStatus.SC_NOT_MODIFIED);
                    return;
                }
            } catch (DateParseException e) {
                e.printStackTrace();
            }
        }

        // We determine if the asset is compressed
        try {
            AssetFileDescriptor afd = mAssetManager.openFd(location);

            // The asset is not compressed
            FileInputStream fis = new FileInputStream(afd.getFileDescriptor());
            fis.skip(afd.getStartOffset());
            body = new InputStreamEntity(fis, afd.getDeclaredLength());

            Log.d(TAG, "Serving uncompressed file " + "www" + url);

        } catch (FileNotFoundException e) {

            // The asset may be compressed
            // AAPT compresses assets so first we need to uncompress them to determine their length
            InputStream stream = mAssetManager.open(location, AssetManager.ACCESS_STREAMING);
            ByteArrayOutputStream buffer = new ByteArrayOutputStream(64000);
            byte[] tmp = new byte[4096];
            int length = 0;
            while ((length = stream.read(tmp)) != -1)
                buffer.write(tmp, 0, length);
            body = new InputStreamEntity(new ByteArrayInputStream(buffer.toByteArray()), buffer.size());
            stream.close();

            Log.d(TAG, "Serving compressed file " + "www" + url);

        }

        body.setContentType(getMimeMediaType(url) + "; charset=UTF-8");
        response.addHeader("Last-Modified", DateUtils.formatDate(mServer.mLastModified));

    } catch (IOException e) {
        // File does not exist
        response.setStatusCode(HttpStatus.SC_NOT_FOUND);
        body = new EntityTemplate(new ContentProducer() {
            @Override
            public void writeTo(final OutputStream outstream) throws IOException {
                OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
                writer.write("<html><body><h1>");
                writer.write("File ");
                writer.write("www" + url);
                writer.write(" not found");
                writer.write("</h1></body></html>");
                writer.flush();
            }
        });
        Log.d(TAG, "File " + "www" + url + " not found");
        body.setContentType("text/html; charset=UTF-8");
    }

    response.setEntity(body);

}

From source file:com.wifi.brainbreaker.mydemo.http.ModAssetServer.java

public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context)
        throws HttpException, IOException {
    AbstractHttpEntity body = null;//from   ww w.j  a  v a2s  .  c o m

    final String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
    if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST")) {
        throw new MethodNotSupportedException(method + " method not supported");
    }

    final String url = URLDecoder.decode(request.getRequestLine().getUri());
    if (request instanceof HttpEntityEnclosingRequest) {
        HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
        byte[] entityContent = EntityUtils.toByteArray(entity);
        Log.d(TAG, "Incoming entity content (bytes): " + entityContent.length);
    }

    final String location = "www" + (url.equals("/") ? "/index.htm" : url);
    response.setStatusCode(HttpStatus.SC_OK);

    try {
        Log.i(TAG, "Requested: \"" + url + "\"");

        // Compares the Last-Modified date header (if present) with the If-Modified-Since date
        if (request.containsHeader("If-Modified-Since")) {
            try {
                Date date = DateUtils.parseDate(request.getHeaders("If-Modified-Since")[0].getValue());
                if (date.compareTo(mServer.mLastModified) <= 0) {
                    // The file has not been modified
                    response.setStatusCode(HttpStatus.SC_NOT_MODIFIED);
                    return;
                }
            } catch (DateParseException e) {
                e.printStackTrace();
            }
        }

        // We determine if the asset is compressed
        try {
            AssetFileDescriptor afd = mAssetManager.openFd(location);

            // The asset is not compressed
            FileInputStream fis = new FileInputStream(afd.getFileDescriptor());
            fis.skip(afd.getStartOffset());
            body = new InputStreamEntity(fis, afd.getDeclaredLength());

            Log.d(TAG, "Serving uncompressed file " + "www" + url);

        } catch (FileNotFoundException e) {

            // The asset may be compressed
            // AAPT compresses assets so first we need to uncompress them to determine their length
            InputStream stream = mAssetManager.open(location, AssetManager.ACCESS_STREAMING);
            ByteArrayOutputStream buffer = new ByteArrayOutputStream(64000);
            byte[] tmp = new byte[4096];
            int length = 0;
            while ((length = stream.read(tmp)) != -1)
                buffer.write(tmp, 0, length);
            body = new InputStreamEntity(new ByteArrayInputStream(buffer.toByteArray()), buffer.size());
            stream.close();

            Log.d(TAG, "Serving compressed file " + "www" + url);

        }

        body.setContentType(getMimeMediaType(url) + "; charset=UTF-8");
        response.addHeader("Last-Modified", DateUtils.formatDate(mServer.mLastModified));

    } catch (IOException e) {
        // File does not exist
        response.setStatusCode(HttpStatus.SC_NOT_FOUND);
        body = new EntityTemplate(new ContentProducer() {
            public void writeTo(final OutputStream outstream) throws IOException {
                OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
                writer.write("<html><body><h1>");
                writer.write("File ");
                writer.write("www" + url);
                writer.write(" not found");
                writer.write("</h1></body></html>");
                writer.flush();
            }
        });
        Log.d(TAG, "File " + "www" + url + " not found");
        body.setContentType("text/html; charset=UTF-8");
    }

    response.setEntity(body);

}