List of usage examples for org.apache.commons.httpclient HttpMethod releaseConnection
public abstract void releaseConnection();
From source file:org.encuestame.core.util.SocialUtils.java
/** * Get TinyUrl./*from w w w . j a v a2 s .c o m*/ * * @param string * @return * @throws HttpException * @throws IOException */ public static String getTinyUrl(String string) { String tinyUrl = string; HttpClientParams params = new HttpClientParams(); params.setConnectionManagerTimeout(EnMePlaceHolderConfigurer.getIntegerProperty("application.timeout")); params.setSoTimeout(EnMePlaceHolderConfigurer.getIntegerProperty("application.timeout")); HttpClient httpclient = new HttpClient(params); //TODO: time out?? //httpclient.setConnectionTimeout(EnMePlaceHolderConfigurer.getIntegerProperty("application.timeout")); log.debug("tiny url timeout " + EnMePlaceHolderConfigurer.getIntegerProperty("application.timeout")); //httpclient.setParams(params); HttpMethod method = new GetMethod(SocialUtils.TINY_URL); method.setQueryString(new NameValuePair[] { new NameValuePair("url", string) }); try { log.debug("tiny url execute: " + string); httpclient.executeMethod(method); tinyUrl = method.getResponseBodyAsString(); } catch (HttpException e) { log.error("HttpException " + e); tinyUrl = string; } catch (IOException e) { log.error("IOException" + e); tinyUrl = string; } finally { method.releaseConnection(); } return tinyUrl; }
From source file:org.executequery.http.spi.DefaultRemoteHttpClient.java
private void releaseMethod(HttpMethod method) { if (method != null) { method.releaseConnection(); } }
From source file:org.gbif.portal.web.download.OpenModellerFileWriter.java
/** * 1) Creates the model - polling for progress * 2) Projects the moodel - polling fro progres * 3) Downloads the generated image to a temp file * /*from w w w .j av a 2 s . c o m*/ * @see org.gbif.portal.web.download.FileWriter#writeFile() */ @Override public void writeFile() throws Exception { OmWSClientProxy omClient = new OmWSClientProxy(); omClient.setOmService(openModellerEndpoint); String soapRequest = omClient.omwsSOAPRequestUtil.getCreateModelRequest(omModel); if (logger.isDebugEnabled()) { logger.debug("Open Modeller request: " + soapRequest); } String displayRequest = omClient.omwsSOAPRequestUtil.cleanup(soapRequest, false); String omwsResponse = omClient.executeOMwsRequest(soapRequest); if (logger.isDebugEnabled()) { logger.debug("Open Modeller response: " + omwsResponse); } omClient.omwsSOAPRequestUtil.parseXMLResponseSAX(omwsResponse); OmWSSAXParser omwsSAXParser = omClient.omwsSOAPRequestUtil.getOMwsSAXParser(); String ticket = omwsSAXParser.getJobResponse(); boolean success = pollforTicket(omClient, ticket); if (!success) { logger.error("Model Generation Timeout at Create Model Stage !!!!!"); signalFileWriteFailure(); return; } //retrieve model logger.debug("Show project model request..."); omwsResponse = omClient.getModel(ticket); omClient.omwsSOAPRequestUtil.parseXMLResponseSAX(omwsResponse); omwsSAXParser = omClient.omwsSOAPRequestUtil.getOMwsSAXParser(); String modelParams = omwsSAXParser.getModelParams(); omModel.setModelParams(modelParams); soapRequest = omClient.omwsSOAPRequestUtil.getProjectModelRequest(omModel); omClient.omwsSOAPRequestUtil.cleanup(soapRequest, false); omwsResponse = omClient.executeOMwsRequest(soapRequest); omClient.omwsSOAPRequestUtil.parseXMLResponseSAX(omwsResponse); omwsSAXParser = omClient.omwsSOAPRequestUtil.getOMwsSAXParser(); ticket = omwsSAXParser.getJobResponse(); if (logger.isDebugEnabled()) { logger.debug("Ticket: " + ticket); } //poll for ticket success = pollforTicket(omClient, ticket); if (!success) { logger.error("Model Generation Timeout at Project Model Stage !!!!!"); signalFileWriteFailure(); return; } String urlStr = omClient.getLayerAsUrl(ticket); if (logger.isDebugEnabled()) { logger.debug("Generated IMG =" + urlStr); } urlStr = urlStr.substring(0, urlStr.length() - 4) + imgFileExtension; if (logger.isDebugEnabled()) { logger.debug("PNG url =" + urlStr); } HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(urlStr); int state = client.executeMethod(method); logger.debug(state); InputStream in = method.getResponseBodyAsStream(); byte[] buffer = new byte[1000]; int bytesRead = in.read(buffer); while (bytesRead > 0) { outputStream.write(buffer, 0, bytesRead); bytesRead = in.read(buffer); } method.releaseConnection(); logger.debug("Image written to file"); signalFileWriteComplete(); }
From source file:org.genemania.util.HttpRetriever.java
private String fetchPage(String url) { String ret = ""; try {/*w ww .jav a 2s.c o m*/ HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(url); int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { System.out.println("HttpRetriever error: " + method.getStatusLine()); } else { byte[] responseBody = method.getResponseBody(); method.releaseConnection(); ret = new String(responseBody); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return ret; }
From source file:org.geoserver.gss.HTTPGSSClient.java
/** * Executes the http method, checks the response status, parses the response and returns it. * Will throw an exception in case of communication errors, error codes, or service exceptions * /* www . j a v a 2 s .co m*/ * @throws IOException */ Object executeMethod(HttpMethod method) throws IOException { Object response; try { if (LOGGER.isLoggable(Level.FINE)) { if (method instanceof GetMethod) { GetMethod gm = (GetMethod) method; LOGGER.fine("Sending GET request:\n " + method.getURI()); } else if (method instanceof PostMethod) { PostMethod pm = (PostMethod) method; XMLEntity entity = (XMLEntity) pm.getRequestEntity(); String request = entity.toString(); LOGGER.fine("Sending POST request:\n " + method.getURI() + "\n" + request); // ugly, but Encoder cannot be reused, so we have to set a new entity // that uses the already generated string pm.setRequestEntity(new StringRequestEntity(request, "text/xml", "UTF-8")); } else { LOGGER.fine("Sending unknown method type : " + method); } } // plain execution int statusCode = client.executeMethod(method); // check the HTTP status if (statusCode != HttpStatus.SC_OK) { throw new IOException("HTTP client returned with code " + statusCode); } // parse the response Parser parser = new Parser(configuration); parser.setStrict(true); parser.setFailOnValidationError(true); InputStream is; if (LOGGER.isLoggable(Level.FINE)) { String responseString = method.getResponseBodyAsString(); LOGGER.log(Level.FINE, "Response from Unit:\n" + responseString); is = new ByteArrayInputStream(responseString.getBytes()); } else { is = method.getResponseBodyAsStream(); } response = parser.parse(is); } catch (Exception e) { throw (IOException) new IOException("Error occurred while executing " + "a call to the Unit") .initCause(e); } finally { method.releaseConnection(); } // convert a service exception into an IOException if necessary if (response instanceof ExceptionReportType) { ExceptionReportType report = (ExceptionReportType) response; StringBuilder sb = new StringBuilder("The Unit service reported a failure: "); for (Iterator it = report.getException().iterator(); it.hasNext();) { ExceptionType et = (ExceptionType) it.next(); for (Iterator eit = et.getExceptionText().iterator(); eit.hasNext();) { String text = (String) eit.next(); sb.append(text); if (eit.hasNext()) sb.append(". "); } } throw new IOException(sb.toString()); } return response; }
From source file:org.geoserver.security.iride.service.policy.handler.IridePolicyRequestHandler.java
/** * * @param serverURL/*w ww . ja va 2 s . c om*/ * @param params * @return * @throws IOException */ public String handleRequest(String serverURL, Map<String, Object> params) throws IOException { final String requestXml = this.createPolicyRequestXml(params); final HttpMethod requestHttpMethod = this.createPolicyRequestMethod(requestXml, serverURL); String result = ""; try { final int responseCode = this.getHttpClient().executeMethod(requestHttpMethod); final String responseXml = requestHttpMethod.getResponseBodyAsString(); if (responseCode == HttpStatus.SC_OK) { result = responseXml; } else { LOGGER.warn("IRIDE error response code: {} {}", responseCode, HttpStatus.getStatusText(responseCode)); } LOGGER.trace("IRIDE SOAP response: " + responseXml); return result; } finally { requestHttpMethod.releaseConnection(); } }
From source file:org.geoserver.wps.Execute.java
/** * Executes/* w ww. j av a 2 s .c o m*/ * * @param ref * @return */ Object executeRemoteRequest(InputReferenceType ref, ComplexPPIO ppio, String inputId) throws Exception { URL destination = new URL(ref.getHref()); HttpMethod method = null; GetMethod refMethod = null; InputStream input = null; InputStream refInput = null; // execute the request try { if ("http".equalsIgnoreCase(destination.getProtocol())) { // setup the client HttpClient client = new HttpClient(); // setting timeouts (30 seconds, TODO: make this configurable) HttpConnectionManagerParams params = new HttpConnectionManagerParams(); params.setSoTimeout(connectionTimeout); params.setConnectionTimeout(connectionTimeout); // TODO: make the http client a well behaved http client, no more than x connections // per server (x admin configurable maybe), persistent connections and so on HttpConnectionManager manager = new SimpleHttpConnectionManager(); manager.setParams(params); client.setHttpConnectionManager(manager); // prepare either a GET or a POST request if (ref.getMethod() == null || ref.getMethod() == MethodType.GET_LITERAL) { GetMethod get = new GetMethod(ref.getHref()); get.setFollowRedirects(true); method = get; } else { String encoding = ref.getEncoding(); if (encoding == null) { encoding = "UTF-8"; } PostMethod post = new PostMethod(ref.getHref()); Object body = ref.getBody(); if (body == null) { if (ref.getBodyReference() != null) { URL refDestination = new URL(ref.getBodyReference().getHref()); if ("http".equalsIgnoreCase(refDestination.getProtocol())) { // open with commons http client refMethod = new GetMethod(ref.getBodyReference().getHref()); refMethod.setFollowRedirects(true); client.executeMethod(refMethod); refInput = refMethod.getResponseBodyAsStream(); } else { // open with the built-in url management URLConnection conn = refDestination.openConnection(); conn.setConnectTimeout(connectionTimeout); conn.setReadTimeout(connectionTimeout); refInput = conn.getInputStream(); } post.setRequestEntity(new InputStreamRequestEntity(refInput, ppio.getMimeType())); } else { throw new WPSException("A POST request should contain a non empty body"); } } else if (body instanceof String) { post.setRequestEntity(new StringRequestEntity((String) body, ppio.getMimeType(), encoding)); } else { throw new WPSException("The request body should be contained in a CDATA section, " + "otherwise it will get parsed as XML instead of being preserved as is"); } method = post; } // add eventual extra headers if (ref.getHeader() != null) { for (Iterator it = ref.getHeader().iterator(); it.hasNext();) { HeaderType header = (HeaderType) it.next(); method.setRequestHeader(header.getKey(), header.getValue()); } } int code = client.executeMethod(method); if (code == 200) { input = method.getResponseBodyAsStream(); } else { throw new WPSException("Error getting remote resources from " + ref.getHref() + ", http error " + code + ": " + method.getStatusText()); } } else { // use the normal url connection methods then... URLConnection conn = destination.openConnection(); conn.setConnectTimeout(connectionTimeout); conn.setReadTimeout(connectionTimeout); input = conn.getInputStream(); } // actually parse teh data if (input != null) { return ppio.decode(input); } else { throw new WPSException("Could not find a mean to read input " + inputId); } } finally { // make sure to close the connection and streams no matter what if (input != null) { input.close(); } if (method != null) { method.releaseConnection(); } if (refMethod != null) { refMethod.releaseConnection(); } } }
From source file:org.geoserver.wps.executor.RemoteRequestInputProvider.java
@Override protected Object getValueInternal(ProgressListener listener) throws Exception { InputReferenceType ref = input.getReference(); URL destination = new URL(ref.getHref()); HttpMethod method = null; GetMethod refMethod = null;/*from ww w. j a v a2 s. c o m*/ InputStream input = null; InputStream refInput = null; // execute the request listener.started(); try { if ("file".equalsIgnoreCase(destination.getProtocol())) { File file = DataUtilities.urlToFile(destination); if (maxSize > 0 && maxSize < file.length()) { throw new WPSException("Input " + getInputId() + " size " + file.length() + " exceeds maximum allowed size of " + maxSize, "NoApplicableCode", getInputId()); } input = new FileInputStream(file); } else if ("http".equalsIgnoreCase(destination.getProtocol())) { // setup the client HttpClient client = new HttpClient(); // setting timeouts (30 seconds, TODO: make this configurable) HttpConnectionManagerParams params = new HttpConnectionManagerParams(); params.setSoTimeout(timeout); params.setConnectionTimeout(timeout); // TODO: make the http client a well behaved http client, no more than x connections // per server (x admin configurable maybe), persistent connections and so on HttpConnectionManager manager = new SimpleHttpConnectionManager(); manager.setParams(params); client.setHttpConnectionManager(manager); // prepare either a GET or a POST request if (ref.getMethod() == null || ref.getMethod() == MethodType.GET_LITERAL) { GetMethod get = new GetMethod(ref.getHref()); get.setFollowRedirects(true); method = get; } else { String encoding = ref.getEncoding(); if (encoding == null) { encoding = "UTF-8"; } PostMethod post = new PostMethod(ref.getHref()); Object body = ref.getBody(); if (body == null) { if (ref.getBodyReference() != null) { URL refDestination = new URL(ref.getBodyReference().getHref()); if ("http".equalsIgnoreCase(refDestination.getProtocol())) { // open with commons http client refMethod = new GetMethod(ref.getBodyReference().getHref()); refMethod.setFollowRedirects(true); client.executeMethod(refMethod); refInput = refMethod.getResponseBodyAsStream(); } else { // open with the built-in url management URLConnection conn = refDestination.openConnection(); conn.setConnectTimeout(timeout); conn.setReadTimeout(timeout); refInput = conn.getInputStream(); } post.setRequestEntity( new InputStreamRequestEntity(refInput, complexPPIO.getMimeType())); } else { throw new WPSException("A POST request should contain a non empty body"); } } else if (body instanceof String) { post.setRequestEntity( new StringRequestEntity((String) body, complexPPIO.getMimeType(), encoding)); } else { throw new WPSException("The request body should be contained in a CDATA section, " + "otherwise it will get parsed as XML instead of being preserved as is"); } method = post; } // add eventual extra headers if (ref.getHeader() != null) { for (Iterator it = ref.getHeader().iterator(); it.hasNext();) { HeaderType header = (HeaderType) it.next(); method.setRequestHeader(header.getKey(), header.getValue()); } } int code = client.executeMethod(method); if (code == 200) { try { Header length = method.getResponseHeader("Content-Lenght"); if (maxSize > 0 && length != null && Long.parseLong(length.getValue()) > maxSize) { throw new WPSException( "Input " + getInputId() + " size " + length.getValue() + " exceeds maximum allowed size of " + maxSize + " according to HTTP Content-Lenght response header", "NoApplicableCode", getInputId()); } } catch (NumberFormatException e) { LOGGER.log(Level.FINE, "Failed to parse content lenght to check input limits respect, " + "moving on and checking data as it comes in", e); } input = method.getResponseBodyAsStream(); if (maxSize > 0) { input = new MaxSizeInputStream(input, getInputId(), maxSize); } } else { throw new WPSException("Error getting remote resources from " + ref.getHref() + ", http error " + code + ": " + method.getStatusText()); } } else { // use the normal url connection methods then... URLConnection conn = destination.openConnection(); conn.setConnectTimeout(timeout); conn.setReadTimeout(timeout); input = conn.getInputStream(); if (maxSize > 0) { input = new MaxSizeInputStream(input, getInputId(), maxSize); } } // actually parse the data if (input != null) { CancellingInputStream is = new CancellingInputStream(input, listener); return complexPPIO.decode(is); } else { throw new WPSException("Could not find a mean to read input " + inputId); } } finally { listener.progress(100); listener.complete(); // make sure to close the connection and streams no matter what if (refInput != null) { refInput.close(); } if (input != null) { input.close(); } if (method != null) { method.releaseConnection(); } if (refMethod != null) { refMethod.releaseConnection(); } } }
From source file:org.geoserver.wps.executor.SimpleInputProvider.java
/** * Executes// w w w.j av a2 s.c o m * * @param ref * @return */ Object executeRemoteRequest(InputReferenceType ref, ComplexPPIO ppio, String inputId) throws Exception { URL destination = new URL(ref.getHref()); HttpMethod method = null; GetMethod refMethod = null; InputStream input = null; InputStream refInput = null; // execute the request try { if ("http".equalsIgnoreCase(destination.getProtocol())) { // setup the client HttpClient client = new HttpClient(); // setting timeouts (30 seconds, TODO: make this configurable) HttpConnectionManagerParams params = new HttpConnectionManagerParams(); params.setSoTimeout(executor.getConnectionTimeout()); params.setConnectionTimeout(executor.getConnectionTimeout()); // TODO: make the http client a well behaved http client, no more than x connections // per server (x admin configurable maybe), persistent connections and so on HttpConnectionManager manager = new SimpleHttpConnectionManager(); manager.setParams(params); client.setHttpConnectionManager(manager); // prepare either a GET or a POST request if (ref.getMethod() == null || ref.getMethod() == MethodType.GET_LITERAL) { GetMethod get = new GetMethod(ref.getHref()); get.setFollowRedirects(true); method = get; } else { String encoding = ref.getEncoding(); if (encoding == null) { encoding = "UTF-8"; } PostMethod post = new PostMethod(ref.getHref()); Object body = ref.getBody(); if (body == null) { if (ref.getBodyReference() != null) { URL refDestination = new URL(ref.getBodyReference().getHref()); if ("http".equalsIgnoreCase(refDestination.getProtocol())) { // open with commons http client refMethod = new GetMethod(ref.getBodyReference().getHref()); refMethod.setFollowRedirects(true); client.executeMethod(refMethod); refInput = refMethod.getResponseBodyAsStream(); } else { // open with the built-in url management URLConnection conn = refDestination.openConnection(); conn.setConnectTimeout(executor.getConnectionTimeout()); conn.setReadTimeout(executor.getConnectionTimeout()); refInput = conn.getInputStream(); } post.setRequestEntity(new InputStreamRequestEntity(refInput, ppio.getMimeType())); } else { throw new WPSException("A POST request should contain a non empty body"); } } else if (body instanceof String) { post.setRequestEntity(new StringRequestEntity((String) body, ppio.getMimeType(), encoding)); } else { throw new WPSException("The request body should be contained in a CDATA section, " + "otherwise it will get parsed as XML instead of being preserved as is"); } method = post; } // add eventual extra headers if (ref.getHeader() != null) { for (Iterator it = ref.getHeader().iterator(); it.hasNext();) { HeaderType header = (HeaderType) it.next(); method.setRequestHeader(header.getKey(), header.getValue()); } } int code = client.executeMethod(method); if (code == 200) { input = method.getResponseBodyAsStream(); } else { throw new WPSException("Error getting remote resources from " + ref.getHref() + ", http error " + code + ": " + method.getStatusText()); } } else { // use the normal url connection methods then... URLConnection conn = destination.openConnection(); conn.setConnectTimeout(executor.getConnectionTimeout()); conn.setReadTimeout(executor.getConnectionTimeout()); input = conn.getInputStream(); } // actually parse teh data if (input != null) { return ppio.decode(input); } else { throw new WPSException("Could not find a mean to read input " + inputId); } } finally { // make sure to close the connection and streams no matter what if (input != null) { input.close(); } if (method != null) { method.releaseConnection(); } if (refMethod != null) { refMethod.releaseConnection(); } } }
From source file:org.gss_project.gss.web.client.TestClient.java
public static void main(String[] args) { String user = "ebstest@grnet-hq.admin.grnet.gr"; String token = "PcxaZ/4oIqCqIvCYgsUcKr1hAFcsW40G3kcWJSRPJV5GjzoNuo8RsA=="; String host = "pithos.grnet.gr"; String restPath = "/pithos/rest"; String path = "/" + user + "/files/"; String now = DateUtil.formatDate(new Date()); String signature = sign("GET", now, path, token); HttpClient client = new HttpClient(); HostConfiguration hostconfig = new HostConfiguration(); hostconfig.setHost(host);/* w w w . j a v a2s.c om*/ HttpMethod method = new GetMethod(restPath + path); Collection<Header> headers = new ArrayList<Header>(); Header auth = new Header("Authorization", user + " " + signature); headers.add(auth); Header date = new Header("X-GSS-Date", now); headers.add(date); System.out.println(headers.toString()); hostconfig.getParams().setParameter("http.default-headers", headers); try { // Execute the method. int statusCode = client.executeMethod(hostconfig, method); if (statusCode != HttpStatus.SC_OK) System.err.println("Method failed: " + method.getStatusLine()); // Read the response body. byte[] responseBody = method.getResponseBody(); // Deal with the response. // Use caution: ensure correct character encoding and is not binary data System.out.println(new String(responseBody)); } catch (HttpException e) { System.err.println("Fatal protocol violation: " + e.getMessage()); e.printStackTrace(); } catch (IOException e) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); } finally { // Release the connection. method.releaseConnection(); } }