Search in sources :

Example 86 with ClientProtocolException

use of org.apache.http.client.ClientProtocolException in project apex-malhar by apache.

the class MRUtil method getJsonForURL.

/**
 * This method returns the response content for a given url
 * @param url
 * @return
 */
public static String getJsonForURL(String url) {
    HttpClient httpclient = new DefaultHttpClient();
    logger.debug(url);
    try {
        HttpGet httpget = new HttpGet(url);
        // Create a response handler
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseBody;
        try {
            responseBody = httpclient.execute(httpget, responseHandler);
        } catch (ClientProtocolException e) {
            logger.debug(e.getMessage());
            return null;
        } catch (IOException e) {
            logger.debug(e.getMessage());
            return null;
        } catch (Exception e) {
            logger.debug(e.getMessage());
            return null;
        }
        return responseBody.trim();
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
}
Also used : DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) HttpGet(org.apache.http.client.methods.HttpGet) BasicResponseHandler(org.apache.http.impl.client.BasicResponseHandler) IOException(java.io.IOException) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) ClientProtocolException(org.apache.http.client.ClientProtocolException) IOException(java.io.IOException) ClientProtocolException(org.apache.http.client.ClientProtocolException)

Example 87 with ClientProtocolException

use of org.apache.http.client.ClientProtocolException in project gradle by gradle.

the class HttpBuildCacheService method store.

@Override
public void store(BuildCacheKey key, final BuildCacheEntryWriter output) throws BuildCacheException {
    final URI uri = root.resolve(key.getHashCode());
    HttpPut httpPut = new HttpPut(uri);
    httpPut.addHeader(HttpHeaders.CONTENT_TYPE, BUILD_CACHE_CONTENT_TYPE);
    addDiagnosticHeaders(httpPut);
    httpPut.setEntity(new AbstractHttpEntity() {

        @Override
        public boolean isRepeatable() {
            return false;
        }

        @Override
        public long getContentLength() {
            return output.getSize();
        }

        @Override
        public InputStream getContent() throws IOException, UnsupportedOperationException {
            throw new UnsupportedOperationException();
        }

        @Override
        public void writeTo(OutputStream outstream) throws IOException {
            output.writeTo(outstream);
        }

        @Override
        public boolean isStreaming() {
            return false;
        }
    });
    CloseableHttpResponse response = null;
    try {
        response = httpClientHelper.performHttpRequest(httpPut);
        StatusLine statusLine = response.getStatusLine();
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Response for PUT {}: {}", safeUri(uri), statusLine);
        }
        int statusCode = statusLine.getStatusCode();
        if (!isHttpSuccess(statusCode)) {
            String defaultMessage = String.format("Storing entry at '%s' response status %d: %s", safeUri(uri), statusCode, statusLine.getReasonPhrase());
            if (isRedirect(statusCode)) {
                handleRedirect(uri, response, statusCode, defaultMessage, "storing entry at");
            } else {
                throwHttpStatusCodeException(statusCode, defaultMessage);
            }
        }
    } catch (ClientProtocolException e) {
        Throwable cause = e.getCause();
        if (cause instanceof NonRepeatableRequestException) {
            throw wrap(cause.getCause());
        } else {
            throw wrap(cause);
        }
    } catch (IOException e) {
        throw wrap(e);
    } finally {
        HttpClientUtils.closeQuietly(response);
    }
}
Also used : InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) UncheckedIOException(org.gradle.api.UncheckedIOException) IOException(java.io.IOException) URI(java.net.URI) HttpPut(org.apache.http.client.methods.HttpPut) ClientProtocolException(org.apache.http.client.ClientProtocolException) StatusLine(org.apache.http.StatusLine) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) NonRepeatableRequestException(org.apache.http.client.NonRepeatableRequestException) AbstractHttpEntity(org.apache.http.entity.AbstractHttpEntity)

Example 88 with ClientProtocolException

use of org.apache.http.client.ClientProtocolException 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 89 with ClientProtocolException

use of org.apache.http.client.ClientProtocolException in project vcell by virtualcell.

the class VCellApiClient method submitOptimization.

