Search in sources :

Example 76 with ByteArrayEntity

use of org.apache.http.entity.ByteArrayEntity in project vcell by virtualcell.

the class VCellApiClient method sendRpcMessage.

public Serializable sendRpcMessage(RpcDestination rpcDestination, VCellApiRpcRequest rpcRequest, boolean returnRequired, int timeoutMS, String[] specialProperties, Object[] specialValues) throws ClientProtocolException, IOException {
    HttpPost httppost = new HttpPost("https://" + httpHost.getHostName() + ":" + httpHost.getPort() + "/rpc");
    VCellApiRpcBody vcellapiRpcBody = new VCellApiRpcBody(rpcDestination, rpcRequest, returnRequired, timeoutMS, specialProperties, specialValues);
    byte[] compressedSerializedRpcBody = null;
    try {
        compressedSerializedRpcBody = toCompressedSerialized(vcellapiRpcBody);
    } catch (IOException e2) {
        e2.printStackTrace();
        throw new RuntimeException("vcellapi rpc failure serializing request body, method=" + rpcRequest.methodName + ": " + e2.getMessage(), e2);
    }
    ByteArrayEntity input = new ByteArrayEntity(compressedSerializedRpcBody);
    input.setContentType(ContentType.APPLICATION_OCTET_STREAM.getMimeType());
    httppost.setEntity(input);
    httppost.addHeader("username", rpcRequest.username);
    httppost.addHeader("destination", rpcRequest.rpcDestination.name());
    httppost.addHeader("method", rpcRequest.methodName);
    httppost.addHeader("returnRequired", Boolean.toString(returnRequired));
    httppost.addHeader("timeoutMS", Integer.toString(timeoutMS));
    httppost.addHeader("compressed", "zip");
    httppost.addHeader("class", VCellApiRpcBody.class.getCanonicalName());
    if (specialProperties != null) {
        httppost.addHeader("specialProperties", Arrays.asList(specialProperties).toString());
    }
    if (lg.isLoggable(Level.INFO)) {
        lg.info("Executing request to submit rpc call " + httppost.getRequestLine());
    }
    ResponseHandler<Serializable> handler = new ResponseHandler<Serializable>() {

        public Serializable handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
            int status = response.getStatusLine().getStatusCode();
            if (lg.isLoggable(Level.INFO)) {
                lg.info("in rpc response handler, status=" + status);
            }
            if (status == 200) {
                HttpEntity entity = response.getEntity();
                try {
                    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                    entity.writeTo(byteArrayOutputStream);
                    byte[] returnValueBytes = byteArrayOutputStream.toByteArray();
                    Serializable returnValue = fromCompressedSerialized(returnValueBytes);
                    if (returnRequired) {
                        if (returnValue instanceof Exception) {
                            Exception e = (Exception) returnValue;
                            e.printStackTrace();
                            lg.severe("vcellapi rpc failure, method=" + rpcRequest.methodName + ": " + e.getMessage());
                            throw new ClientProtocolException("vcellapi rpc failure, method=" + rpcRequest.methodName + ": " + e.getMessage(), e);
                        } else {
                            if (lg.isLoggable(Level.INFO)) {
                                lg.info("returning normally from rpc response handler (" + toStringTruncated(returnValue) + ")");
                            }
                            return returnValue;
                        }
                    } else {
                        if (lg.isLoggable(Level.INFO)) {
                            lg.info("returning null from rpc response handler (returnRequired==false)");
                        }
                        return null;
                    }
                } catch (ClassNotFoundException | IllegalStateException e1) {
                    e1.printStackTrace();
                    lg.severe("vcellapi rpc failure deserializing return value, method=" + rpcRequest.methodName + ": " + e1.getMessage());
                    throw new RuntimeException("vcellapi rpc failure deserializing return value, method=" + rpcRequest.methodName + ": " + e1.getMessage(), e1);
                }
            } else {
                HttpEntity entity = response.getEntity();
                String message = null;
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()))) {
                    message = reader.lines().collect(Collectors.joining());
                }
                lg.severe("RPC method " + rpcDestination + ":" + rpcRequest.methodName + "() failed: response status: " + status + "\nreason: " + message);
                throw new ClientProtocolException("RPC method " + rpcDestination + ":" + rpcRequest.methodName + "() failed: response status: " + status + "\nreason: " + message);
            }
        }
    };
    Serializable returnedValue = httpclient.execute(httppost, handler, httpClientContext);
    if (lg.isLoggable(Level.INFO)) {
        lg.info("returned from vcellapi rpc method=" + rpcDestination + ":" + rpcRequest.methodName + "()");
    }
    return returnedValue;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) Serializable(java.io.Serializable) ResponseHandler(org.apache.http.client.ResponseHandler) HttpEntity(org.apache.http.HttpEntity) InputStreamReader(java.io.InputStreamReader) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ProtocolException(org.apache.http.ProtocolException) URISyntaxException(java.net.URISyntaxException) KeyStoreException(java.security.KeyStoreException) KeyManagementException(java.security.KeyManagementException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ClientProtocolException(org.apache.http.client.ClientProtocolException) IOException(java.io.IOException) ClientProtocolException(org.apache.http.client.ClientProtocolException) ByteArrayEntity(org.apache.http.entity.ByteArrayEntity) BufferedReader(java.io.BufferedReader)

Example 77 with ByteArrayEntity

use of org.apache.http.entity.ByteArrayEntity in project Lucee by lucee.

the class HTTPEngine4Impl method toHttpEntity.

/**
 * convert input to HTTP Entity
 *
 * @param value
 * @param mimetype
 *            not used for binary input
 * @param charset
 *            not used for binary input
 * @return
 * @throws IOException
 */
private static HttpEntity toHttpEntity(Object value, String mimetype, String charset) throws IOException {
    if (value instanceof HttpEntity)
        return (HttpEntity) value;
    // content type
    ContentType ct = HTTPEngine.toContentType(mimetype, charset);
    try {
        if (value instanceof TemporaryStream) {
            if (ct != null)
                return new TemporaryStreamHttpEntity((TemporaryStream) value, ct);
            return new TemporaryStreamHttpEntity((TemporaryStream) value, null);
        } else if (value instanceof InputStream) {
            if (ct != null)
                return new ByteArrayEntity(IOUtil.toBytes((InputStream) value), ct);
            return new ByteArrayEntity(IOUtil.toBytes((InputStream) value));
        } else if (Decision.isCastableToBinary(value, false)) {
            if (ct != null)
                return new ByteArrayEntity(Caster.toBinary(value), ct);
            return new ByteArrayEntity(Caster.toBinary(value));
        } else {
            boolean wasNull = false;
            if (ct == null) {
                wasNull = true;
                ct = ContentType.APPLICATION_OCTET_STREAM;
            }
            String str = Caster.toString(value);
            if (str.equals("<empty>")) {
                return new EmptyHttpEntity(ct);
            }
            if (wasNull && !StringUtil.isEmpty(charset, true))
                return new StringEntity(str, charset.trim());
            else
                return new StringEntity(str, ct);
        }
    } catch (Exception e) {
        throw ExceptionUtil.toIOException(e);
    }
}
Also used : StringEntity(org.apache.http.entity.StringEntity) EmptyHttpEntity(lucee.commons.net.http.httpclient.entity.EmptyHttpEntity) TemporaryStreamHttpEntity(lucee.commons.net.http.httpclient.entity.TemporaryStreamHttpEntity) EmptyHttpEntity(lucee.commons.net.http.httpclient.entity.EmptyHttpEntity) HttpEntity(org.apache.http.HttpEntity) ResourceHttpEntity(lucee.commons.net.http.httpclient.entity.ResourceHttpEntity) ByteArrayHttpEntity(lucee.commons.net.http.httpclient.entity.ByteArrayHttpEntity) ContentType(org.apache.http.entity.ContentType) ByteArrayEntity(org.apache.http.entity.ByteArrayEntity) InputStream(java.io.InputStream) TemporaryStreamHttpEntity(lucee.commons.net.http.httpclient.entity.TemporaryStreamHttpEntity) TemporaryStream(lucee.commons.io.TemporaryStream) PageException(lucee.runtime.exp.PageException) IOException(java.io.IOException)

Example 78 with ByteArrayEntity

use of org.apache.http.entity.ByteArrayEntity in project bayou by capergroup.

the class ApiSynthesisClient method synthesizeHelp.

private List<String> synthesizeHelp(String code, int maxProgramCount, Integer sampleCount) throws IOException, SynthesisError {
    _logger.debug("entering");
    if (code == null)
        throw new IllegalArgumentException("code may not be null");
    if (maxProgramCount < 1)
        throw new IllegalArgumentException("maxProgramCount must be a natural number");
    if (sampleCount != null && sampleCount < 1)
        throw new IllegalArgumentException("sampleCount must be a natural number if non-null");
    /*
         * Create request and send to server.
         */
    JSONObject requestMsg = new JSONObject();
    requestMsg.put("code", code);
    requestMsg.put("max program count", maxProgramCount);
    if (sampleCount != null)
        requestMsg.put("sample count", sampleCount);
    HttpClient httpclient = HttpClients.createDefault();
    HttpPost post = new HttpPost("http://" + host + ":" + port + "/apisynthesis");
    post.addHeader("Origin", "http://askbayou.com");
    post.setEntity(new ByteArrayEntity(requestMsg.toString(4).getBytes()));
    /*
         * Read and parse the response from the server.
         */
    JSONObject responseBodyObj;
    {
        HttpResponse response = httpclient.execute(post);
        if (response.getStatusLine().getStatusCode() != 200 && response.getStatusLine().getStatusCode() != 400) {
            throw new IOException("Unexpected status code: " + response.getStatusLine().getStatusCode());
        }
        String responseBodyAsString;
        {
            byte[] responseBytes = IOUtils.toByteArray(response.getEntity().getContent());
            responseBodyAsString = new String(responseBytes);
        }
        try {
            responseBodyObj = parseResponseMessageBodyToJson(responseBodyAsString);
        } catch (IllegalArgumentException e) {
            _logger.debug("exiting");
            throw new SynthesisError(e.getMessage());
        }
    }
    _logger.debug("exiting");
    return parseResponseMessageBody(responseBodyObj);
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) JSONObject(org.json.JSONObject) ByteArrayEntity(org.apache.http.entity.ByteArrayEntity) HttpClient(org.apache.http.client.HttpClient) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException)

Aggregations

ByteArrayEntity (org.apache.http.entity.ByteArrayEntity)78 HttpEntity (org.apache.http.HttpEntity)28 HttpPost (org.apache.http.client.methods.HttpPost)24 HttpResponse (org.apache.http.HttpResponse)20 IOException (java.io.IOException)17 ByteArrayOutputStream (java.io.ByteArrayOutputStream)16 JSONObject (org.json.JSONObject)11 Test (org.junit.Test)10 HttpClient (org.apache.http.client.HttpClient)9 InputStream (java.io.InputStream)7 JSONArray (org.json.JSONArray)7 URISyntaxException (java.net.URISyntaxException)5 Header (org.apache.http.Header)5 AbstractHttpEntity (org.apache.http.entity.AbstractHttpEntity)5 ContentType (org.apache.http.entity.ContentType)5 BytesRef (org.apache.lucene.util.BytesRef)5 DocWriteRequest (org.elasticsearch.action.DocWriteRequest)5 BulkRequest (org.elasticsearch.action.bulk.BulkRequest)5 DeleteRequest (org.elasticsearch.action.delete.DeleteRequest)5 GetRequest (org.elasticsearch.action.get.GetRequest)5