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.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  a v  a 2s.  c  o  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.github.internal.GitHubService.java

private void executeMethod(HttpMethod method) throws GitHubServiceException {
    int status;/*from   w ww  . jav a  2  s.  com*/
    try {
        status = httpClient.executeMethod(method);
    } catch (HttpException e) {
        throw new GitHubServiceException(e);
    } catch (IOException e) {
        throw new GitHubServiceException(e);
    }
    if (status != HttpStatus.SC_OK) {
        switch (status) {
        case HttpStatus.SC_UNAUTHORIZED:
        case HttpStatus.SC_FORBIDDEN:
            throw new PermissionDeniedException(method.getStatusLine());
        default:
            throw new GitHubServiceException(method.getStatusLine());
        }
    }
}

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 ww w  .  j a  v  a2s. c om*/
        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 va 2  s  . c o m*/
        return false;
    }

    requestCredentials(monitor, authenticationType);
    return true;
}

From source file:org.eclipse.mylyn.internal.monitor.usage.UsageUploadManager.java

public IStatus uploadFile(final String postUrl, final String name, final File file, final String filename,
        final int uid, IProgressMonitor monitor) {

    PostMethod filePost = new PostMethod(postUrl);

    try {/*from  w w  w  .  j a v  a  2s . c  om*/
        Part[] parts = { new FilePart(name, filename, file) };
        filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));

        AbstractWebLocation location = new WebLocation(postUrl);
        HostConfiguration hostConfiguration = WebUtil.createHostConfiguration(httpClient, location, monitor);
        final int status = WebUtil.execute(httpClient, hostConfiguration, filePost, monitor);

        if (status == HttpStatus.SC_UNAUTHORIZED) {
            // The uid was incorrect so inform the user
            return new Status(IStatus.ERROR, UiUsageMonitorPlugin.ID_PLUGIN, status,
                    NLS.bind(Messages.UsageUploadManager_Error_Uploading_Uid_Incorrect, file.getName(), uid),
                    new Exception());

        } else if (status == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
            return new Status(IStatus.ERROR, UiUsageMonitorPlugin.ID_PLUGIN, status,
                    Messages.UsageUploadManager_Error_Uploading_Proxy_Authentication, new Exception());
        } else if (status != 200) {
            // there was a problem with the file upload so throw up an error
            // dialog to inform the user
            return new Status(IStatus.ERROR, UiUsageMonitorPlugin.ID_PLUGIN, status,
                    NLS.bind(Messages.UsageUploadManager_Error_Uploading_Http_Response, file.getName(), status),
                    new Exception());
        } else {
            // the file was uploaded successfully
            return Status.OK_STATUS;
        }

    } catch (final FileNotFoundException e) {
        return new Status(IStatus.ERROR, UiUsageMonitorPlugin.ID_PLUGIN,
                NLS.bind(Messages.UsageUploadManager_Error_Uploading_X_Y, file.getName(),
                        e.getClass().getCanonicalName()),
                e);

    } catch (final IOException e) {
        if (e instanceof NoRouteToHostException || e instanceof UnknownHostException) {
            return new Status(IStatus.ERROR, UiUsageMonitorPlugin.ID_PLUGIN,
                    NLS.bind(Messages.UsageUploadManager_Error_Uploading_X_No_Network, file.getName()), e);

        } else {
            return new Status(IStatus.ERROR, UiUsageMonitorPlugin.ID_PLUGIN,
                    NLS.bind(Messages.UsageUploadManager_Error_Uploading_X_Y, file.getName(),
                            e.getClass().getCanonicalName()),
                    e);
        }
    } finally {
        filePost.releaseConnection();
    }
}

From source file:org.eclipse.mylyn.internal.phabricator.core.client.TracXmlRpcClient.java

