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

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

Introduction

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

Prototype

@Override
public StatusLine getStatusLine() 

Source Link

Document

Provides access to the response status line.

Usage

From source file:edu.indiana.d2i.registryext.RegistryExtAgent.java

/**
 * check whether a resource exists//w  ww. j av  a2  s  .co m
 * 
 * @param repoPath
 *            path in registry
 * @return
 * @throws HttpException
 * @throws IOException
 * @throws RegistryExtException
 * @throws OAuthSystemException
 * @throws OAuthProblemException
 */
public boolean isResourceExist(String repoPath)
        throws HttpException, IOException, RegistryExtException, OAuthSystemException, OAuthProblemException {
    Map<String, Object> session = ActionContext.getContext().getSession();

    int statusCode = 200;
    String accessToken = (String) session.get(Constants.SESSION_TOKEN);

    boolean exist = true;

    String requestURL = composeURL(FILEOPPREFIX, repoPath);

    if (logger.isDebugEnabled()) {
        logger.debug("Check existence request URL=" + requestURL);
    }

    HttpClient httpclient = new HttpClient();
    HeadMethod head = new HeadMethod(requestURL);
    head.addRequestHeader("Authorization", "Bearer " + accessToken);

    try {

        httpclient.executeMethod(head);

        statusCode = head.getStatusLine().getStatusCode();

        /* handle token expiration */
        if (statusCode == 401) {
            logger.info(String.format("Access token %s expired, going to refresh it", accessToken));

            refreshToken(session);

            // use refreshed access token
            accessToken = (String) session.get(Constants.SESSION_TOKEN);
            head.addRequestHeader("Authorization", "Bearer " + accessToken);

            // re-send the request
            httpclient.executeMethod(head);

            statusCode = head.getStatusLine().getStatusCode();

        }

        if (statusCode == 404)
            exist = false;
        else if (statusCode != 200) {
            throw new RegistryExtException(
                    "Failed in checking resource existence: HTTP error code : " + statusCode);
        }

    } finally {
        if (head != null)
            head.releaseConnection();
    }
    return exist;
}

From source file:fedora.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  ava 2  s  .  com
            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.parseDateAsUTC(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.convertStringToDate(lastModified);
            } else {
                // return current date time
                return new Date();
            }
        } finally {
            head.releaseConnection();
        }
    }
}

From source file:org.apache.jackrabbit.spi2davex.ValueLoader.java

public Map<String, String> loadHeaders(String uri, String[] headerNames)
        throws IOException, RepositoryException {
    HeadMethod method = new HeadMethod(uri);
    try {/* ww w  . j  a v a 2  s.  co  m*/
        int statusCode = client.executeMethod(method);
        if (statusCode == DavServletResponse.SC_OK) {
            Map<String, String> headers = new HashMap<String, String>();
            for (String name : headerNames) {
                Header hdr = method.getResponseHeader(name);
                if (hdr != null) {
                    headers.put(name, hdr.getValue());
                }
            }
            return headers;
        } else {
            throw ExceptionConverter.generate(new DavException(statusCode, ("Unable to load headers at " + uri
                    + " - Status line = " + method.getStatusLine().toString())));
        }
    } finally {
        method.releaseConnection();
    }
}

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  ww  w.  java 2  s.  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.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 {/*www . j a v  a2  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;
}