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;
}
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;
}
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);
}
}
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;
}
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);
}
Aggregations