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:org.intermine.webservice.client.util.HttpConnection.java

/**
 * Handles an error response received while executing a service request.
 * Throws a {@link ServiceException} or one of its subclasses, depending on
 * the failure conditions.//w ww . j a va 2  s .  c  o m
 *
 * @throws ServiceException exception describing the failure.
 * @throws IOException error reading the error response from the
 *         service.
 */
protected void handleErrorResponse() throws IOException {

    String message = executedMethod.getResponseBodyAsString();
    try {
        JSONObject jo = new JSONObject(message);
        message = jo.getString("error");
    } catch (JSONException e) {
        // Pass
    }

    switch (executedMethod.getStatusCode()) {

    case HttpURLConnection.HTTP_NOT_FOUND:
        throw new ResourceNotFoundException(this);

    case HttpURLConnection.HTTP_BAD_REQUEST:
        if (message != null) {
            throw new BadRequestException(message);
        } else {
            throw new BadRequestException(this);
        }
    case HttpURLConnection.HTTP_FORBIDDEN:
        if (message != null) {
            throw new ServiceForbiddenException(message);
        } else {
            throw new ServiceForbiddenException(this);
        }
    case HttpURLConnection.HTTP_NOT_IMPLEMENTED:
        throw new NotImplementedException(this);

    case HttpURLConnection.HTTP_INTERNAL_ERROR:
        if (message != null) {
            throw new InternalErrorException(message);
        } else {
            throw new InternalErrorException(this);
        }
    case HttpURLConnection.HTTP_UNAVAILABLE:
        throw new ServiceUnavailableException(this);

    default:
        if (message != null) {
            throw new ServiceException(message);
        } else {
            throw new ServiceException(this);
        }
    }
}

From source file:org.apache.sentry.api.service.thrift.TestSentryWebServerWithKerberos.java

@Test
public void testTraceIsDisabled() throws Exception {
    final URL url = new URL("http://" + SentryServiceIntegrationBase.SERVER_HOST + ":"
            + SentryServiceIntegrationBase.webServerPort);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("TRACE");
    Assert.assertEquals(HttpURLConnection.HTTP_FORBIDDEN, conn.getResponseCode());
}

From source file:org.apache.maven.wagon.providers.http.LightweightHttpWagon.java

protected void finishPutTransfer(Resource resource, InputStream input, OutputStream output)
        throws TransferFailedException, AuthorizationException, ResourceDoesNotExistException {
    try {/*from   w w w .ja  va  2 s.  co m*/
        int statusCode = putConnection.getResponseCode();

        switch (statusCode) {
        // Success Codes
        case HttpURLConnection.HTTP_OK: // 200
        case HttpURLConnection.HTTP_CREATED: // 201
        case HttpURLConnection.HTTP_ACCEPTED: // 202
        case HttpURLConnection.HTTP_NO_CONTENT: // 204
            break;

        case HttpURLConnection.HTTP_FORBIDDEN:
            throw new AuthorizationException("Access denied to: " + buildUrl(resource.getName()));

        case HttpURLConnection.HTTP_NOT_FOUND:
            throw new ResourceDoesNotExistException(
                    "File: " + buildUrl(resource.getName()) + " does not exist");

            // add more entries here
        default:
            throw new TransferFailedException("Failed to transfer file: " + buildUrl(resource.getName())
                    + ". Return code is: " + statusCode);
        }
    } catch (IOException e) {
        fireTransferError(resource, e, TransferEvent.REQUEST_PUT);

        throw new TransferFailedException("Error transferring file: " + e.getMessage(), e);
    }
}

From source file:de.ub0r.android.websms.connector.gmx.ConnectorGMX.java

@Override
protected void parseResponseCode(final Context context, final HttpResponse response) {
    final int resp = response.getStatusLine().getStatusCode();
    switch (resp) {
    case HttpURLConnection.HTTP_OK:
        return;/*from w  w w . j a v a 2  s  . c o  m*/
    case HttpURLConnection.HTTP_ACCEPTED:
        return;
    case HttpURLConnection.HTTP_FORBIDDEN:
        throw new WebSMSException(context, R.string.error_pw);
    default:
        super.parseResponseCode(context, response);
        break;
    }
}

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

@Test
public void testMoveBadRequest() throws IOException, SAXException {
    //create workspace
    String workspaceName = WorkspaceServiceTest.class.getName() + "#testMoveProject";
    URI workspaceLocation = createWorkspace(workspaceName);

    //request a bogus move
    String projectName = "My Project";
    WebRequest request = getCopyMoveProjectRequest(workspaceLocation, projectName, "badsource", true);
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_FORBIDDEN, response.getResponseCode());
}

From source file:de.innovationgate.igutils.pingback.PingBackClient.java

/**
 * checks if the given sourceURI is reachable, has textual content and contains a link to the given target
 * if present the title of the sourceURI is returned
 * @param sourceURI - the sourceURI to check
 * @param targetURI - the targetURI to search as link 
 * @throws PingBackException - thrown if check fails
 * @returns title of the sourceURI - null if not present or found
 *//*from w  w w. ja  v a2 s  . c  o m*/
