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:net.sourceforge.vulcan.web.ProjectFileServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    final String pathInfo = request.getPathInfo();

    if (isBlank(pathInfo)) {
        response.sendRedirect(request.getContextPath());
        return;//  w  w w  .j a va  2 s  .  co  m
    }

    final PathInfo projPathInfo = getProjectNameAndBuildNumber(pathInfo);

    if (isBlank(projPathInfo.projectName)) {
        response.sendRedirect(request.getContextPath());
        return;
    }

    final ProjectConfigDto projectConfig;

    try {
        projectConfig = projectManager.getProjectConfig(projPathInfo.projectName);
    } catch (NoSuchProjectException e) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    final String requestURI = request.getRequestURI();

    if (projPathInfo.buildNumber < 0) {
        redirectWithBuildNumber(response, projPathInfo, requestURI);
        return;
    }

    final ProjectStatusDto buildOutcome = buildManager.getStatusByBuildNumber(projPathInfo.projectName,
            projPathInfo.buildNumber);

    if (buildOutcome == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND,
                "No such build " + projPathInfo.buildNumber + " for project Project.");
        return;
    }

    final String workDir;

    if (StringUtils.isNotBlank(buildOutcome.getWorkDir())) {
        workDir = buildOutcome.getWorkDir();
    } else {
        workDir = projectConfig.getWorkDir();
    }

    final File file = getFile(workDir, pathInfo, true);

    if (!file.exists()) {
        if (shouldFallback(request, workDir, file)) {
            response.sendRedirect(getFallbackParentPath(request, workDir));
            return;
        }
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    } else if (!file.canRead()) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    } else if (file.isDirectory()) {
        if (!pathInfo.endsWith("/")) {
            response.sendRedirect(requestURI + "/");
            return;
        }

        final File[] files = getDirectoryListing(file);

        request.setAttribute(Keys.DIR_PATH, pathInfo);
        request.setAttribute(Keys.FILE_LIST, files);

        request.getRequestDispatcher(Keys.FILE_LIST_VIEW).forward(request, response);
        return;
    }

    setContentType(request, response, pathInfo);

    final Date lastModifiedDate = new Date(file.lastModified());

    if (!checkModifiedSinceHeader(request, lastModifiedDate)) {
        response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    response.setStatus(HttpServletResponse.SC_OK);

    setLastModifiedDate(response, lastModifiedDate);

    response.setContentLength((int) file.length());

    final FileInputStream fis = new FileInputStream(file);
    final ServletOutputStream os = response.getOutputStream();

    sendFile(fis, os);
}

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

/**
 * Fetch all the employees for the given department ID. It will return a light weight version of
 * {@link net.bhira.sample.model.Employee} model without the address and contactInfo objects.
 * //w  w  w  .  jav a  2 s.  c o  m
 * @param departmentId
 *            the ID for {@link net.bhira.sample.model.Department}.
 * @param response
 *            the http response to which the results will be written.
 * @return an array of {@link net.bhira.sample.model.Employee} instances as JSON.
 */
@RequestMapping(value = "/employee/department/{departmentId}", method = RequestMethod.GET)
@ResponseBody
public Callable<String> getEmployeesByDepartment(@PathVariable long departmentId,
        HttpServletResponse response) {
    return new Callable<String>() {
        public String call() throws Exception {
            String body = "";
            try {
                LOG.debug("servicing GET employee/department/{}", departmentId);
                List<Employee> list = employeeService.loadByDepartment(departmentId);
                int count = (list == null) ? 0 : list.size();
                LOG.debug("GET employee/department/{} count = {}", departmentId, count);
                body = JsonUtil.createGson().toJson(list);
            } catch (Exception ex) {
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                body = ex.getLocalizedMessage();
                LOG.warn("Error loading employee/department/{}. {}", departmentId, body);
                LOG.debug("Load error stacktrace: ", ex);
            }
            return body;
        }
    };
}

From source file:org.basinmc.irc.bridge.github.GitHubServerHandler.java