public String submitOptimization(String optProblemJson) throws IOException, URISyntaxException {
    HttpPost httppost = new HttpPost("https://" + httpHost.getHostName() + ":" + httpHost.getPort() + "/optimization");
    StringEntity input = new StringEntity(optProblemJson);
    input.setContentType("application/json");
    httppost.setEntity(input);
    if (lg.isLoggable(Level.INFO)) {
        lg.info("Executing request to submit optProblem " + httppost.getRequestLine());
    }
    ResponseHandler<String> handler = new ResponseHandler<String>() {

        public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
            int status = response.getStatusLine().getStatusCode();
            if (status == 202) {
                HttpEntity entity = response.getEntity();
                if (lg.isLoggable(Level.INFO)) {
                    try (BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()))) {
                        lg.info("optimizationId = " + reader.readLine());
                    }
                }
                final Header locationHeader = response.getFirstHeader("location");
                if (locationHeader == null) {
                    // got a redirect response, but no location header
                    throw new ClientProtocolException("Received redirect response " + response.getStatusLine() + " but no location header");
                }
                final String location = locationHeader.getValue();
                URI uri = createLocationURI(location);
                return uri.toString();
            } else {
                throw new ClientProtocolException("Unexpected response status: " + status);
            }
        }
    };
    String responseUri = httpclient.execute(httppost, handler, httpClientContext);
    if (lg.isLoggable(Level.INFO)) {
        lg.info("returned: " + toStringTruncated(responseUri));
    }
    String optimizationId = responseUri.substring(responseUri.lastIndexOf('/') + 1);
    return optimizationId;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) ResponseHandler(org.apache.http.client.ResponseHandler) HttpEntity(org.apache.http.HttpEntity) InputStreamReader(java.io.InputStreamReader) HttpResponse(org.apache.http.HttpResponse) URI(java.net.URI) ClientProtocolException(org.apache.http.client.ClientProtocolException) StringEntity(org.apache.http.entity.StringEntity) Header(org.apache.http.Header) BufferedReader(java.io.BufferedReader)

Example 90 with ClientProtocolException

use of org.apache.http.client.ClientProtocolException in project vcell by virtualcell.

the class VCellApiClient method insertUserInfo.

public UserInfo insertUserInfo(UserInfo newUserInfo) throws ClientProtocolException, IOException {
    HttpPost httppost = new HttpPost("https://" + httpHost.getHostName() + ":" + httpHost.getPort() + "/newuser");
    Gson gson = new Gson();
    String newUserInfoJSON = gson.toJson(newUserInfo);
    StringEntity input = new StringEntity(newUserInfoJSON);
    input.setContentType(ContentType.APPLICATION_JSON.getMimeType());
    httppost.setEntity(input);
    if (lg.isLoggable(Level.INFO)) {
        lg.info("Executing request to submit new user " + httppost.getRequestLine());
    }
    ResponseHandler<UserInfo> handler = new ResponseHandler<UserInfo>() {

        public UserInfo handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
            int status = response.getStatusLine().getStatusCode();
            if (status == HttpStatus.SC_CREATED) {
                HttpEntity entity = response.getEntity();
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()))) {
                    String json = reader.lines().collect(Collectors.joining());
                    UserInfo userInfo = gson.fromJson(json, UserInfo.class);
                    return userInfo;
                }
            } else {
                HttpEntity entity = response.getEntity();
                String message = null;
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()))) {
                    message = reader.lines().collect(Collectors.joining());
                }
                throw new ClientProtocolException("Unexpected response status: " + status + "\nreason: " + message);
            }
        }
    };
    UserInfo insertedUserInfo = httpclient.execute(httppost, handler, httpClientContext);
    if (lg.isLoggable(Level.INFO)) {
        lg.info("returned userinfo: " + insertedUserInfo);
    }
    return insertedUserInfo;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) ResponseHandler(org.apache.http.client.ResponseHandler) HttpEntity(org.apache.http.HttpEntity) InputStreamReader(java.io.InputStreamReader) Gson(com.google.gson.Gson) HttpResponse(org.apache.http.HttpResponse) UserInfo(org.vcell.api.common.UserInfo) ClientProtocolException(org.apache.http.client.ClientProtocolException) StringEntity(org.apache.http.entity.StringEntity) BufferedReader(java.io.BufferedReader)

Aggregations

ClientProtocolException (org.apache.http.client.ClientProtocolException)92 IOException (java.io.IOException)80 HttpResponse (org.apache.http.HttpResponse)49 HttpPost (org.apache.http.client.methods.HttpPost)37 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)30 HttpClient (org.apache.http.client.HttpClient)29 HttpGet (org.apache.http.client.methods.HttpGet)25 HttpEntity (org.apache.http.HttpEntity)23 BasicNameValuePair (org.apache.http.message.BasicNameValuePair)20 UrlEncodedFormEntity (org.apache.http.client.entity.UrlEncodedFormEntity)19 InputStreamReader (java.io.InputStreamReader)18 ArrayList (java.util.ArrayList)18 UnsupportedEncodingException (java.io.UnsupportedEncodingException)17 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)14 BufferedReader (java.io.BufferedReader)13 InputStream (java.io.InputStream)13 NameValuePair (org.apache.http.NameValuePair)13 StringEntity (org.apache.http.entity.StringEntity)12 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)11 URI (java.net.URI)10