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.artifactory.repo.virtual.interceptor.VirtualRepoInterceptorBase.java

/**
 * @param resource Resource to check/*from  w  ww . ja  v a 2  s  .co  m*/
 * @return Returns the given resource iff the status code is forbidden (403). Otherwise returns null
 */
public static UnfoundRepoResource checkIfForbidden(RepoResource resource) {
    if (resource instanceof UnfoundRepoResource) {
        if (((UnfoundRepoResource) resource).getStatusCode() == HttpStatus.SC_FORBIDDEN) {
            return (UnfoundRepoResource) resource;
        }
    }
    return null;
}

From source file:org.artifactory.repo.webdav.WebdavServiceImpl.java

@Override
public void handleMove(ArtifactoryRequest request, ArtifactoryResponse response) throws IOException {
    RepoPath repoPath = request.getRepoPath();
    if (StringUtils.isEmpty(repoPath.getPath())) {
        response.sendError(HttpStatus.SC_BAD_REQUEST,
                "Cannot perform MOVE action on a repository. " + "Please specify a valid path", log);
        return;//from  ww w .  j a  v  a  2  s. co  m
    }

    String destination = URLDecoder.decode(request.getHeader("Destination"), "UTF-8");
    if (StringUtils.isEmpty(destination)) {
        response.sendError(HttpStatus.SC_BAD_REQUEST, "Header 'Destination' is required.", log);
        return;
    }

    String targetPathWithoutContextUrl = StringUtils.remove(destination, request.getServletContextUrl());
    String targetPathParent = PathUtils.getParent(targetPathWithoutContextUrl);
    RepoPath targetPath = InternalRepoPathFactory.create(targetPathParent);
    if (!authService.canDelete(repoPath) || !authService.canDeploy(targetPath)) {
        response.sendError(HttpStatus.SC_FORBIDDEN, "Insufficient permissions.", log);
        return;
    }

    MoveMultiStatusHolder status = repoService.move(repoPath, targetPath, false, true, true);
    if (!status.hasWarnings() && !status.hasErrors()) {
        response.sendSuccess();
    } else {
        response.sendError(status);
    }
}

From source file:org.artifactory.rest.common.ArtifactoryRestExceptionMapper.java

@Override
public Response toResponse(WebApplicationException exception) {
    Response jerseyResponse = exception.getResponse();
    int status = jerseyResponse.getStatus();
    switch (status) {
    case HttpStatus.SC_FORBIDDEN:
        return interceptForbiddenStatus(jerseyResponse);

    case HttpStatus.SC_UNAUTHORIZED:
        return interceptUnauthorizedStatus(jerseyResponse);
    }/* w  ww.ja va  2  s . c  o  m*/

    return jerseyResponse;
}

From source file:org.artifactory.rest.resource.system.PingResource.java

/**
 * @return The artifactory state "OK" or "Failure"
 *//*from www. j  a v  a 2 s. c o  m*/
@GET
@Produces({ MediaType.TEXT_PLAIN })
public Response pingArtifactory() {
    try {
        log.debug("Received ping call");
        // Check that addons are OK if needed
        if (addonsManager.lockdown()) {
            log.error("Ping failed due to unloaded addons");
            return Response.status(HttpStatus.SC_FORBIDDEN).entity("Addons unloaded").build();
        }
        ArtifactoryHome artifactoryHome = ArtifactoryHome.get();
        if (!artifactoryHome.getDataDir().canWrite() || !artifactoryHome.getLogDir().canWrite()) {
            log.error("Ping failed due to file system access to data or log dir failed");
            return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).entity("File system access failed")
                    .build();
        }
        ContextHelper.get().beanForType(StorageService.class).ping();
    } catch (Exception e) {
        log.error("Error during ping test", e);
        return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
    }
    log.debug("Ping successful");
    return Response.ok().entity("OK").build();
}

From source file:org.collectionspace.chain.csp.webui.authorities.AuthoritiesVocabulariesInitialize.java