private void probeAuthenticationScheme(IProgressMonitor monitor) throws PhabricatorException {
    AuthenticationCredentials credentials = location.getCredentials(AuthenticationType.REPOSITORY);
    if (!credentialsValid(credentials)) {
        return;//  w  w w  .  j  ava 2 s.c  o  m
    }

    if (DEBUG_AUTH) {
        System.err.println(location.getUrl() + ": Probing authentication"); //$NON-NLS-1$
    }
    HostConfiguration hostConfiguration = WebUtil.createHostConfiguration(httpClient, location, monitor);
    HeadMethod method = new HeadMethod(getXmlRpcUrl(credentials).toString());
    try {
        // execute without any credentials set
        int result = WebUtil.execute(httpClient, hostConfiguration, method, new HttpState(), monitor);
        if (DEBUG_AUTH) {
            System.err.println(location.getUrl() + ": Received authentication response (" + result + ")"); //$NON-NLS-1$ //$NON-NLS-2$
        }
        if (result == HttpStatus.SC_UNAUTHORIZED || result == HttpStatus.SC_FORBIDDEN) {
            AuthScheme authScheme = method.getHostAuthState().getAuthScheme();
            if (authScheme instanceof DigestScheme) {
                this.digestScheme = (DigestScheme) authScheme;
                if (DEBUG_AUTH) {
                    System.err.println(location.getUrl() + ": Received digest scheme"); //$NON-NLS-1$
                }
            } else if (authScheme instanceof BasicScheme) {
                httpClient.getParams().setAuthenticationPreemptive(true);
                if (DEBUG_AUTH) {
                    System.err.println(location.getUrl() + ": Received basic scheme"); //$NON-NLS-1$
                }
            } else if (authScheme != null) {
                if (DEBUG_AUTH) {
                    System.err.println(location.getUrl() + ": Received scheme (" + authScheme.getClass() + ")"); //$NON-NLS-1$ //$NON-NLS-2$
                }
            } else {
                if (DEBUG_AUTH) {
                    System.err.println(location.getUrl() + ": No authentication scheme received"); //$NON-NLS-1$
                }
            }

            Header header = method.getResponseHeader("Server"); //$NON-NLS-1$
            isTracd = (header != null && header.getValue().startsWith("tracd")); //$NON-NLS-1$
            if (DEBUG_AUTH && isTracd) {
                System.err.println(location.getUrl() + ": Tracd detected"); //$NON-NLS-1$
            }

            //               Header header = method.getResponseHeader("WWW-Authenticate");
            //               if (header != null) {
            //                  if (header.getValue().startsWith("Basic")) {
            //                     httpClient.getParams().setAuthenticationPreemptive(true);
            //                  } else if (header.getValue().startsWith("Digest")) {
            //                     DigestScheme scheme = new DigestScheme();
            //                     try {
            //                        scheme.processChallenge(header.getValue());
            //                        this.digestScheme = scheme;
            //                     } catch (MalformedChallengeException e) {
            //                        // ignore
            //                     }
            //                  }
            //               }
        }
    } catch (IOException e) {
        // ignore
    } finally {
        WebUtil.releaseConnection(method, monitor);
    }
}

From source file:org.eclipse.mylyn.internal.trac.core.client.TracXmlRpcClient.java

private void probeAuthenticationScheme(IProgressMonitor monitor) throws TracException {
    AuthenticationCredentials credentials = location.getCredentials(AuthenticationType.REPOSITORY);
    if (!credentialsValid(credentials)) {
        return;//from w w w. j  av a  2s  .  co  m
    }

    if (DEBUG_AUTH) {
        System.err.println(location.getUrl() + ": Probing authentication"); //$NON-NLS-1$ 
    }
    HostConfiguration hostConfiguration = WebUtil.createHostConfiguration(httpClient, location, monitor);
    HeadMethod method = new HeadMethod(getXmlRpcUrl(credentials).toString());
    try {
        // execute without any credentials set
        int result = WebUtil.execute(httpClient, hostConfiguration, method, new HttpState(), monitor);
        if (DEBUG_AUTH) {
            System.err.println(location.getUrl() + ": Received authentication response (" + result + ")"); //$NON-NLS-1$ //$NON-NLS-2$ 
        }
        if (result == HttpStatus.SC_UNAUTHORIZED || result == HttpStatus.SC_FORBIDDEN) {
            AuthScheme authScheme = method.getHostAuthState().getAuthScheme();
            if (authScheme instanceof DigestScheme) {
                this.digestScheme = (DigestScheme) authScheme;
                if (DEBUG_AUTH) {
                    System.err.println(location.getUrl() + ": Received digest scheme"); //$NON-NLS-1$ 
                }
            } else if (authScheme instanceof BasicScheme) {
                httpClient.getParams().setAuthenticationPreemptive(true);
                if (DEBUG_AUTH) {
                    System.err.println(location.getUrl() + ": Received basic scheme"); //$NON-NLS-1$ 
                }
            } else if (authScheme != null) {
                if (DEBUG_AUTH) {
                    System.err.println(location.getUrl() + ": Received scheme (" + authScheme.getClass() + ")"); //$NON-NLS-1$ //$NON-NLS-2$ 
                }
            } else {
                if (DEBUG_AUTH) {
                    System.err.println(location.getUrl() + ": No authentication scheme received"); //$NON-NLS-1$ 
                }
            }

            Header header = method.getResponseHeader("Server"); //$NON-NLS-1$
            isTracd = (header != null && header.getValue().startsWith("tracd")); //$NON-NLS-1$
            if (DEBUG_AUTH && isTracd) {
                System.err.println(location.getUrl() + ": Tracd detected"); //$NON-NLS-1$ 
            }

            //               Header header = method.getResponseHeader("WWW-Authenticate");
            //               if (header != null) {
            //                  if (header.getValue().startsWith("Basic")) {
            //                     httpClient.getParams().setAuthenticationPreemptive(true);
            //                  } else if (header.getValue().startsWith("Digest")) {
            //                     DigestScheme scheme = new DigestScheme();
            //                     try {
            //                        scheme.processChallenge(header.getValue());
            //                        this.digestScheme = scheme;
            //                     } catch (MalformedChallengeException e) {
            //                        // ignore
            //                     }
            //                  }
            //               }
        }
    } catch (IOException e) {
        // ignore
    } finally {
        WebUtil.releaseConnection(method, monitor);
    }
}

