Example usage for java.net HttpURLConnection HTTP_FORBIDDEN

List of usage examples for java.net HttpURLConnection HTTP_FORBIDDEN

Introduction

In this page you can find the example usage for java.net HttpURLConnection HTTP_FORBIDDEN.

Prototype

int HTTP_FORBIDDEN

To view the source code for java.net HttpURLConnection HTTP_FORBIDDEN.

Click Source Link

Document

HTTP Status-Code 403: Forbidden.

Usage

From source file:play.modules.resteasy.crud.RESTResource.java

/**
 * Returns a FORBIDDEN response
 */
protected Response forbidden() {
    return status(HttpURLConnection.HTTP_FORBIDDEN);
}

From source file:co.cask.cdap.client.rest.RestStreamClientTest.java

@Test
public void testForbiddenGetTTL() throws IOException {
    try {/*w w w  . ja v  a  2  s  . c  o  m*/
        streamClient.getTTL(TestUtils.FORBIDDEN_STREAM_NAME);
        Assert.fail("Expected HttpFailureException");
    } catch (HttpFailureException e) {
        Assert.assertEquals(HttpURLConnection.HTTP_FORBIDDEN, e.getStatusCode());
    }
}

From source file:org.codinjutsu.tools.jenkins.security.DefaultSecurityClient.java

protected void checkResponse(int statusCode, String responseBody) throws AuthenticationException {
    if (statusCode == HttpURLConnection.HTTP_NOT_FOUND) {
        throw new AuthenticationException("Not found");
    }//from w ww  .j  a  va 2 s  .c  om

    if (statusCode == HttpURLConnection.HTTP_FORBIDDEN || statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
        if (StringUtils.containsIgnoreCase(responseBody, BAD_CRUMB_DATA)) {
            throw new AuthenticationException("CSRF enabled -> Missing or bad crumb data");
        }

        throw new AuthenticationException("Unauthorized -> Missing or bad credentials", responseBody);
    }

    if (HttpURLConnection.HTTP_INTERNAL_ERROR == statusCode) {
        throw new AuthenticationException("Server Internal Error: Server unavailable");
    }
}

From source file:org.apache.geronimo.testsuite.servlets.ServletsTest.java

/**
* Test13/*  ww  w. j av a2s  .c om*/
*/
@Test
public void test_TestDynamic_GET_RoleB_Fail() throws Exception {
    Assert.assertEquals(invoke("/TestDynamic", "GET", "george", "bone"), HttpURLConnection.HTTP_FORBIDDEN);
}

From source file:org.apache.hadoop.http.TestHttpServerWithSpengo.java

/**
 * groupA//  ww w . j  ava 2 s  .c o m
 *  - userA
 * groupB
 *  - userA, userB
 * groupC
 *  - userC
 * SPNEGO filter has been enabled.
 * userA has the privilege to impersonate users in groupB.
 * userA has admin access to all default servlets, but userB
 * and userC don't have. So "/logs" can only be accessed by userA.
 * @throws Exception
 */
@Test
public void testAuthenticationWithProxyUser() throws Exception {

    Configuration spengoConf = getSpengoConf(new Configuration());

    //setup logs dir
    System.setProperty("hadoop.log.dir", testRootDir.getAbsolutePath());

    // Setup user group
    UserGroupInformation.createUserForTesting("userA", new String[] { "groupA", "groupB" });
    UserGroupInformation.createUserForTesting("userB", new String[] { "groupB" });
    UserGroupInformation.createUserForTesting("userC", new String[] { "groupC" });

    // Make userA impersonate users in groupB
    spengoConf.set("hadoop.proxyuser.userA.hosts", "*");
    spengoConf.set("hadoop.proxyuser.userA.groups", "groupB");
    ProxyUsers.refreshSuperUserGroupsConfiguration(spengoConf);

    HttpServer2 httpServer = null;
    try {
        // Create http server to test.
        httpServer = getCommonBuilder().setConf(spengoConf).setACL(new AccessControlList("userA groupA"))
                .build();
        httpServer.start();

        // Get signer to encrypt token
        Signer signer = getSignerToEncrypt();

        // setup auth token for userA
        AuthenticatedURL.Token token = getEncryptedAuthToken(signer, "userA");

        String serverURL = "http://" + NetUtils.getHostPortString(httpServer.getConnectorAddress(0)) + "/";

        // The default authenticator is kerberos.
        AuthenticatedURL authUrl = new AuthenticatedURL();

        // userA impersonates userB, it's allowed.
        for (String servlet : new String[] { "stacks", "jmx", "conf" }) {
            HttpURLConnection conn = authUrl.openConnection(new URL(serverURL + servlet + "?doAs=userB"),
                    token);
            Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
        }

        // userA cannot impersonate userC, it fails.
        for (String servlet : new String[] { "stacks", "jmx", "conf" }) {
            HttpURLConnection conn = authUrl.openConnection(new URL(serverURL + servlet + "?doAs=userC"),
                    token);
            Assert.assertEquals(HttpURLConnection.HTTP_FORBIDDEN, conn.getResponseCode());
        }

        // "/logs" and "/logLevel" require admin authorization,
        // only userA has the access.
        for (String servlet : new String[] { "logLevel", "logs" }) {
            HttpURLConnection conn = authUrl.openConnection(new URL(serverURL + servlet), token);
            Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
        }

        // Setup token for userB
        token = getEncryptedAuthToken(signer, "userB");

        // userB cannot access these servlets.
        for (String servlet : new String[] { "logLevel", "logs" }) {
            HttpURLConnection conn = authUrl.openConnection(new URL(serverURL + servlet), token);
            Assert.assertEquals(HttpURLConnection.HTTP_FORBIDDEN, conn.getResponseCode());
        }

    } finally {
        if (httpServer != null) {
            httpServer.stop();
        }
    }
}

