List of usage examples for org.apache.commons.httpclient HttpMethod releaseConnection
public abstract void releaseConnection();
From source file:net.sourceforge.squirrel_sql.fw.util.IOUtilitiesImpl.java
/** * @see net.sourceforge.squirrel_sql.fw.util.IOUtilities# downloadHttpFile(java.lang.String, int, * java.lang.String, net.sourceforge.squirrel_sql.fw.util.FileWrapper) */// ww w .j a va 2 s .co m public int downloadHttpFile(URL url, FileWrapper destFile, IProxySettings proxySettings) throws IOException { BufferedInputStream is = null; HttpMethod method = null; int resultCode = -1; int result = -1; try { if (s_log.isDebugEnabled()) { s_log.debug("downloadHttpFile: downloading file (" + destFile.getName() + ") from url: " + url); } HttpClient client = new HttpClient(); setupProxy(proxySettings, client, url); method = new GetMethod(url.toString()); method.setFollowRedirects(true); resultCode = client.executeMethod(method); if (s_log.isDebugEnabled()) { s_log.debug("downloadHttpFile: response code was: " + resultCode); } if (resultCode != 200) { throw new FileNotFoundException( "Failed to download file from url (" + url + "): HTTP Response Code=" + resultCode); } InputStream mis = method.getResponseBodyAsStream(); is = new BufferedInputStream(mis); if (s_log.isDebugEnabled()) { s_log.debug("downloadHttpFile: writing http response body to file: " + destFile.getAbsolutePath()); } result = copyBytesToFile(mis, destFile); } catch (IOException e) { s_log.error("downloadHttpFile: Unexpected exception while " + "attempting to open an HTTP connection to url (" + url + ") to download a file (" + destFile.getAbsolutePath() + "): " + e.getMessage(), e); throw e; } finally { closeInputStream(is); method.releaseConnection(); } return result; }
From source file:nl.b3p.viewer.image.ImageCollector.java
/** * Load the image with a http-get//from www . ja v a 2 s.c o m * @param url The url to the image * @param user username * @param pass password * @return The image * @throws IOException * @throws Exception */ protected BufferedImage loadImage(String url, String user, String pass) throws IOException, Exception { HttpMethod method = null; try { method = new GetMethod(url); int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { throw new Exception("Error connecting to server. HTTP status code: " + statusCode); } String mime = method.getResponseHeader("Content-Type").getValue(); return ImageTool.readImage(method, mime); } finally { if (method != null) { method.releaseConnection(); } } }
From source file:nl.nn.adapterframework.http.HttpSender.java
public String sendMessageWithTimeoutGuarded(String correlationID, String message, ParameterResolutionContext prc) throws SenderException, TimeOutException { ParameterValueList pvl = null;// w w w . j a v a 2 s .co m try { if (prc != null && paramList != null) { pvl = prc.getValues(paramList); } } catch (ParameterException e) { throw new SenderException( getLogPrefix() + "Sender [" + getName() + "] caught exception evaluating parameters", e); } URI uri; HttpMethod httpmethod; HostConfiguration hostconfiguration = new HostConfiguration(hostconfigurationBase); try { if (urlParameter != null) { String url = (String) pvl.getParameterValue(getUrlParam()).getValue(); uri = getURI(url); } else { uri = staticUri; } Map<String, String> headersParamsMap = new HashMap<String, String>(); if (headersParams != null) { StringTokenizer st = new StringTokenizer(headersParams, ","); while (st.hasMoreElements()) { headersParamsMap.put(st.nextToken(), null); } } if (!isParamsInUrl()) { httpmethod = getPostMethodWithParamsInBody(uri, message, pvl, headersParamsMap, prc); } else { httpmethod = getMethod(uri, message, pvl, headersParamsMap); if (!"POST".equals(getMethodType()) && !"PUT".equals(getMethodType()) && !"REPORT".equals(getMethodType())) { httpmethod.setFollowRedirects(isFollowRedirects()); } } int port = getPort(uri); if (socketfactory != null && "https".equals(uri.getScheme())) { Protocol authhttps = new Protocol(uri.getScheme(), socketfactory, port); hostconfiguration.setHost(uri.getHost(), port, authhttps); } else { hostconfiguration.setHost(uri.getHost(), port, uri.getScheme()); } log.info(getLogPrefix() + "configured httpclient for host [" + hostconfiguration.getHostURL() + "]"); if (credentials != null) { httpState.setCredentials(null, uri.getHost(), credentials); } } catch (URIException e) { throw new SenderException(e); } String result = null; int statusCode = -1; int count = getMaxExecuteRetries(); String msg = null; while (count-- >= 0 && statusCode == -1) { try { if (log.isDebugEnabled()) log.debug(getLogPrefix() + "executing method"); statusCode = httpclient.executeMethod(hostconfiguration, httpmethod, httpState); if (log.isDebugEnabled()) log.debug(getLogPrefix() + "executed method"); if (statusCode != HttpServletResponse.SC_OK) { StatusLine statusline = httpmethod.getStatusLine(); if (statusline != null) { log.warn(getLogPrefix() + "status [" + statusline.toString() + "]"); } else { log.warn(getLogPrefix() + "no statusline found"); } } else { if (log.isDebugEnabled()) log.debug(getLogPrefix() + "status [" + statusCode + "]"); } HttpServletResponse response = null; if (isStreamResultToServlet()) { response = (HttpServletResponse) prc.getSession().get("restListenerServletResponse"); } String fileName = null; if (StringUtils.isNotEmpty(getStreamResultToFileNameSessionKey())) { fileName = (String) prc.getSession().get(getStreamResultToFileNameSessionKey()); } result = extractResult(httpmethod, prc, response, fileName); if (log.isDebugEnabled()) log.debug(getLogPrefix() + "retrieved result [" + result + "]"); } catch (HttpException e) { Throwable throwable = e.getCause(); String cause = null; if (throwable != null) { cause = throwable.toString(); } msg = e.getMessage(); log.warn(getLogPrefix() + "httpException with message [" + msg + "] and cause [" + cause + "], executeRetries left [" + count + "]"); } catch (IOException e) { httpmethod.abort(); if (e instanceof SocketTimeoutException) { throw new TimeOutException(e); } throw new SenderException(e); } finally { // In case of storeResultAsStreamInSessionKey release connection // is done by ReleaseConnectionAfterReadInputStream. if (StringUtils.isEmpty(getStoreResultAsStreamInSessionKey())) { httpmethod.releaseConnection(); } } } if (statusCode == -1) { if (StringUtils.contains(msg.toUpperCase(), "TIMEOUTEXCEPTION")) { //java.net.SocketTimeoutException: Read timed out throw new TimeOutException("Failed to recover from timeout exception"); } throw new SenderException("Failed to recover from exception"); } if (isXhtml() && StringUtils.isNotEmpty(result)) { result = XmlUtils.skipDocTypeDeclaration(result.trim()); if (result.startsWith("<html>") || result.startsWith("<html ")) { CleanerProperties props = new CleanerProperties(); HtmlCleaner cleaner = new HtmlCleaner(props); TagNode tagNode = cleaner.clean(result); result = new SimpleXmlSerializer(props).getXmlAsString(tagNode); if (transformerPool != null) { log.debug(getLogPrefix() + " transforming result [" + result + "]"); ParameterResolutionContext prc_xslt = new ParameterResolutionContext(result, null, true, true); try { result = transformerPool.transform(prc_xslt.getInputSource(), null); } catch (Exception e) { throw new SenderException("Exception on transforming input", e); } } } } return result; }
From source file:oauth.signpost.commonshttp3.CommonsHttp3OAuthProvider.java
@Override protected void closeConnection(HttpRequest request, oauth.signpost.http.HttpResponse response) throws Exception { if (response != null) { HttpMethod method = (HttpMethod) response.unwrap(); if (method != null) { method.releaseConnection(); }//ww w .j ava 2 s . c o m } }
From source file:org.ado.picasa.FileDownloader.java
public String downloader(String downloadLocation, String filename) throws Exception { if (downloadLocation.trim().equals("")) { throw new Exception("The element you have specified does not link to anything!"); }/*from ww w. ja va2s . co m*/ URL downloadURL = new URL(downloadLocation); HttpClient client = new HttpClient(); client.getParams().setCookiePolicy(CookiePolicy.RFC_2965); client.setHostConfiguration(mimicHostConfiguration(downloadURL.getHost(), downloadURL.getPort())); client.setState(mimicCookieState(driver.manage().getCookies())); HttpMethod getRequest = new GetMethod(downloadURL.getPath()); FileHandler downloadedFile; if (StringUtils.isNotBlank(filename)) { downloadedFile = new FileHandler(downloadPath + "/" + filename, true); } else { downloadedFile = new FileHandler(downloadPath + "/" + downloadURL.getFile().replaceFirst("/|\\\\", ""), true); } try { int status = client.executeMethod(getRequest); System.out.println( String.format("HTTP Status %d when getting '%s'", status, downloadURL.toExternalForm())); BufferedInputStream in = new BufferedInputStream(getRequest.getResponseBodyAsStream()); int offset = 0; int len = 4096; int bytes = 0; byte[] block = new byte[len]; while ((bytes = in.read(block, offset, len)) > -1) { downloadedFile.getWritableFileOutputStream().write(block, 0, bytes); } downloadedFile.close(); in.close(); System.out.println(String.format("File downloaded to '%s'", downloadedFile.getAbsoluteFile())); } catch (Exception e) { throw new Exception("Download failed!"); } finally { getRequest.releaseConnection(); } return downloadedFile.getAbsoluteFile(); }
From source file:org.agnitas.dao.impl.VersionControlDaoImpl.java
private String fetchServerVersion(String currentVersion, String referrer) { HttpClient client = new HttpClient(); client.setConnectionTimeout(CONNECTION_TIMEOUT); HttpMethod method = new GetMethod(URL); method.setRequestHeader("referer", referrer); NameValuePair[] queryParams = new NameValuePair[1]; queryParams[0] = new NameValuePair(VERSION_KEY, currentVersion); method.setQueryString(queryParams);// w w w . j av a 2s . c om method.setFollowRedirects(true); String responseBody = null; try { client.executeMethod(method); responseBody = method.getResponseBodyAsString(); } catch (Exception he) { logger.error("HTTP error connecting to '" + URL + "'", he); } //clean up the connection resources method.releaseConnection(); return responseBody; }
From source file:org.ala.spatial.util.UploadSpatialResource.java
/** * sends a PUT or POST call to a URL using authentication and including a * file upload/*from ww w . ja v a2 s . co m*/ * * @param type one of UploadSpatialResource.PUT for a PUT call or * UploadSpatialResource.POST for a POST call * @param url URL for PUT/POST call * @param username account username for authentication * @param password account password for authentication * @param resourcepath local path to file to upload, null for no file to * upload * @param contenttype file MIME content type * @return server response status code as String or empty String if * unsuccessful */ public static String httpCall(int type, String url, String username, String password, String resourcepath, String contenttype) { String output = ""; HttpClient client = new HttpClient(); client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password)); RequestEntity entity = null; if (resourcepath != null) { File input = new File(resourcepath); entity = new FileRequestEntity(input, contenttype); } HttpMethod call = null; ; if (type == PUT) { PutMethod put = new PutMethod(url); put.setDoAuthentication(true); if (entity != null) { put.setRequestEntity(entity); } call = put; } else if (type == POST) { PostMethod post = new PostMethod(url); if (entity != null) { post.setRequestEntity(entity); } call = post; } else { SpatialLogger.log("UploadSpatialResource", "invalid type: " + type); return output; } // Execute the request try { int result = client.executeMethod(call); output += result; } catch (Exception e) { SpatialLogger.log("UploadSpatialResource", "failed upload to: " + url); } finally { // Release current connection to the connection pool once you are done call.releaseConnection(); } return output; }
From source file:org.alfresco.repo.transfer.HttpClientTransmitterImpl.java
public void verifyTarget(TransferTarget target) throws TransferException { HttpMethod verifyRequest = getPostMethod(); try {//from ww w .ja v a2 s.c o m HostConfiguration hostConfig = getHostConfig(target); HttpState httpState = getHttpState(target); verifyRequest.setPath(target.getEndpointPath() + "/test"); try { int response = httpClient.executeMethod(hostConfig, verifyRequest, httpState); checkResponseStatus("verifyTarget", response, verifyRequest); } catch (RuntimeException e) { throw e; } catch (Exception e) { String error = "Failed to execute HTTP request to target"; log.debug(error, e); throw new TransferException(MSG_HTTP_REQUEST_FAILED, new Object[] { "verifyTraget", target.toString(), e.toString() }, e); } } finally { verifyRequest.releaseConnection(); } }
From source file:org.alfresco.repo.transfer.HttpClientTransmitterImpl.java
public void abort(Transfer transfer) throws TransferException { TransferTarget target = transfer.getTransferTarget(); HttpMethod abortRequest = getPostMethod(); try {// ww w . ja va 2s.c o m HostConfiguration hostConfig = getHostConfig(target); HttpState httpState = getHttpState(target); abortRequest.setPath(target.getEndpointPath() + "/abort"); //Put the transferId on the query string abortRequest.setQueryString( new NameValuePair[] { new NameValuePair("transferId", transfer.getTransferId()) }); try { int responseStatus = httpClient.executeMethod(hostConfig, abortRequest, httpState); checkResponseStatus("abort", responseStatus, abortRequest); //If we get here then we've received a 200 response //We're expecting the transfer id encoded in a JSON object... } catch (RuntimeException e) { throw e; } catch (Exception e) { String error = "Failed to execute HTTP request to target"; log.debug(error, e); throw new TransferException(MSG_HTTP_REQUEST_FAILED, new Object[] { "abort", target.toString(), e.toString() }, e); } } finally { abortRequest.releaseConnection(); } }
From source file:org.alfresco.repo.transfer.HttpClientTransmitterImpl.java
public void commit(Transfer transfer) throws TransferException { TransferTarget target = transfer.getTransferTarget(); HttpMethod commitRequest = getPostMethod(); try {/*from w w w. j av a 2 s .c o m*/ HostConfiguration hostConfig = getHostConfig(target); HttpState httpState = getHttpState(target); commitRequest.setPath(target.getEndpointPath() + "/commit"); //Put the transferId on the query string commitRequest.setQueryString( new NameValuePair[] { new NameValuePair("transferId", transfer.getTransferId()) }); try { int responseStatus = httpClient.executeMethod(hostConfig, commitRequest, httpState); checkResponseStatus("commit", responseStatus, commitRequest); //If we get here then we've received a 200 response //We're expecting the transfer id encoded in a JSON object... } catch (RuntimeException e) { throw e; } catch (Exception e) { String error = "Failed to execute HTTP request to target"; log.error(error, e); throw new TransferException(MSG_HTTP_REQUEST_FAILED, new Object[] { "commit", target.toString(), e.toString() }, e); } } finally { commitRequest.releaseConnection(); } }