/**
 * {@inheritDoc}/*w w w  . ja  v  a 2s  .  c  om*/
 */
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    // only handle requests to /
    if (!target.equals("/webhook")) {
        return;
    }

    // verify whether the call comes directly from GitHub using the X-GitHub-Event,
    // X-Hub-Signature and X-GitHub-Delivery headers
    String eventType = request.getHeader("X-GitHub-Event");
    String signature = request.getHeader("X-Hub-Signature");
    String deliveryId = request.getHeader("X-GitHub-Delivery");

    if (eventType == null || eventType.isEmpty()
            || (this.secret != null && (signature == null || signature.isEmpty())) || deliveryId == null
            || deliveryId.isEmpty()) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        baseRequest.setHandled(true);
        return;
    }

    if (signature != null) {
        // strip sha1=
        // TODO: Decide upon signature method based on this parameter
        signature = signature.substring(5);
    }

    logger.info("Processing GitHub request " + deliveryId + ".");

    // decode the data passed in the request body
    String data;
    try (InputStream inputStream = request.getInputStream()) {
        data = new String(ByteStreams.toByteArray(inputStream),
                Charset.forName(request.getCharacterEncoding()));
    }

    // verify the signature supplied to us (as long as a secret key was configured)
    try {
        if (!verifySignature(data, signature)) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            baseRequest.setHandled(true);
            return;
        }
    } catch (IllegalStateException ex) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        baseRequest.setHandled(true);
        return;
    }

    // find correct event message
    eventType = eventType.replace('_', '.');

    // de-serialize and handle event data
    Map<String, Object> context = new HashMap<>();
    context.put("color", COLOR_MAP);
    context.put("event", reader.readValue(data));

    String message = this.getMessage(eventType, context);

    if (message != null) {
        this.bridge.sendMessage(message);
    }

    // answer with 204 at all times
    response.setStatus(HttpServletResponse.SC_NO_CONTENT);
    baseRequest.setHandled(true);
}

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

/**
 * Fetch the instance of {@link net.bhira.sample.model.Department} represented by given
 * departmentId and return it as JSON object.
 * /* www .ja v  a 2s  .  c  o  m*/
 * @param departmentId
 *            the ID for {@link net.bhira.sample.model.Department}.
 * @param response
 *            the http response to which the results will be written.
 * @return an instance of {@link net.bhira.sample.model.Department} as JSON.
 */
@RequestMapping(value = "/department/{departmentId}", method = RequestMethod.GET)
@ResponseBody
public Callable<String> getDepartment(@PathVariable long departmentId, HttpServletResponse response) {
    return new Callable<String>() {
        public String call() throws Exception {
            String body = "";
            try {
                LOG.debug("servicing GET department/{}", departmentId);
                Department department = departmentService.load(departmentId);
                LOG.debug("GET department/{}, found = {}", departmentId, department != null);
                if (department == null) {
                    response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                } else {
                    body = JsonUtil.createGson().toJson(department);
                }
            } catch (Exception ex) {
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                body = ex.getLocalizedMessage();
                LOG.warn("Error loading department/{}. {}", departmentId, body);
                LOG.debug("Load error stacktrace: ", ex);
            }
            return body;
        }
    };
}

From source file:com.tdclighthouse.prototype.components.json.ValueListAjax.java

protected JSON getValueListAsJson(HstRequest request, HstResponse response, String path,
        BlackListChecker blackListChecker) {
    try {/*from w w  w. j  a v a2  s . c  o  m*/
        JSONObject json = new JSONObject();
        Object object = request.getRequestContext().getObjectBeanManager().getObject(path);
        if (object instanceof ValueList) {
            ValueList bean = (ValueList) object;
            if (!blackListChecker.isBlackListed(bean)) {
                List<ValueListItem> listItem = bean.getItems();
                for (ValueListItem listItemBean : listItem) {
                    json.put(listItemBean.getKey(), listItemBean.getLabel());
                }
            } else {
                setErrorMessage(json, "Forbidden");
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            }
        } else {
            setErrorMessage(json, "Not Found");
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        }
        return json;
    } catch (ObjectBeanManagerException e) {
        throw new HstComponentException(e);
    }
}

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

/**
 * /*from  w  w  w.j  a  v  a2  s  .c  o  m*/
 * @param externalIdentifier the UUID of an annotation.
 * @return the xml-element representing the annotation with "externalIdentifier" built up 
 * from the "annotation" table and the corresponding junction tables. 
 * @throws IOException if sending an error fails.
 */
