Search in sources :

Example 36 with ClientProtocolException

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

the class HypervDirectConnectResource method postHttpRequest.

public static String postHttpRequest(final String jsonCmd, final URI agentUri) {
    // Using Apache's HttpClient for HTTP POST
    // Java-only approach discussed at on StackOverflow concludes with
    // comment to use Apache HttpClient
    // http://stackoverflow.com/a/2793153/939250, but final comment is to
    // use Apache.
    String logMessage = StringEscapeUtils.unescapeJava(jsonCmd);
    logMessage = cleanPassword(logMessage);
    s_logger.debug("POST request to " + agentUri.toString() + " with contents " + logMessage);
    // Create request
    HttpClient httpClient = null;
    final TrustStrategy easyStrategy = new TrustStrategy() {

        @Override
        public boolean isTrusted(final X509Certificate[] chain, final String authType) throws CertificateException {
            return true;
        }
    };
    try {
        final SSLSocketFactory sf = new SSLSocketFactory(easyStrategy, new AllowAllHostnameVerifier());
        final SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("https", DEFAULT_AGENT_PORT, sf));
        final ClientConnectionManager ccm = new BasicClientConnectionManager(registry);
        httpClient = new DefaultHttpClient(ccm);
    } catch (final KeyManagementException e) {
        s_logger.error("failed to initialize http client " + e.getMessage());
    } catch (final UnrecoverableKeyException e) {
        s_logger.error("failed to initialize http client " + e.getMessage());
    } catch (final NoSuchAlgorithmException e) {
        s_logger.error("failed to initialize http client " + e.getMessage());
    } catch (final KeyStoreException e) {
        s_logger.error("failed to initialize http client " + e.getMessage());
    }
    String result = null;
    // TODO: are there timeout settings and worker thread settings to tweak?
    try {
        final HttpPost request = new HttpPost(agentUri);
        // JSON encode command
        // Assumes command sits comfortably in a string, i.e. not used for
        // large data transfers
        final StringEntity cmdJson = new StringEntity(jsonCmd);
        request.addHeader("content-type", "application/json");
        request.setEntity(cmdJson);
        s_logger.debug("Sending cmd to " + agentUri.toString() + " cmd data:" + logMessage);
        final HttpResponse response = httpClient.execute(request);
        // Unsupported commands will not route.
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
            final String errMsg = "Failed to send : HTTP error code : " + response.getStatusLine().getStatusCode();
            s_logger.error(errMsg);
            final String unsupportMsg = "Unsupported command " + agentUri.getPath() + ".  Are you sure you got the right type of" + " server?";
            final Answer ans = new UnsupportedAnswer(null, unsupportMsg);
            s_logger.error(ans);
            result = s_gson.toJson(new Answer[] { ans });
        } else if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            final String errMsg = "Failed send to " + agentUri.toString() + " : HTTP error code : " + response.getStatusLine().getStatusCode();
            s_logger.error(errMsg);
            return null;
        } else {
            result = EntityUtils.toString(response.getEntity());
            final String logResult = cleanPassword(StringEscapeUtils.unescapeJava(result));
            s_logger.debug("POST response is " + logResult);
        }
    } catch (final ClientProtocolException protocolEx) {
        // Problem with HTTP message exchange
        s_logger.error(protocolEx);
    } catch (final IOException connEx) {
        // Problem with underlying communications
        s_logger.error(connEx);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
    return result;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) TrustStrategy(org.apache.http.conn.ssl.TrustStrategy) Scheme(org.apache.http.conn.scheme.Scheme) AllowAllHostnameVerifier(org.apache.http.conn.ssl.AllowAllHostnameVerifier) HttpResponse(org.apache.http.HttpResponse) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStoreException(java.security.KeyStoreException) IOException(java.io.IOException) BasicClientConnectionManager(org.apache.http.impl.conn.BasicClientConnectionManager) ClientConnectionManager(org.apache.http.conn.ClientConnectionManager) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) KeyManagementException(java.security.KeyManagementException) ClientProtocolException(org.apache.http.client.ClientProtocolException) StringEntity(org.apache.http.entity.StringEntity) UnsupportedAnswer(com.cloud.agent.api.UnsupportedAnswer) CheckSshAnswer(com.cloud.agent.api.check.CheckSshAnswer) GetDomRVersionAnswer(com.cloud.agent.api.GetDomRVersionAnswer) CheckS2SVpnConnectionsAnswer(com.cloud.agent.api.CheckS2SVpnConnectionsAnswer) SetPortForwardingRulesAnswer(com.cloud.agent.api.routing.SetPortForwardingRulesAnswer) SetSourceNatAnswer(com.cloud.agent.api.routing.SetSourceNatAnswer) PlugNicAnswer(com.cloud.agent.api.PlugNicAnswer) GetVmConfigAnswer(com.cloud.agent.api.GetVmConfigAnswer) NetworkUsageAnswer(com.cloud.agent.api.NetworkUsageAnswer) Answer(com.cloud.agent.api.Answer) UnPlugNicAnswer(com.cloud.agent.api.UnPlugNicAnswer) SetStaticNatRulesAnswer(com.cloud.agent.api.routing.SetStaticNatRulesAnswer) IpAssocAnswer(com.cloud.agent.api.routing.IpAssocAnswer) SetFirewallRulesAnswer(com.cloud.agent.api.routing.SetFirewallRulesAnswer) CheckRouterAnswer(com.cloud.agent.api.CheckRouterAnswer) SetStaticRouteAnswer(com.cloud.agent.api.routing.SetStaticRouteAnswer) UnsupportedAnswer(com.cloud.agent.api.UnsupportedAnswer) UnrecoverableKeyException(java.security.UnrecoverableKeyException) HttpClient(org.apache.http.client.HttpClient) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) SchemeRegistry(org.apache.http.conn.scheme.SchemeRegistry) BasicClientConnectionManager(org.apache.http.impl.conn.BasicClientConnectionManager) SSLSocketFactory(org.apache.http.conn.ssl.SSLSocketFactory)