From source file:org.debux.webmotion.shiro.Shiro.java

/**
 * Check if the current user is permitted.
 * /*from w ww .j a  v a2s .co m*/
 * @param permission
 * @return 
 */
public Render isPermitted(HttpContext context, Call call) {
    FilterRule rule = (FilterRule) call.getCurrentRule();
    Map<String, String[]> defaultParameters = rule.getDefaultParameters();

    String[] permissions = defaultParameters.get("permission");

    Subject currentUser = getSubject(context);
    if (currentUser.isAuthenticated()) {

        boolean[] permitted = currentUser.isPermitted(permissions);
        if (BooleanUtils.and(permitted)) {
            doProcess();
            return null;
        } else {
            return renderError(HttpURLConnection.HTTP_FORBIDDEN);
        }

    } else {
        return renderError(HttpURLConnection.HTTP_UNAUTHORIZED);
    }
}

From source file:org.eclipse.smarthome.binding.digitalstrom.internal.lib.manager.impl.ConnectionManagerImpl.java

@Override
public synchronized boolean checkConnection() {
    int code = this.digitalSTROMClient.checkConnection(sessionToken);
    switch (code) {
    case HttpURLConnection.HTTP_OK:
        if (!lostConnectionState) {
            lostConnectionState = true;// w w w .j  a va  2 s . c  om
            onConnectionResumed();
        }
        break;
    case HttpURLConnection.HTTP_UNAUTHORIZED:
        lostConnectionState = false;
        break;
    case HttpURLConnection.HTTP_FORBIDDEN:
        if (this.genAppToken) {
            if (StringUtils.isNotBlank(config.getAppToken())) {
                sessionToken = this.digitalSTROMClient.loginApplication(config.getAppToken());
            } else {
                this.onNotAuthenticated();
            }
        } else {
            sessionToken = this.digitalSTROMClient.login(this.config.getUserName(), this.config.getPassword());
        }
        if (sessionToken != null) {
            if (!lostConnectionState) {
                onConnectionResumed();
                lostConnectionState = true;
            }
        } else {
            if (this.genAppToken) {
                onNotAuthenticated();
            }
            lostConnectionState = false;
        }
        break;
    case -2:
        onConnectionLost(ConnectionListener.INVALID_URL);
        lostConnectionState = false;
        break;
    case -3:
    case -4:
        onConnectionLost(ConnectionListener.CONNECTON_TIMEOUT);
        lostConnectionState = false;
        break;
    case -1:
        if (connListener != null) {
            connListener.onConnectionStateChange(ConnectionListener.CONNECTION_LOST);
        }
        break;
    case -5:
        if (connListener != null) {
            onConnectionLost(ConnectionListener.UNKNOWN_HOST);
        }
        break;
    case HttpURLConnection.HTTP_NOT_FOUND:
        onConnectionLost(ConnectionListener.HOST_NOT_FOUND);
        lostConnectionState = false;
        break;
    }
    return lostConnectionState;
}

From source file:com.cloudant.http.internal.interceptors.CookieInterceptor.java