From source file:org.elasticdroid.LoginView.java

/**
 * Process results from model. Called by onPostExecute() method
 * in any given Model class./* ww w. jav  a2  s  .c  o  m*/
 * 
 * Displays either an error message (if result is an exeception)
 * or the next activity.
 * 
 * Overrides
 * @see org.elasticdroid.tpl.GenericActivity#processModelResults(java.lang.Object)
 */
@Override
public void processModelResults(Object result) {
    Log.v(this.getClass().getName(), "Processing model results...");

    //dismiss the progress bar
    if (progressDialogDisplayed) {
        progressDialogDisplayed = false;
        dismissDialog(DialogConstants.PROGRESS_DIALOG.ordinal());
    }

    if (result == null) {
        Toast.makeText(this, Html.fromHtml(this.getString(R.string.cancelled_login)), Toast.LENGTH_LONG).show();

        return; //do not execute the rest of this method.
    }

    /*
     * The result returned by the model can be:
     * a) true: if authentication successful.
     * b) AmazonServiceException: if authentication failed (typically).
     * c) AmazonClientException: if communication to AWS failed (user not connected to internet?).
     * d) null: if the credentials have been validated.
     */
    if (result instanceof Boolean) {
        HashMap<String, String> connectionData = new HashMap<String, String>();

        //TODO add the ability to change the default dashboard for a user
        finish(); //finish the activity; we dont want the user to be able to return to this screen using the 
        //back key.
        Intent displayDashboardIntent = new Intent();
        displayDashboardIntent.setClassName("org.elasticdroid", "org.elasticdroid.EC2DashboardView");
        //pass the username, access key, and secret access key to the dashboard as arguments
        //create a HashMap<String,String> to hold the connection data
        connectionData.put("username", username);
        connectionData.put("accessKey", accessKey);
        connectionData.put("secretAccessKey", secretAccessKey);

        //add connection data to intent, and start new activity
        displayDashboardIntent.putExtra("org.elasticdroid.LoginView.connectionData", connectionData);
        startActivity(displayDashboardIntent);
    } else if (result instanceof AmazonServiceException) {
        if ((((AmazonServiceException) result).getStatusCode() == HttpStatus.SC_UNAUTHORIZED)
                || (((AmazonServiceException) result).getStatusCode() == HttpStatus.SC_FORBIDDEN)) {
            //set errors in the access key and secret access key fields.
            ((EditText) findViewById(R.id.akEntry))
                    .setError(this.getString(R.string.loginview_invalid_credentials_err));
            ((EditText) findViewById(R.id.sakEntry))
                    .setError(this.getString(R.string.loginview_invalid_credentials_err));

            alertDialogMessage = this.getString(R.string.loginview_invalid_keys_dlg);
        } else {
            //TODO a wrong SecretAccessKey is handled using a different error if the AccessKey is right.
            //Handle this.
            alertDialogMessage = this.getString(R.string.loginview_unexpected_err_dlg)
                    + ((AmazonServiceException) result).getStatusCode() + "--"
                    + ((AmazonServiceException) result).getMessage() + ". "
                    + this.getString(R.string.loginview_bug_report_dlg);
        }

        //whatever the error, display the error
        //and set the boolean to true. This is so that we know we should redisplay
        //dialog on restore.
        Log.e(this.getClass().getName(), alertDialogMessage);

        alertDialogDisplayed = true;

    } else if (result instanceof AmazonClientException) {
        alertDialogMessage = this.getString(R.string.loginview_no_connxn_dlg);
        Log.e(this.getClass().getName(), alertDialogMessage);

        alertDialogDisplayed = true;
    } else if (result instanceof IllegalArgumentException) {
        ((EditText) findViewById(R.id.usernameEntry))
                .setError(this.getString(R.string.loginview_invalid_username_err));
        alertDialogMessage = this.getString(R.string.loginview_invalid_username_err);
        Log.e(this.getClass().getName(), alertDialogMessage);
        alertDialogDisplayed = true;
    } else if (result instanceof SQLException) {
        alertDialogMessage = this.getString(R.string.loginview_username_exists_dlg);
        Log.e(this.getClass().getName(), alertDialogMessage);
        alertDialogDisplayed = true;
    } else if (result != null) {
        Log.e(this.getClass().getName(), "Unexpected error!!!");
    }

    //set the loginModel to null
    loginModel = null;
    //display the alert dialog if the user set the displayed var to true
    if (alertDialogDisplayed) {
        alertDialogBox.setMessage(alertDialogMessage);
        alertDialogBox.show();//show error
    }
}

