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

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

Introduction

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

Prototype

int SC_FORBIDDEN

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

Click Source Link

Document

<tt>403 Forbidden</tt> (HTTP/1.0 - RFC 1945)

Usage

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 {//  www.  j a v a 2 s . c o  m
        return false;
    }

    requestCredentials(monitor, authenticationType);
    return true;
}

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;/*  ww  w . j a  v a  2 s  . c  om*/
    }

    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 a  v a2  s  .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.ednovo.gooru.security.DoAuthorization.java

public User doFilter(String sessionToken, String pinToken, final String apiKeyToken,
        final HttpServletRequest request, final HttpServletResponse response, final Authentication auth,
        final String oAuthToken) {
    if (pinToken != null) {
        sessionToken = pinToken;//from   ww  w  .  j  a  va2 s .  com
    }
    User user = null;
    // boolean isSussess = true;
    AuthenticationDo authentication = null;
    UserToken userToken = null;
    String key = null;
    String data = null;
    final String skipCache = request.getParameter("skipCache");

    if (oAuthToken != null) {
        try {
            key = SESSION_TOKEN_KEY + oAuthToken;
            data = getRedisService().getValue(key);
            if (data != null && (skipCache == null || skipCache.equals("0"))) {
                authentication = JsonDeserializer.deserialize(data, AuthenticationDo.class);
            }
        } catch (Exception e) {
            LOGGER.error("Failed to  get  value from redis server");
        }
        if (authentication == null || authentication.getUserToken() == null) {
            try {
                user = oAuthService.getUserByOAuthAccessToken(BaseUtil.extractToken(oAuthToken));
            } catch (Exception e) {
                LOGGER.error("OAuth Authentication failed --- " + e);
            }
            userToken = userToken == null ? new UserToken() : userToken;
            userToken.setUser(user);
        } else {
            userToken = authentication.getUserToken();
        }
        if (userToken == null) {
            throw new AccessDeniedException("Invalid oauth access token : " + oAuthToken);
        } else {
            user = userToken.getUser();
        }
        request.setAttribute(Constants.OAUTH_ACCESS_TOKEN, oAuthToken);
    } else if (sessionToken != null) {
        try {
            key = SESSION_TOKEN_KEY + sessionToken;
            data = getRedisService().get(key);
            if (data != null && (skipCache == null || skipCache.equals("0"))) {
                authentication = JsonDeserializer.deserialize(data, AuthenticationDo.class);
            }
        } catch (Exception e) {
            LOGGER.error("Failed to  get  value from redis server");
        }
        if (authentication == null || authentication.getUserToken() == null) {
            userToken = userTokenRepository.findByToken(sessionToken);
        } else {
            userToken = authentication.getUserToken();
        }
        if (userToken == null) {
            throw new AccessDeniedException("Invalid session token : " + sessionToken);
        } else {
            user = userToken.getUser();
        }

        String token = redisService.getValue(sessionToken);
        if (token == null && userToken.getScope().equalsIgnoreCase("expired")) {
            response.setStatus(HttpStatus.SC_FORBIDDEN);
            throw new AccessDeniedException("error:Session is Expired.");
        } else if (sessionToken != null) {
            Organization organization = null;
            if (userToken.getApplication() != null) {
                organization = userToken.getApplication().getOrganization();
            }
            redisService.addSessionEntry(sessionToken, organization);
        }
    } else if (apiKeyToken != null) {
        if (authentication == null) {
            final Application application = this.getApplicationRepository().getApplication(apiKeyToken);
            if (application == null) {
                throw new AccessDeniedException("Invalid ApiKey : " + apiKeyToken);
            } else {
                String anonymousUid = organizationSettingRepository.getOrganizationSetting(Constants.ANONYMOUS,
                        application.getOrganization().getPartyUid());
                user = userService.findByGooruId(anonymousUid);
                userToken = userToken == null ? new UserToken() : userToken;
                userToken.setUser(user);
            }
        }
    } else {
        throw new AccessDeniedException("Session token or api key is mandatory.");
    }
    if (authentication == null) {
        authentication = new AuthenticationDo();
        authentication.setUserToken(userToken);
    }
    if (authentication.getUserToken().getUser() == null) {
        throw new AccessDeniedException("Invalid session token : " + sessionToken);
    }
    // check token expires
    if (authentication.getUserToken().getUser() != null
            && (auth == null || hasRoleChanged(auth, authentication.getUserToken().getUser()))) {
        doAuthentication(request, response, authentication.getUserToken().getUser(),
                authentication.getUserToken().getToken(), skipCache, authentication, key);
    }

    // set to request so that controllers can read it.
    request.setAttribute(Constants.USER, authentication.getUserToken().getUser());
    if (authentication.getUserToken().getApplication() != null) {
        request.getSession().setAttribute(Constants.APPLICATION_KEY,
                authentication.getUserToken().getApplication().getKey());
    }
    request.getSession().setAttribute(Constants.SESSION_TOKEN, authentication.getUserToken().getToken());
    return authentication.getUserToken().getUser();
}