@Override
public HttpConnectionInterceptorContext interceptResponse(HttpConnectionInterceptorContext context) {

    // Check if this interceptor is valid before attempting any kind of renewal
    if (shouldAttemptCookieRequest.get()) {

        HttpURLConnection connection = context.connection.getConnection();

        // If we got a 401 or 403 we might need to renew the cookie
        try {//from   w  ww  .j  a  v  a 2s .  c  o m
            boolean renewCookie = false;
            int statusCode = connection.getResponseCode();

            if (statusCode == HttpURLConnection.HTTP_FORBIDDEN
                    || statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
                InputStream errorStream = connection.getErrorStream();
                String errorString = null;
                if (errorStream != null) {
                    try {
                        // Get the string value of the error stream
                        errorString = IOUtils.toString(errorStream, "UTF-8");
                    } finally {
                        IOUtils.closeQuietly(errorStream);
                    }
                }
                logger.log(Level.FINE, String.format(Locale.ENGLISH, "Intercepted " + "response %d %s",
                        statusCode, errorString));
                switch (statusCode) {
                case HttpURLConnection.HTTP_FORBIDDEN: //403
                    // Check if it was an expiry case
                    // Check using a regex to avoid dependency on a JSON library.
                    // Note (?siu) flags used for . to also match line breaks and for
                    // unicode
                    // case insensitivity.
                    if (errorString != null && errorString
                            .matches("(?siu)" + ".*\\\"error\\\"\\s*:\\s*\\\"credentials_expired\\\".*")) {
                        // Was expired - set boolean to renew cookie
                        renewCookie = true;
                    } else {
                        // Wasn't a credentials expired, throw exception
                        HttpConnectionInterceptorException toThrow = new HttpConnectionInterceptorException(
                                errorString);
                        // Set the flag for deserialization
                        toThrow.deserialize = errorString != null;
                        throw toThrow;
                    }
                    break;
                case HttpURLConnection.HTTP_UNAUTHORIZED: //401
                    // We need to get a new cookie
                    renewCookie = true;
                    break;
                default:
                    break;
                }

                if (renewCookie) {
                    logger.finest("Cookie was invalid attempt to get new cookie.");
                    boolean success = requestCookie(context);
                    if (success) {
                        // New cookie obtained, replay the request
                        context.replayRequest = true;
                    } else {
                        // Didn't successfully renew, maybe creds are invalid
                        context.replayRequest = false; // Don't replay
                        shouldAttemptCookieRequest.set(false); // Set the flag to stop trying
                    }
                }
            } else {
                // Store any cookies provided on the response
                storeCookiesFromResponse(connection);
            }
        } catch (IOException e) {
            logger.log(Level.SEVERE, "Error reading response code or body from request", e);
        }
    }
    return context;

}

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

@Override
public ChangeDetail cherryPick(String reviewId, int patchSetId, final String message, final String destBranch,
        IProgressMonitor monitor) throws GerritException {
    final PatchSet.Id id = new PatchSet.Id(new Change.Id(id(reviewId)), patchSetId);
    String url = "/changes/" + id.getParentKey() + "/revisions/" + id.get() + "/cherrypick"; //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
    CherryPickInput input = new CherryPickInput(message, destBranch);
    ChangeInfo result = executePostRestRequest(url, input, ChangeInfo.class, new ErrorHandler() {
        @Override//from  w ww  .ja va  2  s .  c o  m
        public void handleError(HttpMethodBase method) throws GerritException {
            String errorMsg = getResponseBodyAsString(method);
            if (isNotPermitted(method, errorMsg)) {
                errorMsg = NLS.bind("Cannot cherry pick: {0}", errorMsg); //$NON-NLS-1$
            } else if (isConflict(method)) {
                errorMsg = NLS.bind("Request Conflict: {0}", errorMsg); //$NON-NLS-1$
            } else if (isBadRequest(method)) {
                errorMsg = NLS.bind("Bad Request: {0}", errorMsg); //$NON-NLS-1$
            }
            throw new GerritException(errorMsg);
        }

        private String getResponseBodyAsString(HttpMethodBase method) {
            try {
                return method.getResponseBodyAsString();
            } catch (IOException e) {
                return null;
            }
        }

        private boolean isNotPermitted(HttpMethodBase method, String msg) {
            return method.getStatusCode() == HttpURLConnection.HTTP_FORBIDDEN
                    && msg.toLowerCase().startsWith("cherry pick not permitted"); //$NON-NLS-1$
        }

        private boolean isConflict(HttpMethodBase method) {
            return method.getStatusCode() == HttpURLConnection.HTTP_CONFLICT;
        }

        private boolean isBadRequest(HttpMethodBase method) {
            return method.getStatusCode() == HttpURLConnection.HTTP_BAD_REQUEST;
        }
    }, monitor);

    return getChangeDetail(result.getNumber(), monitor);
}