Example usage for org.apache.commons.httpclient HttpMethodBase releaseConnection

List of usage examples for org.apache.commons.httpclient HttpMethodBase releaseConnection

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpMethodBase releaseConnection.

Prototype

@Override
public void releaseConnection() 

Source Link

Document

Releases the connection being used by this HTTP method.

Usage

From source file:org.apache.geronimo.testsuite.security.test.GenericRealmTest.java

private int getHTTPResponseStatus(String username) throws Exception {
    HttpMethodBase httpMethod;
    httpMethod = new PostMethod(url);
    httpMethod.setRequestHeader("SM_USER", username);
    int status = 0;

    HttpClient nclient = new HttpClient();
    status = nclient.executeMethod(httpMethod);
    httpMethod.releaseConnection();
    return status;
}

From source file:org.apache.ivy.util.url.HttpClientHandler.java

public URLInfo getURLInfo(URL url, int timeout) {
    HttpMethodBase method = null;
    try {//from w w  w .java 2  s  .  co m
        if (getRequestMethod() == URLHandler.REQUEST_METHOD_HEAD) {
            method = doHead(url, timeout);
        } else {
            method = doGet(url, timeout);
        }
        if (checkStatusCode(url, method)) {
            return new URLInfo(true, getResponseContentLength(method), getLastModified(method),
                    method.getRequestCharSet());
        }
    } catch (HttpException e) {
        Message.error("HttpClientHandler: " + e.getMessage() + ":" + e.getReasonCode() + "=" + e.getReason()
                + " url=" + url);
    } catch (UnknownHostException e) {
        Message.warn("Host " + e.getMessage() + " not found. url=" + url);
        Message.info("You probably access the destination server through "
                + "a proxy server that is not well configured.");
    } catch (IOException e) {
        Message.error("HttpClientHandler: " + e.getMessage() + " url=" + url);
    } catch (IllegalArgumentException e) {
        // thrown by HttpClient to indicate the URL is not valid, this happens for instance
        // when trying to download a dynamic version (cfr IVY-390)
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
    return UNAVAILABLE;
}

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   ww w .j a  va 2  s  .c o  m*/
 * <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 w w  .j av a 2  s.  c  o m*/
 * <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.archive.crawler.fetcher.OptimizeFetchHTTP.java

protected void innerProcess(final CrawlURI curi) throws InterruptedException {
    if (!canFetch(curi)) {
        // Cannot fetch this, due to protocol, retries, or other problems
        return;/* www. ja v a2s  .com*/
    }

    HttpClient http = this.getClient();
    setLocalIP(http);

    this.curisHandled++;

    // Note begin time
    curi.putLong(A_FETCH_BEGAN_TIME, System.currentTimeMillis());

    // Get a reference to the HttpRecorder that is set into this ToeThread.
    HttpRecorder rec = HttpRecorder.getHttpRecorder();

    // Shall we get a digest on the content downloaded?
    boolean digestContent = ((Boolean) getUncheckedAttribute(curi, ATTR_DIGEST_CONTENT)).booleanValue();
    String algorithm = null;
    if (digestContent) {
        algorithm = ((String) getUncheckedAttribute(curi, ATTR_DIGEST_ALGORITHM));
        rec.getRecordedInput().setDigest(algorithm);
    } else {
        // clear
        rec.getRecordedInput().setDigest((MessageDigest) null);
    }

    // Below we do two inner classes that add check of midfetch
    // filters just as we're about to receive the response body.
    String curiString = curi.getUURI().toString();
    HttpMethodBase method = null;
    if (curi.isPost()) {
        method = new HttpRecorderPostMethod(curiString, rec) {
            protected void readResponseBody(HttpState state, HttpConnection conn)
                    throws IOException, HttpException {
                addResponseContent(this, curi);
                if (checkMidfetchAbort(curi, this.httpRecorderMethod, conn)) {
                    doAbort(curi, this, MIDFETCH_ABORT_LOG);
                } else {
                    super.readResponseBody(state, conn);
                }
            }
        };
    } else {
        method = new HttpRecorderGetMethod(curiString, rec) {
            protected void readResponseBody(HttpState state, HttpConnection conn)
                    throws IOException, HttpException {
                addResponseContent(this, curi);
                if (checkMidfetchAbort(curi, this.httpRecorderMethod, conn)) {
                    doAbort(curi, this, MIDFETCH_ABORT_LOG);
                } else {
                    super.readResponseBody(state, conn);
                }
            }
        };
    }

    HostConfiguration customConfigOrNull = configureMethod(curi, method);

    // Set httpRecorder into curi. Subsequent code both here and later
    // in extractors expects to find the HttpRecorder in the CrawlURI.
    curi.setHttpRecorder(rec);

    // Populate credentials. Set config so auth. is not automatic.
    boolean addedCredentials = populateCredentials(curi, method);
    method.setDoAuthentication(addedCredentials);

    // set hardMax on bytes (if set by operator)
    long hardMax = getMaxLength(curi);
    // set overall timeout (if set by operator)
    long timeoutMs = 1000 * getTimeout(curi);
    // Get max fetch rate (bytes/ms). It comes in in KB/sec
    long maxRateKBps = getMaxFetchRate(curi);
    rec.getRecordedInput().setLimits(hardMax, timeoutMs, maxRateKBps);

    try {
        http.executeMethod(customConfigOrNull, method);
    } catch (RecorderTooMuchHeaderException ex) {
        // when too much header material, abort like other truncations
        doAbort(curi, method, HEADER_TRUNC);
    } catch (IOException e) {
        failedExecuteCleanup(method, curi, e);
        return;
    } catch (ArrayIndexOutOfBoundsException e) {
        // For weird windows-only ArrayIndex exceptions in native
        // code... see
        // http://forum.java.sun.com/thread.jsp?forum=11&thread=378356
        // treating as if it were an IOException
        failedExecuteCleanup(method, curi, e);
        return;
    }

    // set softMax on bytes to get (if implied by content-length) 
    long softMax = method.getResponseContentLength();

    try {
        if (!curi.isSeed() && curi.getFetchStatus() == HttpStatus.SC_NOT_MODIFIED) {
            logger.debug(curi.getUURI().toString() + " is not modify");
            curi.skipToProcessorChain(getController().getPostprocessorChain());
        } else if (!method.isAborted()) {
            // Force read-to-end, so that any socket hangs occur here,
            // not in later modules.
            rec.getRecordedInput().readFullyOrUntil(softMax);
        }
    } catch (RecorderTimeoutException ex) {
        doAbort(curi, method, TIMER_TRUNC);
    } catch (RecorderLengthExceededException ex) {
        doAbort(curi, method, LENGTH_TRUNC);
    } catch (IOException e) {
        cleanup(curi, e, "readFully", S_CONNECT_LOST);
        return;
    } catch (ArrayIndexOutOfBoundsException e) {
        // For weird windows-only ArrayIndex exceptions from native code
        // see http://forum.java.sun.com/thread.jsp?forum=11&thread=378356
        // treating as if it were an IOException
        cleanup(curi, e, "readFully", S_CONNECT_LOST);
        return;
    } finally {
        // ensure recording has stopped
        rec.closeRecorders();
        logger.debug("cloase backup file.&uri= " + curi.getCrawlURIString());
        if (!method.isAborted()) {
            method.releaseConnection();
        }
        // Note completion time
        curi.putLong(A_FETCH_COMPLETED_TIME, System.currentTimeMillis());
        // Set the response charset into the HttpRecord if available.
        setCharacterEncoding(rec, method);
        setSizes(curi, rec);
    }

    if (digestContent) {
        curi.setContentDigest(algorithm, rec.getRecordedInput().getDigestValue());
    }

    logger.info((curi.isPost() ? "POST" : "GET") + " " + curi.getUURI().toString() + " "
            + method.getStatusCode() + " " + rec.getRecordedInput().getSize() + " " + curi.getContentType());

    if (curi.isSuccess() && addedCredentials) {
        // Promote the credentials from the CrawlURI to the CrawlServer
        // so they are available for all subsequent CrawlURIs on this
        // server.
        promoteCredentials(curi);
        if (logger.isDebugEnabled()) {
            // Print out the cookie.  Might help with the debugging.
            Header setCookie = method.getResponseHeader("set-cookie");
            if (setCookie != null) {
                logger.debug(setCookie.toString().trim());
            }
        }
    } else if (method.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
        // 401 is not 'success'.
        handle401(method, curi);
    }

    if (rec.getRecordedInput().isOpen()) {
        logger.error(curi.toString() + " RIS still open. Should have" + " been closed by method release: "
                + Thread.currentThread().getName());
        try {
            rec.getRecordedInput().close();
        } catch (IOException e) {
            logger.error("second-chance RIS close failed", e);
        }
    }
}

From source file:org.collectionspace.services.client.test.BaseServiceTest.java

/**
 * Submits an HTTP request to a specified URL, and returns the
 * status code of the response.  Currently accepts GET and DELETE
 * requests.//  ww w  .  ja  v a 2  s .c  o m
 *
 * @param  method  An HTTP method.
 *
 * @param  url     A String representation of a URL.
 *
 * @return The status code received in the HTTP response.
 */
protected int submitRequest(String method, String url) {
    int statusCode = 0;
    HttpMethodBase httpMethod = null;
    try {
        TestServiceClient client = new TestServiceClient();
        if (method.equals(javax.ws.rs.HttpMethod.DELETE)) {
            httpMethod = new DeleteMethod(url);
        } else if (method.equals(javax.ws.rs.HttpMethod.GET)) {
            httpMethod = new GetMethod(url);
        }
        if (httpMethod != null) {
            statusCode = client.getHttpClient().executeMethod(httpMethod);
        }
    } catch (Exception e) {
        logger.error("Exception during HTTP " + method + " request to " + url + ":", e);
    } finally {
        if (httpMethod != null)
            httpMethod.releaseConnection();
    }
    return statusCode;
}

From source file:org.deegree.portal.owswatch.ServiceInvoker.java

/**
 * Executes the test in the main thread/*from  ww  w .  j  ava 2s. com*/
 *
 */
public void executeTest() {

    ValidatorResponse tmpResponse = null;
    try {
        HttpMethodBase method = serviceConfig.getHttpMethodBase();
        tmpResponse = executeHttpMethod(method);
        method.releaseConnection();
    } catch (OGCWebServiceException e) {
        tmpResponse = new ValidatorResponse("Page Unavailable: " + e.getLocalizedMessage(),
                Status.RESULT_STATE_PAGE_UNAVAILABLE);
        tmpResponse.setLastLapse(-1);
        tmpResponse.setLastTest(Calendar.getInstance().getTime());
    }

    serviceLog.addMessage(tmpResponse, serviceConfig);
}

From source file:org.deegree.portal.owswatch.ServiceInvoker.java

/**
 * @param method/*from w  ww  .  j  a  va2s . c om*/
 * @return The response OGCWebServiceResponseData
 * @throws OGCWebServiceException
 */
protected ValidatorResponse executeHttpMethod(HttpMethodBase method) throws OGCWebServiceException {

    HttpClient client = new HttpClient();
    HttpConnectionManagerParams cmParams = client.getHttpConnectionManager().getParams();
    cmParams.setConnectionTimeout(serviceConfig.getTimeout() * 1000);
    client.getHttpConnectionManager().setParams(cmParams);
    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(2, false));
    ValidatorResponse response = null;
    try {
        long startTime = System.currentTimeMillis();
        int statusCode = client.executeMethod(method);
        long lapse = System.currentTimeMillis() - startTime;
        response = serviceConfig.getValidator().validateAnswer(method, statusCode);

        response.setLastLapse(lapse);
        Calendar date = Calendar.getInstance();
        date.setTimeInMillis(startTime);
        response.setLastTest(date.getTime());
    } catch (Exception e) {
        throw new OGCWebServiceException(e.getLocalizedMessage());
    } finally {
        method.releaseConnection();
    }
    return response;
}

