Example usage for javax.servlet.http HttpServletResponse SC_FORBIDDEN

List of usage examples for javax.servlet.http HttpServletResponse SC_FORBIDDEN

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse SC_FORBIDDEN.

Prototype

int SC_FORBIDDEN

To view the source code for javax.servlet.http HttpServletResponse SC_FORBIDDEN.

Click Source Link

Document

Status code (403) indicating the server understood the request but refused to fulfill it.

Usage

From source file:eu.trentorise.smartcampus.unidataservice.controller.rest.StudentInfoController.java

@RequestMapping(method = RequestMethod.GET, value = "/getoperacard")
public @ResponseBody OperaStudent getCard(HttpServletRequest request, HttpServletResponse response,
        HttpSession session) throws IOException {
    try {//from ww w .j a  v  a 2  s.c o m
        User user = getCurrentUser();
        String userId = getUserId(user);
        if (userId == null) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            return null;
        }

        String token = getToken(request);
        String idAda = getIdAda(token);
        OperaStudent result = getCard(idAda);
        if (result != null) {
            return result;
        } else {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        }

    } catch (Exception e) {
        e.printStackTrace();
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
    return null;
}

From source file:com.google.gerrit.httpd.auth.oauth.OAuthSession.java

private boolean authenticateWithLinkedIdentity(AuthRequest areq, HttpServletResponse rsp)
        throws AccountException, IOException {
    try {/*from   w w w.  ja  v  a 2s .c om*/
        accountManager.link(identifiedUser.get().getAccountId(), areq);
    } catch (OrmException | ConfigInvalidException e) {
        log.error("Cannot link: " + user.getExternalId() + " to user identity: "
                + identifiedUser.get().getAccountId());
        rsp.sendError(HttpServletResponse.SC_FORBIDDEN);
        return false;
    } finally {
        linkMode = false;
    }
    return true;
}

From source file:com.novartis.pcs.ontology.rest.servlet.OntologiesServlet.java

