Example usage for org.apache.commons.httpclient HttpStatus SC_UNAUTHORIZED

List of usage examples for org.apache.commons.httpclient HttpStatus SC_UNAUTHORIZED

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpStatus SC_UNAUTHORIZED.

Prototype

int SC_UNAUTHORIZED

To view the source code for org.apache.commons.httpclient HttpStatus SC_UNAUTHORIZED.

Click Source Link

Document

<tt>401 Unauthorized</tt> (HTTP/1.0 - RFC 1945)

Usage

From source file:org.apache.maven.wagon.providers.http.HttpWagon.java

public List getFileList(String destinationDirectory)
        throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException {
    if (destinationDirectory.length() > 0 && !destinationDirectory.endsWith("/")) {
        destinationDirectory += "/";
    }//  w ww  .j av a 2s  .  c  o m

    String url = getRepository().getUrl() + "/" + destinationDirectory;

    GetMethod getMethod = new GetMethod(url);

    try {
        int statusCode = execute(getMethod);

        fireTransferDebug(url + " - Status code: " + statusCode);

        // TODO [BP]: according to httpclient docs, really should swallow the output on error. verify if that is required
        switch (statusCode) {
        case HttpStatus.SC_OK:
            break;

        case SC_NULL:
            throw new TransferFailedException("Failed to transfer file: ");

        case HttpStatus.SC_FORBIDDEN:
            throw new AuthorizationException("Access denied to: " + url);

        case HttpStatus.SC_UNAUTHORIZED:
            throw new AuthorizationException("Not authorized.");

        case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED:
            throw new AuthorizationException("Not authorized by proxy.");

        case HttpStatus.SC_NOT_FOUND:
            throw new ResourceDoesNotExistException("File: " + url + " does not exist");

            //add more entries here
        default:
            throw new TransferFailedException(
                    "Failed to transfer file: " + url + ". Return code is: " + statusCode);
        }

        InputStream is = null;

        is = getMethod.getResponseBodyAsStream();

        return HtmlFileListParser.parseFileList(url, is);
    } catch (IOException e) {
        throw new TransferFailedException("Could not read response body.", e);
    } finally {
        getMethod.releaseConnection();
    }
}

From source file:org.apache.maven.wagon.providers.webdav.AbstractHttpClientWagon.java

public boolean resourceExists(String resourceName) throws TransferFailedException, AuthorizationException {
    StringBuilder url = new StringBuilder(getRepository().getUrl());
    if (!url.toString().endsWith("/")) {
        url.append('/');
    }/*w  ww.j  av a  2  s .co  m*/
    url.append(resourceName);
    HeadMethod headMethod = new HeadMethod(url.toString());

    int statusCode;
    try {
        statusCode = execute(headMethod);
    } catch (IOException e) {
        throw new TransferFailedException(e.getMessage(), e);
    }
    try {
        switch (statusCode) {
        case HttpStatus.SC_OK:
            return true;

        case HttpStatus.SC_NOT_MODIFIED:
            return true;

        case SC_NULL:
            throw new TransferFailedException("Failed to transfer file: " + url);

        case HttpStatus.SC_FORBIDDEN:
            throw new AuthorizationException("Access denied to: " + url);

        case HttpStatus.SC_UNAUTHORIZED:
            throw new AuthorizationException("Not authorized.");

        case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED:
            throw new AuthorizationException("Not authorized by proxy.");

        case HttpStatus.SC_NOT_FOUND:
            return false;

        //add more entries here
        default:
            throw new TransferFailedException(
                    "Failed to transfer file: " + url + ". Return code is: " + statusCode);
        }
    } finally {
        headMethod.releaseConnection();
    }
}

From source file:org.apache.maven.wagon.providers.webdav.AbstractHttpClientWagon.java