Example 37 with ClientProtocolException

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

the class NexentaNmsClient method execute.

public NmsResponse execute(Class responseClass, String object, String method, Object... params) {
    StringBuilder sb = new StringBuilder();
    NmsRequest nmsRequest = new NmsRequest(object, method, params);
    if (logger.isDebugEnabled()) {
        logger.debug(nmsRequest);
    }
    final Gson gson = new Gson();
    String jsonRequest = gson.toJson(nmsRequest);
    StringEntity input = new StringEntity(jsonRequest, ContentType.APPLICATION_JSON);
    HttpPost postRequest = new HttpPost(nmsUrl.toString());
    postRequest.setEntity(input);
    DefaultHttpClient httpClient = getClient();
    try {
        HttpResponse response = httpClient.execute(postRequest);
        final int status = response.getStatusLine().getStatusCode();
        if (!isSuccess(status)) {
            throw new CloudRuntimeException("Failed on JSON-RPC API call. HTTP error code = " + status);
        }
        try (BufferedReader buffer = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))) {
            String tmp;
            while ((tmp = buffer.readLine()) != null) {
                sb.append(tmp);
            }
        } catch (IOException ex) {
            throw new CloudRuntimeException(ex.getMessage());
        }
    } catch (ClientProtocolException ex) {
        throw new CloudRuntimeException(ex.getMessage());
    } catch (IOException ex) {
        throw new CloudRuntimeException(ex.getMessage());
    } finally {
        if (httpClient != null) {
            try {
                httpClient.getConnectionManager().shutdown();
            } catch (Exception t) {
                logger.debug(t.getMessage());
            }
        }
    }
    String responseString = sb.toString();
    if (logger.isDebugEnabled()) {
        logger.debug("NexentaStor Appliance response: " + responseString);
    }
    NmsResponse nmsResponse = (NmsResponse) gson.fromJson(responseString, responseClass);
    if (nmsResponse.getError() != null) {
        throw new CloudRuntimeException(nmsResponse.getError().getMesssage());
    }
    return nmsResponse;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) InputStreamReader(java.io.InputStreamReader) Gson(com.google.gson.Gson) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) ClientProtocolException(org.apache.http.client.ClientProtocolException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) IOException(java.io.IOException) KeyManagementException(java.security.KeyManagementException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ClientProtocolException(org.apache.http.client.ClientProtocolException) StringEntity(org.apache.http.entity.StringEntity) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) BufferedReader(java.io.BufferedReader)

Example 38 with ClientProtocolException

use of org.apache.http.client.ClientProtocolException in project indy by Commonjava.

the class IndyClientHttp method putWithStream.

public void putWithStream(final String path, final InputStream stream, final int... responseCodes) throws IndyClientException {
    connect();
    final HttpPut put = newRawPut(buildUrl(baseUrl, path));
    final CloseableHttpClient client = newClient();
    CloseableHttpResponse response = null;
    try {
        put.setEntity(new InputStreamEntity(stream));
        response = client.execute(put, newContext());
        final StatusLine sl = response.getStatusLine();
        if (!validResponseCode(sl.getStatusCode(), responseCodes)) {
            throw new ClientProtocolException(new IndyClientException(sl.getStatusCode(), "Error in response from: %s.\n%s", path, new IndyResponseErrorDetails(response)));
        }
    } catch (final ClientProtocolException e) {
        final Throwable cause = e.getCause();
        if (cause != null && (cause instanceof IndyClientException)) {
            throw (IndyClientException) cause;
        }
        throw new IndyClientException("Indy request failed: %s", e, e.getMessage());
    } catch (final IOException e) {
        throw new IndyClientException("Indy request failed: %s", e, e.getMessage());
    } finally {
        cleanupResources(put, response, client);
    }
}
Also used : StatusLine(org.apache.http.StatusLine) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) IOException(java.io.IOException) HttpPut(org.apache.http.client.methods.HttpPut) InputStreamEntity(org.apache.http.entity.InputStreamEntity) ClientProtocolException(org.apache.http.client.ClientProtocolException)

Example 39 with ClientProtocolException

use of org.apache.http.client.ClientProtocolException in project galley by Commonjava.

the class AbstractHttpJob method executeHttp.

