List of usage examples for org.apache.commons.httpclient HttpMethod releaseConnection
public abstract void releaseConnection();
From source file:com.cyberway.issue.crawler.fetcher.FetchHTTP.java
/** * Cleanup after a failed method execute. * @param curi CrawlURI we failed on.//from w w w. jav a2s .c o m * @param method Method we failed on. * @param exception Exception we failed with. */ private void failedExecuteCleanup(final HttpMethod method, final CrawlURI curi, final Exception exception) { cleanup(curi, exception, "executeMethod", S_CONNECT_FAILED); method.releaseConnection(); }
From source file:com.dlecan.agreg.AgregResultsBot.java
public boolean isResultatsDisponibles(String type) throws Exception { boolean resultatsDisponibles = false; String urlAppelee = URL_PUBLINET_PREFIX + type + URL_PUBLINET_SUFFIX; HttpMethod getUrlPublinet = new GetMethod(urlAppelee); try {//from www . ja v a 2 s .c om int status = client.executeMethod(getUrlPublinet); if (status == HttpStatus.SC_OK) { InputStream streamPage = getUrlPublinet.getResponseBodyAsStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(streamPage)); String line; while ((line = reader.readLine()) != null) { if (line.toUpperCase().contains("AUCUN CANDIDAT ADMIS")) { resultatsDisponibles = false; break; } else if (line.toUpperCase() .contains("Cliquez sur une des lettres de l'alphabet".toUpperCase())) { resultatsDisponibles = true; break; } else { // Le systme dconne } } if (resultatsDisponibles) { while ((line = reader.readLine()) != null) { if (line.toUpperCase().contains("VALADE")) { recue = true; messageAEnvoyer = urlAppelee + "\n\n" + line; break; } else { // Le systme dconne } } } } else { logger.error("Method failed: {}", getUrlPublinet.getStatusLine()); } } finally { getUrlPublinet.releaseConnection(); } return resultatsDisponibles; }
From source file:com.bugclipse.fogbugz.api.client.FogBugzClient.java
private Response unmarshalResponse(HttpMethod method) throws FogBugzClientException { try {/*from www. j a va2 s .com*/ Unmarshaller un = new Unmarshaller(Response.class); un.setIgnoreExtraElements(true); un.setIgnoreExtraAttributes(true); un.setValidation(false); un.setWhitespacePreserve(true); String respBody = method.getResponseBodyAsString(); System.out.println("response - " + respBody); Response r = (Response) un.unmarshal(new StringReader(respBody)); if (r.getError() != null) throw new FogBugzAPIException(r.getError()); return r; } catch (IOException e) { throw new FogBugzClientException(e); } catch (MarshalException e) { throw new FogBugzClientException(e); } catch (ValidationException e) { throw new FogBugzClientException(e); } finally { method.releaseConnection(); } }
From source file:it.drwolf.ridire.session.CrawlerManager.java
public Long getRawBytes(String jobName, User user) throws HeritrixException, CrawlingFileException { // this.updateJobsList(user); Job j = this.getPersistedJob(jobName); if (j == null) { return 0L; }//from www . j a va2 s . c o m if (j.getChildJobName() != null && j.getChildJobName().length() > 0) { jobName = j.getChildJobName(); } HttpMethod method = null; try { method = new GetMethod(this.engineUri + "job/" + URLEncoder.encode(jobName, "UTF-8") + "/jobdir/reports/crawl-report.txt"); // TODO check status int status = this.httpClient.executeMethod(method); String report = method.getResponseBodyAsString(); method.releaseConnection(); long parseLong = 0L; Matcher m = CrawlerManager.pDownloadedBytes.matcher(report); if (m.find()) { String bytes = m.group(1); parseLong = Long.parseLong(bytes); } if (parseLong == 0L) { try { parseLong = this.getRawBytesFromFileSystem(jobName); } catch (Exception exception) { parseLong = 0; } } return parseLong; } catch (HttpException e) { e.printStackTrace(); throw new HeritrixException(); } catch (IOException e) { e.printStackTrace(); throw new HeritrixException(); } finally { if (method != null) { method.releaseConnection(); } } }
From source file:net.sourceforge.jwbf.actions.HttpActionClient.java
/** * Process a POST Message.//from w w w .j a va 2 s . c om * * @param authpost * a * @param cp * a * @return a returning message, not null * @throws IOException on problems * @throws ProcessException on problems * @throws CookieException on problems */ protected String post(HttpMethod authpost, ContentProcessable cp) throws IOException, ProcessException, CookieException { showCookies(client); authpost.getParams().setParameter("http.protocol.content-charset", MediaWikiBot.CHARSET); String out = ""; client.executeMethod(authpost); // Header locationHeader = authpost.getResponseHeader("location"); // if (locationHeader != null) { // authpost.setRequestHeader(locationHeader) ; // } // Usually a successful form-based login results in a redicrect to // another url int statuscode = authpost.getStatusCode(); if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY) || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY) || (statuscode == HttpStatus.SC_SEE_OTHER) || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) { Header header = authpost.getResponseHeader("location"); if (header != null) { String newuri = header.getValue(); if ((newuri == null) || (newuri.equals(""))) { newuri = "/"; } LOG.debug("Redirect target: " + newuri); GetMethod redirect = new GetMethod(newuri); client.executeMethod(redirect); LOG.debug("Redirect: " + redirect.getStatusLine().toString()); // release any connection resources used by the method authpost.releaseConnection(); authpost = redirect; } } out = authpost.getResponseBodyAsString(); out = cp.processReturningText(out, authpost); cp.validateReturningCookies(client.getState().getCookies(), authpost); authpost.releaseConnection(); LOG.debug(authpost.getURI() + " || " + "POST: " + authpost.getStatusLine().toString()); return out; }
From source file:com.zimbra.qa.unittest.prov.ldap.TestProvIDN.java
@Test public void testBasicAuth() throws Exception { Names.IDNName domainName = new Names.IDNName(makeTestDomainName("basicAuthTest.")); Domain domain = createDomain(domainName.uName(), domainName.uName()); Names.IDNName acctName = new Names.IDNName("acct", domainName.uName()); Account acct = (Account) createTest(EntryType.ACCOUNT, NameType.UNAME, acctName); HttpState initialState = new HttpState(); /*/* w ww . j av a 2 s . c o m*/ Cookie authCookie = new Cookie(restURL.getURL().getHost(), "ZM_AUTH_TOKEN", mAuthToken, "/", null, false); Cookie sessionCookie = new Cookie(restURL.getURL().getHost(), "JSESSIONID", mSessionId, "/zimbra", null, false); initialState.addCookie(authCookie); initialState.addCookie(sessionCookie); */ String guestName = acct.getUnicodeName(); String guestPassword = "test123"; Credentials loginCredentials = new UsernamePasswordCredentials(guestName, guestPassword); initialState.setCredentials(AuthScope.ANY, loginCredentials); HttpClient client = new HttpClient(); client.setState(initialState); String url = UserServlet.getRestUrl(acct) + "/Calendar"; System.out.println("REST URL: " + url); HttpMethod method = new GetMethod(url); HttpMethodParams methodParams = method.getParams(); methodParams.setCredentialCharset("UTF-8"); try { int respCode = HttpClientUtil.executeMethod(client, method); if (respCode != HttpStatus.SC_OK) { System.out.println("failed, respCode=" + respCode); } else { boolean chunked = false; boolean textContent = false; /* System.out.println("Headers:"); System.out.println("--------"); for (Header header : method.getRequestHeaders()) { System.out.print(" " + header.toString()); } System.out.println(); System.out.println("Body:"); System.out.println("-----"); String respBody = method.getResponseBodyAsString(); System.out.println(respBody); */ } } finally { // Release the connection. method.releaseConnection(); } }
From source file:it.geosolutions.geostore.services.rest.security.WebServiceTokenAuthenticationFilter.java
@Override protected Authentication checkToken(String token) { String webServiceUrl = url.replace("{token}", token); HttpClient client = getHttpClient(); client.getParams().setParameter(HttpClientParams.CONNECTION_MANAGER_TIMEOUT, connectTimeout * 1000l); client.getParams().setParameter(HttpClientParams.SO_TIMEOUT, readTimeout * 1000); HttpMethod method = null; try {/*w ww .j ava2 s . c o m*/ LOGGER.debug("Issuing request to webservice: " + url); method = new GetMethod(webServiceUrl); int statusCode = client.executeMethod(method); if (statusCode == HttpStatus.SC_OK) { // get response content as a single string, without new lines // so that is simpler to apply an extraction regular expression String response = method.getResponseBodyAsString().replace("\r", "").replace("\n", ""); if (response != null) { if (searchUserRegex == null) { return createAuthenticationForUser(response, null, ""); } else { Matcher matcher = searchUserRegex.matcher(response); if (matcher.find()) { return createAuthenticationForUser(matcher.group(1), null, response); } else { LOGGER.warn( "Error in getting username from webservice response cannot find userName in response"); } } } else { LOGGER.error("No response received from webservice: " + url); } } } catch (HttpException e) { LOGGER.error("Error contacting webservice: " + url, e); } catch (IOException e) { LOGGER.error("Error reading data from webservice: " + url, e); } finally { if (method != null) { method.releaseConnection(); } } return null; }
From source file:com.mythesis.userbehaviouranalysis.AnnotationClient.java
public String request(HttpMethod method) throws AnnotationException { String response = null;/*w ww. j ava 2 s. c o m*/ // Provide custom retry handler is necessary method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); try { // Execute the method. int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { LOG.error("Method failed: " + method.getStatusLine()); } // Read the response body. //byte[] responseBody = method.getResponseBody(); //TODO Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended. InputStream responseBodyAsStream = method.getResponseBodyAsStream(); // Deal with the response. // Use caution: ensure correct character encoding and is not binary data StringWriter writer = new StringWriter(); IOUtils.copy(responseBodyAsStream, writer, "utf-8"); response = writer.toString(); } catch (HttpException e) { LOG.error("Fatal protocol violation: " + e.getMessage()); throw new AnnotationException("Protocol error executing HTTP request.", e); } catch (IOException e) { LOG.error("Fatal transport error: " + e.getMessage()); LOG.error(method.getQueryString()); throw new AnnotationException("Transport error executing HTTP request.", e); } finally { // Release the connection. method.releaseConnection(); } return response; }
From source file:freeciv.servlet.ProxyServlet.java
/** * Executes the {@link HttpMethod} passed in and sends the proxy response * back to the client via the given {@link HttpServletResponse} * @param httpMethodProxyRequest An object representing the proxy request to be made * @param httpServletResponse An object by which we can send the proxied * response back to the client * @throws IOException Can be thrown by the {@link HttpClient}.executeMethod * @throws ServletException Can be thrown to indicate that another error has occurred *//*from w ww. jav a 2 s . co m*/ private void executeProxyRequest(HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException { httpMethodProxyRequest.setFollowRedirects(false); String port = "" + httpServletRequest.getSession().getAttribute("civserverport"); String host = "" + httpServletRequest.getSession().getAttribute("civserverhost"); String username = "" + httpServletRequest.getSession().getAttribute("username"); httpMethodProxyRequest.addRequestHeader("civserverport", port); httpMethodProxyRequest.addRequestHeader("civserverhost", host); httpMethodProxyRequest.addRequestHeader("username", username); int intProxyResponseCode = 0; // Execute the request try { intProxyResponseCode = client.executeMethod(httpMethodProxyRequest); } catch (IOException ioErr) { //- If an I/O (transport) error occurs. Some transport exceptions can be recovered from. //- If a protocol exception occurs. Usually protocol exceptions cannot be recovered from. OutputStream outputStreamClientResponse = httpServletResponse.getOutputStream(); httpServletResponse.setStatus(502); outputStreamClientResponse .write("Freeciv web client proxy not responding (most likely died).".getBytes()); httpMethodProxyRequest.releaseConnection(); return; } // Check if the proxy response is a redirect // The following code is adapted from org.tigris.noodle.filters.CheckForRedirect // Hooray for open source software if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */ && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) { String stringStatusCode = Integer.toString(intProxyResponseCode); String stringLocation = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue(); if (stringLocation == null) { httpMethodProxyRequest.releaseConnection(); throw new ServletException("Recieved status code: " + stringStatusCode + " but no " + STRING_LOCATION_HEADER + " header was found in the response"); } // Modify the redirect to go to this proxy servlet rather that the proxied host String stringMyHostName = httpServletRequest.getServerName(); if (httpServletRequest.getServerPort() != 80) { stringMyHostName += ":" + httpServletRequest.getServerPort(); } stringMyHostName += httpServletRequest.getContextPath(); httpServletResponse.sendRedirect( stringLocation.replace(getProxyHostAndPort() + this.getProxyPath(), stringMyHostName)); httpMethodProxyRequest.releaseConnection(); return; } else if (intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) { // 304 needs special handling. See: // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304 // We get a 304 whenever passed an 'If-Modified-Since' // header and the data on disk has not changed; server // responds w/ a 304 saying I'm not going to send the // body because the file has not changed. httpServletResponse.setIntHeader(STRING_CONTENT_LENGTH_HEADER_NAME, 0); httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED); httpMethodProxyRequest.releaseConnection(); return; } // Pass the response code back to the client httpServletResponse.setStatus(intProxyResponseCode); // Pass response headers back to the client Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders(); for (Header header : headerArrayResponse) { httpServletResponse.setHeader(header.getName(), header.getValue()); } // Send the content to the client InputStream inputStreamProxyResponse = httpMethodProxyRequest.getResponseBodyAsStream(); BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStreamProxyResponse); OutputStream outputStreamClientResponse = httpServletResponse.getOutputStream(); int intNextByte; while ((intNextByte = bufferedInputStream.read()) != -1) { outputStreamClientResponse.write(intNextByte); } httpMethodProxyRequest.releaseConnection(); }
From source file:com.zimbra.cs.fb.ExchangeFreeBusyProvider.java
public List<FreeBusy> getFreeBusyForHost(String host, ArrayList<Request> req) throws IOException { ArrayList<FreeBusy> ret = new ArrayList<FreeBusy>(); int fb_interval = LC.exchange_free_busy_interval_min.intValueWithinRange(5, 1444); Request r = req.get(0);//from w ww. java2 s .c o m ServerInfo serverInfo = (ServerInfo) r.data; if (serverInfo == null) { ZimbraLog.fb.warn("no exchange server info for user " + r.email); return ret; } if (!serverInfo.enabled) { return ret; } String url = constructGetUrl(serverInfo, req); ZimbraLog.fb.debug("fetching fb from url=" + url); HttpMethod method = new GetMethod(url); Element response = null; try { int status = sendRequest(method, serverInfo); if (status != 200) return getEmptyList(req); if (ZimbraLog.fb.isDebugEnabled()) { Header cl = method.getResponseHeader("Content-Length"); int contentLength = 10240; if (cl != null) contentLength = Integer.valueOf(cl.getValue()); String buf = new String(com.zimbra.common.util.ByteUtil.readInput(method.getResponseBodyAsStream(), contentLength, contentLength), "UTF-8"); ZimbraLog.fb.debug(buf); response = Element.parseXML(buf); } else response = Element.parseXML(method.getResponseBodyAsStream()); } catch (XmlParseException e) { ZimbraLog.fb.warn("error parsing fb response from exchange", e); return getEmptyList(req); } catch (IOException e) { ZimbraLog.fb.warn("error parsing fb response from exchange", e); return getEmptyList(req); } finally { method.releaseConnection(); } for (Request re : req) { String fb = getFbString(response, re.email); ret.add(new ExchangeUserFreeBusy(fb, re.email, fb_interval, re.start, re.end)); } return ret; }