List of usage examples for org.apache.commons.httpclient HttpMethod releaseConnection
public abstract void releaseConnection();
From source file:com.worldline.easycukes.rest.client.RestService.java
/** * Gets the result of the execution of a get request. the attempt will be * repeated several times in case of failures * * @param path the path on which the request should be sent * @throws Exception if something's going wrong... *///from w ww . jav a 2 s . c o m public void retryGetRequestUntilSucceed(@NonNull String path) throws Exception { String fullpath = path; if (path.startsWith("/")) fullpath = baseUrl + path; log.debug("Sending GET request to " + fullpath + " with several attemps"); final int maxAttempts = Integer.parseInt(ExecutionContext.get(RestConstants.MAX_ATTEMPTS_KEY)); final int timeToWait = Integer.parseInt(ExecutionContext.get(RestConstants.TIME_TO_WAIT_KEY)); final HttpMethod method = new GetMethod(fullpath); try { for (final Map.Entry<String, String> header : requestHeaders.entrySet()) method.setRequestHeader(header.getKey(), header.getValue()); String responseAsString = null; int statusCode; int attempts = 0; boolean success = false; do { // waiting timeToWait seconds Thread.sleep(timeToWait * 1000); statusCode = httpClient.executeMethod(method); attempts++; // check for status code 200 if (statusCode == HttpStatus.SC_OK) { responseAsString = method.getResponseBodyAsString(); success = true; log.info("The result is available! "); } else log.warn("unsuccessful GET request : " + method.getStatusLine() + " | Waiting " + timeToWait + " seconds ..."); } while (!success && maxAttempts > attempts); response = new ResponseWrapper(responseAsString, statusCode); } catch (final Exception e) { log.error(e.getMessage(), e); throw e; } finally { method.releaseConnection(); } }
From source file:com.cloud.test.regression.ApiCommand.java
public Element queryAsyncJobResult(String jobId) { Element returnBody = null;/*from w w w . j av a 2 s . c o m*/ int code = 400; String resultUrl = this.host + ":8096/?command=queryAsyncJobResult&jobid=" + jobId; HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(resultUrl); while (true) { try { code = client.executeMethod(method); if (code == 200) { InputStream is = method.getResponseBodyAsStream(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(is); doc.getDocumentElement().normalize(); returnBody = doc.getDocumentElement(); Element jobStatusTag = (Element) returnBody.getElementsByTagName("jobstatus").item(0); String jobStatus = jobStatusTag.getTextContent(); if (jobStatus.equals("0")) { try { Thread.sleep(1000); } catch (InterruptedException e) { } } else { break; } method.releaseConnection(); } else { s_logger.error("Error during queryJobAsync. Error code is " + code); this.responseCode = code; return null; } } catch (Exception ex) { s_logger.error(ex); } } return returnBody; }
From source file:com.gs.jrpip.client.FastServletProxyInvocationHandler.java
protected Object invokeRemoteMethod(Object proxy, Method method, Object[] args) throws Throwable { if (LOGGER.isDebugEnabled()) { LOGGER.debug("starting remote method {}.{}", method.getDeclaringClass(), method.getName()); }/*from w ww.jav a2s .c om*/ RequestId requestId = new RequestId(this.proxyId); int retries = RETRY_COUNT; int state = SEND_PARAMETERS_STATE; Exception lastException = null; boolean checkServerStatus = false; while (retries > 0) { InputStream is = null; byte status = StreamBasedInvocator.FAULT_STATUS; Object returned = null; HttpClient httpClient = FastServletProxyFactory.getHttpClient(this.url); httpClient.getState().addCookies(this.cookies); boolean gotResult = false; HttpMethod postMethod = null; try { OutputStreamWriter writer = null; switch (state) { case SEND_PARAMETERS_STATE: writer = new ParameterWriter(proxy, method, args, requestId); break; case RECEIVE_RESULT_STATE: writer = new ResultResendWriter(requestId); break; } postMethod = this.getPostMethod(writer); this.setMethodTimeout(postMethod, method); httpClient.executeMethod(postMethod); this.cookies = httpClient.getState().getCookies(); state = RECEIVE_RESULT_STATE; int code = postMethod.getStatusCode(); if (code != 200) { checkServerStatus = true; this.analyzeServerErrorAndThrow(code, postMethod); } is = postMethod.getResponseBodyAsStream(); //if (CAUSE_RANDOM_ERROR) if (Math.random() > ERROR_RATE) throw new IOException("Random error, for testing only!"); status = (byte) is.read(); if (status != StreamBasedInvocator.REQUEST_NEVER_ARRVIED_STATUS) { returned = this.getResult(method, args, is); } gotResult = true; is.close(); is = null; postMethod.releaseConnection(); postMethod = null; } catch (SocketTimeoutException e) { LOGGER.debug("Socket timeout reached for JRPIP invocation", e); throw new JrpipTimeoutException("Remote method " + method.getName() + " timed out." + this.url, e); } catch (NotSerializableException e) { throw new JrpipRuntimeException("Method arguments are not serializable!", e); } catch (ClassNotFoundException e) { throw new JrpipRuntimeException("Method call successfully completed but result class not found", e); } catch (Exception e) { retries--; lastException = e; LOGGER.debug("Exception in JRPIP invocation. Retries left {}", retries, e); } finally { if (is != null) { try { is.close(); } catch (IOException e) { LOGGER.debug("Could not close stream. See previous exception for cause", e); } } if (postMethod != null) { postMethod.releaseConnection(); } } if (gotResult) { switch (status) { case StreamBasedInvocator.OK_STATUS: ThankYouWriter.getINSTANCE().addRequest(this.url, this.cookies, requestId); if (LOGGER.isDebugEnabled()) { LOGGER.debug("finished remote method normally {}.{}", method.getDeclaringClass(), method.getName()); } return returned; case StreamBasedInvocator.FAULT_STATUS: ThankYouWriter.getINSTANCE().addRequest(this.url, this.cookies, requestId); if (LOGGER.isDebugEnabled()) { LOGGER.debug("finished remote method {}.{} with exception {}", method.getDeclaringClass(), method.getName(), returned.getClass().getName(), new JrpipRuntimeException("for tracing local invocation context")); } Class[] exceptions = method.getExceptionTypes(); for (int i = 0; i < exceptions.length; i++) { if (exceptions[i].isAssignableFrom(returned.getClass())) { throw (Throwable) returned; } } if (RuntimeException.class.isAssignableFrom(returned.getClass())) { throw (RuntimeException) returned; } if (Error.class.isAssignableFrom(returned.getClass())) { throw (Error) returned; } if (Throwable.class.isAssignableFrom(returned.getClass()) && !Exception.class.isAssignableFrom(returned.getClass())) { throw (Throwable) returned; } throw new JrpipRuntimeException( "Could not throw returned exception, as it was not declared in the method signature for method " + method.getName(), (Throwable) returned); case StreamBasedInvocator.REQUEST_NEVER_ARRVIED_STATUS: state = SEND_PARAMETERS_STATE; break; } } else { checkServerStatus = true; } if (checkServerStatus) { this.determineServerStatus(state == RECEIVE_RESULT_STATE); checkServerStatus = false; } } throw new JrpipRuntimeException( "Could not invoke remote method " + method.getName() + " while accessing " + this.url, lastException); }
From source file:com.zimbra.qa.unittest.prov.soap.TestAutoProvision.java
@Test public void preauthServlet() throws Exception { String testName = getTestName(); String externalPassword = "test456"; String extAcctLocalPart = testName; String extAcctName = createExternalAcctEntry(extAcctLocalPart, externalPassword, null); Map<String, Object> zimbraDomainAttrs = commonZimbraDomainAttrs(); // setup auto prov // commonZimbraDomainAttrs added only LDAP, add preauth here StringUtil.addToMultiMap(zimbraDomainAttrs, Provisioning.A_zimbraAutoProvAuthMech, AutoProvAuthMech.PREAUTH.name()); zimbraDomainAttrs.put(Provisioning.A_zimbraAutoProvLdapSearchBase, extDomainDn); zimbraDomainAttrs.put(Provisioning.A_zimbraAutoProvLdapSearchFilter, "(uid=%u)"); // setup external LDAP auth zimbraDomainAttrs.put(Provisioning.A_zimbraAuthMech, AuthMech.ldap.name()); zimbraDomainAttrs.put(Provisioning.A_zimbraAuthLdapURL, "ldap://localhost:389"); zimbraDomainAttrs.put(Provisioning.A_zimbraAuthLdapBindDn, "uid=%u,ou=people," + extDomainDn); // setup preauth String preAuthKey = PreAuthKey.generateRandomPreAuthKey(); zimbraDomainAttrs.put(Provisioning.A_zimbraPreAuthKey, preAuthKey); Domain zimbraDomain = createZimbraDomain(testName, zimbraDomainAttrs); String loginName = extAcctLocalPart + "@" + zimbraDomain.getName(); // preauth data String preAuthUrl = TestPreAuthServlet.genPreAuthUrl(preAuthKey, loginName, false, false); // do the preauth servlet request String url = TestUtil.getBaseUrl() + preAuthUrl; HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(url); boolean ok = false; try {//from ww w .ja v a 2s . com int respCode = HttpClientUtil.executeMethod(client, method); int statusCode = method.getStatusCode(); String statusLine = method.getStatusLine().toString(); ok = (respCode == 200); /* System.out.println("respCode=" + respCode); System.out.println("statusCode=" + statusCode); System.out.println("statusLine=" + statusLine); System.out.println("Headers"); Header[] respHeaders = method.getResponseHeaders(); for (int i=0; i < respHeaders.length; i++) { String header = respHeaders[i].toString(); System.out.println(header); } */ /* String respBody = method.getResponseBodyAsString(); System.out.println(respBody); */ } catch (HttpException e) { throw e; } catch (IOException e) { throw e; } finally { method.releaseConnection(); } assertTrue(ok); /* String encodedAuthToken = response.getElement(AccountConstants.E_AUTH_TOKEN).getText(); assertNotNull(encodedAuthToken); AuthToken authToken = AuthToken.getAuthToken(encodedAuthToken); String acctId = authToken.getAccountId(); Account acct = prov.get(AccountBy.id, acctId); verifyAcctAutoProvisioned(acct, loginName.toLowerCase()); */ }
From source file:com.ideabase.repository.webservice.client.impl.HttpWebServiceControllerImpl.java
/** * {@inheritDoc}// w w w . j a v a 2 s . c o m */ public WebServiceResponse sendServiceRequest(final WebServiceRequest pRequest) { if (LOG.isDebugEnabled()) { LOG.debug("Sending request - " + pRequest); } // build query string final NameValuePair[] parameters = buildParameters(pRequest); // Send request to server final HttpMethod httpMethod = prepareMethod(pRequest.getRequestMethod(), pRequest.getServiceUri(), parameters); // set cookie policy httpMethod.getParams().setCookiePolicy(CookiePolicy.RFC_2109); // set cookies if (mCookies != null) { httpMethod.setRequestHeader(HEADER_COOKIE, mCookies); } if (pRequest.getCookies() != null) { httpMethod.setRequestHeader(HEADER_COOKIE, pRequest.getCookies()); mCookies = pRequest.getCookies(); } // execute method final HttpClient httpClient = new HttpClient(); final WebServiceResponse response; try { final int status = httpClient.executeMethod(httpMethod); // build web sercie response response = new WebServiceResponse(); response.setResponseStatus(status); response.setResponseContent(new String(httpMethod.getResponseBody())); response.setContentType(httpMethod.getResponseHeader(HEADER_CONTENT_TYPE).getValue()); response.setServiceUri(httpMethod.getURI().toString()); // set cookies final Header cookieHeader = httpMethod.getResponseHeader(HEADER_SET_COOKIE); if (cookieHeader != null) { mCookies = cookieHeader.getValue(); } // set cookies to the returning response object. response.setCookies(mCookies); if (LOG.isDebugEnabled()) { LOG.debug("Cookies - " + mCookies); LOG.debug("Response - " + response); } } catch (Exception e) { throw ServiceException.aNew(pRequest, "Failed to send web service request.", e); } finally { httpMethod.releaseConnection(); } return response; }
From source file:com.dtolabs.client.utils.HttpClientChannel.java
/** * Perform the HTTP request. Can only be performed once. *///from w w w. j a v a 2s.com public void makeRequest() throws IOException, HttpClientException { if (requestMade) { return; } requestMade = true; RequestEntity reqEntity = null; NameValuePair[] postBody = null; if (isPostMethod()) { setMethodType("POST"); } HttpMethod method = initMethod(); if (isPostMethod()) { reqEntity = getRequestEntity((PostMethod) method); if (null != reqEntity) { logger.debug("preparing to post request entity data: " + reqEntity.getContentType()); ((PostMethod) method).setRequestEntity(reqEntity); } else { logger.debug("preparing to post form data"); postBody = getRequestBody((PostMethod) method); ((PostMethod) method).setRequestBody(postBody); } } logger.debug("calling preMakeRequest"); if (!preMakeRequest(method)) { return; } logger.debug("calling doAuthentication..."); if (!doAuthentication(method)) { return; } int bytesread = 0; try { if (!isPostMethod()) { method.setFollowRedirects(true); } logger.debug("make request..."); resultCode = httpc.executeMethod(method); reasonCode = method.getStatusText(); if (isPostMethod()) { //check redirect after post method = checkFollowRedirect(method, resultCode); } logger.debug("check needs reauth..."); if (needsReAuthentication(resultCode, method)) { logger.debug("re-authentication needed, performing..."); method.releaseConnection(); method.abort(); //need to re-authenticate. method = initMethod(); if (isPostMethod() && null != reqEntity) { ((PostMethod) method).setRequestEntity(reqEntity); } else if (isPostMethod() && null != postBody) { ((PostMethod) method).setRequestBody(postBody); } if (!doAuthentication(method)) { //user login failed return; } //user login has succeeded logger.debug("remaking original request..."); resultCode = httpc.executeMethod(method); reasonCode = method.getStatusText(); if (needsReAuthentication(resultCode, method)) { //user request was unauthorized throw new HttpClientException("Unauthorized Action: " + (null != method.getResponseHeader(Constants.X_RUNDECK_ACTION_UNAUTHORIZED_HEADER) ? method.getResponseHeader(Constants.X_RUNDECK_ACTION_UNAUTHORIZED_HEADER) .getValue() : reasonCode)); } } logger.debug("finish..."); if (null != method.getResponseHeader("Content-Type")) { resultType = method.getResponseHeader("Content-Type").getValue(); } String type = resultType; if (type != null && type.indexOf(";") > 0) { type = type.substring(0, type.indexOf(";")).trim(); } if (null == expectedContentType || expectedContentType.equals(type)) { if (null != destinationStream && resultCode >= 200 && resultCode < 300) { //read the input stream and write it to the destination contentLengthRetrieved = Streams.copyStreamCount(method.getResponseBodyAsStream(), destinationStream); } else { final ByteArrayOutputStream outputBytes = new ByteArrayOutputStream(1024 * 50); Streams.copyStream(method.getResponseBodyAsStream(), outputBytes); resultStream = new ByteArrayInputStream(outputBytes.toByteArray()); } } reqMadeMethod = method; } catch (HttpException e) { logger.error("HTTP error: " + e.getMessage(), e); } finally { method.releaseConnection(); } logger.debug("Response received"); postMakeRequest(); }
From source file:com.taobao.diamond.client.processor.ServerAddressProcessor.java
/** * diamond//from w w w . j a v a 2 s .c o m * * @param acquireCount * 01 * @return */ private boolean acquireServerAddressOnce(int acquireCount) { HostConfiguration hostConfiguration = configHttpClient.getHostConfiguration(); String configServerAddress; int port; if (null != diamondConfigure.getConfigServerAddress()) { configServerAddress = diamondConfigure.getConfigServerAddress(); port = diamondConfigure.getConfigServerPort(); } else { if (acquireCount == 0) { configServerAddress = Constants.DEFAULT_DOMAINNAME; port = Constants.DEFAULT_PORT; } else { configServerAddress = Constants.DAILY_DOMAINNAME; port = Constants.DEFAULT_PORT; } } hostConfiguration.setHost(configServerAddress, port); String serverAddressUrl = Constants.CONFIG_HTTP_URI_FILE; HttpMethod httpMethod = new GetMethod(serverAddressUrl); // HttpMethod HttpMethodParams params = new HttpMethodParams(); params.setSoTimeout(diamondConfigure.getOnceTimeout()); // /////////////////////// httpMethod.setParams(params); try { if (SC_OK == configHttpClient.executeMethod(httpMethod)) { InputStreamReader reader = new InputStreamReader(httpMethod.getResponseBodyAsStream()); BufferedReader bufferedReader = new BufferedReader(reader); String address = null; List<String> newDomainNameList = new LinkedList<String>(); while ((address = bufferedReader.readLine()) != null) { address = address.trim(); if (StringUtils.isNotBlank(address)) { newDomainNameList.add(address); } } if (newDomainNameList.size() > 0) { log.debug(""); this.diamondConfigure.setDomainNameList(newDomainNameList); return true; } } else { log.warn(""); } } catch (HttpException e) { log.error(getErrorMessage(configServerAddress) + ", " + e); } catch (IOException e) { log.error(getErrorMessage(configServerAddress) + ", " + e); } catch (Exception e) { log.error(getErrorMessage(configServerAddress) + ", " + e); } finally { httpMethod.releaseConnection(); } return false; }
From source file:cn.leancloud.diamond.client.processor.ServerAddressProcessor.java
/** * ?diamond??/* ww w.j ava2 s .c o m*/ * * @param acquireCount * ?01? * @return */ private boolean acquireServerAddressOnce(int acquireCount) { HostConfiguration hostConfiguration = configHttpClient.getHostConfiguration(); String configServerAddress; int port; if (null != diamondConfigure.getConfigServerAddress()) { configServerAddress = diamondConfigure.getConfigServerAddress(); port = diamondConfigure.getConfigServerPort(); } else { if (acquireCount == 0) { configServerAddress = Constants.DEFAULT_DOMAINNAME; port = Constants.DEFAULT_PORT; } else { configServerAddress = Constants.DAILY_DOMAINNAME; port = Constants.DEFAULT_PORT; } } hostConfiguration.setHost(configServerAddress, port); String serverAddressUrl = Constants.CONFIG_HTTP_URI_FILE; HttpMethod httpMethod = new GetMethod(serverAddressUrl); // HttpMethod? HttpMethodParams params = new HttpMethodParams(); params.setSoTimeout(diamondConfigure.getOnceTimeout()); // /////////////////////// httpMethod.setParams(params); try { if (SC_OK == configHttpClient.executeMethod(httpMethod)) { InputStreamReader reader = new InputStreamReader(httpMethod.getResponseBodyAsStream()); BufferedReader bufferedReader = new BufferedReader(reader); String address = null; List<String> newDomainNameList = new LinkedList<String>(); while ((address = bufferedReader.readLine()) != null) { address = address.trim(); if (StringUtils.isNotBlank(address)) { newDomainNameList.add(address); } } if (newDomainNameList.size() > 0) { log.debug("?"); this.diamondConfigure.setDomainNameList(newDomainNameList); return true; } } else { log.warn("??"); } } catch (HttpException e) { log.error(getErrorMessage(configServerAddress) + ", " + e); } catch (IOException e) { log.error(getErrorMessage(configServerAddress) + ", " + e); } catch (Exception e) { log.error(getErrorMessage(configServerAddress) + ", " + e); } finally { httpMethod.releaseConnection(); } return false; }
From source file:com.starit.diamond.client.processor.ServerAddressProcessor.java
/** * ?diamond??/*from w ww . j av a2 s. co m*/ * * @param acquireCount * ?01? * @return */ private boolean acquireServerAddressOnce(int acquireCount) { HostConfiguration hostConfiguration = configHttpClient.getHostConfiguration(); String configServerAddress; int port; if (null != diamondConfigure.getConfigServerAddress()) { configServerAddress = diamondConfigure.getConfigServerAddress(); port = diamondConfigure.getConfigServerPort(); } else { if (acquireCount == 0) { configServerAddress = Constants.DEFAULT_DOMAINNAME; port = Constants.DEFAULT_PORT; } else { configServerAddress = Constants.DAILY_DOMAINNAME; port = Constants.DEFAULT_PORT; } } hostConfiguration.setHost(configServerAddress, port); // ??serverURL by leiwen String serverAddressUrl = Constants.BASE_URI + "/" + clusterType; HttpMethod httpMethod = new GetMethod(serverAddressUrl); // HttpMethod? HttpMethodParams params = new HttpMethodParams(); params.setSoTimeout(diamondConfigure.getOnceTimeout()); // /////////////////////// httpMethod.setParams(params); try { if (SC_OK == configHttpClient.executeMethod(httpMethod)) { InputStreamReader reader = new InputStreamReader(httpMethod.getResponseBodyAsStream()); BufferedReader bufferedReader = new BufferedReader(reader); String address = null; List<String> newDomainNameList = new LinkedList<String>(); while ((address = bufferedReader.readLine()) != null) { address = address.trim(); if (StringUtils.isNotBlank(address)) { newDomainNameList.add(address); } } if (newDomainNameList.size() > 0) { log.debug("?"); this.diamondConfigure.setDomainNameList(newDomainNameList); return true; } } else { log.warn("??"); } } catch (HttpException e) { log.error(getErrorMessage(configServerAddress) + ", " + e); } catch (IOException e) { log.error(getErrorMessage(configServerAddress) + ", " + e); } catch (Exception e) { log.error(getErrorMessage(configServerAddress) + ", " + e); } finally { httpMethod.releaseConnection(); } return false; }
From source file:com.jackbe.mapreduce.EMMLRestRunner.java
protected String executeRESTCall(String scriptName, String encodedValue) { // "http://localhost:8080/presto/edge/api/rest/StockQuoteMapper/runMashup?x-presto-resultFormat=xml&value=<encodedValue>" HttpMethod httpMethod = null; String result = null;/*from www . j a v a 2s . com*/ if (encodedValue != null) { httpMethod = new GetMethod(protocol + host + ":" + port + path + scriptName + "/" + operation + "?" + format + "&value=" + encodedValue); log.debug("Invoking REST service: " + protocol + host + ":" + port + path + scriptName + "/" + operation + "?" + format + "&value=" + encodedValue); } else { httpMethod = new GetMethod( protocol + host + ":" + port + path + scriptName + "/" + operation + "?" + format); log.debug("Invoking REST service: " + protocol + host + ":" + port + path + scriptName + "/" + operation + "?" + format); } try { client.executeMethod(httpMethod); if (httpMethod.getStatusCode() != HttpStatus.SC_OK) { log.error("HTTP Error status connecting to Presto: " + httpMethod.getStatusCode()); log.error("HTTP Error message connecting to Presto: " + httpMethod.getStatusText()); return null; } else { if (log.isDebugEnabled()) { log.debug("Status code: " + httpMethod.getStatusCode()); Header contentTypeHeader = httpMethod.getResponseHeader("content-type"); log.debug("Mimetype: " + contentTypeHeader.getValue()); } } result = httpMethod.getResponseBodyAsString(); // log.debug(httpMethod.getStatusText()); if (log.isDebugEnabled()) log.debug("Response: " + result); } catch (Exception e) { log.error("Exception executing REST call: " + e, e); } finally { httpMethod.releaseConnection(); } return result; }