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

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

Introduction

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

Prototype

public EntityTemplate(ContentProducer contentProducer) 

Source Link

Usage

From source file:com.wentam.defcol.connect_to_computer.HomeCommandHandler.java

@Override
public void handle(final HttpRequest request, final HttpResponse response, HttpContext httpContext)
        throws HttpException, IOException {
    HttpEntity entity = new EntityTemplate(new ContentProducer() {
        public void writeTo(final OutputStream outstream) throws IOException {
            OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
            String req = request.getRequestLine().getUri();

            req = req.replaceAll("/\\?", "");

            String[] pairs = req.split("&");

            HashMap data = new HashMap();

            for (int i = 0; i < pairs.length; i++) {
                if (pairs[i].contains("=")) {
                    String[] pair = pairs[i].split("=");
                    data.put(pair[0], pair[1]);
                }/*from  w  w  w .  j av  a  2 s  .  c om*/
            }

            String action = "none";
            if (data.containsKey("action")) {
                action = (String) data.get("action");
            }

            String resp = "404 on " + action;
            if (action.equals("none") || action.equals("home")) {
                response.setHeader("Content-Type", "text/html");

                resp = getHtml();

            } else if (action.equals("getPalettes")) {
                response.setHeader("Content-Type", "application/json");

                JSONArray json = new JSONArray();

                int tmp[] = { 0 };
                ArrayList<String> palettes = pFile.getRows(tmp);
                Iterator i = palettes.iterator();
                while (i.hasNext()) {
                    JSONObject item = new JSONObject();
                    try {
                        item.put("name", i.next());
                    } catch (JSONException e) {
                    }
                    json.put(item);
                }

                resp = json.toString();

            } else if (action.equals("getJquery")) {
                response.setHeader("Content-Type", "application/javascript");
                resp = jquery;
            } else if (action.equals("getJs")) {
                response.setHeader("Content-Type", "application/javascript");
                resp = getJs();
            } else if (action.equals("getPaletteColors")) {
                response.setHeader("Content-Type", "application/javascript");
                int id = Integer.parseInt((String) data.get("id"));

                int tmp[] = { 1 };
                String row = pFile.getRow(id, tmp);

                String colors[] = row.split("\\.");

                JSONArray json = new JSONArray();

                for (int i = 0; i < colors.length; i++) {
                    json.put(colors[i]);
                }

                resp = json.toString();
            }

            writer.write(resp);
            writer.flush();
        }
    });

    response.setEntity(entity);
}

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 w  w.j  a va2  s. c  o  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(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  av 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: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 ww w  .ja v  a2 s  .c  om*/

    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");
    }//from   w w  w.jav a  2 s  .co  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:org.wrml.runtime.service.rest.RestService.java

@Override
public Model save(final Model model) {

    final Document document = (Document) model;
    final URI uri = document.getUri();

    final HttpPut httpPut = new HttpPut(uri);

    final Context context = model.getContext();

    final ModelContentProducer httpWriter = new ModelContentProducer(context, null, model);
    httpPut.setEntity(new EntityTemplate(httpWriter));

    final HttpResponse response = executeRequest(httpPut);
    final Dimensions responseDimensions = RestUtils.extractResponseDimensions(context, response,
            model.getDimensions());/*from  w  ww  . java2s  . c  om*/

    return readResponseModel(response, model.getContext(), model.getKeys(), responseDimensions);
}

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();/*from   w  w w .  ja  v  a2 s.  co 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;/*w  w w  .  j  a v a2  s .  co  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  w  w w .j a  va2  s .  c o  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:com.teradata.tempto.internal.hadoop.hdfs.WebHDFSClient.java

@Override
public void saveFile(String path, String username, RepeatableContentProducer repeatableContentProducer) {
    saveFile(path, username, new EntityTemplate(toApacheContentProducer(repeatableContentProducer)));
}