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:co.cask.cdap.client.rest.RestStreamClientTest.java

@Test
public void testForbiddenTruncate() throws IOException {
    try {//from  ww  w .ja v  a2  s.  com
        streamClient.truncate(TestUtils.FORBIDDEN_STREAM_NAME);
        Assert.fail("Expected HttpFailureException");
    } catch (HttpFailureException e) {
        Assert.assertEquals(HttpURLConnection.HTTP_FORBIDDEN, e.getStatusCode());
    }
}

From source file:org.eclipse.orion.server.tests.servlets.users.BasicUsersTest.java

@Test
public void testCreateDeleteRights() throws IOException, SAXException, CoreException, JSONException {
    WebConversation webConversation = new WebConversation();
    webConversation.setExceptionsThrownOnErrorStatus(false);

    // create user
    Map<String, String> params = new HashMap<String, String>();
    params.put("login", "testCrDelRights");
    params.put("name", "username_" + System.currentTimeMillis());
    params.put("email", "test@test_" + System.currentTimeMillis());
    params.put("workspace", "workspace_" + System.currentTimeMillis());
    params.put("password", "pass_" + System.currentTimeMillis());
    WebRequest request = getPostUsersRequest("", params, true);
    WebResponse response = webConversation.getResponse(request);
    assertEquals(response.getText(), HttpURLConnection.HTTP_OK, response.getResponseCode());

    JSONObject responseObject = new JSONObject(response.getText());

    assertTrue("Response should contian user uid", responseObject.has("uid"));

    String uid = responseObject.getString("uid");

    // check if user can authenticate
    request = getGetUsersRequest("", true);
    setAuthentication(request, params.get("login"), params.get("password"));
    response = webConversation.getResponse(request);
    assertEquals("User with no roles has admin privileges", HttpURLConnection.HTTP_FORBIDDEN,
            response.getResponseCode());
    // add admin rights
    //TODO/*w  ww.j  a  v  a  2s. c o  m*/

    AuthorizationService.addUserRight(uid, "/users");
    AuthorizationService.addUserRight(uid, "/users/*");

    // check if user can authenticate
    request = getGetUsersRequest("", true);
    setAuthentication(request, params.get("login"), params.get("password"));
    response = webConversation.getResponse(request);
    assertEquals("User tried to use his admin role but did not get the valid response: " + response.getText(),
            HttpURLConnection.HTTP_OK, response.getResponseCode());

    // delete admin rights
    AuthorizationService.removeUserRight(uid, "/users");
    AuthorizationService.removeUserRight(uid, "/users/*");

    // check if user can authenticate
    request = getGetUsersRequest("", true);
    setAuthentication(request, params.get("login"), params.get("password"));
    response = webConversation.getResponse(request);
    assertEquals("User with no roles has admin privileges", HttpURLConnection.HTTP_FORBIDDEN,
            response.getResponseCode());

    // delete user
    request = getDeleteUsersRequest(uid, true);
    response = webConversation.getResponse(request);
    assertEquals(response.getText(), HttpURLConnection.HTTP_OK, response.getResponseCode());
}

From source file:org.jboss.test.web.test.WebIntegrationUnitTestCase.java

/** 
 * JBAS-3279: Authenticated user can bypass declarative role checks for servlets
 *//*w w w. j  a  va  2s .  c o  m*/
public void testUnauthorizedAccess() throws Exception {
    URL url = new URL(baseURL + "jbosstest//restricted3//SecureServlet");
    HttpUtils.accessURL(url, REALM, HttpURLConnection.HTTP_FORBIDDEN);
    url = new URL(baseURL + "jbosstest/%2frestricted3//SecureServlet");
    HttpUtils.accessURL(url, REALM, HttpURLConnection.HTTP_FORBIDDEN);
}

From source file:org.eclipse.mylyn.internal.bugzilla.core.BugzillaClient.java