@GET
@Produces(MediaType.TEXT_XML)
@Path("{annotationid: " + BackendConstants.regExpIdentifier + "}")
@Transactional(readOnly = true)
public JAXBElement<Annotation> getAnnotation(@PathParam("annotationid") String externalIdentifier)
        throws IOException {
    Map params = new HashMap();
    try {
        Annotation result = (Annotation) (new RequestWrappers(this)).wrapRequestResource(params,
                new GetAnnotation(), Resource.ANNOTATION, Access.READ, externalIdentifier);
        if (result != null) {
            return (new ObjectFactory()).createAnnotation(result);
        } else {
            return (new ObjectFactory()).createAnnotation(new Annotation());
        }
    } catch (NotInDataBaseException e1) {
        httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND, e1.getMessage());
        return (new ObjectFactory()).createAnnotation(new Annotation());
    } catch (ForbiddenException e2) {
        httpServletResponse.sendError(HttpServletResponse.SC_FORBIDDEN, e2.getMessage());
        return (new ObjectFactory()).createAnnotation(new Annotation());
    }
}

From source file:com.imaginary.home.cloud.api.call.LocationCall.java

@Override
public void post(@Nonnull String requestId, @Nullable String userId, @Nonnull String[] path,
        @Nonnull HttpServletRequest req, @Nonnull HttpServletResponse resp,
        @Nonnull Map<String, Object> headers, @Nonnull Map<String, Object> parameters)
        throws RestException, IOException {
    try {/* w w w.j  av a2  s.  c o m*/
        if (userId == null) {
            throw new RestException(HttpServletResponse.SC_FORBIDDEN, RestException.RELAY_NOT_ALLOWED,
                    "A relay cannot add locations");
        }
        User user = User.getUserByUserId(userId);

        if (user == null) {
            throw new RestException(HttpServletResponse.SC_FORBIDDEN, RestException.NO_SUCH_USER,
                    "An error occurred identifying the user record for this key");
        }

        BufferedReader reader = new BufferedReader(new InputStreamReader(req.getInputStream()));
        StringBuilder source = new StringBuilder();
        String line;

        while ((line = reader.readLine()) != null) {
            source.append(line);
            source.append(" ");
        }
        String name = null, description = null, tz = null;
        JSONObject object = new JSONObject(source.toString());

        if (object.has("name") && !object.isNull("name")) {
            name = object.getString("name");
        }
        if (object.has("description") && !object.isNull("description")) {
            description = object.getString("description");
        }
        if (object.has("timeZone") && !object.isNull("timeZone")) {
            tz = object.getString("timeZone");
        }
        if (name == null || description == null) {
            throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.MISSING_DATA,
                    "Required fields: name, description");
        }

        TimeZone timeZone = (tz == null ? TimeZone.getTimeZone("UTC") : TimeZone.getTimeZone(tz));
        Location location = Location.create(userId, name, description, timeZone);

        user.grant(location);

        resp.setStatus(HttpServletResponse.SC_CREATED);
        resp.getWriter().println((new JSONObject(toJSON(location))).toString());
        resp.getWriter().flush();
    } catch (JSONException e) {
        throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_JSON,
                "Invalid JSON in request");
    } catch (PersistenceException e) {
        throw new RestException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, RestException.INTERNAL_ERROR,
                e.getMessage());
    }
}

From source file:org.abstracthorizon.proximity.webapp.controllers.RepositoryController.java

/**
 * Repository list./*from www  .ja va2  s .  com*/
 * 
 * @param request the request
 * @param response the response
 * 
 * @return the model and view
 * 
 * @throws Exception the exception
 */