public int createIfMissingAuthority(Storage storage, StringBuffer tty, Record record, Instance instance)
        throws ExistException, UnimplementedException, UIException, JSONException, UnderlyingStorageException {
    int result = HttpStatus.SC_OK;

    String url = record.getID() + "/" + instance.getTitleRef();
    try {/*from w  w w  . jav a2 s  . co m*/
        storage.getPathsJSON(url, new JSONObject()).toString();
        if (tty != null) {
            log.debug("--- Instance " + instance.getID() + " exists.");
            tty.append("--- Instance " + instance.getID() + " exists.\n");
        }
    } catch (UnderlyingStorageException e) {
        if (e.getStatus() == HttpStatus.SC_NOT_FOUND) {
            failedPosts++; // assume we're going to fail
            log.info("Need to create instance " + fInstance.getID());
            if (tty != null) {
                tty.append("Need to create instance " + fInstance.getID() + '\n');
            }
            JSONObject fields = new JSONObject("{'displayName':'" + instance.getTitle()
                    + "', 'shortIdentifier':'" + instance.getWebURL() + "'}");
            String base = record.getID();
            storage.autocreateJSON(base, fields, null);
            failedPosts--; // We succeeded, so subtract our assumed failure
            log.info("Instance " + instance.getID() + " created.");
            if (tty != null) {
                tty.append("Instance " + instance.getID() + " created.\n");
            }
        } else if (e.getStatus() == HttpStatus.SC_FORBIDDEN) {
            result = -1; // We don't have the permissions needed to see if the instance exists.
        } else {
            throw e;
        }
    }

    return result;
}

From source file:org.collectionspace.chain.csp.webui.misc.WebReset.java

private boolean initialiseAll(Storage storage, UIRequest request, String path, boolean modifyResponse)
        throws UIException {
    StringBuffer responseMessage = new StringBuffer();
    boolean initializationFailed = false;
    boolean initializationUnknown = false;

    try {/*from   w  ww  .  j  a  va2s .c o  m*/
        logInitMessage(responseMessage, "Initializing vocab/auth entries...", modifyResponse);
        JSONObject myjs = new JSONObject();
        myjs.put("pageSize", "10");
        myjs.put("pageNum", "0");
        JSONObject data = storage.getPathsJSON("/", null);
        String[] paths = (String[]) data.get("listItems");
        for (String dir : paths) {
            try {
                if (this.spec.hasRecord(dir)) {
                    Record record = this.spec.getRecord(dir);
                    if (record.isType("authority") == true) {
                        for (Instance instance : record.getAllInstances()) {
                            if (instance.getCreateUnreferenced() || isInstanceReferenced(instance)) {
                                avi = new AuthoritiesVocabulariesInitialize(instance, populate, modifyResponse);
                                Option[] allOpts = instance.getAllOptions();
                                boolean creatingTerm = false;
                                try {
                                    if (avi.createIfMissingAuthority(storage, responseMessage, record,
                                            instance) == -1) {
                                        log.warn(String.format(
                                                "The currently authenticated user does not have sufficient permission to determine if the '%s' authority/term-list is properly initialized.",
                                                instance.getID()));
                                        initializationUnknown = true; // since the logged in user doesn't have the correct perms, we can't verify that the authorities and term lists have been properly initialized
                                    } else {
                                        //
                                        // Create the missing items.
                                        //
                                        creatingTerm = true;
                                        avi.fillVocab(storage, record, instance, responseMessage, allOpts,
                                                true);
                                    }
                                } catch (UnderlyingStorageException e) {
                                    if (e.getStatus() == HttpStatus.SC_CONFLICT) {
                                        // This means the authority/vocabulary instance already exists in the backend, so move on to the next instance.
                                        log.warn(String.format(
                                                "A short ID for the authority/vocabulary instance '%s' already exists.",
                                                instance.getID()));
                                        continue; // Not a fatal error.
                                    } else {
                                        throw e;
                                    }
                                } catch (Exception e) {
                                    if (avi.success() == false) {
                                        initializationFailed = true;
                                    }
                                    throw e;
                                }
                            } else {
                                logInitMessage(responseMessage,
                                        "Instance " + instance.getID() + " is defined by not referenced.",
                                        modifyResponse);
                            }
                        }
                    }
                }
            } catch (UnderlyingStorageException e) {
                //
                // If we get here, the system is either in an unknown or incomplete initialization state.  If it's incomplete, we'll put up
                // a message.
                //
                if (e.getCause() instanceof ConnectionException) {
                    if (initializationFailed == true) {
                        modifyResponse = true;
                        if (e.getStatus() == HttpStatus.SC_UNAUTHORIZED
                                || e.getStatus() == HttpStatus.SC_FORBIDDEN) {
                            logInitMessage(responseMessage,
                                    "\nSummary:\n\t*** ERROR *** CollectionSpace has not been properly initialized: The CollectionSpace administrator needs to login to the correct tenant and initialize the default term lists and authorities.\n\n",
                                    modifyResponse);
                        } else {
                            logInitMessage(responseMessage,
                                    "\nSummary:\n\t*** ERROR *** CollectionSpace has not been properly initialized: Ask the CollectionSpace administrator to login to the correct tenant and initialize the default term lists and authorities.\n\n",
                                    modifyResponse);
                        }
                    } else if (initializationUnknown == true) {
                        log.warn(
                                "The currently logged in user does not have the correct permissions to determin whether or not the default authorities and term lists have been properly initialized.");
                    } else {
                        throw e; // Should never get here unless we've got a bug in our code
                    }
                }

                logException(e, responseMessage, modifyResponse);
                break; // no need to continue if the user hasn't authenticated or has incorrect permissions
            }
        }
    } catch (ExistException e) {
        logInitMessage(responseMessage, "ExistException " + e.getLocalizedMessage(), modifyResponse);
        throw new UIException("Existence problem", e);
    } catch (UnimplementedException e) {
        logInitMessage(responseMessage, "UnimplementedException " + e.getLocalizedMessage(), modifyResponse);
        throw new UIException("Unimplemented ", e);
    } catch (UnderlyingStorageException x) {
        if (x.getStatus() == HttpStatus.SC_UNAUTHORIZED) {
            initializationFailed = true;
            logInitMessage(responseMessage,
                    "\n*** ERROR *** You need to be logged in to the correct tenant with the proper credentials before attempting to initialize the default term lists and authorities.\n",
                    modifyResponse);
            logException(x, responseMessage, modifyResponse);
        } else {
            logInitMessage(responseMessage, "UnderlyingStorageException " + x.getLocalizedMessage(),
                    modifyResponse);
            throw new UIException("Problem storing:" + x.getLocalizedMessage(), x.getStatus(), x.getUrl(), x);
        }
    } catch (JSONException e) {
        logInitMessage(responseMessage, "JSONException " + e.getLocalizedMessage(), modifyResponse);
        throw new UIException("Invalid JSON", e);
    }

    //
    // If the caller is requesting we add our messages to the HTTP request response, then create a
    // TTY out instance and add our messages.
    //
    if (modifyResponse == true && request != null) {
        TTYOutputter tty = request.getTTYOutputter();
        tty.line(responseMessage.toString());
    }

    return !initializationFailed; // report success if we didn't see a failure
}