public void fillInputData(InputData inputData)
        throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException {
    Resource resource = inputData.getResource();

    StringBuilder url = new StringBuilder(getRepository().getUrl());
    if (!url.toString().endsWith("/")) {
        url.append('/');
    }//from  ww  w.ja va  2s  . co  m
    url.append(resource.getName());

    getMethod = new GetMethod(url.toString());

    long timestamp = resource.getLastModified();
    if (timestamp > 0) {
        SimpleDateFormat fmt = new SimpleDateFormat("EEE, dd-MMM-yy HH:mm:ss zzz", Locale.US);
        fmt.setTimeZone(GMT_TIME_ZONE);
        Header hdr = new Header("If-Modified-Since", fmt.format(new Date(timestamp)));
        fireTransferDebug("sending ==> " + hdr + "(" + timestamp + ")");
        getMethod.addRequestHeader(hdr);
    }

    int statusCode;
    try {
        statusCode = execute(getMethod);
    } catch (IOException e) {
        fireTransferError(resource, e, TransferEvent.REQUEST_GET);

        throw new TransferFailedException(e.getMessage(), e);
    }

    fireTransferDebug(url + " - Status code: " + statusCode);

    // TODO [BP]: according to httpclient docs, really should swallow the output on error. verify if that is
    // required
    switch (statusCode) {
    case HttpStatus.SC_OK:
        break;

    case HttpStatus.SC_NOT_MODIFIED:
        // return, leaving last modified set to original value so getIfNewer should return unmodified
        return;

    case SC_NULL: {
        TransferFailedException e = new TransferFailedException("Failed to transfer file: " + url);
        fireTransferError(resource, e, TransferEvent.REQUEST_GET);
        throw e;
    }

    case HttpStatus.SC_FORBIDDEN:
        fireSessionConnectionRefused();
        throw new AuthorizationException("Access denied to: " + url);

    case HttpStatus.SC_UNAUTHORIZED:
        fireSessionConnectionRefused();
        throw new AuthorizationException("Not authorized.");

    case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED:
        fireSessionConnectionRefused();
        throw new AuthorizationException("Not authorized by proxy.");

    case HttpStatus.SC_NOT_FOUND:
        throw new ResourceDoesNotExistException("File: " + url + " does not exist");

        // add more entries here
    default: {
        cleanupGetTransfer(resource);
        TransferFailedException e = new TransferFailedException(
                "Failed to transfer file: " + url + ". Return code is: " + statusCode);
        fireTransferError(resource, e, TransferEvent.REQUEST_GET);
        throw e;
    }
    }

    InputStream is = null;

    Header contentLengthHeader = getMethod.getResponseHeader("Content-Length");

    if (contentLengthHeader != null) {
        try {
            long contentLength = Integer.valueOf(contentLengthHeader.getValue()).intValue();

            resource.setContentLength(contentLength);
        } catch (NumberFormatException e) {
            fireTransferDebug(
                    "error parsing content length header '" + contentLengthHeader.getValue() + "' " + e);
        }
    }

    Header lastModifiedHeader = getMethod.getResponseHeader("Last-Modified");

    long lastModified = 0;

    if (lastModifiedHeader != null) {
        try {
            lastModified = DateUtil.parseDate(lastModifiedHeader.getValue()).getTime();

            resource.setLastModified(lastModified);
        } catch (DateParseException e) {
            fireTransferDebug("Unable to parse last modified header");
        }

        fireTransferDebug("last-modified = " + lastModifiedHeader.getValue() + " (" + lastModified + ")");
    }

    Header contentEncoding = getMethod.getResponseHeader("Content-Encoding");
    boolean isGZipped = contentEncoding != null && "gzip".equalsIgnoreCase(contentEncoding.getValue());

    try {
        is = getMethod.getResponseBodyAsStream();
        if (isGZipped) {
            is = new GZIPInputStream(is);
        }
    } catch (IOException e) {
        fireTransferError(resource, e, TransferEvent.REQUEST_GET);

        String msg = "Error occurred while retrieving from remote repository:" + getRepository() + ": "
                + e.getMessage();

        throw new TransferFailedException(msg, e);
    }

    inputData.setInputStream(is);
}