public ModelAndView repositoryList(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String requestURI = request.getRequestURI()
            .substring(request.getContextPath().length() + request.getServletPath().length());
    if (requestURI.length() == 0) {
        requestURI = "/";
    }
    logger.debug("Got repository request on URI " + requestURI);
    String orderBy = request.getParameter("orderBy") == null ? "name" : request.getParameter("orderBy");
    String targetRepository = request.getParameter("repositoryId");
    String targetGroup = request.getParameter("repositoryGroupId");

    Item item = null;
    ProximityRequest pRequest = new ProximityRequest();
    pRequest.setPath(requestURI);
    pRequest.setTargetedReposId(targetRepository);
    pRequest.setTargetedReposGroupId(targetGroup);
    pRequest.setGrantee(null);
    pRequest.getAttributes().put(ProximityRequest.REQUEST_REMOTE_ADDRESS, request.getRemoteAddr());

    // issue #42, collect header information
    Enumeration headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String headerName = (String) headerNames.nextElement();
        pRequest.getAttributes().put("http." + headerName.toLowerCase(), request.getHeader(headerName));
    }

    try {
        logger.debug("Got request for " + targetRepository + " repository on URI: " + requestURI);
        item = proximity.retrieveItem(pRequest);
        logger.debug("Got response " + item.getProperties().getPath());

        if (item.getProperties().isDirectory()) {
            List items = null;
            items = proximity.listItems(pRequest);
            PropertyComparator.sort(items, new MutableSortDefinition(orderBy, true, true));
            Map result = new HashMap();
            result.put("items", items);
            result.put("orderBy", orderBy);
            result.put("requestUri", requestURI);
            result.put("requestPathList", explodeUriToList(requestURI));
            return new ModelAndView("repository/repositoryList", result);
        } else {
            // TODO: check for If-Modified-Since?
            // response.setContentType("application/octet-stream");
            response.setContentType(
                    getWebApplicationContext().getServletContext().getMimeType(item.getProperties().getName()));
            response.setContentLength((int) item.getProperties().getSize());
            response.setDateHeader("Last-Modified", item.getProperties().getLastModified().getTime());
            InputStream is = item.getStream();
            OutputStream os = response.getOutputStream();
            IOUtils.copy(is, os);
            is.close();
            return null;
        }
    } catch (ItemNotFoundException ex) {
        logger.info("Item not found on URI " + requestURI);
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return null;
    } catch (AccessDeniedException ex) {
        logger.info("Access forbidden to " + requestURI + " for " + request.getRemoteAddr(), ex);
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return null;
    }
}

From source file:com.vmware.identity.samlservice.LogoutState.java

/**
 * Construct logout state object//from   w  w  w .  ja v  a 2 s .c o m
 *
 * @param request
 * @param response2
 * @param sessionManager
 * @param locale
 */
public LogoutState(HttpServletRequest request, HttpServletResponse response, SessionManager sessionManager,
        Locale locale, MessageSource messageSource) {
    log.debug("Constructing from request " + request.toString());

    Validate.notNull(request);
    Validate.notNull(sessionManager);
    this.processingState = ProcessingState.UNKNOWN;
    this.setRequest(request);
    this.setResponse(response);
    this.setLocale(locale);
    this.setMessageSource(messageSource);
    this.sessionManager = sessionManager;
    //TODO - check for correlation id in the headers PR1561606
    this.correlationId = UUID.randomUUID().toString();
    this.factory = new DefaultIdmAccessorFactory(this.correlationId);
    Validate.notNull(factory);
    this.idmAccessor = factory.getIdmAccessor();
    this.validator = new LogoutStateValidator();
    RequestCacheFactory requestFactory = new DefaultRequestCacheFactory();
    this.requestCache = requestFactory.getRequestCache();

    this.relayState = request.getParameter(Shared.RELAY_STATE_PARAMETER);
    this.signature = request.getParameter(Shared.SIGNATURE_PARAMETER);
    this.sigAlg = request.getParameter(Shared.SIGNATURE_ALGORITHM_PARAMETER);
    this.samlRequest = request.getParameter(Shared.SAML_REQUEST_PARAMETER);
    this.samlResponse = request.getParameter(Shared.SAML_RESPONSE_PARAMETER);
    this.validationResult = new ValidationResult(HttpServletResponse.SC_FORBIDDEN, "Forbidden", null);
    Validate.isTrue(this.samlRequest != null || this.samlResponse != null);

    // construct message that was supposed to be signed
    if (this.signature != null && this.sigAlg != null) {
        try {
            if (this.samlRequest != null) {
                this.signedMessage = Shared.SAML_REQUEST_PARAMETER + "="
                        + URLEncoder.encode(this.samlRequest, "UTF-8");
            } else if (this.samlResponse != null) {
                this.signedMessage = Shared.SAML_RESPONSE_PARAMETER + "="
                        + URLEncoder.encode(this.samlResponse, "UTF-8");
            }
            if (this.relayState != null) {
                this.signedMessage = this.signedMessage + "&" + Shared.RELAY_STATE_PARAMETER + "="
                        + URLEncoder.encode(this.relayState, "UTF-8");
                // print out decoded relay state. Note that we do not need
                // to
                // store decoded value.
                byte[] relayStateBytes = Base64.decode(this.relayState);
                log.debug("Relay state specified was " + new String(relayStateBytes));
            }
            this.signedMessage = this.signedMessage + "&" + Shared.SIGNATURE_ALGORITHM_PARAMETER + "="
                    + URLEncoder.encode(this.sigAlg, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            log.debug("Could not reconstruct signed message");
            this.signedMessage = null;
        }
    }

    this.processingState = ProcessingState.INITIALIZED;
}