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

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

Introduction

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

Prototype

int SC_PROXY_AUTHENTICATION_REQUIRED

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

Click Source Link

Document

<tt>407 Proxy Authentication Required</tt> (HTTP/1.1 - RFC 2616)

Usage

From source file:org.apache.jackrabbit.spi2dav.RepositoryServiceImpl.java

/**
 * @see RepositoryService#getRepositoryDescriptors()
 *///from ww  w.  java  2s  .c  o m
public Map<String, QValue[]> getRepositoryDescriptors() throws RepositoryException {
    if (descriptors.isEmpty()) {
        ReportInfo info = new ReportInfo(JcrRemotingConstants.REPORT_REPOSITORY_DESCRIPTORS,
                ItemResourceConstants.NAMESPACE);
        ReportMethod method = null;
        try {
            method = new ReportMethod(uriResolver.getRepositoryUri(), info);
            int sc = getClient(null).executeMethod(method);
            if (sc == HttpStatus.SC_UNAUTHORIZED || sc == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
                // JCR-3076: Mandatory authentication prevents us from
                // accessing the descriptors on the server, so instead
                // of failing with an exception we simply return an empty
                // set of descriptors
                log.warn("Authentication required to access repository descriptors");
                return descriptors;
            }

            method.checkSuccess();
            Document doc = method.getResponseBodyAsDocument();

            if (doc != null) {
                Element rootElement = doc.getDocumentElement();
                ElementIterator nsElems = DomUtil.getChildren(rootElement, JcrRemotingConstants.XML_DESCRIPTOR,
                        ItemResourceConstants.NAMESPACE);
                while (nsElems.hasNext()) {
                    Element elem = nsElems.nextElement();
                    String key = DomUtil.getChildText(elem, JcrRemotingConstants.XML_DESCRIPTORKEY,
                            ItemResourceConstants.NAMESPACE);
                    ElementIterator it = DomUtil.getChildren(elem, JcrRemotingConstants.XML_DESCRIPTORVALUE,
                            ItemResourceConstants.NAMESPACE);
                    List<QValue> vs = new ArrayList<QValue>();
                    while (it.hasNext()) {
                        Element dv = it.nextElement();
                        String descriptor = DomUtil.getText(dv);
                        if (key != null && descriptor != null) {
                            String typeStr = (DomUtil.getAttribute(dv, JcrRemotingConstants.ATTR_VALUE_TYPE,
                                    null));
                            int type = (typeStr == null) ? PropertyType.STRING
                                    : PropertyType.valueFromName(typeStr);
                            vs.add(getQValueFactory().create(descriptor, type));
                        } else {
                            log.error("Invalid descriptor key / value pair: " + key + " -> " + descriptor);
                        }

                    }
                    descriptors.put(key, vs.toArray(new QValue[vs.size()]));
                }
            }
        } catch (IOException e) {
            throw new RepositoryException(e);
        } catch (DavException e) {
            throw ExceptionConverter.generate(e);
        } finally {
            if (method != null) {
                method.releaseConnection();
            }
        }
    }
    return descriptors;
}

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 += "/";
    }/*from   w  w  w.  ja  v a 2  s  .co  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 w w  . j  a va 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  .j  a va  2 s . c  o  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 {/*from ww  w .  j  a  v a  2 s .c o  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 w  w  .  j a v a2s.  com
        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.wookie.proxy.ProxyClient.java

private String executeMethod(HttpMethod method, Configuration properties)
        throws Exception, AuthenticationException {
    // Execute the method.
    try {/*from   w  w w .  j a v  a2 s  . c  om*/
        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.eclipse.mylyn.commons.net.http.CommonHttpClient3.java

protected boolean needsReauthentication(int code, IProgressMonitor monitor) throws IOException {
    final AuthenticationType authenticationType;
    if (code == HttpStatus.SC_UNAUTHORIZED || code == HttpStatus.SC_FORBIDDEN) {
        authenticationType = AuthenticationType.HTTP;
    } else if (code == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
        authenticationType = AuthenticationType.PROXY;
    } else {/*from www  . j  av  a  2  s  .  co  m*/
        return false;
    }

    try {
        location.requestCredentials(authenticationType, null, monitor);
    } catch (UnsupportedRequestException e) {
        IOException ioe = new IOException(HttpStatus.getStatusText(code));
        ioe.initCause(e);
        throw ioe;
    } catch (UnsupportedOperationException e) {
        IOException ioe = new IOException(HttpStatus.getStatusText(code));
        ioe.initCause(e);
        throw ioe;
    }

    return true;
}

From source file:org.eclipse.mylyn.internal.commons.xmlrpc.XmlRpcOperation.java

protected boolean handleAuthenticationException(int code, AuthScheme authScheme) throws XmlRpcException {
    if (code == HttpStatus.SC_UNAUTHORIZED) {
        if (CommonXmlRpcClient.DEBUG_AUTH) {
            System.err.println(client.getLocation().getUrl() + ": Unauthorized (" + code + ")"); //$NON-NLS-1$ //$NON-NLS-2$ 
        }/*from   w ww  . j av a  2  s.c o m*/
        client.digestScheme = null;
        XmlRpcLoginException exception = new XmlRpcLoginException();
        exception.setNtlmAuthRequested(authScheme instanceof NTLMScheme);
        throw exception;
    } else if (code == HttpStatus.SC_FORBIDDEN) {
        if (CommonXmlRpcClient.DEBUG_AUTH) {
            System.err.println(client.getLocation().getUrl() + ": Forbidden (" + code + ")"); //$NON-NLS-1$ //$NON-NLS-2$ 
        }
        client.digestScheme = null;
        throw new XmlRpcPermissionDeniedException();
    } else if (code == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
        if (CommonXmlRpcClient.DEBUG_AUTH) {
            System.err
                    .println(client.getLocation().getUrl() + ": Proxy authentication required (" + code + ")"); //$NON-NLS-1$ //$NON-NLS-2$ 
        }
        throw new XmlRpcProxyAuthenticationException();
    }
    return false;
}

From source file:org.eclipse.mylyn.internal.gerrit.core.client.GerritHttpClient.java

private boolean needsReauthentication(int code, IProgressMonitor monitor)
        throws IOException, GerritLoginException {
    final AuthenticationType authenticationType;
    if (code == HttpStatus.SC_UNAUTHORIZED || code == HttpStatus.SC_FORBIDDEN) {
        authenticationType = AuthenticationType.REPOSITORY;
    } else if (code == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
        authenticationType = AuthenticationType.PROXY;
    } else {/*from w  ww .j  a v  a2  s  . c om*/
        return false;
    }

    requestCredentials(monitor, authenticationType);
    return true;
}