From source file:org.apache.maven.wagon.shared.http.AbstractHttpClientWagon.java

public boolean resourceExists(String resourceName) throws TransferFailedException, AuthorizationException {
    String url = getRepository().getUrl() + "/" + resourceName;
    HeadMethod headMethod = new HeadMethod(url);
    int statusCode;
    try {/*w w w . j  a va  2 s.  co  m*/
        statusCode = execute(headMethod);
    } catch (IOException e) {
        throw new TransferFailedException(e.getMessage(), e);
    }
    try {
        switch (statusCode) {
        case HttpStatus.SC_OK:
            return true;

        case HttpStatus.SC_NOT_MODIFIED:
            return true;

        case SC_NULL:
            throw new TransferFailedException("Failed to transfer file: " + url);

        case HttpStatus.SC_FORBIDDEN:
            throw new AuthorizationException("Access denied to: " + url);

        case HttpStatus.SC_UNAUTHORIZED:
            throw new AuthorizationException("Not authorized.");

        case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED:
            throw new AuthorizationException("Not authorized by proxy.");

        case HttpStatus.SC_NOT_FOUND:
            return false;

        //add more entries here
        default:
            throw new TransferFailedException(
                    "Failed to transfer file: " + url + ". Return code is: " + statusCode);
        }
    } finally {
        headMethod.releaseConnection();
    }
}

From source file:org.apache.maven.wagon.shared.http.AbstractHttpClientWagon.java

public void fillInputData(InputData inputData)
        throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException {
    Resource resource = inputData.getResource();

    String url = getRepository().getUrl() + "/" + resource.getName();
    getMethod = new GetMethod(url);
    long timestamp = resource.getLastModified();
    if (timestamp > 0) {
        SimpleDateFormat fmt = new SimpleDateFormat("EEE, dd-MMM-yy HH:mm:ss zzz", Locale.US);
        fmt.setTimeZone(GMT_TIME_ZONE);/*from  w ww  . ja v a2s . c o  m*/
        Header hdr = new Header("If-Modified-Since", fmt.format(new Date(timestamp)));
        fireTransferDebug("sending ==> " + hdr + "(" + timestamp + ")");
        getMethod.addRequestHeader(hdr);
    }

    int statusCode;
    try {
        statusCode = execute(getMethod);
    } catch (IOException e) {
        fireTransferError(resource, e, TransferEvent.REQUEST_GET);

        throw new TransferFailedException(e.getMessage(), e);
    }

    fireTransferDebug(url + " - Status code: " + statusCode);

    // TODO [BP]: according to httpclient docs, really should swallow the output on error. verify if that is
    // required
    switch (statusCode) {
    case HttpStatus.SC_OK:
        break;

    case HttpStatus.SC_NOT_MODIFIED:
        // return, leaving last modified set to original value so getIfNewer should return unmodified
        return;

    case SC_NULL: {
        TransferFailedException e = new TransferFailedException("Failed to transfer file: " + url);
        fireTransferError(resource, e, TransferEvent.REQUEST_GET);
        throw e;
    }

    case HttpStatus.SC_FORBIDDEN:
        fireSessionConnectionRefused();
        throw new AuthorizationException("Access denied to: " + url);

    case HttpStatus.SC_UNAUTHORIZED:
        fireSessionConnectionRefused();
        throw new AuthorizationException("Not authorized.");

    case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED:
        fireSessionConnectionRefused();
        throw new AuthorizationException("Not authorized by proxy.");

    case HttpStatus.SC_NOT_FOUND:
        throw new ResourceDoesNotExistException("File: " + url + " does not exist");

        // add more entries here
    default: {
        cleanupGetTransfer(resource);
        TransferFailedException e = new TransferFailedException(
                "Failed to transfer file: " + url + ". Return code is: " + statusCode);
        fireTransferError(resource, e, TransferEvent.REQUEST_GET);
        throw e;
    }
    }

    InputStream is = null;

    Header contentLengthHeader = getMethod.getResponseHeader("Content-Length");

    if (contentLengthHeader != null) {
        try {
            long contentLength = Integer.valueOf(contentLengthHeader.getValue()).intValue();

            resource.setContentLength(contentLength);
        } catch (NumberFormatException e) {
            fireTransferDebug(
                    "error parsing content length header '" + contentLengthHeader.getValue() + "' " + e);
        }
    }

    Header lastModifiedHeader = getMethod.getResponseHeader("Last-Modified");

    long lastModified = 0;

    if (lastModifiedHeader != null) {
        try {
            lastModified = DateUtil.parseDate(lastModifiedHeader.getValue()).getTime();

            resource.setLastModified(lastModified);
        } catch (DateParseException e) {
            fireTransferDebug("Unable to parse last modified header");
        }

        fireTransferDebug("last-modified = " + lastModifiedHeader.getValue() + " (" + lastModified + ")");
    }

    Header contentEncoding = getMethod.getResponseHeader("Content-Encoding");
    boolean isGZipped = contentEncoding == null ? false : "gzip".equalsIgnoreCase(contentEncoding.getValue());

    try {
        is = getMethod.getResponseBodyAsStream();
        if (isGZipped) {
            is = new GZIPInputStream(is);
        }
    } catch (IOException e) {
        fireTransferError(resource, e, TransferEvent.REQUEST_GET);

        String msg = "Error occurred while retrieving from remote repository:" + getRepository() + ": "
                + e.getMessage();

        throw new TransferFailedException(msg, e);
    }

    inputData.setInputStream(is);
}

