Example usage for org.apache.commons.httpclient.methods HeadMethod releaseConnection

List of usage examples for org.apache.commons.httpclient.methods HeadMethod releaseConnection

Introduction

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

Prototype

@Override
public void releaseConnection() 

Source Link

Document

Releases the connection being used by this HTTP method.

Usage

From source file:org.fcrepo.client.FedoraClient.java

public Date getLastModifiedDate(String locator) throws IOException {
    if (locator.startsWith(FEDORA_URI_PREFIX)) {
        String query = "select $date " + "from <#ri> " + "where <" + locator + "> <"
                + VIEW.LAST_MODIFIED_DATE.uri + "> $date";
        Map<String, String> map = new HashMap<String, String>();
        map.put("lang", "itql");
        map.put("query", query);
        TupleIterator tuples = getTuples(map);
        try {/*from   w w w .  j av  a2s.c o m*/
            if (tuples.hasNext()) {
                Map<String, Node> row = tuples.next();
                Literal dateLiteral = (Literal) row.get("date");
                if (dateLiteral == null) {
                    throw new IOException("A row was returned, but it did not contain a 'date' binding");
                }
                return DateUtility.parseDateLoose(dateLiteral.getLexicalForm());
            } else {
                throw new IOException("No rows were returned");
            }
        } catch (TrippiException e) {
            throw new IOException(e.getMessage());
        } finally {
            try {
                tuples.close();
            } catch (Exception e) {
            }
        }
    } else {
        HttpClient client = getHttpClient();

        HeadMethod head = new HeadMethod(locator);
        head.setDoAuthentication(true);
        head.setFollowRedirects(FOLLOW_REDIRECTS);

        try {
            int statusCode = client.executeMethod(head);
            if (statusCode != HttpStatus.SC_OK) {
                throw new IOException("Method failed: " + head.getStatusLine());
            }
            //Header[] headers = head.getResponseHeaders();

            // Retrieve just the last modified header value.
            Header header = head.getResponseHeader("last-modified");
            if (header != null) {
                String lastModified = header.getValue();
                return DateUtility.parseDateLoose(lastModified);
            } else {
                // return current date time
                return new Date();
            }
        } finally {
            head.releaseConnection();
        }
    }
}

From source file:org.globus.cog.abstraction.impl.file.http.FileResourceImpl.java

public GridFile getGridFile(String fileName) throws FileResourceException {
    HeadMethod m = new HeadMethod(contact + '/' + fileName);
    try {/*from  w ww.j a  v a2 s.c o m*/
        int code = client.executeMethod(m);
        try {
            if (code != HttpStatus.SC_OK) {
                throw new FileResourceException("Failed to get file information about " + fileName + " from "
                        + contact + ". Server returned " + code + " (" + HttpStatus.getStatusText(code) + ").");
            }
            GridFile gf = new GridFileImpl();
            gf.setName(fileName);
            Header clh = m.getResponseHeader("Content-Length");
            gf.setSize(Long.parseLong(clh.getValue()));
            return gf;
        } finally {
            m.releaseConnection();
        }
    } catch (FileResourceException e) {
        throw e;
    } catch (Exception e) {
        throw new FileResourceException(e);
    }
}

From source file:org.globus.cog.abstraction.impl.file.http.FileResourceImpl.java

public boolean exists(String filename) throws FileResourceException {
    HeadMethod m = new HeadMethod(contact + '/' + filename);
    try {//from  w w w .jav a2 s  .  c o  m
        int code = client.executeMethod(m);
        try {
            if (code != HttpStatus.SC_OK) {
                return false;
            } else {
                return true;
            }
        } finally {
            m.releaseConnection();
        }
    } catch (Exception e) {
        throw new FileResourceException(e);
    }
}

From source file:org.nuxeo.ecm.core.storage.sql.ScalityBinaryManager.java

/**
 * Verifies if a specific named bucket exists.
 *
 * @param objectID//  w  w  w.j a  v  a2  s . c om
 */
