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

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

Introduction

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

Prototype

@Override
public void setDoAuthentication(boolean doAuthentication) 

Source Link

Document

Sets whether or not the HTTP method should automatically handle HTTP authentication challenges (status code 401, etc.)

Usage

From source file:fr.jayasoft.ivy.url.HttpClientHandler.java

private HeadMethod doHead(URL url, int timeout) throws IOException, HttpException {
    HttpClient client = getClient(url);//from w  ww . ja v a  2 s . c  o  m
    client.setTimeout(timeout);

    HeadMethod head = new HeadMethod(url.toExternalForm());
    head.setDoAuthentication(useAuthentication(url) || useProxyAuthentication());
    client.executeMethod(head);
    return head;
}

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 {// w  ww .  ja v  a 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.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.ivy.util.url.HttpClientHandler.java

private HeadMethod doHead(URL url, int timeout) throws IOException {
    HttpClient client = getClient();//from  w  ww .  j ava 2 s  .c  o m
    client.setTimeout(timeout);

    HeadMethod head = new HeadMethod(normalizeToString(url));
    head.setDoAuthentication(useAuthentication(url) || useProxyAuthentication());
    client.executeMethod(head);
    return head;
}

From source file:org.apache.maven.plugin.docck.AbstractCheckDocumentationMojo.java

private void checkURL(String url, String description, DocumentationReporter reporter) {
    try {//w  w w . j  av a 2s . co  m
        String protocol = getURLProtocol(url);

        if (protocol.startsWith("http")) {
            if (offline) {
                reporter.warn("Cannot verify " + description + " in offline mode with URL: \'" + url + "\'.");
            } else if (!validUrls.contains(url)) {
                HeadMethod headMethod = new HeadMethod(url);
                headMethod.setFollowRedirects(true);
                headMethod.setDoAuthentication(false);

                try {
                    getLog().debug("Verifying http url: " + url);
                    if (httpClient.executeMethod(headMethod) != HTTP_STATUS_200) {
                        reporter.error("Cannot reach " + description + " with URL: \'" + url + "\'.");
                    } else {
                        validUrls.add(url);
                    }
                } catch (HttpException e) {
                    reporter.error("Cannot reach " + description + " with URL: \'" + url + "\'.\nError: "
                            + e.getMessage());
                } catch (IOException e) {
                    reporter.error("Cannot reach " + description + " with URL: \'" + url + "\'.\nError: "
                            + e.getMessage());
                } finally {
                    headMethod.releaseConnection();
                }
            }
        } else {
            reporter.warn("Non-HTTP " + description + " URL not verified.");
        }
    } catch (MalformedURLException e) {
        reporter.warn("The " + description + " appears to have an invalid URL \'" + url + "\'." + " Message: \'"
                + e.getMessage() + "\'. Trying to access it as a file instead.");

        checkFile(url, description, reporter);
    }
}

From source file:org.eclipse.mylyn.internal.bugzilla.core.BugzillaClient.java

private HeadMethod connectHead(String requestURL, IProgressMonitor monitor) throws IOException, CoreException {
    hostConfiguration = WebUtil.createHostConfiguration(httpClient, location, monitor);
    for (int attempt = 0; attempt < 2; attempt++) {
        // force authentication
        authenticate(monitor);/*from  w  ww.j  av  a  2  s  . c  o m*/

        HeadMethod headMethod = new HeadMethod(WebUtil.getRequestPath(requestURL));
        if (requestURL.contains(QUERY_DELIMITER)) {
            headMethod.setQueryString(requestURL.substring(requestURL.indexOf(QUERY_DELIMITER)));
        }

        headMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=" //$NON-NLS-1$ //$NON-NLS-2$
                + getCharacterEncoding());

        // WARNING!! Setting browser compatability breaks Bugzilla
        // authentication
        // getMethod.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);

        //         headMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new BugzillaRetryHandler());
        headMethod.setDoAuthentication(true);

        int code;
        try {
            code = WebUtil.execute(httpClient, hostConfiguration, headMethod, monitor);
        } catch (IOException e) {
            //            ignore the response
            WebUtil.releaseConnection(headMethod, monitor);
            throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN,
                    RepositoryStatus.ERROR_IO, repositoryUrl.toString(), e));
        }

        if (code == HttpURLConnection.HTTP_OK) {
            return headMethod;
        } else if (code == HttpURLConnection.HTTP_UNAUTHORIZED || code == HttpURLConnection.HTTP_FORBIDDEN) {
            //            ignore the response
            WebUtil.releaseConnection(headMethod, monitor);
            loggedIn = false;
            authenticate(monitor);
        } else if (code == HttpURLConnection.HTTP_PROXY_AUTH) {
            loggedIn = false;
            //            ignore the response
            WebUtil.releaseConnection(headMethod, monitor);
            throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN,
                    RepositoryStatus.ERROR_REPOSITORY_LOGIN, repositoryUrl.toString(),
                    "Proxy authentication required")); //$NON-NLS-1$
        } else {
            //            ignore the response
            WebUtil.releaseConnection(headMethod, monitor);
            throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN,
                    RepositoryStatus.ERROR_NETWORK, "Http error: " + HttpStatus.getStatusText(code))); //$NON-NLS-1$
            // throw new IOException("HttpClient connection error response
            // code: " + code);
        }
    }

    throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN,
            RepositoryStatus.ERROR_REPOSITORY_LOGIN, "All connection attempts to " + repositoryUrl.toString() //$NON-NLS-1$
                    + " failed. Please verify connection and authentication information.")); //$NON-NLS-1$
}

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  a v  a2  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.structr.function.UiFunction.java

protected GraphObjectMap headFromUrl(final ActionContext ctx, final String requestUrl, final String username,
        final String password) throws IOException, FrameworkException {

    final HttpClientParams params = new HttpClientParams(HttpClientParams.getDefaultParams());
    final HttpClient client = new HttpClient(params);
    final HeadMethod headMethod = new HeadMethod(requestUrl);

    if (username != null && password != null) {

        Credentials defaultcreds = new UsernamePasswordCredentials(username, password);
        client.getState().setCredentials(AuthScope.ANY, defaultcreds);
        client.getParams().setAuthenticationPreemptive(true);

        headMethod.setDoAuthentication(true);
    }// w  w  w .  j  a v a2 s .  com

    headMethod.addRequestHeader("Connection", "close");
    // Don't follow redirects automatically, return status code 302 etc. instead
    headMethod.setFollowRedirects(false);

    // add request headers from context
    for (final Map.Entry<String, String> header : ctx.getHeaders().entrySet()) {
        headMethod.addRequestHeader(header.getKey(), header.getValue());
    }

    client.executeMethod(headMethod);

    final GraphObjectMap response = new GraphObjectMap();
    response.setProperty(new IntProperty("status"), headMethod.getStatusCode());
    response.setProperty(new StringProperty("headers"), extractHeaders(headMethod.getResponseHeaders()));

    return response;

}