public String checkSourceURI(String sourceURI, String targetURI) throws PingBackException {
    HttpClient client = WGFactory.getHttpClientFactory().createHttpClient();
    GetMethod sourceGET = new GetMethod(sourceURI);
    sourceGET.setFollowRedirects(false);
    try {
        int responseCode = client.executeMethod(sourceGET);
        if (responseCode != HttpURLConnection.HTTP_OK) {
            if (responseCode == HttpURLConnection.HTTP_FORBIDDEN) {
                throw new PingBackException(PingBackException.ERROR_ACCESS_DENIED,
                        "Access denied on source uri '" + sourceURI + "'.");
            } else if (responseCode == HttpURLConnection.HTTP_BAD_GATEWAY) {
                throw new PingBackException(PingBackException.ERROR_UPSTREAM_SERVER_COMMUNICATION_ERROR,
                        "Get request on source uri '" + sourceURI + "' returned '" + responseCode + "'.");
            } else {
                throw new PingBackException(PingBackException.ERROR_GENERIC,
                        "Source uri is unreachable. Get request on source uri '" + sourceURI + "' returned '"
                                + responseCode + "'.");
            }
        }

        checkTextualContentType(sourceGET);

        // search link to target in source
        InputStream sourceIn = sourceGET.getResponseBodyAsStream();
        String searchTerm = targetURI.toLowerCase();
        boolean linkFound = false;
        String title = null;
        if (sourceIn == null) {
            throw new PingBackException(PingBackException.ERROR_SOURCE_URI_HAS_NO_LINK,
                    "Source uri contains no link to target '" + targetURI + "'.");
        } else {
            // first of all read response into a fix buffer of 2Mb - all further content will be ignored for doS-reason
            ByteArrayOutputStream htmlPageBuffer = new ByteArrayOutputStream();
            inToOut(sourceGET.getResponseBodyAsStream(), htmlPageBuffer, 1024, documentSizeLimit);

            try {
                // search for title
                DOMParser parser = new DOMParser();
                parser.parse(new InputSource(new ByteArrayInputStream(htmlPageBuffer.toByteArray())));
                Document doc = parser.getDocument();
                NodeList titleElements = doc.getElementsByTagName("title");
                if (titleElements.getLength() > 0) {
                    // retrieve first title
                    Node titleNode = titleElements.item(0);
                    title = titleNode.getFirstChild().getNodeValue();
                }
            } catch (Exception e) {
                // ignore any parsing exception - title is just a goodie
            }

            // read line per line and search for link
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    new ByteArrayInputStream(htmlPageBuffer.toByteArray()), sourceGET.getResponseCharSet()));
            String line = reader.readLine();
            while (line != null) {
                line = line.toLowerCase();
                if (line.indexOf(searchTerm) != -1) {
                    linkFound = true;
                    break;
                }
                line = reader.readLine();
            }
        }

        if (!linkFound) {
            throw new PingBackException(PingBackException.ERROR_SOURCE_URI_HAS_NO_LINK,
                    "Source uri '" + sourceURI + "' contains no link to target '" + targetURI + "'.");
        } else {
            return title;
        }
    } catch (HttpException e) {
        throw new PingBackException(PingBackException.ERROR_GENERIC,
                "Unable to check source uri '" + sourceURI + "'.", e);
    } catch (IOException e) {
        throw new PingBackException(PingBackException.ERROR_GENERIC,
                "Unable to check source uri '" + sourceURI + "'.", e);
    }
}

From source file:me.philio.ghost.ui.LoginFragment.java

@Override
public void failure(RetrofitError error) {
    Log.d(TAG, "Authentication failed");

    // Parse error JSON
    ErrorResponse errorResponse = (ErrorResponse) error.getBodyAs(ErrorResponse.class);

    // Extract the first error message (at time of writing there is only ever one)
    String errorMsg = null;/* w w  w .j  a v a  2s  .  co m*/
    if (errorResponse != null && errorResponse.errors != null && errorResponse.errors.size() > 0) {
        String rawMsg = errorResponse.errors.get(0).message;
        errorMsg = Html.fromHtml(rawMsg).toString();
    }

    // Show user an error
    int status = 0;
    if (error.getResponse() != null) {
        status = error.getResponse().getStatus();
    }
    switch (status) {
    case HttpURLConnection.HTTP_NOT_FOUND:
        mEditEmail.setError(errorMsg != null ? errorMsg : getString(R.string.error_incorrect_email));
        break;
    case HttpURLConnection.HTTP_FORBIDDEN:
        mEditEmail.setError(errorMsg != null ? errorMsg : getString(R.string.error_incorrect_email));
        break;
    case HttpURLConnection.HTTP_UNAUTHORIZED:
        mEditPassword.setError(errorMsg != null ? errorMsg : getString(R.string.error_invalid_password));
        break;
    }

    // Enable button and hide progress bar
    mBtnLogin.setEnabled(true);
    ((LoginActivity) getActivity()).setToolbarProgressBarVisibility(false);
}

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

TenantResult<JsonObject> removeTenant(final String tenantId) {

    Objects.requireNonNull(tenantId);

    if (getConfig().isModificationEnabled()) {
        if (tenants.remove(tenantId) != null) {
            dirty = true;/*from w w w  .  ja  v a  2s  . com*/
            return TenantResult.from(HttpURLConnection.HTTP_NO_CONTENT);
        } else {
            return TenantResult.from(HttpURLConnection.HTTP_NOT_FOUND);
        }
    } else {
        return TenantResult.from(HttpURLConnection.HTTP_FORBIDDEN);
    }
}

From source file:org.apache.hadoop.hdfs.tools.offlineImageViewer.TestOfflineImageViewerForXAttr.java

@Test
public void testResponseCode() throws Exception {
    try (WebImageViewer viewer = new WebImageViewer(NetUtils.createSocketAddr("localhost:0"))) {
        viewer.initServer(originalFsimage.getAbsolutePath());
        int port = viewer.getPort();

        URL url = new URL("http://localhost:" + port
                + "/webhdfs/v1/dir1/?op=GETXATTRS&xattr.name=user.notpresent&encoding=TEXT");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.connect();// w  w  w.  j  a v  a 2 s. co m

        assertEquals(HttpURLConnection.HTTP_FORBIDDEN, connection.getResponseCode());

    }
}