@Override
protected void doPut(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String mediaType = StringUtils.trimToNull(request.getContentType());
    String encoding = StringUtils.trimToNull(request.getCharacterEncoding());
    String pathInfo = StringUtils.trimToNull(request.getPathInfo());
    Curator curator = loadCurator(request);

    if (mediaType != null && mediaType.indexOf(';') > 0) {
        mediaType = mediaType.substring(0, mediaType.indexOf(';'));
    }//  w w w  .  ja  va  2  s.  co m

    if (!StringUtils.equalsIgnoreCase(mediaType, MEDIA_TYPE_OBO)
            || !StringUtils.equalsIgnoreCase(encoding, "utf-8")) {
        log("Failed to import ontology: invalid media type or encoding " + mediaType + ";charset=" + encoding);
        response.setStatus(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
    } else if (pathInfo == null || pathInfo.length() <= 1) {
        log("Failed to import ontology: ontology name not include in path");
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    } else if (curator == null) {
        log("Failed to import ontology: curator not found in request");
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
    } else {
        try {
            String ontologyName = pathInfo.substring(1);
            importService.importOntology(ontologyName, request.getInputStream(), curator);
            response.setStatus(HttpServletResponse.SC_OK);
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Cache-Control", "public, max-age=0");
        } catch (DuplicateEntityException e) {
            log("Failed to import ontology: duplicate term", e);
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        } catch (InvalidEntityException e) {
            log("Failed to import ontology: invalid entity", e);
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        } catch (InvalidFormatException e) {
            log("Failed to import ontology: invalid format", e);
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        } catch (Exception e) {
            log("Failed to import ontology: system error", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
    response.setContentLength(0);
}

From source file:net.bhira.sample.api.controller.DepartmentController.java

/**
 * Delete the instance of {@link net.bhira.sample.model.Department} represented by given
 * departmentId. In case of an error return the error message.
 * /*from  w  w w .jav a  2  s. c om*/
 * @param departmentId
 *            the ID for {@link net.bhira.sample.model.Department}.
 * @param response
 *            the http response to which the results will be written.
 * @return the error message, if save was not successful.
 */
@RequestMapping(value = "/department/{departmentId}", method = RequestMethod.DELETE)
@ResponseBody
public Callable<String> deleteDepartment(@PathVariable long departmentId, HttpServletResponse response) {
    return new Callable<String>() {
        public String call() throws Exception {
            LOG.debug("servicing DELETE department/{}", departmentId);
            String body = "";
            try {
                boolean success = departmentService.delete(departmentId);
                LOG.debug("DELETE department/{} status = {}", departmentId, success);
                if (!success) {
                    response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                }
            } catch (Exception ex) {
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                body = ex.getLocalizedMessage();
                LOG.warn("Error deleting department/{}. {}", departmentId, body);
                LOG.debug("Delete error stacktrace: ", ex);
            }
            return body;
        }
    };
}

From source file:com.zimbra.cs.zimlet.ProxyServlet.java

private void doProxy(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    ZimbraLog.clearContext();/*from   www  .  j a v  a  2  s. com*/
    boolean isAdmin = isAdminRequest(req);
    AuthToken authToken = isAdmin ? getAdminAuthTokenFromCookie(req, resp, true)
            : getAuthTokenFromCookie(req, resp, true);
    if (authToken == null) {
        String zAuthToken = req.getParameter(QP_ZAUTHTOKEN);
        if (zAuthToken != null) {
            try {
                authToken = AuthProvider.getAuthToken(zAuthToken);
                if (authToken.isExpired()) {
                    resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "authtoken expired");
                    return;
                }
                if (!authToken.isRegistered()) {
                    resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "authtoken is invalid");
                    return;
                }
                if (isAdmin && !authToken.isAdmin()) {
                    resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "permission denied");
                    return;
                }
            } catch (AuthTokenException e) {
                resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "unable to parse authtoken");
                return;
            }
        }
    }
    if (authToken == null) {
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "no authtoken cookie");
        return;
    }

    // get the posted body before the server read and parse them.
    byte[] body = copyPostedData(req);

    // sanity check
    String target = req.getParameter(TARGET_PARAM);
    if (target == null) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    // check for permission
    URL url = new URL(target);
    if (!isAdmin && !checkPermissionOnTarget(url, authToken)) {
        resp.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    // determine whether to return the target inline or store it as an upload
    String uploadParam = req.getParameter(UPLOAD_PARAM);
    boolean asUpload = uploadParam != null && (uploadParam.equals("1") || uploadParam.equalsIgnoreCase("true"));

    HttpMethod method = null;
    try {
        HttpClient client = ZimbraHttpConnectionManager.getExternalHttpConnMgr().newHttpClient();
        HttpProxyUtil.configureProxy(client);
        String reqMethod = req.getMethod();
        if (reqMethod.equalsIgnoreCase("GET")) {
            method = new GetMethod(target);
        } else if (reqMethod.equalsIgnoreCase("POST")) {
            PostMethod post = new PostMethod(target);
            if (body != null)
                post.setRequestEntity(new ByteArrayRequestEntity(body, req.getContentType()));
            method = post;
        } else if (reqMethod.equalsIgnoreCase("PUT")) {
            PutMethod put = new PutMethod(target);
            if (body != null)
                put.setRequestEntity(new ByteArrayRequestEntity(body, req.getContentType()));
            method = put;
        } else if (reqMethod.equalsIgnoreCase("DELETE")) {
            method = new DeleteMethod(target);
        } else {
            ZimbraLog.zimlet.info("unsupported request method: " + reqMethod);
            resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            return;
        }

        // handle basic auth
        String auth, user, pass;
        auth = req.getParameter(AUTH_PARAM);
        user = req.getParameter(USER_PARAM);
        pass = req.getParameter(PASS_PARAM);
        if (auth != null && user != null && pass != null) {
            if (!auth.equals(AUTH_BASIC)) {
                ZimbraLog.zimlet.info("unsupported auth type: " + auth);
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
                return;
            }
            HttpState state = new HttpState();
            state.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, pass));
            client.setState(state);
            method.setDoAuthentication(true);
        }

        Enumeration headers = req.getHeaderNames();
        while (headers.hasMoreElements()) {
            String hdr = (String) headers.nextElement();
            ZimbraLog.zimlet.debug("incoming: " + hdr + ": " + req.getHeader(hdr));
            if (canProxyHeader(hdr)) {
                ZimbraLog.zimlet.debug("outgoing: " + hdr + ": " + req.getHeader(hdr));
                if (hdr.equalsIgnoreCase("x-host"))
                    method.getParams().setVirtualHost(req.getHeader(hdr));
                else
                    method.addRequestHeader(hdr, req.getHeader(hdr));
            }
        }

        try {
            if (!(reqMethod.equalsIgnoreCase("POST") || reqMethod.equalsIgnoreCase("PUT"))) {
                method.setFollowRedirects(true);
            }
            HttpClientUtil.executeMethod(client, method);
        } catch (HttpException ex) {
            ZimbraLog.zimlet.info("exception while proxying " + target, ex);
            resp.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        int status = method.getStatusLine() == null ? HttpServletResponse.SC_INTERNAL_SERVER_ERROR
                : method.getStatusCode();

        // workaround for Alexa Thumbnails paid web service, which doesn't bother to return a content-type line
        Header ctHeader = method.getResponseHeader("Content-Type");
        String contentType = ctHeader == null || ctHeader.getValue() == null ? DEFAULT_CTYPE
                : ctHeader.getValue();

        InputStream targetResponseBody = method.getResponseBodyAsStream();

        if (asUpload) {
            String filename = req.getParameter(FILENAME_PARAM);
            if (filename == null || filename.equals(""))
                filename = new ContentType(contentType).getParameter("name");
            if ((filename == null || filename.equals(""))
                    && method.getResponseHeader("Content-Disposition") != null)
                filename = new ContentDisposition(method.getResponseHeader("Content-Disposition").getValue())
                        .getParameter("filename");
            if (filename == null || filename.equals(""))
                filename = "unknown";

            List<Upload> uploads = null;

            if (targetResponseBody != null) {
                try {
                    Upload up = FileUploadServlet.saveUpload(targetResponseBody, filename, contentType,
                            authToken.getAccountId());
                    uploads = Arrays.asList(up);
                } catch (ServiceException e) {
                    if (e.getCode().equals(MailServiceException.UPLOAD_REJECTED))
                        status = HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE;
                    else
                        status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
                }
            }

            resp.setStatus(status);
            FileUploadServlet.sendResponse(resp, status, req.getParameter(FORMAT_PARAM), null, uploads, null);
        } else {
            resp.setStatus(status);
            resp.setContentType(contentType);
            for (Header h : method.getResponseHeaders())
                if (canProxyHeader(h.getName()))
                    resp.addHeader(h.getName(), h.getValue());
            if (targetResponseBody != null)
                ByteUtil.copy(targetResponseBody, true, resp.getOutputStream(), true);
        }
    } finally {
        if (method != null)
            method.releaseConnection();
    }
}

