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:fr.jayasoft.ivy.url.BasicURLHandler.java

public boolean isReachable(URL url, int timeout) {
    try {/*  w ww  .  ja  v a2  s.  c o  m*/
        URLConnection con = url.openConnection();
        if (con instanceof HttpURLConnection) {
            int status = ((HttpURLConnection) con).getResponseCode();
            if (status == HttpStatus.SC_OK) {
                return true;
            }
            if (status == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
                Message.warn("Your proxy requires authentication.");
            } else if (String.valueOf(status).startsWith("4")) {
                Message.verbose(
                        "CLIENT ERROR: " + ((HttpURLConnection) con).getResponseMessage() + " url=" + url);
            } else if (String.valueOf(status).startsWith("5")) {
                Message.error(
                        "SERVER ERROR: " + ((HttpURLConnection) con).getResponseMessage() + " url=" + url);
            }
            Message.debug("HTTP response status: " + status + " url=" + url);
        } else {
            int contentLength = con.getContentLength();
            return contentLength > 0;
        }
    } catch (UnknownHostException e) {
        Message.warn("Host " + e.getMessage() + " not found. url=" + url);
        Message.info(
                "You probably access the destination server through a proxy server that is not well configured.");
    } catch (IOException e) {
        Message.error("Server access Error: " + e.getMessage() + " url=" + url);
    }
    return false;
}

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

public URLInfo getURLInfo(URL url, int timeout) {
    HeadMethod head = null;//from ww  w.  j  av  a2 s  .  c om
    try {
        head = doHead(url, timeout);
        int status = head.getStatusCode();
        head.releaseConnection();
        if (status == HttpStatus.SC_OK) {
            return new URLInfo(true, getResponseContentLength(head), getLastModified(head));
        }
        if (status == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
            Message.error("Your proxy requires authentication.");
        } else if (String.valueOf(status).startsWith("4")) {
            Message.verbose("CLIENT ERROR: " + head.getStatusText() + " url=" + url);
        } else if (String.valueOf(status).startsWith("5")) {
            Message.warn("SERVER ERROR: " + head.getStatusText() + " url=" + url);
        }
        Message.debug("HTTP response status: " + status + "=" + head.getStatusText() + " url=" + url);
    } catch (HttpException e) {
        Message.error("HttpClientHandler: " + e.getMessage() + ":" + e.getReasonCode() + "=" + e.getReason()
                + " url=" + url);
    } catch (UnknownHostException e) {
        Message.warn("Host " + e.getMessage() + " not found. url=" + url);
        Message.info(
                "You probably access the destination server through a proxy server that is not well configured.");
    } catch (IOException e) {
        Message.error("HttpClientHandler: " + e.getMessage() + " url=" + url);
    } finally {
        if (head != null) {
            head.releaseConnection();
        }
    }
    return UNAVAILABLE;
}

From source file:com.globalsight.everest.webapp.applet.admin.customer.FileSystemApplet.java

/**
 * Zip the selected files and send the zip to the server.
 * @param p_filesToBeZipped - A list of selected files to be uploaded.
 * @param p_targetURL - The target URL representing server URL.
 * @param p_targetLocation - A string representing the link to the next page.
 *//* w  w  w.java 2  s .  c om*/
public void sendZipFile(File[] p_filesToBeZipped, String p_targetURL, final String p_targetLocation)
        throws Exception {
    StringBuffer sb = new StringBuffer();
    sb.append("GS_");
    sb.append(System.currentTimeMillis());
    sb.append(".zip");

    File targetFile = getFile(sb.toString());
    ZipIt.addEntriesToZipFile(targetFile, p_filesToBeZipped);
    m_progressBar.setValue(30);

    PostMethod filePost = new PostMethod(p_targetURL + "&doPost=true");
    filePost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
    filePost.setDoAuthentication(true);
    try {
        Part[] parts = { new FilePart(targetFile.getName(), targetFile) };

        m_progressBar.setValue(40);
        filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));

        HttpClient client = new HttpClient();
        setUpClientForProxy(client);
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

        m_progressBar.setValue(50);
        int status = client.executeMethod(filePost);
        if (status == HttpStatus.SC_OK) {
            //no need to ask for auth again since the first upload was fine
            s_authPrompter.setAskForAuthentication(false);

            m_progressBar.setValue(60);
            InputStream is = filePost.getResponseBodyAsStream();
            m_progressBar.setValue(70);
            ObjectInputStream inputStreamFromServlet = new ObjectInputStream(is);
            Vector incomingData = (Vector) inputStreamFromServlet.readObject();

            inputStreamFromServlet.close();
            if (incomingData != null) {
                if (incomingData.elementAt(0) instanceof ExceptionMessage) {
                    resetProgressBar();
                    AppletHelper.displayErrorPage((ExceptionMessage) incomingData.elementAt(0), this);
                }
            } else {
                boolean deleted = targetFile.delete();
                m_progressBar.setValue(100);
                try {
                    Thread.sleep(1000);
                } catch (Exception e) {
                }
                // now move to some other page...
                goToTargetPage(p_targetLocation);
            }
        } else {
            //authentication may have failed, reset the need to ask
            s_authPrompter.setAskForAuthentication(true);
            resetProgressBar();
            String errorMessage = "Upload failed because: (" + status + ") " + HttpStatus.getStatusText(status);
            if (status == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
                errorMessage = "Incorrect NTDomain\\username or password entered. Hit 'upload' again to re-try.";
            }
            AppletHelper.getErrorDlg(errorMessage, null);
        }
    } catch (Exception ex) {
        //authentication may have failed, reset the need to ask
        s_authPrompter.setAskForAuthentication(true);

        resetProgressBar();
        System.err.println(ex);
        AppletHelper.getErrorDlg(ex.getMessage(), null);
    } finally {
        filePost.releaseConnection();
    }

}

