List of usage examples for org.apache.commons.httpclient HttpMethod releaseConnection
public abstract void releaseConnection();
From source file:org.alfresco.repo.transfer.HttpClientTransmitterImpl.java
public void prepare(Transfer transfer) throws TransferException { TransferTarget target = transfer.getTransferTarget(); HttpMethod prepareRequest = getPostMethod(); try {//from ww w . j a va 2s . co m HostConfiguration hostConfig = getHostConfig(target); HttpState httpState = getHttpState(target); prepareRequest.setPath(target.getEndpointPath() + "/prepare"); //Put the transferId on the query string prepareRequest.setQueryString( new NameValuePair[] { new NameValuePair("transferId", transfer.getTransferId()) }); try { int responseStatus = httpClient.executeMethod(hostConfig, prepareRequest, httpState); checkResponseStatus("prepare", responseStatus, prepareRequest); //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[] { "prepare", target.toString(), e.toString() }, e); } } finally { prepareRequest.releaseConnection(); } }
From source file:org.alfresco.repo.transfer.HttpClientTransmitterImpl.java
/** * *//* w ww. j a va 2 s.co m*/ public TransferProgress getStatus(Transfer transfer) throws TransferException { TransferTarget target = transfer.getTransferTarget(); HttpMethod statusRequest = getPostMethod(); try { HostConfiguration hostConfig = getHostConfig(target); HttpState httpState = getHttpState(target); statusRequest.setPath(target.getEndpointPath() + "/status"); //Put the transferId on the query string statusRequest.setQueryString( new NameValuePair[] { new NameValuePair("transferId", transfer.getTransferId()) }); try { int responseStatus = httpClient.executeMethod(hostConfig, statusRequest, httpState); checkResponseStatus("status", responseStatus, statusRequest); //If we get here then we've received a 200 response String statusPayload = statusRequest.getResponseBodyAsString(); JSONObject statusObj = new JSONObject(statusPayload); //We're expecting the transfer progress encoded in a JSON object... int currentPosition = statusObj.getInt("currentPosition"); int endPosition = statusObj.getInt("endPosition"); String statusStr = statusObj.getString("status"); TransferProgress p = new TransferProgress(); if (statusObj.has("error")) { JSONObject errorJSON = statusObj.getJSONObject("error"); Throwable throwable = rehydrateError(errorJSON); p.setError(throwable); } p.setStatus(TransferProgress.Status.valueOf(statusStr)); p.setCurrentPosition(currentPosition); p.setEndPosition(endPosition); return p; } 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[] { "status", target.toString(), e.toString() }, e); } } finally { statusRequest.releaseConnection(); } }
From source file:org.alfresco.rest.api.tests.client.AuthenticatedHttp.java
/** * Execute the given method, authenticated as the given user using Basic Authentication. * @param method method to execute//from ww w. j a v a 2s.c o m * @param userName name of user to authenticate (note: if null then attempts to run with no authentication - eq. Quick/Shared Link test) * @param callback called after http-call is executed. When callback returns, the * response stream is closed, so all respose-related operations should be done in the callback. Can be null. * @return result returned by the callback or null if no callback is given. */ private <T extends Object> T executeWithBasicAuthentication(HttpMethod method, String userName, String password, HttpRequestCallback<T> callback) { try { HttpState state = new HttpState(); if (userName != null) { state.setCredentials(new AuthScope(null, AuthScope.ANY_PORT), new UsernamePasswordCredentials(userName, password)); } httpProvider.getHttpClient().executeMethod(null, method, state); if (callback != null) { return callback.onCallSuccess(method); } // No callback used, return null return null; } catch (Throwable t) { boolean handled = false; // Delegate to callback to handle error. If not available, throw exception if (callback != null) { handled = callback.onError(method, t); } if (!handled) { throw new RuntimeException("Error while executing HTTP-call (" + method.getPath() + ")", t); } return null; } finally { method.releaseConnection(); } }
From source file:org.alfresco.rest.api.tests.client.AuthenticatedHttp.java
/** * Execute the given method, authenticated as the given user using ticket-based authentication. * @param method method to execute//from w ww . ja va 2 s . c o m * @param userName name of user to authenticate * @return status-code resulting from the request */ private <T extends Object> T executeWithTicketAuthentication(HttpMethod method, String userName, String password, HttpRequestCallback<T> callback) { String ticket = authDetailProvider.getTicketForUser(userName); if (ticket == null) { ticket = fetchLoginTicket(userName, password); authDetailProvider.updateTicketForUser(userName, ticket); } try { HttpState state = applyTicketToMethod(method, ticket); // Try executing the method int result = httpProvider.getHttpClient().executeMethod(null, method, state); if (result == HttpStatus.SC_UNAUTHORIZED || result == HttpStatus.SC_FORBIDDEN) { method.releaseConnection(); if (!method.validate()) { throw new RuntimeException( "Ticket re-authentication failed for user " + userName + " (HTTPMethod not reusable)"); } // Fetch new ticket, store and apply to HttpMethod ticket = fetchLoginTicket(userName, userName); authDetailProvider.updateTicketForUser(userName, ticket); state = applyTicketToMethod(method, ticket); // Run method agian with new ticket result = httpProvider.getHttpClient().executeMethod(null, method, state); } if (callback != null) { return callback.onCallSuccess(method); } return null; } catch (Throwable t) { boolean handled = false; // Delegate to callback to handle error. If not available, throw exception if (callback != null) { handled = callback.onError(method, t); } if (!handled) { throw new RuntimeException("Error while executing HTTP-call (" + method.getPath() + ")", t); } return null; } finally { method.releaseConnection(); } }
From source file:org.alfresco.rest.api.tests.client.PublicApiHttpClient.java
public HttpResponse submitRequest(HttpMethod req, final RequestContext rq) throws HttpException, IOException { try {//from w w w . j av a2 s . c o m final long start = System.currentTimeMillis(); final HttpRequestCallback<HttpResponse> callback = new HttpRequestCallback<HttpResponse>() { @Override public HttpResponse onCallSuccess(HttpMethod method) throws Exception { long end = System.currentTimeMillis(); Map<String, String> headersMap = null; Header[] headers = method.getResponseHeaders(); if (headers != null) { headersMap = new HashMap<String, String>(headers.length); for (Header header : headers) { headersMap.put(header.getName(), header.getValue()); } } return new HttpResponse(method, rq.getRunAsUser(), method.getResponseBody(), headersMap, (end - start)); } @Override public boolean onError(HttpMethod method, Throwable t) { return false; } }; HttpResponse response = null; if (rq.getPassword() != null) { response = authenticatedHttp.executeHttpMethodAuthenticated(req, rq.getRunAsUser(), rq.getPassword(), callback); } else { response = authenticatedHttp.executeHttpMethodAuthenticated(req, rq.getRunAsUser(), callback); } return response; } finally { if (req != null) { req.releaseConnection(); } } }
From source file:org.alfresco.wcm.client.impl.WebScriptCallerImpl.java
private void executeRequest(WebscriptResponseHandler handler, HttpMethod httpMethod, boolean ignoreUnauthorized) { long startTime = 0L; if (log.isDebugEnabled()) { startTime = System.currentTimeMillis(); }/*from w w w.java2s . co m*/ try { httpClient.executeMethod(httpMethod); if ((httpMethod.getStatusCode() == 401 || httpMethod.getStatusCode() == 403) && !ignoreUnauthorized) { discardResponse(httpMethod); this.getTicket(username, password); httpClient.executeMethod(httpMethod); } if (httpMethod.getStatusCode() == 200) { handler.handleResponse(httpMethod.getResponseBodyAsStream()); } else { // Must read the response, even though we don't use it discardResponse(httpMethod); } } catch (RuntimeException ex) { log.error("Rethrowing runtime exception.", ex); throw ex; } catch (Exception ex) { log.error("Failed to make request to Alfresco web script", ex); } finally { if (log.isDebugEnabled()) { log.debug(httpMethod.getName() + " request to " + httpMethod.getPath() + "?" + httpMethod.getQueryString() + " completed in " + (System.currentTimeMillis() - startTime) + "ms"); } httpMethod.releaseConnection(); } }
From source file:org.alfresco.web.bean.ajax.PresenceProxyBean.java
/** * Perform request/*from ww w . j ava2s . co m*/ */ public String getUrlResponse(String requestUrl) { String response = ""; HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(requestUrl); method.setRequestHeader("Accept", "*/*"); client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); try { int statusCode = client.executeMethod(method); if (statusCode == HttpStatus.SC_OK) { response = method.getResponseBodyAsString(); } else { response = method.getStatusText(); } } catch (HttpException e) { response = e.getMessage(); } catch (IOException e) { response = e.getMessage(); } finally { // Release the connection. method.releaseConnection(); } return response; }
From source file:org.apache.axis2.transport.http.HTTPSender.java
private void cleanup(MessageContext msgContext, HttpMethod method) { if (msgContext.isPropertyTrue(HTTPConstants.AUTO_RELEASE_CONNECTION)) { log.trace("AutoReleasing " + method); method.releaseConnection(); }/* w w w. jav a2 s . c om*/ }
From source file:org.apache.camel.component.http.HttpPollingConsumer.java
protected Exchange doReceive(int timeout) { Exchange exchange = endpoint.createExchange(); HttpMethod method = createMethod(exchange); // set optional timeout in millis if (timeout > 0) { method.getParams().setSoTimeout(timeout); }// w w w. j a v a 2s . c o m try { // execute request int responseCode = httpClient.executeMethod(method); Object body = HttpHelper.readResponseBodyFromInputStream(method.getResponseBodyAsStream(), exchange); // lets store the result in the output message. Message message = exchange.getOut(); message.setBody(body); // lets set the headers Header[] headers = method.getResponseHeaders(); HeaderFilterStrategy strategy = endpoint.getHeaderFilterStrategy(); for (Header header : headers) { String name = header.getName(); // mapping the content-type if (name.toLowerCase().equals("content-type")) { name = Exchange.CONTENT_TYPE; } String value = header.getValue(); if (strategy != null && !strategy.applyFilterToExternalHeaders(name, value, exchange)) { message.setHeader(name, value); } } message.setHeader(Exchange.HTTP_RESPONSE_CODE, responseCode); return exchange; } catch (IOException e) { throw new RuntimeCamelException(e); } finally { method.releaseConnection(); } }
From source file:org.apache.camel.component.http.HttpProducer.java
public void process(Exchange exchange) throws Exception { // if we bridge endpoint then we need to skip matching headers with the HTTP_QUERY to avoid sending // duplicated headers to the receiver, so use this skipRequestHeaders as the list of headers to skip Map<String, Object> skipRequestHeaders = null; if (getEndpoint().isBridgeEndpoint()) { exchange.setProperty(Exchange.SKIP_GZIP_ENCODING, Boolean.TRUE); String queryString = exchange.getIn().getHeader(Exchange.HTTP_QUERY, String.class); if (queryString != null) { skipRequestHeaders = URISupport.parseQuery(queryString); }/*from w w w .ja v a 2 s .com*/ // Need to remove the Host key as it should be not used exchange.getIn().getHeaders().remove("host"); } HttpMethod method = createMethod(exchange); Message in = exchange.getIn(); String httpProtocolVersion = in.getHeader(Exchange.HTTP_PROTOCOL_VERSION, String.class); if (httpProtocolVersion != null) { // set the HTTP protocol version HttpMethodParams params = method.getParams(); params.setVersion(HttpVersion.parse(httpProtocolVersion)); } HeaderFilterStrategy strategy = getEndpoint().getHeaderFilterStrategy(); // propagate headers as HTTP headers for (Map.Entry<String, Object> entry : in.getHeaders().entrySet()) { String key = entry.getKey(); Object headerValue = in.getHeader(key); if (headerValue != null) { // use an iterator as there can be multiple values. (must not use a delimiter, and allow empty values) final Iterator<?> it = ObjectHelper.createIterator(headerValue, null, true); // the value to add as request header final List<String> values = new ArrayList<String>(); // if its a multi value then check each value if we can add it and for multi values they // should be combined into a single value while (it.hasNext()) { String value = exchange.getContext().getTypeConverter().convertTo(String.class, it.next()); // we should not add headers for the parameters in the uri if we bridge the endpoint // as then we would duplicate headers on both the endpoint uri, and in HTTP headers as well if (skipRequestHeaders != null && skipRequestHeaders.containsKey(key)) { continue; } if (value != null && strategy != null && !strategy.applyFilterToCamelHeaders(key, value, exchange)) { values.add(value); } } // add the value(s) as a http request header if (values.size() > 0) { // use the default toString of a ArrayList to create in the form [xxx, yyy] // if multi valued, for a single value, then just output the value as is String s = values.size() > 1 ? values.toString() : values.get(0); method.addRequestHeader(key, s); } } } // lets store the result in the output message. try { if (LOG.isDebugEnabled()) { LOG.debug("Executing http {} method: {}", method.getName(), method.getURI().toString()); } int responseCode = executeMethod(method); LOG.debug("Http responseCode: {}", responseCode); if (!throwException) { // if we do not use failed exception then populate response for all response codes populateResponse(exchange, method, in, strategy, responseCode); } else { if (responseCode >= 100 && responseCode < 300) { // only populate response for OK response populateResponse(exchange, method, in, strategy, responseCode); } else { // operation failed so populate exception to throw throw populateHttpOperationFailedException(exchange, method, responseCode); } } } finally { method.releaseConnection(); } }