From source file:org.exoplatform.addons.es.client.ElasticClient.java

/**
 * Handle Http response receive from ES Log an INFO if the return status code
 * is 2xx Log an ERROR if the return code is different from 2xx
 *
 * @param httpResponse The Http Response to handle
 *//* ww  w. ja va2  s  .  c om*/
private ElasticResponse handleHttpResponse(HttpResponse httpResponse) throws IOException {
    String response = null;
    InputStream is = null;

    if (httpResponse.getEntity() != null) {
        try {
            is = httpResponse.getEntity().getContent();
            response = IOUtils.toString(is, "UTF-8");
        } finally {
            if (is != null) {
                is.close();
            }
        }
    }

    if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
        throw new ElasticClientAuthenticationException();
    }
    return new ElasticResponse(response, httpResponse.getStatusLine().getStatusCode());
}

From source file:org.glite.authz.common.http.JettyAdminServiceCLI.java

/**
 * Executes the service command. Also checks to ensure the HTTP return code was 200.
 * //from   w  ww  . ja v a2s . com
 * @param host host to which to connect
 * @param port port to which to connect
 * @param command command sent to the admin service
 * @param password admin command password, may be null
 */
private static void executeCommand(String host, int port, String command, String password) {
    HttpClientBuilder clientBuilder = new HttpClientBuilder();
    HttpClient httpClient = clientBuilder.buildClient();

    GetMethod getMethod = new GetMethod("http://" + host + ":" + port + "/" + command);
    if (password != null) {
        getMethod.setQueryString(new NameValuePair[] {
                new NameValuePair(PasswordProtectFilter.PASSWORD_PARAM_NAME, password), });
    }

    try {
        httpClient.executeMethod(getMethod);
        String response = Strings.safeTrimOrNullString(getMethod.getResponseBodyAsString());
        if (response != null) {
            System.out.println(response);
        }
    } catch (ConnectException e) {
        exit("Unable to connect to " + host + ":" + port + ", perhaps the service is not running", RC_CTX);
    } catch (IOException e) {
        exit("Error executing service command:\n" + e.getMessage(), RC_CTX);
    }

    int statusCode = getMethod.getStatusCode();
    if (statusCode == HttpStatus.SC_OK) {
        return;
    } else if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
        exit("you are not authorized to execute admin commands; invalid password", RC_UNAUTHORIZED);
    } else {
        exit("Service returned unexpected HTTP status code; " + statusCode, RC_UNKNOWN);
    }
}