From source file:org.apache.webdav.cmd.Client.java

private void handleException(Exception ex) {
    if (ex instanceof HttpException) {
        if (((HttpException) ex).getReasonCode() == HttpStatus.SC_METHOD_NOT_ALLOWED) {
            out.println("Warning: Not WebDAV-enabled?");
        } else if (((HttpException) ex).getReasonCode() == HttpStatus.SC_UNAUTHORIZED) {
            out.println("Warning: Unauthorized");
        } else {/*  w w w.ja  va2 s  .com*/
            out.println("Warning: " + ex.getMessage());
        }
    } else if (ex instanceof IOException) {
        out.println("Error: " + ex.getMessage());
    } else {
        out.println("Fatal Error: " + ex.getMessage());
        ex.printStackTrace(out);
        out.println("Please, email to slide-user@jakarta.apache.org");
        System.exit(-1);
    }
}

From source file:org.apache.webdav.cmd.Client.java

void connect(String uri) {

    if (!uri.endsWith("/") && !uri.endsWith("\\")) {
        // append / to the path
        uri += "/";
    }//from  w  ww . j  av a  2s. co m

    out.println("connect " + uri);

    try {
        // Set up for processing WebDAV resources
        httpURL = uriToHttpURL(uri);
        if (webdavResource == null) {
            webdavResource = new WebdavResource(httpURL);
            webdavResource.setDebug(debugLevel);

            // is not a collection?
            if (!((ResourceTypeProperty) webdavResource.getResourceType()).isCollection()) {
                webdavResource = null;
                httpURL = null;
                out.println("Error: " + uri + " is not a collection! Use open/connect only for collections!");
            }

        } else {
            webdavResource.close();
            webdavResource.setHttpURL(httpURL);
        }
        setPath(webdavResource.getPath());
    } catch (HttpException we) {
        out.print("HttpException.getReasonCode(): " + we.getReasonCode());
        if (we.getReasonCode() == HttpStatus.SC_UNAUTHORIZED) {
            try {
                out.print("UserName: ");
                BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
                String userName = in.readLine();
                if ((userName == null) || (userName.length() == 0)) {
                    disconnect();
                    return;
                }
                userName = userName.trim();
                System.out.print("Password: ");
                String password = in.readLine();
                if (password != null)
                    password = password.trim();
                try {
                    if (webdavResource != null)
                        webdavResource.close();
                } catch (IOException e) {
                } finally {
                    httpURL = null;
                    webdavResource = null;
                }
                httpURL = uriToHttpURL(uri);
                // It should be used like this way.
                httpURL.setUserinfo(userName, password);
                webdavResource = new WebdavResource(httpURL);
                webdavResource.setDebug(debugLevel);
                setPath(webdavResource.getPath());

                if (!((ResourceTypeProperty) webdavResource.getResourceType()).isCollection()) {
                    webdavResource = null;
                    httpURL = null;
                    out.println(
                            "Error: " + uri + " is not a collection! Use open/connect only for collections!");
                }
            } catch (Exception ex) {
                handleException(ex);
                httpURL = null;
                webdavResource = null;
            }
        } else {
            handleException(we);
            httpURL = null;
            webdavResource = null;
        }
    } catch (Exception ex) {
        handleException(ex);
        webdavResource = null;
        httpURL = null;
    }
    updatePrompt(getPath());
}