From source file:org.collectionspace.chain.csp.webui.userdetails.UserDetailsCreateUpdate.java

private void store_set(Storage storage, UIRequest request, String path) throws UIException {
    JSONObject data = null;//from w  w  w .  ja  va 2 s .c  o m
    data = request.getJSONBody();

    boolean notfailed = true;
    String msg = "";
    try {
        boolean currentUserPasswordChange = false;
        String newPassword = null;
        boolean absorbedSvcsError = false;
        if (create) {
            path = sendJSON(storage, null, data);
            // assign to default role.
        } else {
            // Check for password update. If doing that, absorb 403 errors and redirect
            // as though we are doing a logout.
            JSONObject fields = data.optJSONObject("fields");
            if (fields != null && fields.has(PASSWORD_FIELD)) {
                String passwd = fields.getString(PASSWORD_FIELD);
                if (passwd != null) {
                    if (passwd.isEmpty()) {
                        fields.remove(PASSWORD_FIELD); // Preclude removl of a password
                    } else {
                        String editedUserId = fields.getString(USER_ID_FIELD);
                        UISession session = request.getSession();
                        if (session != null) {
                            Object currentUserId = session.getValue(UISession.USERID);
                            if (currentUserId != null && currentUserId.equals(editedUserId)) {
                                newPassword = passwd;
                                currentUserPasswordChange = true;
                            }
                        }
                    }
                }
            }
            path = sendJSON(storage, path, data);
            // If that succeeded, and if we updated the current password, set session
            // credentials
            if (currentUserPasswordChange) {
                request.getSession().setValue(UISession.PASSWORD, newPassword);
            }
        }
        if (path == null) {
            throw new UIException("Insufficient data for create (no fields?)");
        }
        data.put("csid", path);
        try {
            assignRole(storage, path, data);
        } catch (UnderlyingStorageException usex) {
            Integer status = usex.getStatus();
            if (status != null && (status == HttpStatus.SC_FORBIDDEN || status == HttpStatus.SC_UNAUTHORIZED)) {
                absorbedSvcsError = true;
                msg = "Cannot update roles for this account.";
                log.warn("UserDetailsCreateUpdate changing roles, and absorbing error returned: "
                        + usex.getStatus());
            } else {
                throw usex; // Propagate
            }
        }
        boolean isError = !notfailed;
        data.put("isError", isError);
        JSONObject messages = new JSONObject();
        messages.put("message", msg);
        messages.put("severity", "info");
        JSONArray arr = new JSONArray();
        arr.put(messages);
        data.put("messages", arr);
        // Elide the value of the password field before returning a response
        data.optJSONObject("fields").remove(PASSWORD_FIELD);
        request.sendJSONResponse(data);
        request.setOperationPerformed(create ? Operation.CREATE : Operation.UPDATE);
        if (create && notfailed)
            request.setSecondaryRedirectPath(new String[] { url_base, path });
    } catch (JSONException x) {
        throw new UIException("Failed to parse json: ", x);
    } catch (ExistException x) {
        throw new UIException("Existence exception: ", x);
    } catch (UnimplementedException x) {
        throw new UIException("Unimplemented exception: ", x);
    } catch (UnderlyingStorageException x) {
        UIException uiexception = new UIException(x.getMessage(), x.getStatus(), x.getUrl(), x);
        request.sendJSONResponse(uiexception.getJSON());
    }

}

