List of usage examples for org.apache.commons.httpclient HttpMethod releaseConnection
public abstract void releaseConnection();
From source file:org.eclipse.scada.hd.exporter.http.client.HdHttpClient.java
public List<DataPoint> getData(final String item, final String type, final Date from, final Date to, final Integer number) throws Exception { final HttpClient client = new HttpClient(); final HttpMethod method = new GetMethod( this.baseUrl + "/" + URLEncoder.encode(item, "UTF-8") + "/" + URLEncoder.encode(type, "UTF-8") + "?from=" + URLEncoder.encode(Utils.isoDateFormat.format(from), "UTF-8") + "&to=" + URLEncoder.encode(Utils.isoDateFormat.format(to), "UTF-8") + "&no=" + number); client.getParams().setSoTimeout((int) this.timeout); try {// www .java 2s . c om final int status = client.executeMethod(method); if (status != HttpStatus.SC_OK) { throw new RuntimeException("Method failed with error " + status + " " + method.getStatusLine()); } return Utils.fromJson(method.getResponseBodyAsString()); } finally { method.releaseConnection(); } }
From source file:org.eclipse.smarthome.binding.fsinternetradio.internal.radio.FrontierSiliconRadioConnection.java
/** * Perform login/establish a new session. Uses the PIN number and when successful saves the assigned sessionID for * future requests./* w ww. j av a 2s.c om*/ * * @return <code>true</code> if login was successful; <code>false</code> otherwise. * @throws IOException if communication with the radio failed, e.g. because the device is not reachable. */ public boolean doLogin() throws IOException { isLoggedIn = false; // reset login flag if (httpClient == null) { httpClient = new HttpClient(); } final String url = "http://" + hostname + ":" + port + "/fsapi/CREATE_SESSION?pin=" + pin; logger.trace("opening URL:" + url); final HttpMethod method = new GetMethod(url); method.getParams().setSoTimeout(SOCKET_TIMEOUT); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); try { final int statusCode = httpClient.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { logger.debug("Communication with radio failed: " + method.getStatusLine()); if (method.getStatusCode() == 403) { throw new RuntimeException("Radio does not allow connection, maybe wrong pin?"); } throw new IOException("Communication with radio failed, return code: " + statusCode); } final String responseBody = IOUtils.toString(method.getResponseBodyAsStream()); if (!responseBody.isEmpty()) { logger.trace("login response: " + responseBody); } final FrontierSiliconRadioApiResult result = new FrontierSiliconRadioApiResult(responseBody); if (result.isStatusOk()) { logger.trace("login successful"); sessionId = result.getSessionId(); isLoggedIn = true; return true; // login successful :-) } } catch (HttpException he) { logger.debug("Fatal protocol violation: {}", he.toString()); throw he; } catch (IOException ioe) { logger.debug("Fatal transport error: {}", ioe.toString()); throw ioe; } finally { method.releaseConnection(); } return false; // login not successful }
From source file:org.eclipse.smarthome.binding.fsinternetradio.internal.radio.FrontierSiliconRadioConnection.java
/** * Performs a request to the radio with addition parameters. * * Typically used for changing parameters. * * @param REST/* w w w.j a va 2s . co m*/ * API requestString, e.g. "SET/netRemote.sys.power" * @param params * , e.g. "value=1" * @return request result * @throws IOException if the request failed. */ public FrontierSiliconRadioApiResult doRequest(String requestString, String params) throws IOException { // 3 retries upon failure for (int i = 0; i < 2; i++) { if (!isLoggedIn && !doLogin()) { continue; // not logged in and login was not successful - try again! } final String url = "http://" + hostname + ":" + port + "/fsapi/" + requestString + "?pin=" + pin + "&sid=" + sessionId + (params == null || params.trim().length() == 0 ? "" : "&" + params); logger.trace("calling url: '" + url + "'"); final HttpMethod method = new GetMethod(url); method.getParams().setSoTimeout(SOCKET_TIMEOUT); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(2, false)); try { final int statusCode = httpClient.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { logger.warn("Method failed: " + method.getStatusLine()); isLoggedIn = false; method.releaseConnection(); continue; } final String responseBody = IOUtils.toString(method.getResponseBodyAsStream()); if (!responseBody.isEmpty()) { logger.trace("got result: " + responseBody); } else { logger.debug("got empty result"); isLoggedIn = false; method.releaseConnection(); continue; } final FrontierSiliconRadioApiResult result = new FrontierSiliconRadioApiResult(responseBody); if (result.isStatusOk()) { return result; } isLoggedIn = false; method.releaseConnection(); continue; // try again } catch (HttpException he) { logger.error("Fatal protocol violation: {}", he.toString()); isLoggedIn = false; throw he; } catch (IOException ioe) { logger.error("Fatal transport error: {}", ioe.toString()); throw ioe; } finally { method.releaseConnection(); } } isLoggedIn = false; // 3 tries failed. log in again next time, maybe our session went invalid (radio restarted?) return null; }
From source file:org.eclipse.smarthome.io.net.http.HttpUtil.java
/** * Executes the given <code>url</code> with the given <code>httpMethod</code> * /*from w w w . j ava2s .c o m*/ * @param httpMethod the HTTP method to use * @param url the url to execute (in milliseconds) * @param httpHeaders optional HTTP headers which has to be set on request * @param content the content to be send to the given <code>url</code> or * <code>null</code> if no content should be send. * @param contentType the content type of the given <code>content</code> * @param timeout the socket timeout to wait for data * @param proxyHost the hostname of the proxy * @param proxyPort the port of the proxy * @param proxyUser the username to authenticate with the proxy * @param proxyPassword the password to authenticate with the proxy * @param nonProxyHosts the hosts that won't be routed through the proxy * @return the response body or <code>NULL</code> when the request went wrong */ public static String executeUrl(String httpMethod, String url, Properties httpHeaders, InputStream content, String contentType, int timeout, String proxyHost, Integer proxyPort, String proxyUser, String proxyPassword, String nonProxyHosts) { HttpClient client = new HttpClient(); // only configure a proxy if a host is provided if (StringUtils.isNotBlank(proxyHost) && proxyPort != null && shouldUseProxy(url, nonProxyHosts)) { client.getHostConfiguration().setProxy(proxyHost, proxyPort); if (StringUtils.isNotBlank(proxyUser)) { client.getState().setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials(proxyUser, proxyPassword)); } } HttpMethod method = HttpUtil.createHttpMethod(httpMethod, url); method.getParams().setSoTimeout(timeout); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); if (httpHeaders != null) { for (String httpHeaderKey : httpHeaders.stringPropertyNames()) { method.addRequestHeader(new Header(httpHeaderKey, httpHeaders.getProperty(httpHeaderKey))); } } // add content if a valid method is given ... if (method instanceof EntityEnclosingMethod && content != null) { EntityEnclosingMethod eeMethod = (EntityEnclosingMethod) method; eeMethod.setRequestEntity(new InputStreamRequestEntity(content, contentType)); } Credentials credentials = extractCredentials(url); if (credentials != null) { client.getParams().setAuthenticationPreemptive(true); client.getState().setCredentials(AuthScope.ANY, credentials); } if (logger.isDebugEnabled()) { try { logger.debug("About to execute '" + method.getURI().toString() + "'"); } catch (URIException e) { logger.debug(e.getMessage()); } } try { int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { logger.warn("Method failed: " + method.getStatusLine()); } String responseBody = IOUtils.toString(method.getResponseBodyAsStream()); if (!responseBody.isEmpty()) { logger.debug(responseBody); } return responseBody; } catch (HttpException he) { logger.error("Fatal protocol violation: {}", he.toString()); } catch (IOException ioe) { logger.error("Fatal transport error: {}", ioe.toString()); } finally { method.releaseConnection(); } return null; }
From source file:org.eclipse.swordfish.internal.resolver.backend.base.impl.HttpClientProxy.java
private ClientResponse doInvoke(ClientRequest request) { ClientResponse response = RegistryProxyFactory.getInstance().createResponse(); HttpMethod method = getMethod(request.getMethod()); try {/*from w w w .j a v a2 s . c om*/ String escapedRequestUrl = request.getURI().toASCIIString(); HttpURL requestUrl = new HttpURL(escapedRequestUrl.toCharArray()); if (request.getProperties() != null) { Map<String, String> properties = request.getProperties(); String[] queryNames = properties.keySet().toArray(new String[0]); String[] queryValues = properties.values().toArray(new String[0]); requestUrl.setQuery(queryNames, queryValues); } method.setURI(requestUrl); int statusCode = getClient().executeMethod(method); response.setStatus(Status.get(statusCode)); String responseBody = method.getResponseBodyAsString(); if (request.getEntityType() != null) { response.setEntity(mapResponse(responseBody, request.getEntityType())); } else { response.setEntity(responseBody); } } catch (HttpException e) { LOG.error("Couldn't perform call to registry: ", e); response.setStatus(Status.ERROR); response.setEntity(e); } catch (IOException e) { LOG.error("Couldn't perform call to registry: ", e); response.setStatus(Status.ERROR); response.setEntity(e); } finally { if (method != null) { method.releaseConnection(); } } return response; }
From source file:org.eclipse.virgo.qa.performance.UrlWaitLatch.java
private static void wait(String url, HttpClient client, long interval, long duration) { HttpMethod get = new GetMethod(url); try {/*from www. j av a 2 s.c om*/ long startTime = System.currentTimeMillis(); int statusCode = 999; while (System.currentTimeMillis() - startTime < duration) { try { statusCode = client.executeMethod(get); if (statusCode < 400) { return; } } catch (ConnectException e) { // Swallow this and retry } Thread.sleep(interval); } fail(String.format("After %d ms, status code was %d", duration, statusCode)); } catch (Exception e) { throw new RuntimeException(e); } finally { get.releaseConnection(); } }
From source file:org.eclipse.virgo.qa.performance.UrlWaitLatch.java
private static void waitForNotExistence(String url, HttpClient client, long interval, long duration) { HttpMethod get = new GetMethod(url); try {/*from www . j av a2 s . c o m*/ long startTime = System.currentTimeMillis(); int statusCode = 100; while (System.currentTimeMillis() - startTime < duration) { try { statusCode = client.executeMethod(get); if (statusCode > 400) { return; } } catch (ConnectException e) { // Swallow this and retry } Thread.sleep(interval); } fail(String.format("After %d ms, status code was %d", duration, statusCode)); } catch (Exception e) { throw new RuntimeException(e); } finally { get.releaseConnection(); } }
From source file:org.eclipse.virgo.qa.performance.UrlWaitLatch.java
private static void waitForServerShutdownFully(String url, HttpClient client, long interval, long duration) { HttpMethod get = new GetMethod(url); try {//from w w w . j ava 2 s . c om for (;;) { try { client.executeMethod(get); Thread.sleep(interval); } catch (ConnectException e) { break; } catch (Exception e) { e.printStackTrace(); } } } finally { get.releaseConnection(); } }
From source file:org.eclipse.virgo.server.smoketest.UrlWaitLatch.java
private static void wait(String url, HttpClient client, long interval, long duration) { HttpMethod get = new GetMethod(url); try {/*from w w w .j a v a 2s.c o m*/ long startTime = System.currentTimeMillis(); int statusCode = 999; while (System.currentTimeMillis() - startTime < duration) { statusCode = client.executeMethod(get); if (statusCode < 400) { return; } Thread.sleep(interval); } fail(String.format("After %d ms, status code was %d", duration, statusCode)); } catch (Exception e) { throw new RuntimeException(e); } finally { get.releaseConnection(); } }
From source file:org.eclipse.winery.highlevelrestapi.LowLevelRestApi.java
/** * Executes a passed HttpMethod (Method type is either PUT, POST, GET or * DELETE) and returns a HttpResponseMessage * /*from w w w. j av a 2s.c om*/ * @param method Method to execute * @return HttpResponseMessage which contains all information about the * execution */ public static HttpResponseMessage executeHttpMethod(HttpMethod method) { HttpResponseMessage responseMessage = null; try { System.out.println("Method invocation on URI: \n"); System.out.println(method.getURI().toString()); // Execute Request LowLevelRestApi.httpClient.executeMethod(method); responseMessage = LowLevelRestApi.extractResponseInformation(method); } catch (Exception e) { e.printStackTrace(); } finally { // Release Connection anyway method.releaseConnection(); } // Extract response information and return return responseMessage; }