From source file:davmail.http.DavGatewayHttpClientFacade.java

private static int checkNTLM(HttpClient httpClient, HttpMethod currentMethod) throws IOException {
    int status = currentMethod.getStatusCode();
    if ((status == HttpStatus.SC_UNAUTHORIZED || status == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED)
            && acceptsNTLMOnly(currentMethod) && !hasNTLM(httpClient)) {
        LOGGER.debug(//from www  .ja  v  a2 s  . c  o m
                "Received " + status + " unauthorized at " + currentMethod.getURI() + ", retrying with NTLM");
        resetMethod(currentMethod);
        addNTLM(httpClient);
        status = httpClient.executeMethod(currentMethod);
    }
    return status;
}

From source file:JiraWebSession.java

private boolean needsReauthentication(HttpClient httpClient, PostMethod method, IProgressMonitor monitor)
        throws JiraAuthenticationException, IOException, JiraServiceUnavailableException {
    final AuthenticationType authenticationType;
    int code = method.getStatusCode();
    if (code == HttpStatus.SC_OK) {
        authenticationType = AuthenticationType.REPOSITORY;
    } else if (code == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
        authenticationType = AuthenticationType.PROXY;
    } else {//  w  w w .  java  2s .c  o m
        return false;
    }

    // the server specified a different character set than what was returned by the server, try to re-authenticate 
    if (!getContentType().endsWith(method.getResponseCharSet())) {
        this.characterEncoding = method.getResponseCharSet();
        return true;
    }

    if (method.getResponseHeader("Content-Type").getValue().startsWith("application/json")) { //$NON-NLS-1$//$NON-NLS-2$
        // we're talking to JIRA 4.x
        String json = method.getResponseBodyAsString(1024);
        if (json.contains("\"captchaFailure\":true")) { //$NON-NLS-1$
            throw new JiraCaptchaRequiredException(null);
        }
        if (json.contains("\"loginFailedByPermissions\":true")) { //$NON-NLS-1$
            throw new JiraServiceUnavailableException("You don't have permission to login"); //$NON-NLS-1$
        }
    }

    try {
        // PLE-960, PLE-1259 - we don't want a background monitor here, we want to force requestCredentials to prompt the user
        location.requestCredentials(authenticationType, null,
                Policy.isBackgroundMonitor(monitor) ? SubMonitor.convert(monitor) : monitor);
    } catch (UnsupportedRequestException ignored) {
        throw new JiraAuthenticationException("Login failed."); //$NON-NLS-1$
    }

    return true;
}

From source file:davmail.http.DavGatewayHttpClientFacade.java

/**
 * Execute method with httpClient, do not follow 30x redirects.
 *
 * @param httpClient Http client instance
 * @param method     Http method//from  w w  w  .j  a v  a2 s.  c  o  m
 * @return status
 * @throws IOException on error
 */
public static int executeNoRedirect(HttpClient httpClient, HttpMethod method) throws IOException {
    int status;
    try {
        status = httpClient.executeMethod(method);
        // check NTLM
        if ((status == HttpStatus.SC_UNAUTHORIZED || status == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED)
                && acceptsNTLMOnly(method) && !hasNTLM(httpClient)) {
            LOGGER.debug("Received " + status + " unauthorized at " + method.getURI() + ", retrying with NTLM");
            resetMethod(method);
            addNTLM(httpClient);
            status = httpClient.executeMethod(method);
        }
    } finally {
        method.releaseConnection();
    }
    // caller will need to release connection
    return status;
}