public boolean objectExists(String objectID) {
    boolean objectExists = false;
    String url = PROTOCOL_PREFIX + this.bucketName + "." + this.hostBase;
    log.debug(url);
    HeadMethod headMethod = new HeadMethod(url);
    String contentMD5 = "";
    String stringToSign = StringGenerator.getStringToSign(HTTPMethod.HEAD, contentMD5, DEFAULT_CONTENT_TYPE,
            this.bucketName, objectID, new Date());
    try {
        headMethod.addRequestHeader("Authorization",
                StringGenerator.getAuthorizationString(stringToSign, awsID, awsSecret));
        headMethod.addRequestHeader("x-amz-date", StringGenerator.getCurrentDateString());
        headMethod.setPath("/" + objectID);
        HttpClient client = new HttpClient();
        int returnCode = client.executeMethod(headMethod);
        log.debug(headMethod.getResponseBodyAsString());
        // only for logging
        if (returnCode == HttpStatus.SC_OK) {
            objectExists = true;
        } else if (returnCode == HttpStatus.SC_NOT_FOUND) {
            objectExists = false;
            log.debug("Object " + objectID + " does not exist");
        } else {
            String connectionMsg = "Scality connection problem. Object could not be verified";
            log.debug(connectionMsg);
            throw new RuntimeException(connectionMsg);
        }
        headMethod.releaseConnection();
    } catch (SignatureException e) {
        throw new RuntimeException(e);
    } catch (FileNotFoundException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return objectExists;
}

From source file:org.nuxeo.ecm.core.storage.sql.ScalityBinaryManager.java

/**
 * Retrieves the content-length of the remote object
 *
 * @param objectID//  w  w w  .  j  a v a 2s.  com
 */
public long getContentLength(String objectID) {
    String url = PROTOCOL_PREFIX + this.bucketName + "." + this.hostBase;
    log.debug(url);
    HeadMethod headMethod = new HeadMethod(url);
    String contentMD5 = "";
    String stringToSign = StringGenerator.getStringToSign(HTTPMethod.HEAD, contentMD5, DEFAULT_CONTENT_TYPE,
            this.bucketName, objectID, new Date());
    long contentLength = 0;
    try {
        headMethod.addRequestHeader("Authorization",
                StringGenerator.getAuthorizationString(stringToSign, awsID, awsSecret));
        headMethod.addRequestHeader("x-amz-date", StringGenerator.getCurrentDateString());
        headMethod.setPath("/" + objectID);
        HttpClient client = new HttpClient();
        int returnCode = client.executeMethod(headMethod);
        // specific header
        if (returnCode == HttpStatus.SC_OK) {
            Header contentLengthHeader = headMethod.getResponseHeader("Content-Length");
            contentLength = Long.parseLong(contentLengthHeader.getValue());

        } else if (returnCode == HttpStatus.SC_NOT_FOUND) {
            log.debug("Object " + objectID + " does not exist");
        } else {
            String connectionMsg = "Scality connection problem. Object could not be verified";
            log.debug(connectionMsg);
            throw new RuntimeException(connectionMsg);
        }
        headMethod.releaseConnection();
    } catch (NumberFormatException e) {
        throw new RuntimeException(e);
    } catch (SignatureException e) {
        throw new RuntimeException(e);
    } catch (FileNotFoundException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return contentLength;
}

From source file:org.opens.tanaguru.util.http.HttpRequestHandler.java

public int getHttpStatus(String url) {
    String encodedUrl = getEncodedUrl(url);
    HttpClient httpClient = getHttpClient(encodedUrl);
    HeadMethod head = new HeadMethod(encodedUrl);
    try {/*w ww. j  a  v a  2 s  .co m*/
        LOGGER.debug("executing head request to retrieve page status on " + head.getURI());
        int status = httpClient.executeMethod(head);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("received " + status + " from head request");
            for (Header h : head.getResponseHeaders()) {
                LOGGER.debug("header : " + h.toExternalForm());
            }
        }

        return status;
    } catch (UnknownHostException uhe) {
        LOGGER.warn("UnknownHostException on " + encodedUrl);
        return HttpStatus.SC_NOT_FOUND;
    } catch (IllegalArgumentException iae) {
        LOGGER.warn("IllegalArgumentException on " + encodedUrl);
        return HttpStatus.SC_NOT_FOUND;
    } catch (IOException ioe) {
        LOGGER.warn("IOException on " + encodedUrl);
        ioe.fillInStackTrace();
        return HttpStatus.SC_NOT_FOUND;
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        head.releaseConnection();
    }
}

From source file:org.paxle.crawler.urlRedirector.impl.testers.HttpTester.java

public boolean reject(URI requestUri) {
    // doing a head request to determine the mime-type
    HeadMethod head = null;
    try {//w  w w  . j  a  v  a  2  s .  c o  m
        // trying to do a head request
        head = new HeadMethod(requestUri.toString());
        final int status = this.httpClient.executeMethod(head);

        // skipping not OK ressources
        if (status != HttpStatus.SC_OK) {
            logger.info(
                    String.format("Rejecting URL '%s'. Status-Code was: %s", requestUri, head.getStatusLine()));
            return true;
        }

        // getting mime-type
        final String mimeType = this.getMimeType(head);

        // skipping images / css
        if (mimeType == null || mimeType.startsWith("image/") || mimeType.equalsIgnoreCase("text/css")
                || mimeType.equalsIgnoreCase("text/javascript")
                || mimeType.equalsIgnoreCase("application/x-javascript")) {
            logger.info(String.format("Rejecting URL '%s'. Unsupported mime-type: %s", requestUri, mimeType));
            return true;
        }

        // URI seems to be ok
        return false;
    } catch (NoRouteToHostException e) {
        this.logger.warn(String.format("Rejecting URL %s: %s", requestUri, e.getMessage()));
    } catch (UnknownHostException e) {
        this.logger.warn(String.format("Rejecting URL %s: Unknown host.", requestUri));
    } catch (ConnectException e) {
        this.logger.warn(String.format("Rejecting URL %s: Unable to connect to host.", requestUri));
    } catch (ConnectTimeoutException e) {
        this.logger.warn(String.format("Rejecting URL %s: %s.", requestUri, e.getMessage()));
    } catch (SocketTimeoutException e) {
        this.logger.warn(String.format("Rejecting URL %s: Connection timeout.", requestUri));
    } catch (CircularRedirectException e) {
        this.logger.warn(String.format("Rejecting URL %s: %s", requestUri, e.getMessage()));
    } catch (NoHttpResponseException e) {
        this.logger.warn(String.format("Rejecting URL %s: %s", requestUri, e.getMessage()));
    } catch (ContentLengthLimitExceededException e) {
        this.logger.warn(String.format("Rejecting URL %s: %s", requestUri, e.getMessage()));
    } catch (Throwable e) {
        logger.error(String.format("Rejecting URL '%s': ", requestUri, e.getMessage()), e);
    } finally {
        if (head != null)
            head.releaseConnection();
    }

    return true;
}

From source file:org.springsource.ide.eclipse.commons.internal.core.net.HttpClientTransportService.java

/**
 * Verify availability of resources at the given web locations. Normally
 * this would be done using an HTTP HEAD.
 * //from  w w  w.  jav a  2 s .com
 * @param locations the locations of the resource to verify
 * @param one indicate if only one of the resources must exist
 * @param progressMonitor the monitor
 * @return true if the resource exists
 */
public long getLastModified(java.net.URI uri, IProgressMonitor progressMonitor) throws CoreException {
    WebLocation location = new WebLocation(uri.toString());
    SubMonitor monitor = SubMonitor.convert(progressMonitor);
    monitor.subTask(NLS.bind("Fetching {0}", location.getUrl()));
    try {
        HttpClient client = new HttpClient();
        org.eclipse.mylyn.commons.net.WebUtil.configureHttpClient(client, ""); //$NON-NLS-1$

        HeadMethod method = new HeadMethod(location.getUrl());
        try {
            HostConfiguration hostConfiguration = org.eclipse.mylyn.commons.net.WebUtil
                    .createHostConfiguration(client, location, monitor);
            int result = org.eclipse.mylyn.commons.net.WebUtil.execute(client, hostConfiguration, method,
                    monitor);
            if (result == HttpStatus.SC_OK) {
                Header lastModified = method.getResponseHeader("Last-Modified"); //$NON-NLS-1$
                if (lastModified != null) {
                    try {
                        return DateUtil.parseDate(lastModified.getValue()).getTime();
                    } catch (DateParseException e) {
                        // fall through
                    }
                }
                return 0;
            } else {
                throw toException(location, result);
            }
        } catch (IOException e) {
            throw toException(location, e);
        } finally {
            method.releaseConnection();
        }
    } finally {
        monitor.done();
    }
}

From source file:phex.download.PushRequestSleeper.java

private boolean requestViaPushProxies() {
    assert pushProxyAddresses != null && pushProxyAddresses.length > 0;

    // format: /gnet/push-proxy?guid=<ServentIdAsABase16UrlEncodedString>
    String requestPart = "/gnet/push-proxy?guid=" + clientGUID.toHexString();

    ((SimpleStatisticProvider) statsService
            .getStatisticProvider(StatisticsManager.PUSH_DLDPUSHPROXY_ATTEMPTS_PROVIDER)).increment(1);

    for (int i = 0; i < pushProxyAddresses.length; i++) {
        String urlStr = "http://" + pushProxyAddresses[i].getFullHostName() + requestPart;
        NLogger.debug(PushRequestSleeper.class, "PUSH via push proxy: " + urlStr);

        HttpClient httpClient = HttpClientFactory.createHttpClient();
        httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(1, false));

        httpClient.getParams().setSoTimeout(10000);
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        HeadMethod method = null;
        try {//from ww  w  .  j a v  a 2 s. co m
            method = new HeadMethod(urlStr);
            method.addRequestHeader(GnutellaHeaderNames.X_NODE, serventAddress.getFullHostName());
            method.addRequestHeader("Cache-Control", "no-cache");
            method.addRequestHeader(HTTPHeaderNames.CONNECTION, "close");

            int responseCode = httpClient.executeMethod(method);

            NLogger.debug(PushRequestSleeper.class,
                    "PUSH via push proxy response code: " + responseCode + " (" + urlStr + ')');

            // if 202
            if (responseCode == HttpURLConnection.HTTP_ACCEPTED) {
                ((SimpleStatisticProvider) statsService
                        .getStatisticProvider(StatisticsManager.PUSH_DLDPUSHPROXY_SUCESS_PROVIDER))
                                .increment(1);
                return true;
            }
        } catch (IOException exp) {
            NLogger.warn(PushRequestSleeper.class, exp);
        } finally {
            if (method != null) {
                method.releaseConnection();
            }
        }
    }
    return false;
}