From source file:com.adito.vfs.webdav.DAVTransaction.java

boolean verifyIp() {
    try {// w  w  w .j  a  va2s .  c om
        if (SystemDatabaseFactory.getInstance().verifyIPAddress(req.getRemoteAddr())) {
            return true;
        }
    } catch (Exception e) {
        log.error("Failed to verify IP address. Considering unauthorized.", e);
    }
    if (log.isDebugEnabled())
        log.debug(req.getRemoteHost() + " is not authorized");
    res.setStatus(HttpServletResponse.SC_FORBIDDEN);
    return false;
}

From source file:com.googlecode.noweco.calendar.CaldavServlet.java

@SuppressWarnings("unchecked")
@Override/*  w ww .  j a  v a 2 s .c  o m*/
public void service(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    String method = req.getMethod();
    if (LOGGER.isDebugEnabled()) {
        List<String> headers = Collections.list((Enumeration<String>) req.getHeaderNames());
        LOGGER.debug("Command : {}, Appel : {}, headers {}",
                new Object[] { method, req.getRequestURI(), headers });
    }

    if (!authent(req)) {
        resp.addHeader("WWW-Authenticate", "BASIC realm=\"Noweco CalDAV\"");
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return;
    }
    String requestURI = req.getRequestURI();
    if (requestURI.length() != 0 && requestURI.charAt(0) != '/') {
        // unknown relative URI
        resp.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    try {
        if (METHOD_PROPFIND.equals(method)) {
            doPropfind(req, resp);
        } else if (METHOD_REPORT.equals(method)) {
            doReport(req, resp);
        } else {
            super.service(req, resp);
        }
    } catch (Throwable e) {
        LOGGER.error("Unexpected throwable", e);
    }
}

From source file:com.alfaariss.oa.profile.saml2.profile.artifactresolution.ArtifactResolutionService.java

/**
 * @see ISAML2Profile#process(javax.servlet.http.HttpServletRequest, 
 *  javax.servlet.http.HttpServletResponse)
 *//*from  w ww .  j  a  v  a 2s . c  o m*/
public void process(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws OAException {
    SAMLMessageContext<SignableSAMLObject, SignableSAMLObject, SAMLObject> context = null;
    try {
        //Decode SOAP message
        AbstractDecodingFactory decFactory = AbstractDecodingFactory.createInstance(servletRequest,
                servletResponse, SAMLConstants.SAML2_SOAP11_BINDING_URI, null);

        SAMLMessageDecoder decoder = decFactory.getDecoder();
        context = decFactory.getContext();
        context.setLocalEntityId(_sEntityID);
        context.setLocalEntityMetadata(_entityDescriptor);

        //Decode request
        try {
            decoder.decode(context);
        } catch (SecurityException e) {
            _logger.debug("Could not decode inbound message due to security exception", e);
            throw new SAML2SecurityException(RequestorEvent.REQUEST_INVALID);
        }

        //verify saml message in request
        SignableSAMLObject requestMessage = context.getInboundSAMLMessage();

        if (_logger.isDebugEnabled()) {
            if (requestMessage != null)
                logXML(requestMessage);
        }

        //Validate requestor and signature
        validateRequest(context, SPSSODescriptor.DEFAULT_ELEMENT_NAME);

        _protocol.processProtocol(context);
        //DD TOKEN_DEREFERENCE events are used for artifact resolution
        _eventLogger.info(new RequestorEventLogItem(null, null, null,
                RequestorEvent.TOKEN_DEREFERENCE_SUCCESSFUL, null, servletRequest.getRemoteAddr(),
                context.getInboundMessageIssuer(), this, context.getOutboundSAMLMessageId()));

        sendResponse(context, servletRequest, servletResponse);
    } catch (StatusException e) //SAML processing error
    {
        _eventLogger.info(new RequestorEventLogItem(null, null, null, e.getEvent(), null,
                servletRequest.getRemoteAddr(), e.getRequestorID(), this, e.getMessage()));

        sendResponse(context, servletRequest, servletResponse);
    } catch (MessageDecodingException e) //SOAP binding processing error  
    {
        _logger.debug("SOAP decoding error", e);
        _eventLogger.info(new RequestorEventLogItem(null, null, null, RequestorEvent.REQUEST_INVALID, null,
                servletRequest.getRemoteAddr(), null, this, "SOAP Fault"));
        SOAP11Utils.sendSOAPFault(context, RequestorEvent.REQUEST_INVALID);
    } catch (SAML2SecurityException e)
    //The message does not meet the required security constraints
    {
        //DD Security error -> Return a "403 Forbidden" response [saml-bindings-2.0-os r370]
        _logger.debug("Security error", e);
        _eventLogger.info(new RequestorEventLogItem(null, null, null, e.getEvent(), null,
                servletRequest.getRemoteAddr(), null, this, "Security Fault"));
        try {
            if (!servletResponse.isCommitted())
                servletResponse.sendError(HttpServletResponse.SC_FORBIDDEN);
        } catch (IOException e1) {
            _logger.warn("Could not send response", e1);
        }
    } catch (OAException e) //Internal error
    {
        throw e;
    } catch (Exception e) {
        _logger.fatal("Could not process SAML request message", e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    }
}

From source file:net.bhira.sample.api.controller.EmployeeController.java

/**
 * Save the given instance of {@link net.bhira.sample.model.Employee}. It will create a new
 * instance of the employee does not exist, otherwise it will update the existing instance.
 * /*w ww . j  a  v  a 2 s . co m*/
 * @param request
 *            the http request containing JSON payload in its body.
 * @param response
 *            the http response to which the results will be written.
 * @return the error message, if save was not successful.
 */
@RequestMapping(value = "/employee", method = RequestMethod.POST)
@ResponseBody
public Callable<String> saveEmployee(HttpServletRequest request, HttpServletResponse response) {
    return new Callable<String>() {
        public String call() throws Exception {
            String body = "";
            try {
                LOG.debug("servicing POST employee");
                Gson gson = JsonUtil.createGson();
                Employee employee = gson.fromJson(request.getReader(), Employee.class);
                LOG.debug("POST employee received json = {}", gson.toJson(employee));
                employeeService.save(employee);
                HashMap<String, Long> map = new HashMap<String, Long>();
                map.put("id", employee.getId());
                body = gson.toJson(map);
                LOG.debug("POST employee/ successful with return ID = {}", employee.getId());
            } catch (Exception ex) {
                if (ex instanceof JsonSyntaxException) {
                    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                } else {
                    response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                }
                body = ex.getLocalizedMessage();
                LOG.warn("Error saving employee. {}", body);
                LOG.debug("Save error stacktrace: ", ex);
            }
            return body;
        }
    };
}

From source file:eu.dasish.annotation.backend.rest.DebugResource.java

/**
 * /* w w w .  j  av  a 2s.  c  o m*/
 * @param resource a type of resource (annotation, target, cached representation, principal, notebook).
 * @param oldExternalId the old external UUID of the resource.
 * @param newExternalId the new UUID of the resource
 * @return a message telling if the "newExternalIdentifier" has replaced the "oldExternalIdentifier" or not.
 * @throws IOException is sending an error fails.
 */
@PUT
@Produces(MediaType.TEXT_XML)
@Path("/resource/{resource}/{oldId: " + BackendConstants.regExpIdentifier + "}/newid/{newId:"
        + BackendConstants.regExpIdentifier + "}")
public String updateResourceIdentifier(@PathParam("resource") String resource,
        @PathParam("oldId") String oldExternalId, @PathParam("newId") String newExternalId) throws IOException {
    Number remotePrincipalID = this.getPrincipalID();
    if (remotePrincipalID == null) {
        return "null inlogged principal";
    }
    String typeOfAccount = dbDispatcher.getTypeOfPrincipalAccount(remotePrincipalID);
    if (typeOfAccount.equals(admin)) {
        try {
            final boolean update = dbDispatcher.updateResourceIdentifier(Resource.valueOf(resource),
                    UUID.fromString(oldExternalId), UUID.fromString(newExternalId));
            return (update ? "The identifier is updated" : "The account is not updated, see the log.");
        } catch (NotInDataBaseException e) {
            httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
            return e.toString();
        }
    } else {
        this.ADMIN_RIGHTS_EXPECTED();
        httpServletResponse.sendError(HttpServletResponse.SC_FORBIDDEN);
        return "Dooooeeeii!!";
    }

}