From source file:org.apache.webdav.cmd.Client.java

void options(String path) {
    out.println("options " + path);

    String param = path;/*from w w w  .jav  a 2 s.  c o m*/
    try {
        boolean succeeded = false;
        if (param != null) {
            if (!param.startsWith("/")) {
                httpURL = uriToHttpURL(param);
                Enumeration opts = null;
                try {
                    // OPTIONS business logic
                    opts = webdavResource.optionsMethod(httpURL);
                    while (opts.hasMoreElements()) {
                        out.print(opts.nextElement());
                        if (opts.hasMoreElements()) {
                            out.print(", ");
                        } else {
                            out.println();
                        }
                    }
                } catch (HttpException we) {
                    if (we.getReasonCode() == HttpStatus.SC_UNAUTHORIZED) {
                        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
                        out.print("UserName: ");
                        String userName = in.readLine();
                        if (userName != null && userName.length() > 0) {
                            userName = userName.trim();
                            out.print("Password: ");
                            String password = in.readLine();
                            if (password != null)
                                password = password.trim();
                            try {
                                // OPTIONS business logic
                                httpURL.setUserinfo(userName, password);
                                opts = webdavResource.optionsMethod(httpURL);
                                while (opts.hasMoreElements()) {
                                    out.print(opts.nextElement());
                                    if (opts.hasMoreElements()) {
                                        out.print(", ");
                                    } else {
                                        out.println();
                                    }
                                }
                            } catch (Exception e) {
                                out.println("Error: " + e.getMessage());
                            }
                        }
                    } else {
                        out.println("Error: " + we.getMessage());
                    }
                } catch (IOException e) {
                    out.println("Error: Check! " + e.getMessage());
                }
                httpURL = null;
                return;
            } else if (webdavResource != null) {
                succeeded = webdavResource.optionsMethod(param);
            } else {
                out.println("Not connected yet.");
            }
        } else if (webdavResource != null) {
            succeeded = webdavResource.optionsMethod("*");
        } else {
            out.println("Not connected yet.");
        }

        if (succeeded) {
            out.print("Allowed methods by http OPTIONS: ");
            Enumeration allowed = webdavResource.getAllowedMethods();
            while (allowed.hasMoreElements()) {
                out.print(allowed.nextElement());
                if (allowed.hasMoreElements())
                    out.print(", ");
            }
            Enumeration davCapabilities = webdavResource.getDavCapabilities();
            if (davCapabilities.hasMoreElements())
                out.print("\nDAV: ");
            while (davCapabilities.hasMoreElements()) {
                out.print(davCapabilities.nextElement());
                if (davCapabilities.hasMoreElements())
                    out.print(", ");
            }
            out.println();
        }
    } catch (Exception ex) {
        handleException(ex);
    }
}

From source file:org.apache.wookie.proxy.ProxyClient.java

