List of usage examples for org.apache.commons.httpclient.methods HeadMethod HeadMethod
public HeadMethod(String paramString)
From source file:org.apache.jackrabbit.spi2dav.RepositoryServiceImpl.java
private boolean exists(SessionInfo sInfo, String uri) { HeadMethod method = new HeadMethod(uri); try {//from w w w .j av a2 s. co m int statusCode = getClient(sInfo).executeMethod(method); if (statusCode == DavServletResponse.SC_OK) { return true; } } catch (IOException e) { log.error("Unexpected error while testing existence of item.", e); } catch (RepositoryException e) { log.error(e.getMessage()); } finally { method.releaseConnection(); } return false; }
From source file:org.apache.jackrabbit.spi2davex.ValueLoader.java
public Map<String, String> loadHeaders(String uri, String[] headerNames) throws IOException, RepositoryException { HeadMethod method = new HeadMethod(uri); try {/* ww w . j av a 2 s .co m*/ int statusCode = client.executeMethod(method); if (statusCode == DavServletResponse.SC_OK) { Map<String, String> headers = new HashMap<String, String>(); for (String name : headerNames) { Header hdr = method.getResponseHeader(name); if (hdr != null) { headers.put(name, hdr.getValue()); } } return headers; } else { throw ExceptionConverter.generate(new DavException(statusCode, ("Unable to load headers at " + uri + " - Status line = " + method.getStatusLine().toString()))); } } finally { method.releaseConnection(); } }
From source file:org.apache.jackrabbit.webdav.server.BindTest.java
public void testRebind() throws Exception { String testcol = this.root + "testRebind/"; String subcol1 = testcol + "bindtest1/"; String testres1 = subcol1 + "res1"; String subcol2 = testcol + "bindtest2/"; String testres2 = subcol2 + "res2"; int status;/*from ww w . j ava 2 s . co m*/ try { MkColMethod mkcol = new MkColMethod(testcol); status = this.client.executeMethod(mkcol); assertEquals(201, status); mkcol = new MkColMethod(subcol1); status = this.client.executeMethod(mkcol); assertEquals(201, status); mkcol = new MkColMethod(subcol2); status = this.client.executeMethod(mkcol); assertEquals(201, status); //create new resource R with path bindtest1/res1 PutMethod put = new PutMethod(testres1); put.setRequestEntity(new StringRequestEntity("foo", "text/plain", "UTF-8")); status = this.client.executeMethod(put); assertEquals(201, status); // enabling version control always makes the resource referenceable VersionControlMethod versioncontrol = new VersionControlMethod(testres1); status = this.client.executeMethod(versioncontrol); assertTrue("status: " + status, status == 200 || status == 201); URI r1 = this.getResourceId(testres1); GetMethod get = new GetMethod(testres1); status = this.client.executeMethod(get); assertEquals(200, status); assertEquals("foo", get.getResponseBodyAsString()); //rebind R with path bindtest2/res2 DavMethodBase rebind = new RebindMethod(subcol2, new RebindInfo(testres1, "res2")); status = this.client.executeMethod(rebind); assertEquals(201, status); URI r2 = this.getResourceId(testres2); get = new GetMethod(testres2); status = this.client.executeMethod(get); assertEquals(200, status); assertEquals("foo", get.getResponseBodyAsString()); //make sure that rebind did not change the resource-id assertEquals(r1, r2); //verify that the initial binding is gone HeadMethod head = new HeadMethod(testres1); status = this.client.executeMethod(head); assertEquals(404, status); } finally { DeleteMethod delete = new DeleteMethod(testcol); status = this.client.executeMethod(delete); assertTrue("status: " + status, status == 200 || status == 204); } }
From source file:org.apache.jackrabbit.webdav.server.BindTest.java
public void testBindOverwrite() throws Exception { String testcol = this.root + "testSimpleBind/"; String subcol1 = testcol + "bindtest1/"; String testres1 = subcol1 + "res1"; String subcol2 = testcol + "bindtest2/"; String testres2 = subcol2 + "res2"; int status;//from w ww. jav a 2 s.c o m try { MkColMethod mkcol = new MkColMethod(testcol); status = this.client.executeMethod(mkcol); assertEquals(201, status); mkcol = new MkColMethod(subcol1); status = this.client.executeMethod(mkcol); assertEquals(201, status); mkcol = new MkColMethod(subcol2); status = this.client.executeMethod(mkcol); assertEquals(201, status); //create new resource R with path bindtest1/res1 PutMethod put = new PutMethod(testres1); put.setRequestEntity(new StringRequestEntity("foo", "text/plain", "UTF-8")); status = this.client.executeMethod(put); assertEquals(201, status); //create new resource R' with path bindtest2/res2 put = new PutMethod(testres2); put.setRequestEntity(new StringRequestEntity("bar", "text/plain", "UTF-8")); status = this.client.executeMethod(put); assertEquals(201, status); //try to create new binding of R with path bindtest2/res2 and Overwrite:F DavMethodBase bind = new BindMethod(subcol2, new BindInfo(testres1, "res2")); bind.addRequestHeader(new Header("Overwrite", "F")); status = this.client.executeMethod(bind); assertEquals(412, status); //verify that bindtest2/res2 still points to R' GetMethod get = new GetMethod(testres2); status = this.client.executeMethod(get); assertEquals(200, status); assertEquals("bar", get.getResponseBodyAsString()); //create new binding of R with path bindtest2/res2 bind = new BindMethod(subcol2, new BindInfo(testres1, "res2")); status = this.client.executeMethod(bind); assertTrue("status: " + status, status == 200 || status == 204); //verify that bindtest2/res2 now points to R get = new GetMethod(testres2); status = this.client.executeMethod(get); assertEquals(200, status); assertEquals("foo", get.getResponseBodyAsString()); //verify that the initial binding is still there HeadMethod head = new HeadMethod(testres1); status = this.client.executeMethod(head); assertEquals(200, status); } finally { DeleteMethod delete = new DeleteMethod(testcol); status = this.client.executeMethod(delete); assertTrue("status: " + status, status == 200 || status == 204); } }
From source file:org.apache.jackrabbit.webdav.server.BindTest.java
public void testRebindOverwrite() throws Exception { String testcol = this.root + "testSimpleBind/"; String subcol1 = testcol + "bindtest1/"; String testres1 = subcol1 + "res1"; String subcol2 = testcol + "bindtest2/"; String testres2 = subcol2 + "res2"; int status;/* w w w . j a va2 s .c o m*/ try { MkColMethod mkcol = new MkColMethod(testcol); status = this.client.executeMethod(mkcol); assertEquals(201, status); mkcol = new MkColMethod(subcol1); status = this.client.executeMethod(mkcol); assertEquals(201, status); mkcol = new MkColMethod(subcol2); status = this.client.executeMethod(mkcol); assertEquals(201, status); //create new resource R with path testSimpleBind/bindtest1/res1 PutMethod put = new PutMethod(testres1); put.setRequestEntity(new StringRequestEntity("foo", "text/plain", "UTF-8")); status = this.client.executeMethod(put); assertEquals(201, status); // enabling version control always makes the resource referenceable VersionControlMethod versioncontrol = new VersionControlMethod(testres1); status = this.client.executeMethod(versioncontrol); assertTrue("status: " + status, status == 200 || status == 201); //create new resource R' with path testSimpleBind/bindtest2/res2 put = new PutMethod(testres2); put.setRequestEntity(new StringRequestEntity("bar", "text/plain", "UTF-8")); status = this.client.executeMethod(put); assertEquals(201, status); //try rebind R with path testSimpleBind/bindtest2/res2 and Overwrite:F RebindMethod rebind = new RebindMethod(subcol2, new RebindInfo(testres1, "res2")); rebind.addRequestHeader(new Header("Overwrite", "F")); status = this.client.executeMethod(rebind); assertEquals(412, status); //verify that testSimpleBind/bindtest2/res2 still points to R' GetMethod get = new GetMethod(testres2); status = this.client.executeMethod(get); assertEquals(200, status); assertEquals("bar", get.getResponseBodyAsString()); //rebind R with path testSimpleBind/bindtest2/res2 rebind = new RebindMethod(subcol2, new RebindInfo(testres1, "res2")); status = this.client.executeMethod(rebind); assertTrue("status: " + status, status == 200 || status == 204); //verify that testSimpleBind/bindtest2/res2 now points to R get = new GetMethod(testres2); status = this.client.executeMethod(get); assertEquals(200, status); assertEquals("foo", get.getResponseBodyAsString()); //verify that the initial binding is gone HeadMethod head = new HeadMethod(testres1); status = this.client.executeMethod(head); assertEquals(404, status); } finally { DeleteMethod delete = new DeleteMethod(testcol); status = this.client.executeMethod(delete); assertTrue("status: " + status, status == 200 || status == 204); } }
From source file:org.apache.jackrabbit.webdav.server.BindTest.java
public void testUnbind() throws Exception { String testcol = this.root + "testUnbind/"; String subcol1 = testcol + "bindtest1/"; String testres1 = subcol1 + "res1"; String subcol2 = testcol + "bindtest2/"; String testres2 = subcol2 + "res2"; int status;/*w ww . j a v a 2s . c om*/ try { MkColMethod mkcol = new MkColMethod(testcol); status = this.client.executeMethod(mkcol); assertEquals(201, status); mkcol = new MkColMethod(subcol1); status = this.client.executeMethod(mkcol); assertEquals(201, status); mkcol = new MkColMethod(subcol2); status = this.client.executeMethod(mkcol); assertEquals(201, status); //create new resource R with path testSimpleBind/bindtest1/res1 PutMethod put = new PutMethod(testres1); put.setRequestEntity(new StringRequestEntity("foo", "text/plain", "UTF-8")); status = this.client.executeMethod(put); assertEquals(201, status); //create new binding of R with path testSimpleBind/bindtest2/res2 DavMethodBase bind = new BindMethod(subcol2, new BindInfo(testres1, "res2")); status = this.client.executeMethod(bind); assertEquals(201, status); //check if both bindings report the same DAV:resource-id assertEquals(this.getResourceId(testres1), this.getResourceId(testres2)); //remove new path UnbindMethod unbind = new UnbindMethod(subcol2, new UnbindInfo("res2")); status = this.client.executeMethod(unbind); assertTrue("status: " + status, status == 200 || status == 204); //verify that the new binding is gone HeadMethod head = new HeadMethod(testres2); status = this.client.executeMethod(head); assertEquals(404, status); //verify that the initial binding is still there head = new HeadMethod(testres1); status = this.client.executeMethod(head); assertEquals(200, status); } finally { DeleteMethod delete = new DeleteMethod(testcol); status = this.client.executeMethod(delete); assertTrue("status: " + status, status == 200 || status == 204); } }
From source file:org.apache.jackrabbit.webdav.server.RFC4918DestinationHeaderTest.java
public void testMove() throws HttpException, IOException, DavException, URISyntaxException { String testuri = this.root + "movetest"; String destinationuri = testuri + "2"; String destinationpath = new URI(destinationuri).getRawPath(); // make sure the scheme is removed assertFalse(destinationpath.contains(":")); int status;/* w w w . j a v a2s.c om*/ try { PutMethod put = new PutMethod(testuri); status = this.client.executeMethod(put); assertTrue("status: " + status, status == 200 || status == 201 || status == 204); // try to move outside the servlet's name space MoveMethod move = new MoveMethod(testuri, "/foobar", true); status = this.client.executeMethod(move); assertTrue("status: " + status, status == 403); // try a relative path move = new MoveMethod(testuri, "foobar", true); status = this.client.executeMethod(move); assertTrue("status: " + status, status == 400); move = new MoveMethod(testuri, destinationpath, true); status = this.client.executeMethod(move); assertTrue("status: " + status, status == 200 || status == 201 || status == 204); HeadMethod head = new HeadMethod(destinationuri); status = this.client.executeMethod(head); assertTrue("status: " + status, status == 200); head = new HeadMethod(testuri); status = this.client.executeMethod(head); assertTrue("status: " + status, status == 404); } finally { DeleteMethod delete = new DeleteMethod(testuri); status = this.client.executeMethod(delete); assertTrue("status: " + status, status == 200 || status == 204 || status == 404); delete = new DeleteMethod(destinationuri); status = this.client.executeMethod(delete); assertTrue("status: " + status, status == 200 || status == 204 || status == 404); } }
From source file:org.apache.jmeter.protocol.http.sampler.HTTPHC3Impl.java
/** * Samples the URL passed in and stores the result in * <code>HTTPSampleResult</code>, following redirects and downloading * page resources as appropriate.//from www . ja v a 2 s. com * <p> * When getting a redirect target, redirects are not followed and resources * are not downloaded. The caller will take care of this. * * @param url * URL to sample * @param method * HTTP method: GET, POST,... * @param areFollowingRedirect * whether we're getting a redirect target * @param frameDepth * Depth of this target in the frame structure. Used only to * prevent infinite recursion. * @return results of the sampling */ @Override protected HTTPSampleResult sample(URL url, String method, boolean areFollowingRedirect, int frameDepth) { String urlStr = url.toString(); if (log.isDebugEnabled()) { log.debug("Start : sample " + urlStr); log.debug("method " + method + " followingRedirect " + areFollowingRedirect + " depth " + frameDepth); } HttpMethodBase httpMethod = null; HTTPSampleResult res = new HTTPSampleResult(); res.setMonitor(isMonitor()); res.setSampleLabel(urlStr); // May be replaced later res.setHTTPMethod(method); res.setURL(url); res.sampleStart(); // Count the retries as well in the time try { // May generate IllegalArgumentException if (method.equals(HTTPConstants.POST)) { httpMethod = new PostMethod(urlStr); } else if (method.equals(HTTPConstants.GET)) { httpMethod = new GetMethod(urlStr); } else if (method.equals(HTTPConstants.PUT)) { httpMethod = new PutMethod(urlStr); } else if (method.equals(HTTPConstants.HEAD)) { httpMethod = new HeadMethod(urlStr); } else if (method.equals(HTTPConstants.TRACE)) { httpMethod = new TraceMethod(urlStr); } else if (method.equals(HTTPConstants.OPTIONS)) { httpMethod = new OptionsMethod(urlStr); } else if (method.equals(HTTPConstants.DELETE)) { httpMethod = new EntityEnclosingMethod(urlStr) { @Override public String getName() { // HC3.1 does not have the method return HTTPConstants.DELETE; } }; } else if (method.equals(HTTPConstants.PATCH)) { httpMethod = new EntityEnclosingMethod(urlStr) { @Override public String getName() { // HC3.1 does not have the method return HTTPConstants.PATCH; } }; } else { throw new IllegalArgumentException("Unexpected method: '" + method + "'"); } final CacheManager cacheManager = getCacheManager(); if (cacheManager != null && HTTPConstants.GET.equalsIgnoreCase(method)) { if (cacheManager.inCache(url)) { return updateSampleResultForResourceInCache(res); } } // Set any default request headers setDefaultRequestHeaders(httpMethod); // Setup connection HttpClient client = setupConnection(url, httpMethod, res); savedClient = client; // Handle the various methods if (method.equals(HTTPConstants.POST)) { String postBody = sendPostData((PostMethod) httpMethod); res.setQueryString(postBody); } else if (method.equals(HTTPConstants.PUT) || method.equals(HTTPConstants.PATCH) || method.equals(HTTPConstants.DELETE)) { String putBody = sendEntityData((EntityEnclosingMethod) httpMethod); res.setQueryString(putBody); } int statusCode = client.executeMethod(httpMethod); // We've finished with the request, so we can add the LocalAddress to it for display final InetAddress localAddr = client.getHostConfiguration().getLocalAddress(); if (localAddr != null) { httpMethod.addRequestHeader(HEADER_LOCAL_ADDRESS, localAddr.toString()); } // Needs to be done after execute to pick up all the headers res.setRequestHeaders(getConnectionHeaders(httpMethod)); // Request sent. Now get the response: InputStream instream = httpMethod.getResponseBodyAsStream(); if (instream != null) {// will be null for HEAD instream = new CountingInputStream(instream); try { Header responseHeader = httpMethod.getResponseHeader(HTTPConstants.HEADER_CONTENT_ENCODING); if (responseHeader != null && HTTPConstants.ENCODING_GZIP.equals(responseHeader.getValue())) { InputStream tmpInput = new GZIPInputStream(instream); // tmp inputstream needs to have a good counting res.setResponseData( readResponse(res, tmpInput, (int) httpMethod.getResponseContentLength())); } else { res.setResponseData( readResponse(res, instream, (int) httpMethod.getResponseContentLength())); } } finally { JOrphanUtils.closeQuietly(instream); } } res.sampleEnd(); // Done with the sampling proper. // Now collect the results into the HTTPSampleResult: res.setSampleLabel(httpMethod.getURI().toString()); // Pick up Actual path (after redirects) res.setResponseCode(Integer.toString(statusCode)); res.setSuccessful(isSuccessCode(statusCode)); res.setResponseMessage(httpMethod.getStatusText()); String ct = null; Header h = httpMethod.getResponseHeader(HTTPConstants.HEADER_CONTENT_TYPE); if (h != null)// Can be missing, e.g. on redirect { ct = h.getValue(); res.setContentType(ct);// e.g. text/html; charset=ISO-8859-1 res.setEncodingAndType(ct); } res.setResponseHeaders(getResponseHeaders(httpMethod)); if (res.isRedirect()) { final Header headerLocation = httpMethod.getResponseHeader(HTTPConstants.HEADER_LOCATION); if (headerLocation == null) { // HTTP protocol violation, but avoids NPE throw new IllegalArgumentException("Missing location header"); } String redirectLocation = headerLocation.getValue(); res.setRedirectLocation(redirectLocation); // in case sanitising fails } // record some sizes to allow HTTPSampleResult.getBytes() with different options if (instream != null) { res.setBodySize(((CountingInputStream) instream).getCount()); } res.setHeadersSize(calculateHeadersSize(httpMethod)); if (log.isDebugEnabled()) { log.debug("Response headersSize=" + res.getHeadersSize() + " bodySize=" + res.getBodySize() + " Total=" + (res.getHeadersSize() + res.getBodySize())); } // If we redirected automatically, the URL may have changed if (getAutoRedirects()) { res.setURL(new URL(httpMethod.getURI().toString())); } // Store any cookies received in the cookie manager: saveConnectionCookies(httpMethod, res.getURL(), getCookieManager()); // Save cache information if (cacheManager != null) { cacheManager.saveDetails(httpMethod, res); } // Follow redirects and download page resources if appropriate: res = resultProcessing(areFollowingRedirect, frameDepth, res); log.debug("End : sample"); return res; } catch (IllegalArgumentException e) { // e.g. some kinds of invalid URL res.sampleEnd(); // pick up headers if failed to execute the request // httpMethod can be null if method is unexpected if (httpMethod != null) { res.setRequestHeaders(getConnectionHeaders(httpMethod)); } errorResult(e, res); return res; } catch (IOException e) { res.sampleEnd(); // pick up headers if failed to execute the request // httpMethod cannot be null here, otherwise // it would have been caught in the previous catch block res.setRequestHeaders(getConnectionHeaders(httpMethod)); errorResult(e, res); return res; } finally { savedClient = null; if (httpMethod != null) { httpMethod.releaseConnection(); } } }
From source file:org.apache.jmeter.protocol.oauth.sampler.OAuthSampler.java
/** * Samples the URL passed in and stores the result in * <code>HTTPSampleResult</code>, following redirects and downloading * page resources as appropriate./* w ww . ja v a 2 s. c om*/ * <p> * When getting a redirect target, redirects are not followed and resources * are not downloaded. The caller will take care of this. * * @param url * URL to sample * @param method * HTTP method: GET, POST,... * @param areFollowingRedirect * whether we're getting a redirect target * @param frameDepth * Depth of this target in the frame structure. Used only to * prevent infinite recursion. * @return results of the sampling */ protected HTTPSampleResult sample(URL url, String method, boolean areFollowingRedirect, int frameDepth) { String urlStr = url.toExternalForm(); // Check if this is an entity-enclosing method boolean isPost = method.equals(POST) || method.equals(PUT); HTTPSampleResult res = new HTTPSampleResult(); res.setMonitor(isMonitor()); // Handles OAuth signing try { message = getOAuthMessage(url, method); urlStr = message.URL; if (isPost) { urlStr = message.URL; } else { if (useAuthHeader) urlStr = OAuth.addParameters(message.URL, nonOAuthParams); else urlStr = OAuth.addParameters(message.URL, message.getParameters()); } } catch (IOException e) { res.sampleEnd(); HTTPSampleResult err = errorResult(e, res); err.setSampleLabel("Error: " + url.toString()); //$NON-NLS-1$ return err; } catch (OAuthException e) { res.sampleEnd(); HTTPSampleResult err = errorResult(e, res); err.setSampleLabel("Error: " + url.toString()); //$NON-NLS-1$ return err; } catch (URISyntaxException e) { res.sampleEnd(); HTTPSampleResult err = errorResult(e, res); err.setSampleLabel("Error: " + url.toString()); //$NON-NLS-1$ return err; } log.debug("Start : sample " + urlStr); //$NON-NLS-1$ log.debug("method " + method); //$NON-NLS-1$ HttpMethodBase httpMethod = null; res.setSampleLabel(urlStr); // May be replaced later res.setHTTPMethod(method); res.sampleStart(); // Count the retries as well in the time HttpClient client = null; InputStream instream = null; try { // May generate IllegalArgumentException if (method.equals(POST)) { httpMethod = new PostMethod(urlStr); } else if (method.equals(PUT)) { httpMethod = new PutMethod(urlStr); } else if (method.equals(HEAD)) { httpMethod = new HeadMethod(urlStr); } else if (method.equals(TRACE)) { httpMethod = new TraceMethod(urlStr); } else if (method.equals(OPTIONS)) { httpMethod = new OptionsMethod(urlStr); } else if (method.equals(DELETE)) { httpMethod = new DeleteMethod(urlStr); } else if (method.equals(GET)) { httpMethod = new GetMethod(urlStr); } else { log.error("Unexpected method (converted to GET): " + method); //$NON-NLS-1$ httpMethod = new GetMethod(urlStr); } // Set any default request headers setDefaultRequestHeaders(httpMethod); // Setup connection client = setupConnection(new URL(urlStr), httpMethod, res); // Handle POST and PUT if (isPost) { String postBody = sendPostData(httpMethod); res.setQueryString(postBody); } res.setRequestHeaders(getConnectionHeaders(httpMethod)); int statusCode = client.executeMethod(httpMethod); // Request sent. Now get the response: instream = httpMethod.getResponseBodyAsStream(); if (instream != null) {// will be null for HEAD Header responseHeader = httpMethod.getResponseHeader(HEADER_CONTENT_ENCODING); if (responseHeader != null && ENCODING_GZIP.equals(responseHeader.getValue())) { instream = new GZIPInputStream(instream); } res.setResponseData(readResponse(res, instream, (int) httpMethod.getResponseContentLength())); } res.sampleEnd(); // Done with the sampling proper. // Now collect the results into the HTTPSampleResult: res.setSampleLabel(httpMethod.getURI().toString()); // Pick up Actual path (after redirects) res.setResponseCode(Integer.toString(statusCode)); res.setSuccessful(isSuccessCode(statusCode)); res.setResponseMessage(httpMethod.getStatusText()); String ct = null; org.apache.commons.httpclient.Header h = httpMethod.getResponseHeader(HEADER_CONTENT_TYPE); if (h != null)// Can be missing, e.g. on redirect { ct = h.getValue(); res.setContentType(ct);// e.g. text/html; charset=ISO-8859-1 res.setEncodingAndType(ct); } res.setResponseHeaders(getResponseHeaders(httpMethod)); if (res.isRedirect()) { final Header headerLocation = httpMethod.getResponseHeader(HEADER_LOCATION); if (headerLocation == null) { // HTTP protocol violation, but avoids NPE throw new IllegalArgumentException("Missing location header"); //$NON-NLS-1$ } res.setRedirectLocation(headerLocation.getValue()); } // If we redirected automatically, the URL may have changed if (getAutoRedirects()) { res.setURL(new URL(httpMethod.getURI().toString())); } // Store any cookies received in the cookie manager: saveConnectionCookies(httpMethod, res.getURL(), getCookieManager()); // Save cache information final CacheManager cacheManager = getCacheManager(); if (cacheManager != null) { cacheManager.saveDetails(httpMethod, res); } // Follow redirects and download page resources if appropriate: res = resultProcessing(areFollowingRedirect, frameDepth, res); log.debug("End : sample"); //$NON-NLS-1$ httpMethod.releaseConnection(); return res; } catch (IllegalArgumentException e)// e.g. some kinds of invalid URL { res.sampleEnd(); HTTPSampleResult err = errorResult(e, res); err.setSampleLabel("Error: " + url.toString()); //$NON-NLS-1$ return err; } catch (IOException e) { res.sampleEnd(); HTTPSampleResult err = errorResult(e, res); err.setSampleLabel("Error: " + url.toString()); //$NON-NLS-1$ return err; } finally { JOrphanUtils.closeQuietly(instream); if (httpMethod != null) { httpMethod.releaseConnection(); } } }
From source file:org.apache.maven.doxia.linkcheck.validation.OnlineHTTPLinkValidator.java
/** * Checks the given link./*from w ww .ja v a2 s . c o m*/ * * @param link the link to check. * @param nbRedirect the number of current redirects. * @return HttpMethod * @throws IOException if something goes wrong. */ private HttpMethod checkLink(String link, int nbRedirect) throws IOException { int max = MAX_NB_REDIRECT; if (this.http.getHttpClientParameters() != null && this.http.getHttpClientParameters().get(HttpClientParams.MAX_REDIRECTS) != null) { try { max = Integer .valueOf(this.http.getHttpClientParameters().get(HttpClientParams.MAX_REDIRECTS).toString()) .intValue(); } catch (NumberFormatException e) { if (LOG.isWarnEnabled()) { LOG.warn("HttpClient parameter '" + HttpClientParams.MAX_REDIRECTS + "' is not a number. Ignoring!"); } } } if (nbRedirect > max) { throw new HttpException("Maximum number of redirections (" + max + ") exceeded"); } HttpMethod hm; if (HEAD_METHOD.equalsIgnoreCase(this.http.getMethod())) { hm = new HeadMethod(link); } else if (GET_METHOD.equalsIgnoreCase(this.http.getMethod())) { hm = new GetMethod(link); } else { if (LOG.isErrorEnabled()) { LOG.error("Unsupported method: " + this.http.getMethod() + ", using 'get'."); } hm = new GetMethod(link); } // Default hm.setFollowRedirects(this.http.isFollowRedirects()); try { URL url = new URL(link); cl.getHostConfiguration().setHost(url.getHost(), url.getPort(), url.getProtocol()); cl.executeMethod(hm); StatusLine sl = hm.getStatusLine(); if (sl == null) { if (LOG.isErrorEnabled()) { LOG.error("Unknown error validating link : " + link); } return null; } if (hm.getStatusCode() == HttpStatus.SC_MOVED_PERMANENTLY || hm.getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY || hm.getStatusCode() == HttpStatus.SC_TEMPORARY_REDIRECT) { Header locationHeader = hm.getResponseHeader("location"); if (locationHeader == null) { LOG.error("Site sent redirect, but did not set Location header"); return hm; } String newLink = locationHeader.getValue(); // Be careful to absolute/relative links if (!newLink.startsWith("http://") && !newLink.startsWith("https://")) { if (newLink.startsWith("/")) { URL oldUrl = new URL(link); newLink = oldUrl.getProtocol() + "://" + oldUrl.getHost() + (oldUrl.getPort() > 0 ? ":" + oldUrl.getPort() : "") + newLink; } else { newLink = link + newLink; } } HttpMethod oldHm = hm; if (LOG.isDebugEnabled()) { LOG.debug("[" + link + "] is redirected to [" + newLink + "]"); } oldHm.releaseConnection(); hm = checkLink(newLink, nbRedirect + 1); // Restore the hm to "Moved permanently" | "Moved temporarily" | "Temporary redirect" // if the new location is found to allow us to report it if (hm.getStatusCode() == HttpStatus.SC_OK && nbRedirect == 0) { return oldHm; } } } finally { hm.releaseConnection(); } return hm; }