List of usage examples for org.apache.commons.httpclient HttpMethod releaseConnection
public abstract void releaseConnection();
From source file:org.codehaus.mojo.fitnesse.FitnesseRemoteRunnerMojo.java
void getRemoteResource(String pUrl, OutputStream pOutStream, Fitnesse pServer) throws MojoExecutionException { try {/*from w w w . j a v a2s .c o m*/ HttpClient tClient = new HttpClient(); getLog().info("Request resources from [" + pUrl + "]"); if (pServer.getServerId() != null) { tClient.getParams().setAuthenticationPreemptive(true); Credentials defaultcreds = getCredential(pServer.getServerId()); AuthScope tAuthScope = new AuthScope(pServer.getHostName(), pServer.getPort(), AuthScope.ANY_REALM); tClient.getState().setCredentials(tAuthScope, defaultcreds); getLog().info("Use credential for remote connection"); } HttpMethod tMethod = new GetMethod(pUrl); int tStatusCode = tClient.executeMethod(tMethod); if (tStatusCode != 200) { throw new MojoExecutionException( "Bad response code from resource [" + pUrl + "], return code=[" + tStatusCode + "]"); } InputStream tResponseStream = tMethod.getResponseBodyAsStream(); byte[] tbytes = new byte[512]; int tReadBytes = tResponseStream.read(tbytes); while (tReadBytes >= 0) { pOutStream.write(tbytes, 0, tReadBytes); tReadBytes = tResponseStream.read(tbytes); } pOutStream.flush(); tMethod.releaseConnection(); } catch (IOException e) { throw new MojoExecutionException("Unable to read FitNesse server response.", e); } finally { try { pOutStream.close(); } catch (IOException e) { getLog().error("Unable to close Stream."); } } }
From source file:org.collectionspace.chain.csp.persistence.services.connection.ServicesConnection.java
private void doRequest(Returned out, RequestMethod method_type, String uri, RequestDataSource src, CSPRequestCredentials creds, CSPRequestCache cache) throws ConnectionException { InputStream body_data = null; if (src != null) { body_data = src.getStream();//from w w w. j a v a 2 s .com } try { HttpMethod method = createMethod(method_type, uri, body_data); if (body_data != null) { method.setRequestHeader("Content-Type", src.getMIMEType()); // XXX Not sure if or when this ever actually writes to stderr? body_data = new TeeInputStream(body_data, System.err); } try { HttpClient client = makeClient(creds, cache); String requestContext = null; if (perflog.isDebugEnabled()) { // TODO add more context, e.g. session id? requestContext = "HttpClient@" + Integer.toHexString(client.hashCode()); requestContext += "/CSPRequestCache@" + Integer.toHexString(cache.hashCode()) + ","; //String queryString = method.getQueryString(); perflog.debug(System.currentTimeMillis() + ",\"" + Thread.currentThread().getName() + "\",app,svc," + requestContext + method.getName() + " " + method.getURI() //+ (queryString!=null ? queryString : "") ); } int response = client.executeMethod(method); if (perflog.isDebugEnabled()) { perflog.debug(System.currentTimeMillis() + ",\"" + Thread.currentThread().getName() + "\",svc,app," + requestContext + "HttpClient.executeMethod done"); } out.setResponse(method, response); } catch (ConnectionException e) { throw new ConnectionException(e.getMessage(), e.status, base_url + "/" + uri, e); } catch (Exception e) { throw new ConnectionException(e.getMessage(), 0, base_url + "/" + uri, e); } finally { method.releaseConnection(); if (log.isWarnEnabled()) { if (manager.getConnectionsInPool() >= MAX_SERVICES_CONNECTIONS) { log.warn("reached max services connection limit of " + MAX_SERVICES_CONNECTIONS); // Delete closed connections from the pool, so that the warning will cease // once a connection becomes available. manager.deleteClosedConnections(); } } } } finally { closeStream(body_data); } }
From source file:org.colombbus.tangara.net.TConnection.java
public synchronized Document sendCommand(Command cmd) throws CommandException { HttpMethod method = createMethod(cmd); Document doc = null;/* ww w . j a v a 2s . c om*/ try { String logMsg = String.format("Prepare executing method %s", //$NON-NLS-1$ method.getPath()); LOG.info(logMsg); String httpResponse = executeMethod(method); doc = buildXmlResponse(method, httpResponse); logMsg = String.format("Method succeed %s %s", //$NON-NLS-1$ method.getPath(), method.getStatusLine().toString()); LOG.info(logMsg); } catch (CommandException cmdEx) { LOG.error("Command excetion catched in the command", cmdEx);//$NON-NLS-1$ throw cmdEx; } catch (Throwable th) { LOG.error("Unknown error catched in the command", th);//$NON-NLS-1$ throw new CommandException(method.getPath(), CommandException.UNKNOWN_ERR, "Unknown error catched in the command", th);//$NON-NLS-1$ } finally { method.releaseConnection(); } return doc; }
From source file:org.craftercms.cstudio.publishing.processor.CacheInvalidatePostProcessor.java
@Override public void doProcess(PublishedChangeSet changeSet, Map<String, String> parameters, PublishingTarget target) throws PublishingException { HttpMethod cacheInvalidateGetMethod = new GetMethod(cacheInvalidateUrl); HttpClient client = new HttpClient(); try {//w w w . ja v a 2 s .c o m int status = client.executeMethod(cacheInvalidateGetMethod); if (status != HttpServletResponse.SC_OK) { throw new PublishingException("Unable to invalidate cache: URL " + cacheInvalidateUrl + " returned status '" + cacheInvalidateGetMethod.getStatusText() + "' with body \n" + cacheInvalidateGetMethod.getResponseBodyAsString()); } else { if (logger.isDebugEnabled()) { logger.debug("Cache invalidated: URL " + cacheInvalidateUrl + " returned status '" + cacheInvalidateGetMethod.getStatusText() + "'"); } } } catch (IOException e) { throw new PublishingException(e); } finally { cacheInvalidateGetMethod.releaseConnection(); } }
From source file:org.crosswire.common.util.WebResource.java
/** * Determine the size of this WebResource. * <p>Note that the http client may read the entire file to determine this.</p> * * @return the size of the file//from w w w . ja v a 2 s . co m */ public int getSize() { HttpMethod method = new HeadMethod(uri.getPath()); try { // Execute the method. int status = client.executeMethod(method); if (status == HttpStatus.SC_OK) { return new HttpURLConnection(method, NetUtil.toURL(uri)).getContentLength(); } String reason = HttpStatus.getStatusText(status); Reporter.informUser(this, Msg.MISSING_FILE, new Object[] { reason + ':' + uri.getPath() }); } catch (IOException e) { return 0; } finally { // Release the connection. method.releaseConnection(); } return 0; }
From source file:org.crosswire.common.util.WebResource.java
/** * Determine the last modified date of this WebResource. * <p>Note that the http client may read the entire file.</p> * * @return the last mod date of the file *///from w ww. j a v a 2s . com public long getLastModified() { HttpMethod method = new HeadMethod(uri.getPath()); try { // Execute the method. if (client.executeMethod(method) == HttpStatus.SC_OK) { return new HttpURLConnection(method, NetUtil.toURL(uri)).getLastModified(); } } catch (IOException e) { return new Date().getTime(); } finally { // Release the connection. method.releaseConnection(); } return new Date().getTime(); }
From source file:org.crosswire.common.util.WebResource.java
/** * Copy this WebResource to the destination. * * @param dest//from ww w . j ava 2 s . c om * @throws LucidException */ public void copy(URI dest) throws LucidException { InputStream in = null; OutputStream out = null; HttpMethod method = new GetMethod(uri.getPath()); try { // Execute the method. if (client.executeMethod(method) == HttpStatus.SC_OK) { in = method.getResponseBodyAsStream(); // Download the index file out = NetUtil.getOutputStream(dest); byte[] buf = new byte[4096]; int count = in.read(buf); while (-1 != count) { out.write(buf, 0, count); count = in.read(buf); } } } catch (IOException e) { throw new LucidException(Msg.MISSING_FILE, e); } finally { // Release the connection. method.releaseConnection(); // Close the streams IOUtil.close(in); IOUtil.close(out); } }
From source file:org.cryptomator.frontend.webdav.WebDavServerTest.java
@Test public void testGet() throws HttpException, IOException { final HttpClient client = new HttpClient(); // write test content: final byte[] testContent = "hello world".getBytes(); try (WritableFile w = fs.file("foo.txt").openWritable()) { w.write(ByteBuffer.wrap(testContent)); }/* w w w .j av a2 s . c o m*/ // check get response body: final HttpMethod getMethod = new GetMethod(servletRoot + "/foo.txt"); final int statusCode = client.executeMethod(getMethod); Assert.assertEquals(200, statusCode); Assert.assertThat(getMethod.getResponseHeaders(), hasItemInArray(new Header("Accept-Ranges", "bytes"))); Assert.assertTrue( IOUtils.contentEquals(new ByteArrayInputStream(testContent), getMethod.getResponseBodyAsStream())); getMethod.releaseConnection(); }
From source file:org.cryptomator.frontend.webdav.WebDavServerTest.java
@Test public void testMkcol() throws HttpException, IOException { final HttpClient client = new HttpClient(); // create directory: final HttpMethod mkcolMethod = new MkColMethod(servletRoot + "/foo"); final int statusCode = client.executeMethod(mkcolMethod); Assert.assertEquals(201, statusCode); Assert.assertTrue(fs.folder("foo").exists()); mkcolMethod.releaseConnection(); }
From source file:org.cryptomator.frontend.webdav.WebDavServerTest.java
@Test public void testGetWithUnsatisfiableRange() throws IOException { final HttpClient client = new HttpClient(); // write test content: final byte[] testContent = "hello world".getBytes(); try (WritableFile w = fs.file("foo.txt").openWritable()) { w.write(ByteBuffer.wrap(testContent)); }//from ww w. j a v a 2 s .com // check get response body: final HttpMethod getMethod = new GetMethod(servletRoot + "/foo.txt"); getMethod.addRequestHeader("Range", "chunks=1-2"); final int statusCode = client.executeMethod(getMethod); Assert.assertEquals(200, statusCode); Assert.assertArrayEquals(testContent, getMethod.getResponseBody()); getMethod.releaseConnection(); }