From source file:org.eclipse.andmore.android.localization.translators.GoogleTranslator.java

private static void checkStatusCode(int statusCode, String response) throws HttpException {
    switch (statusCode) {
    case HttpStatus.SC_OK:
        // do nothing
        break;//from w  ww  .j av a 2 s .  co  m
    case HttpStatus.SC_BAD_REQUEST:
        throw new HttpException(NLS.bind(TranslateNLS.GoogleTranslator_ErrorMessageExecutingRequest,
                getErrorMessage(response)));

    case HttpStatus.SC_REQUEST_URI_TOO_LONG:
        throw new HttpException(TranslateNLS.GoogleTranslator_Error_QueryTooBig);

    case HttpStatus.SC_FORBIDDEN:
        throw new HttpException(NLS.bind(TranslateNLS.GoogleTranslator_ErrorMessageNoValidTranslationReturned,
                getErrorMessage(response)));

    default:
        throw new HttpException(NLS.bind(TranslateNLS.GoogleTranslator_Error_HTTPRequestError,
                new Object[] { statusCode, getErrorMessage(response) }));

    }
}

From source file:org.eclipse.buckminster.jnlp.MaterializationUtils.java

/**
 * Checks HTTP response code and throws JNLPException if there is a problem
 * // w w w  .jav  a2 s .c  o  m
 * @param connection
 * @throws JNLPException
 * @throws IOException
 */
public static void checkConnection(int status, String originalURL) throws JNLPException {
    if (status != HttpStatus.SC_OK) {
        String errorCode;

        switch (status) {
        case HttpStatus.SC_FORBIDDEN:

            errorCode = ERROR_CODE_403_EXCEPTION;
            break;

        case HttpStatus.SC_NOT_FOUND:

            errorCode = ERROR_CODE_404_EXCEPTION;
            break;

        case HttpStatus.SC_INTERNAL_SERVER_ERROR:

            errorCode = ERROR_CODE_500_EXCEPTION;
            break;

        default:
            errorCode = ERROR_CODE_REMOTE_IO_EXCEPTION;
            break;
        }

        throw new JNLPException(Messages.cannot_read_materialization_specification, errorCode,
                BuckminsterException.fromMessage("%s - %s", originalURL, HttpStatus.getStatusText(status))); //$NON-NLS-1$
    }
}

From source file:org.eclipse.buckminster.jnlp.p2.MaterializationUtils.java

/**
 * Checks HTTP response code and throws JNLPException if there is a problem
 * /*from  w w  w.j a v  a2  s. c o  m*/
 * @param connection
 * @throws JNLPException
 * @throws IOException
 */
public static void checkConnection(int status, String originalURL) throws JNLPException {
    if (status != HttpStatus.SC_OK) {
        String errorCode;

        switch (status) {
        case HttpStatus.SC_FORBIDDEN:

            errorCode = ERROR_CODE_403_EXCEPTION;
            break;

        case HttpStatus.SC_NOT_FOUND:

            errorCode = ERROR_CODE_404_EXCEPTION;
            break;

        case HttpStatus.SC_INTERNAL_SERVER_ERROR:

            errorCode = ERROR_CODE_500_EXCEPTION;
            break;

        default:
            errorCode = ERROR_CODE_REMOTE_IO_EXCEPTION;
            break;
        }

        throw new JNLPException("Cannot read materialization specification", errorCode,
                BuckminsterException.fromMessage("%s - %s", originalURL, HttpStatus.getStatusText(status)));
    }
}