From source file:org.elasticdroid.LoginView.java

/**
 * Process results from model. Called by onPostExecute() method
 * in any given Model class./*from  w ww . j  av  a  2  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.infoscoop.manager.controller.AuthenticationInterceptor.java

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {

    if (handler instanceof ControllerInterface) {
        ControllerInterface con = (ControllerInterface) handler;

        PortalAdminsService service = PortalAdminsService.getHandle();
        if (con.getRoleName() != null && !service.isPermitted(con.getRoleName())) {
            response.sendError(HttpStatus.SC_FORBIDDEN);
            return false;
        }/*from   w  w  w  .j  a  va2 s. com*/
    }
    return super.preHandle(request, response, handler);
}

From source file:org.jboss.tools.livereload.internal.server.jetty.LiveReloadServerTestCase.java

@Test
public void shouldAcceptHttpConnexionAndReturnForbiddenResponseWhenRequestingFolder() throws Exception {
    // pre-condition
    createAndLaunchLiveReloadServer(true);
    // operation/* ww  w . j a  v a2 s  .  co  m*/
    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(folderDocumentLocation);
    int status = client.executeMethod(method);
    // verification
    assertThat(status).isEqualTo(HttpStatus.SC_FORBIDDEN);
}

From source file:org.jetbrains.plugins.github.api.GithubApiUtil.java

private static void checkStatusCode(@NotNull HttpMethod method) throws IOException {
    int code = method.getStatusCode();
    switch (code) {
    case HttpStatus.SC_OK:
    case HttpStatus.SC_CREATED:
    case HttpStatus.SC_ACCEPTED:
    case HttpStatus.SC_NO_CONTENT:
        return;//from   w  w  w . j a v a  2 s  .  c  o m
    case HttpStatus.SC_BAD_REQUEST:
    case HttpStatus.SC_UNAUTHORIZED:
    case HttpStatus.SC_PAYMENT_REQUIRED:
    case HttpStatus.SC_FORBIDDEN:
        throw new GithubAuthenticationException("Request response: " + getErrorMessage(method));
    default:
        throw new GithubStatusCodeException(code + ": " + getErrorMessage(method), code);
    }
}

From source file:org.jetbrains.tfsIntegration.exceptions.TfsExceptionManager.java

public static TfsException createHttpTransportErrorException(int errorCode, AxisFault axisFault) {
    switch (errorCode) {
    case HttpStatus.SC_UNAUTHORIZED:
        return new UnauthorizedException(axisFault);
    case HttpStatus.SC_BAD_GATEWAY:
        return new HostNotFoundException(axisFault);
    case HttpStatus.SC_NOT_FOUND:
        return new HostNotApplicableException(axisFault);
    case HttpStatus.SC_FORBIDDEN:
        return new ForbiddenException(axisFault);
    case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED:
        return new TfsException(TFSBundle.message("proxy.auth.failed"));
    default:/*from  w ww  .  j a va 2s .  c o m*/
        return new ConnectionFailedException(axisFault, errorCode);
    }
}

From source file:org.ldp4j.server.frontend.ServerFrontendITest.java

@Test
@Category({ ExceptionPath.class })
@OperateOnDeployment(DEPLOYMENT)//from  w ww  .  j a va2 s .  c o m
public void testNoQuerySupport(@ArquillianResource final URL url) throws Exception {
    LOGGER.info("Started {}", testName.getMethodName());
    HELPER.base(url);
    HELPER.setLegacy(false);

    HttpGet get = HELPER.newRequest(
            MyApplication.ROOT_PERSON_CONTAINER_PATH + "?param1=value1&param2=value2&param2=value3&param3",
            HttpGet.class);
    Metadata getResponse = HELPER.httpRequest(get);
    assertThat(getResponse.status, equalTo(HttpStatus.SC_FORBIDDEN));
    assertThat(getResponse.body, notNullValue());
    assertThat(getResponse.contentType, startsWith("text/plain"));
    assertThat(getResponse.language, equalTo(Locale.ENGLISH));
}