private GzipGetMethod connectInternal(String requestURL, boolean gzip, IProgressMonitor monitor,
        String eTagValue) throws IOException, CoreException {
    monitor = Policy.monitorFor(monitor);
    hostConfiguration = WebUtil.createHostConfiguration(httpClient, location, monitor);

    for (int attempt = 0; attempt < 2; attempt++) {
        // force authentication
        authenticate(monitor);/*from   ww  w .java2s  .  c o m*/

        GzipGetMethod getMethod = new GzipGetMethod(WebUtil.getRequestPath(requestURL), gzip);
        if (requestURL.contains(QUERY_DELIMITER)) {
            getMethod.setQueryString(requestURL.substring(requestURL.indexOf(QUERY_DELIMITER)));
        }

        getMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=" //$NON-NLS-1$ //$NON-NLS-2$
                + getCharacterEncoding());

        if (eTagValue != null && eTagValue.compareTo("") != 0) { //$NON-NLS-1$
            getMethod.setRequestHeader("If-None-Match", eTagValue); //$NON-NLS-1$
        }
        // Resolves bug#195113
        httpClient.getParams().setParameter("http.protocol.single-cookie-header", true); //$NON-NLS-1$

        // WARNING!! Setting browser compatibility breaks Bugzilla
        // authentication
        // getMethod.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
        // getMethod.getParams().setCookiePolicy(CookiePolicy.RFC_2109);

        getMethod.setDoAuthentication(true);

        int code;
        try {
            code = WebUtil.execute(httpClient, hostConfiguration, getMethod, monitor);
        } catch (IOException e) {
            WebUtil.releaseConnection(getMethod, monitor);
            throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN,
                    RepositoryStatus.ERROR_IO, repositoryUrl.toString(), e));
        }
        switch (code) {
        case HttpURLConnection.HTTP_OK:
            return getMethod;
        case HttpURLConnection.HTTP_NOT_MODIFIED:
            WebUtil.releaseConnection(getMethod, monitor);
            throw new CoreException(new Status(IStatus.WARNING, BugzillaCorePlugin.ID_PLUGIN, "Not changed")); //$NON-NLS-1$
        case HttpURLConnection.HTTP_UNAUTHORIZED:
        case HttpURLConnection.HTTP_FORBIDDEN:
            // login or reauthenticate due to an expired session
            loggedIn = false;
            WebUtil.releaseConnection(getMethod, monitor);
            authenticate(monitor);
            break;
        case HttpURLConnection.HTTP_PROXY_AUTH:
            loggedIn = false;
            WebUtil.releaseConnection(getMethod, monitor);
            throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN,
                    RepositoryStatus.ERROR_REPOSITORY_LOGIN, repositoryUrl.toString(),
                    "Proxy authentication required")); //$NON-NLS-1$
        case HttpURLConnection.HTTP_INTERNAL_ERROR:
            loggedIn = false;
            InputStream stream = getResponseStream(getMethod, monitor);
            ByteArrayOutputStream ou = new ByteArrayOutputStream(1024);
            transferData(stream, ou);
            WebUtil.releaseConnection(getMethod, monitor);
            throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN,
                    RepositoryStatus.ERROR_NETWORK, repositoryUrl.toString(), "Error = 500")); //$NON-NLS-1$
        default:
            WebUtil.releaseConnection(getMethod, monitor);
            throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN,
                    RepositoryStatus.ERROR_NETWORK, "Http error: " + HttpStatus.getStatusText(code))); //$NON-NLS-1$
        }

    }

    throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN,
            RepositoryStatus.ERROR_REPOSITORY_LOGIN, "All connection attempts to " + repositoryUrl.toString() //$NON-NLS-1$
                    + " failed. Please verify connection and authentication information.")); //$NON-NLS-1$
}

From source file:org.apache.hadoop.hbase.rest.TestSecureRESTServer.java