From source file:org.deri.pipes.utils.HttpResponseCache.java

private static HttpResponseData getDataFromRequest(HttpClient client, String location,
        Map<String, String> requestHeaders) throws IOException, HttpException {
    HttpMethodBase method = new GetMethod(location);
    method.setFollowRedirects(true);/*from  w ww.  j a  v  a2s.c om*/
    try {
        if (location.length() > 2000 && location.indexOf('?') >= 0) {
            logger.info("Using post method because request location is very long");
            PostMethod postMethod = new PostMethod(location.substring(0, location.indexOf('?')));
            String urlDecoded = URLDecoder.decode(location.substring(location.indexOf('?') + 1), "UTF-8");
            String[] parts = urlDecoded.split("\\&");
            for (String part : parts) {
                String[] keyval = part.split("=", 2);
                if (keyval.length == 2) {
                    postMethod.addParameter(keyval[0], keyval[1]);
                } else {
                    postMethod.addParameter(keyval[0], "");
                }
            }
            method = postMethod;
        }
        addRequestHeaders(method, requestHeaders);
        int response = client.executeMethod(method);
        HttpResponseData data = new HttpResponseData();
        setExpires(data, method);
        data.setResponse(response);
        data.setCharSet(method.getResponseCharSet());
        Header lastModifiedHeader = method.getResponseHeader(HEADER_LAST_MODIFIED);
        if (lastModifiedHeader != null) {
            data.setLastModified(lastModifiedHeader.getValue());
        }
        Header contentTypeHeader = method.getResponseHeader(HEADER_CONTENT_TYPE);
        if (contentTypeHeader != null) {
            data.setContentType(contentTypeHeader.getValue());
        }
        data.setBody(method.getResponseBody(MAX_CONTENT_SIZE));

        return data;
    } finally {
        method.releaseConnection();
    }
}

From source file:org.eclipse.mylyn.commons.net.WebUtil.java

/**
 * Releases the connection used by <code>method</code>. If <code>monitor</code> is cancelled the connection is
 * aborted to avoid blocking.//from  ww w.jav a 2 s  .c  o  m
 * 
 * @since 3.4
 */
public static void releaseConnection(HttpMethodBase method, IProgressMonitor monitor) {
    if (monitor != null && monitor.isCanceled()) {
        // force a connection close on cancel to avoid blocking to do reading the remainder of the response
        method.abort();
    } else {
        try {
            method.releaseConnection();
        } catch (NullPointerException e) {
            // ignore, see bug 255417
        }
    }
}