From source file:davmail.http.DavGatewayHttpClientFacade.java

/**
 * Test method header for supported authentication mode,
 * return true if Basic authentication is not available
 *
 * @param getMethod http method/*ww  w . j a  v a2  s  .c o m*/
 * @return true if only NTLM is enabled
 */
public static boolean acceptsNTLMOnly(HttpMethod getMethod) {
    Header authenticateHeader = null;
    if (getMethod.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
        authenticateHeader = getMethod.getResponseHeader("WWW-Authenticate");
    } else if (getMethod.getStatusCode() == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
        authenticateHeader = getMethod.getResponseHeader("Proxy-Authenticate");
    }
    if (authenticateHeader == null) {
        return false;
    } else {
        boolean acceptBasic = false;
        boolean acceptNTLM = false;
        HeaderElement[] headerElements = authenticateHeader.getElements();
        for (HeaderElement headerElement : headerElements) {
            if ("NTLM".equalsIgnoreCase(headerElement.getName())) {
                acceptNTLM = true;
            }
            if ("Basic realm".equalsIgnoreCase(headerElement.getName())) {
                acceptBasic = true;
            }
        }
        return acceptNTLM && !acceptBasic;

    }
}

From source file:davmail.http.DavGatewayHttpClientFacade.java

/**
 * Execute test method from checkConfig, with proxy credentials, but without Exchange credentials.
 *
 * @param httpClient Http client instance
 * @param method     Http method//from www  .  ja  v a 2s .c  o m
 * @return Http status
 * @throws IOException on error
 */
public static int executeTestMethod(HttpClient httpClient, GetMethod method) throws IOException {
    // do not follow redirects in expired sessions
    method.setFollowRedirects(false);
    int status = httpClient.executeMethod(method);
    if (status == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED && acceptsNTLMOnly(method)
            && !hasNTLM(httpClient)) {
        resetMethod(method);
        LOGGER.debug("Received " + status + " unauthorized at " + method.getURI() + ", retrying with NTLM");
        addNTLM(httpClient);
        status = httpClient.executeMethod(method);
    }

    return status;
}

From source file:davmail.http.DavGatewayHttpClientFacade.java

/**
 * Execute Get method, do not follow redirects.
 *
 * @param httpClient      Http client instance
 * @param method          Http method//from   w  w  w.j a  v a2 s. c om
 * @param followRedirects Follow redirects flag
 * @throws IOException on error
 */
public static void executeGetMethod(HttpClient httpClient, GetMethod method, boolean followRedirects)
        throws IOException {
    // do not follow redirects in expired sessions
    method.setFollowRedirects(followRedirects);
    int status = httpClient.executeMethod(method);
    if ((status == HttpStatus.SC_UNAUTHORIZED || status == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED)
            && acceptsNTLMOnly(method) && !hasNTLM(httpClient)) {
        resetMethod(method);
        LOGGER.debug("Received " + status + " unauthorized at " + method.getURI() + ", retrying with NTLM");
        addNTLM(httpClient);
        status = httpClient.executeMethod(method);
    }
    if (status != HttpStatus.SC_OK && (followRedirects || !isRedirect(status))) {
        LOGGER.warn("GET failed with status " + status + " at " + method.getURI());
        if (status != HttpStatus.SC_NOT_FOUND && status != HttpStatus.SC_FORBIDDEN) {
            LOGGER.warn(method.getResponseBodyAsString());
        }
        throw DavGatewayHttpClientFacade.buildHttpException(method);
    }
    // check for expired session
    if (followRedirects) {
        String queryString = method.getQueryString();
        checkExpiredSession(queryString);
    }
}

From source file:org.apache.ivy.util.url.HttpClientHandler.java

private boolean checkStatusCode(URL url, HttpMethodBase method) throws IOException {
    int status = method.getStatusCode();
    if (status == HttpStatus.SC_OK) {
        return true;
    }//w  ww .  j  a v  a2s  .c o  m

    // IVY-1328: some servers return a 204 on a HEAD request
    if ("HEAD".equals(method.getName()) && (status == 204)) {
        return true;
    }

    Message.debug("HTTP response status: " + status + " url=" + url);
    if (status == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
        Message.warn("Your proxy requires authentication.");
    } else if (String.valueOf(status).startsWith("4")) {
        Message.verbose("CLIENT ERROR: " + method.getStatusText() + " url=" + url);
    } else if (String.valueOf(status).startsWith("5")) {
        Message.error("SERVER ERROR: " + method.getStatusText() + " url=" + url);
    }

    return false;
}