@Test
public void testNegativeAuthorization() throws Exception {
    Pair<CloseableHttpClient, HttpClientContext> pair = getClient();
    CloseableHttpClient client = pair.getFirst();
    HttpClientContext context = pair.getSecond();

    StringEntity entity = new StringEntity("{\"name\":\"test\", \"ColumnSchema\":[{\"name\":\"f\"}]}",
            ContentType.APPLICATION_JSON);
    HttpPut put = new HttpPut("http://localhost:" + REST_TEST.getServletPort() + "/test/schema");
    put.setEntity(entity);//from   ww w.  j a v  a  2 s . c  o m

    UserGroupInformation unprivileged = UserGroupInformation.loginUserFromKeytabAndReturnUGI(CLIENT_PRINCIPAL,
            clientKeytab.getAbsolutePath());
    unprivileged.doAs(new PrivilegedExceptionAction<Void>() {
        @Override
        public Void run() throws Exception {
            try (CloseableHttpResponse response = client.execute(put, context)) {
                final int statusCode = response.getStatusLine().getStatusCode();
                HttpEntity entity = response.getEntity();
                assertEquals("Got response: " + EntityUtils.toString(entity), HttpURLConnection.HTTP_FORBIDDEN,
                        statusCode);
            }
            return null;
        }
    });
}

From source file:org.eclipse.hono.deviceregistry.FileBasedCredentialsService.java

@Override
public void update(final String tenantId, final JsonObject newCredentials,
        final Handler<AsyncResult<CredentialsResult<JsonObject>>> resultHandler) {

    Objects.requireNonNull(tenantId);
    Objects.requireNonNull(newCredentials);
    Objects.requireNonNull(resultHandler);

    if (getConfig().isModificationEnabled()) {
        final String authId = newCredentials.getString(CredentialsConstants.FIELD_AUTH_ID);
        final String type = newCredentials.getString(CredentialsConstants.FIELD_TYPE);
        log.debug("updating credentials for device [tenant-id: {}, auth-id: {}, type: {}]", tenantId, authId,
                type);//from   w ww. j a  v a 2s  .c o m

        final Map<String, JsonArray> credentialsForTenant = getCredentialsForTenant(tenantId);
        if (credentialsForTenant == null) {
            resultHandler
                    .handle(Future.succeededFuture(CredentialsResult.from(HttpURLConnection.HTTP_NOT_FOUND)));
        } else {
            final JsonArray credentialsForAuthId = credentialsForTenant.get(authId);
            if (credentialsForAuthId == null) {
                resultHandler.handle(
                        Future.succeededFuture(CredentialsResult.from(HttpURLConnection.HTTP_NOT_FOUND)));
            } else {
                // find credentials of given type
                boolean removed = false;
                final Iterator<Object> credentialsIterator = credentialsForAuthId.iterator();
                while (credentialsIterator.hasNext()) {
                    final JsonObject creds = (JsonObject) credentialsIterator.next();
                    if (creds.getString(CredentialsConstants.FIELD_TYPE).equals(type)) {
                        credentialsIterator.remove();
                        removed = true;
                        break;
                    }
                }
                if (removed) {
                    credentialsForAuthId.add(newCredentials);
                    dirty = true;
                    resultHandler.handle(
                            Future.succeededFuture(CredentialsResult.from(HttpURLConnection.HTTP_NO_CONTENT)));
                } else {
                    resultHandler.handle(
                            Future.succeededFuture(CredentialsResult.from(HttpURLConnection.HTTP_NOT_FOUND)));
                }
            }
        }
    } else {
        resultHandler.handle(Future.succeededFuture(CredentialsResult.from(HttpURLConnection.HTTP_FORBIDDEN)));
    }
}

From source file:org.eclipse.orion.server.tests.servlets.workspace.WorkspaceServiceTest.java

/**
 * Tests creating a project that is stored at a non-default location on the server.
 *///from  w ww. ja v a  2s  .  c  om