protected boolean executeHttp() throws TransferException {
    try {
        client = http.createClient(location);
        response = client.execute(request, http.createContext(location));
        final StatusLine line = response.getStatusLine();
        final int sc = line.getStatusCode();
        logger.debug("{} {} : {}", request.getMethod(), line, url);
        if (!successStatuses.contains(sc)) {
            logger.debug("Detected failure response: " + sc);
            success = TransferResponseUtils.handleUnsuccessfulResponse(request, response, location, url);
            logger.debug("Returning non-error failure response for code: " + sc);
            return false;
        }
    } catch (final NoHttpResponseException e) {
        throw new TransferTimeoutException(location, url, "Repository remote request failed for: {}. Reason: {}", e, url, e.getMessage());
    } catch (final ConnectTimeoutException e) {
        throw new TransferTimeoutException(location, url, "Repository remote request failed for: {}. Reason: {}", e, url, e.getMessage());
    } catch (final SocketTimeoutException e) {
        throw new TransferTimeoutException(location, url, "Repository remote request failed for: {}. Reason: {}", e, url, e.getMessage());
    } catch (final ClientProtocolException e) {
        throw new TransferLocationException(location, "Repository remote request failed for: {}. Reason: {}", e, url, e.getMessage());
    } catch (BadGatewayException e) {
        throw e;
    } catch (final GalleyException e) {
        throw new TransferException("Repository remote request failed for: {}. Reason: {}", e, url, e.getMessage());
    } catch (final IOException e) {
        throw new TransferLocationException(location, "Repository remote request failed for: {}. Reason: {}", e, url, e.getMessage());
    } finally {
        /*
            * we need to integrate the writeMetadata() method into the executeHttp() call in a finally block,
            * and with a condition that it only runs on HEAD or GET. This would allow us to capture metadata on failed requests too,
            * which is critical for responding consistently to the user after a failed request is cached in the NFC.
            */
        String method = request.getMethod();
        if ("GET".equalsIgnoreCase(method) || "HEAD".equalsIgnoreCase(method)) {
            Transfer target = getTransfer();
            ObjectMapper mapper = getMetadataObjectMapper();
            if (target != null && mapper != null) {
                writeMetadata(target, mapper);
            }
        }
    }
    return true;
}
Also used : NoHttpResponseException(org.apache.http.NoHttpResponseException) TransferTimeoutException(org.commonjava.maven.galley.TransferTimeoutException) IOException(java.io.IOException) GalleyException(org.commonjava.maven.galley.GalleyException) ClientProtocolException(org.apache.http.client.ClientProtocolException) StatusLine(org.apache.http.StatusLine) TransferException(org.commonjava.maven.galley.TransferException) SocketTimeoutException(java.net.SocketTimeoutException) Transfer(org.commonjava.maven.galley.model.Transfer) BadGatewayException(org.commonjava.maven.galley.BadGatewayException) TransferLocationException(org.commonjava.maven.galley.TransferLocationException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException)

Example 40 with ClientProtocolException

use of org.apache.http.client.ClientProtocolException in project Gargoyle by callakrsos.

the class RequestUtilTest method testRequest200.

/**
	 * Test method for
	 * {@link com.kyj.fx.voeditor.visual.util.RequestUtil#request200(java.net.URL, java.util.function.BiFunction, boolean)}
	 * .
	 *
	 * @throws Exception
	 * @throws MalformedURLException
	 */
@Test
public final void testRequest200() throws MalformedURLException, Exception {
    FileMoveSVO svo = new FileMoveSVO();
    FileMoveDVO fileMoveDVO = new FileMoveDVO();
    fileMoveDVO.setSrcFile(new File("C:\\Users\\KYJ\\내자료\\src").getAbsolutePath());
    fileMoveDVO.setDstFile(new File("C:\\Users\\KYJ\\내자료\\dst").getAbsolutePath());
    svo.setFileMoveDVO(fileMoveDVO);
    JSONObject jsonObject = new JSONObject(svo);
    System.out.println(jsonObject.toString());
    CloseableHttpClient build = HttpClientBuilder.create().build();
    HttpPost httpPost = new HttpPost("http://localhost:8100/filemove");
    httpPost.addHeader("content-type", "application/json");
    // StringEntity stringEntity = new StringEntity();
    StringEntity requestEntity = new StringEntity(jsonObject.toString(), "application/json", "UTF-8");
    // stringEntity.setContentType("application/json; charset=UTF-8");
    // stringEntity.setContentEncoding("UTF-8");
    httpPost.setEntity(requestEntity);
    String execute = build.execute(httpPost, new ResponseHandler<String>() {

        @Override
        public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
            int statusCode = response.getStatusLine().getStatusCode();
            if (200 == statusCode) {
                return ValueUtil.toString(response.getEntity().getContent());
            }
            System.out.println("res code invalide " + statusCode);
            return "";
        }
    });
    System.out.println(execute);
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpPost(org.apache.http.client.methods.HttpPost) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) ClientProtocolException(org.apache.http.client.ClientProtocolException) StringEntity(org.apache.http.entity.StringEntity) JSONObject(org.json.JSONObject) File(java.io.File) Test(org.junit.Test)

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