private String executeMethod(HttpMethod method, Configuration properties)
        throws Exception, AuthenticationException {
    // Execute the method.
    try {//w  ww .  j  a  v a  2 s.com
        HttpClient client = new HttpClient();

        // set the clients proxy values if needed
        ConnectionsPrefsManager.setProxySettings(client, properties);

        if (fUseProxyAuthentication) {
            if (fBase64Auth != null) {
                method.setRequestHeader("Authorization", fBase64Auth);
            } else {
                List<String> authPrefs = new ArrayList<String>(2);
                authPrefs.add(AuthPolicy.DIGEST);
                authPrefs.add(AuthPolicy.BASIC);
                client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
                // send the basic authentication response even before the server gives an unauthorized response
                client.getParams().setAuthenticationPreemptive(true);
                // Pass our credentials to HttpClient
                client.getState().setCredentials(
                        new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM),
                        new UsernamePasswordCredentials(fProxyUsername, fProxyPassword));
            }
        }

        // Add user language to http request in order to notify server of user's language
        Locale locale = Locale.getDefault();

        method.setRequestHeader("Accept-Language", locale.getLanguage()); //$NON-NLS-1$
        method.removeRequestHeader("Content-Type");
        //method.setRequestHeader("Content-Type","application/json");
        //method.setRequestHeader("Referer", "");
        //method.removeRequestHeader("Referer");
        method.setRequestHeader("Accept", "*/*");

        int statusCode = client.executeMethod(method);

        //System.out.println("response="+method.getResponseBodyAsString());
        //System.out.println("method="+method.toString());
        //System.out.println("response="+method.getResponseBodyAsStream());

        if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) {
            Header hType = method.getResponseHeader("Content-Type");
            if (hType != null) {
                fContentType = hType.getValue();
            }
            // for now we are only expecting Strings
            //return method.getResponseBodyAsString();
            return readFully(new InputStreamReader(method.getResponseBodyAsStream(), "UTF-8"));
        } else if (statusCode == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED
                || statusCode == HttpStatus.SC_UNAUTHORIZED) {
            throw new AuthenticationException("Authentication failed:" + method.getStatusLine() + ' '
                    + method.getURI() + ' ' + method.getStatusText());
        } else {
            throw new Exception("Method failed: " + method.getStatusLine() + ' ' + method.getURI() + ' ' //$NON-NLS-1$
                    + method.getStatusText());
        }
    } catch (IOException e) {
        throw e;
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
}

From source file:org.araqne.pkg.HttpWagon.java

public static InputStream openDownloadStream(URL url, boolean useAuth, String username, String password)
        throws IOException {
    Logger logger = LoggerFactory.getLogger(HttpWagon.class.getName());
    logger.trace("http wagon: downloading {}", url);

    int socketTimeout = getSocketTimeout();
    int connectionTimeout = getConnectTimeout();

    HttpClient client = new HttpClient();

    client.getParams().setParameter("http.socket.timeout", socketTimeout);
    client.getParams().setParameter("http.connection.timeout", connectionTimeout);
    client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, null);

    String realm = "";
    if (useAuth) {
        client.getParams().setAuthenticationPreemptive(true);
        if (realmCache.containsKey(getRealmCacheKey(url)))
            realm = realmCache.get(getRealmCacheKey(url));
        setClientAuth(url, username, password, realm, client);
    }/*from   ww  w  . j av a  2  s.  c o m*/

    HttpMethod method = new GetMethod(url.toString());

    int statusCode = client.executeMethod(method);

    if (useAuth && statusCode == HttpStatus.SC_UNAUTHORIZED) {
        realm = getRealm(method);
        setClientAuth(url, username, password, realm, client);
        method = new GetMethod(url.toString());
        statusCode = client.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            throw new IOException("digest auth failed: " + method.getStatusLine());
        } else {
            realmCache.put(getRealmCacheKey(url), realm);
        }
    }

    if (statusCode != HttpStatus.SC_OK) {
        throw new IOException("method failed: " + method.getStatusLine());
    }

    return method.getResponseBodyAsStream();
}