@Test
public void testCreateProjectNonDefaultLocation() throws IOException, SAXException, JSONException {
    //create workspace
    String workspaceName = WorkspaceServiceTest.class.getName() + "#testCreateProjectNonDefaultLocation";
    URI workspaceLocation = createWorkspace(workspaceName);

    String tmp = System.getProperty("java.io.tmpdir");
    File projectLocation = new File(new File(tmp), "Orion-testCreateProjectNonDefaultLocation");
    toDelete.add(EFS.getLocalFileSystem().getStore(projectLocation.toURI()));
    projectLocation.mkdir();

    //at first forbid all project locations
    ServletTestingSupport.allowedPrefixes = null;

    //create a project
    String projectName = "My Project";
    WebRequest request = getCreateProjectRequest(workspaceLocation, projectName, projectLocation.toString());
    if (projectName != null)
        request.setHeaderField(ProtocolConstants.HEADER_SLUG, projectName);
    request.setHeaderField(ProtocolConstants.HEADER_ORION_VERSION, "1");
    setAuthentication(request);
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_FORBIDDEN, response.getResponseCode());

    //now set the allowed prefixes and try again
    ServletTestingSupport.allowedPrefixes = projectLocation.toString();
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());
    JSONObject project = new JSONObject(response.getText());
    assertEquals(projectName, project.getString(ProtocolConstants.KEY_NAME));
    String projectId = project.optString(ProtocolConstants.KEY_ID, null);
    assertNotNull(projectId);
}

From source file:org.projectbuendia.client.ui.OdkActivityLauncher.java

private static void handleSubmitError(VolleyError error) {
    SubmitXformFailedEvent.Reason reason = SubmitXformFailedEvent.Reason.UNKNOWN;

    if (error instanceof TimeoutError) {
        reason = SubmitXformFailedEvent.Reason.SERVER_TIMEOUT;
    } else if (error.networkResponse != null) {
        switch (error.networkResponse.statusCode) {
        case HttpURLConnection.HTTP_UNAUTHORIZED:
        case HttpURLConnection.HTTP_FORBIDDEN:
            reason = SubmitXformFailedEvent.Reason.SERVER_AUTH;
            break;
        case HttpURLConnection.HTTP_NOT_FOUND:
            reason = SubmitXformFailedEvent.Reason.SERVER_BAD_ENDPOINT;
            break;
        case HttpURLConnection.HTTP_INTERNAL_ERROR:
            if (error.networkResponse.data == null) {
                LOG.e("Server error, but no internal error stack trace available.");
            } else {
                LOG.e(new String(error.networkResponse.data, Charsets.UTF_8));
                LOG.e("Server error. Internal error stack trace:\n");
            }//from ww w.j a va  2s . c om
            reason = SubmitXformFailedEvent.Reason.SERVER_ERROR;
            break;
        default:
            reason = SubmitXformFailedEvent.Reason.SERVER_ERROR;
            break;
        }
    }

    EventBus.getDefault().post(new SubmitXformFailedEvent(reason, error));
}

From source file:org.eclipse.hono.deviceregistry.FileBasedCredentialsService.java

@Override
public void remove(final String tenantId, final String type, final String authId,
        final Handler<AsyncResult<CredentialsResult<JsonObject>>> resultHandler) {

    Objects.requireNonNull(tenantId);
    Objects.requireNonNull(type);
    Objects.requireNonNull(authId);
    Objects.requireNonNull(resultHandler);

    if (getConfig().isModificationEnabled()) {
        final Map<String, JsonArray> credentialsForTenant = credentials.get(tenantId);
        if (credentialsForTenant == null) {
            resultHandler//from w ww . j a va 2  s  .com
                    .handle(Future.succeededFuture(CredentialsResult.from(HttpURLConnection.HTTP_NOT_FOUND)));
        } else {
            final JsonArray credentialsForAuthId = credentialsForTenant.get(authId);
            if (credentialsForAuthId == null) {
                resultHandler.handle(
                        Future.succeededFuture(CredentialsResult.from(HttpURLConnection.HTTP_NOT_FOUND)));
            } else if (removeCredentialsFromCredentialsArray(null, type, credentialsForAuthId)) {
                if (credentialsForAuthId.isEmpty()) {
                    credentialsForTenant.remove(authId); // do not leave empty array as value
                }
                resultHandler.handle(
                        Future.succeededFuture(CredentialsResult.from(HttpURLConnection.HTTP_NO_CONTENT)));
            } else {
                resultHandler.handle(
                        Future.succeededFuture(CredentialsResult.from(HttpURLConnection.HTTP_NOT_FOUND)));
            }
        }
    } else {
        resultHandler.handle(Future.succeededFuture(CredentialsResult.from(HttpURLConnection.HTTP_FORBIDDEN)));
    }
}