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:jp.or.openid.eiwg.scim.servlet.Users.java

/**
 * ?/*from   www.j  a v a 2  s. co m*/
 * (PATCH ?????? HttpServlet.service() ?)
 *
 * @param request 
 * @param response ?
 * @throws ServletException
 * @throws IOException
 */
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String method = request.getMethod();
    if (method.equals("GET")) {
        doGet(request, response);
    } else if (method.equals("POST")) {
        doPost(request, response);
    } else if (method.equals("PUT")) {
        doPut(request, response);
    } else if (method.equals("PATCH")) {
        doPatch(request, response);
    } else if (method.equals("DELETE")) {
        doDelete(request, response);
    } else {
        this.errorResponse(response, HttpServletResponse.SC_FORBIDDEN, null,
                MessageConstants.ERROR_NOT_SUPPORT_OPERATION);
    }
}

From source file:org.dspace.webmvc.controller.ResourceController.java

protected LookupResult lookupNoCache(HttpServletRequest req) {
    final String path = getPath(req);
    if (isForbidden(path)) {
        return new Error(HttpServletResponse.SC_FORBIDDEN, "Forbidden");
    }/*from   w ww  .  j  a v  a2s .  c  o  m*/

    final URL url;
    try {
        url = req.getSession().getServletContext().getResource(path);
    } catch (MalformedURLException e) {
        return new Error(HttpServletResponse.SC_BAD_REQUEST, "Malformed path");
    }

    final String mimeType = getMimeType(req, path);

    final String realpath = req.getSession().getServletContext().getRealPath(path);
    if (url != null && realpath != null) {
        // Try as an ordinary file
        File f = new File(realpath);
        if (!f.isFile()) {
            return new Error(HttpServletResponse.SC_FORBIDDEN, "Forbidden");
        } else {
            return new StaticFile(f.lastModified(), mimeType, (int) f.length(), acceptsDeflate(req), url);
        }
    } else {
        ClassPathResource cpr = new ClassPathResource(path);
        if (cpr.exists()) {
            URL cprURL = null;
            try {
                cprURL = cpr.getURL();

                // Try as a JAR Entry
                final ZipEntry ze = ((JarURLConnection) cprURL.openConnection()).getJarEntry();
                if (ze != null) {
                    if (ze.isDirectory()) {
                        return new Error(HttpServletResponse.SC_FORBIDDEN, "Forbidden");
                    } else {
                        return new StaticFile(ze.getTime(), mimeType, (int) ze.getSize(), acceptsDeflate(req),
                                cprURL);
                    }
                } else {
                    // Unexpected?
                    return new StaticFile(-1, mimeType, -1, acceptsDeflate(req), cprURL);
                }
            } catch (ClassCastException e) {
                // Unknown resource type
                if (url != null) {
                    return new StaticFile(-1, mimeType, -1, acceptsDeflate(req), cprURL);
                } else {
                    return new Error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error");
                }
            } catch (IOException e) {
                return new Error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error");
            }
        } else {
            return new Error(HttpServletResponse.SC_NOT_FOUND, "Not found");
        }
    }
}

From source file:org.craftercms.security.authorization.impl.AccessDeniedHandlerImplTest.java

@Test
public void testSendError() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    MockHttpServletResponse response = new MockHttpServletResponse();
    RequestContext context = new RequestContext(request, response);

    handler.handle(context, new AccessDeniedException(""));

    assertEquals(HttpServletResponse.SC_FORBIDDEN, response.getStatus());
    assertTrue(response.isCommitted());/* ww w  . j  a v a2s. c om*/
}

From source file:com.controller.schedule.ScheduleSocialPostServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from w w w  .j a v  a  2 s. c  o m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    response.setContentType("application/json");
    HttpSession session = request.getSession();
    if (session.getAttribute("UID") == null) {
        Map<String, Object> error = new HashMap<>();
        error.put("error", "User is not logged in");
        response.getWriter().write(AppConstants.GSON.toJson(error));
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        response.getWriter().flush();
        response.setContentType("application/json");
        return;
    }
    Integer userId = Integer.parseInt(session.getAttribute("UID").toString());
    List<Map<String, Object>> requestBodyList = AppConstants.GSON
            .fromJson(new BufferedReader(request.getReader()), List.class);
    if (requestBodyList == null || requestBodyList.isEmpty()) {
        Map<String, Object> error = new HashMap<>();
        error.put("error", "Request body is missing");
        response.getWriter().write(AppConstants.GSON.toJson(error));
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        response.getWriter().flush();
        return;
    }
    System.out.println(requestBodyList);
    List<String> errorMessages = validateRequestBodyList(requestBodyList);
    if (!errorMessages.isEmpty()) {
        Map<String, Object> error = new HashMap<>();
        error.put("error", errorMessages);
        response.getWriter().write(AppConstants.GSON.toJson(error));
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        response.getWriter().flush();
        return;
    }

    /*
     If no error messages in the above validation, then next is to validate
     the JSON structure associated with the keys token_data and metadata
     */
    for (Map<String, Object> requestBodyMap : requestBodyList) {
        String tokenDataString = requestBodyMap.get("token_data").toString();
        String type = requestBodyMap.get("type").toString();
        errorMessages.addAll(validateTokenData(tokenDataString, type));
        String metadataString = requestBodyMap.get("metadata").toString();
        errorMessages.addAll(validateMetadata(metadataString, type));
    }

    if (!errorMessages.isEmpty()) {
        Map<String, Object> error = new HashMap<>();
        error.put("error", errorMessages);
        response.getWriter().write(AppConstants.GSON.toJson(error));
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        response.getWriter().flush();
        return;
    }
    List<Map<String, Integer>> daoResponseList = new ArrayList<>();
    try (Connection conn = ConnectionManager.getInstance().getConnection()) {
        conn.setAutoCommit(false);
        try {
            for (Map<String, Object> requestBodyMap : requestBodyList) {
                Double schedule = (Double) requestBodyMap.get("schedule_time");

                Timestamp scheduleTimeStamp = new Timestamp(schedule.longValue());
                String tokenDataString = requestBodyMap.get("token_data").toString();
                String metadataString = requestBodyMap.get("metadata").toString();

                //As of now schedule description is not yet mandatory.
                String scheduleDesc = requestBodyMap.containsKey("schedule_desc")
                        ? String.valueOf(requestBodyMap.get("schedule_desc"))
                        : null;

                Map<String, Integer> daoResponse = ScheduleSocialPostDAO.addToScheduleSocialPost(userId,
                        requestBodyMap.get("image_name").toString(),
                        AppConstants.GSON.fromJson(tokenDataString, Map.class),
                        AppConstants.GSON.fromJson(metadataString, Map.class),
                        requestBodyMap.get("type").toString(), requestBodyMap.get("schedule_title").toString(),
                        scheduleDesc, scheduleTimeStamp, TemplateStatus.template_saved.toString(), conn);
                daoResponseList.add(daoResponse);
            }
            conn.commit();
        } catch (SQLException ex) {
            conn.rollback();
            throw ex;
        }
        response.setStatus(HttpServletResponse.SC_OK);
        response.getWriter().write(AppConstants.GSON.toJson(daoResponseList));
        response.getWriter().flush();

    } catch (SQLException ex) {
        Logger.getLogger(ScheduleSocialPostServlet.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:net.incrementalism.tooter.ProfileServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    User currentUser = getCurrentUser(request);
    if (currentUser == null) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;//from   w w w.  j  a v  a 2 s . co m
    }
    displayProfile(currentUser, request, response);
}

From source file:com.haulmont.cuba.core.controllers.LogDownloadController.java

@RequestMapping(value = "/log/{file:[a-zA-Z0-9\\.\\-_]+}", method = RequestMethod.GET)
public void getLogFile(HttpServletResponse response, @RequestParam(value = "s") String sessionId,
        @RequestParam(value = "full", required = false) Boolean downloadFull,
        @PathVariable(value = "file") String logFileName) throws IOException {
    UserSession userSession = getSession(sessionId, response);
    if (userSession == null)
        return;//ww  w.  j  a  v  a2s. co m

    if (!userSession.isSpecificPermitted("cuba.gui.administration.downloadlogs")) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    // security check, handle only valid file name
    String filename = FilenameUtils.getName(logFileName);

    try {
        File logFile = logControl.getLogFile(filename);

        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setHeader("Content-Type", "application/zip");
        response.setHeader("Pragma", "no-cache");

        response.setHeader("Content-Disposition", "attachment; filename=" + filename);

        OutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();

            if (BooleanUtils.isTrue(downloadFull)) {
                LogArchiver.writeArchivedLogToStream(logFile, outputStream);
            } else {
                LogArchiver.writeArchivedLogTailToStream(logFile, outputStream);
            }
        } catch (RuntimeException | IOException ex) {
            log.error("Unable to download file", ex);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } finally {
            IOUtils.closeQuietly(outputStream);
        }

    } catch (LogFileNotFoundException e) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
    }
}

From source file:com.haulmont.cuba.web.sys.CubaWebJarsHandler.java

@Override
public boolean handleRequest(VaadinSession session, VaadinRequest request, VaadinResponse response)
        throws IOException {
    String path = request.getPathInfo();

    if (StringUtils.isEmpty(path) || StringUtils.isNotEmpty(path) && !path.startsWith(VAADIN_WEBJARS_PREFIX)) {
        return false;
    }//  w  ww  .j a  v a 2  s.  c  o  m

    log.trace("WebJar resource requested: {}", path.replace(VAADIN_WEBJARS_PREFIX, ""));

    String errorMessage = checkResourcePath(path);
    if (StringUtils.isNotEmpty(errorMessage)) {
        log.warn(errorMessage);
        response.sendError(HttpServletResponse.SC_FORBIDDEN, errorMessage);
        return false;
    }

    URL resourceUrl = getStaticResourceUrl(path);

    if (resourceUrl == null) {
        resourceUrl = getClassPathResourceUrl(path);
    }

    if (resourceUrl == null) {
        String msg = String.format("Requested WebJar resource is not found: %s", path);
        response.sendError(HttpServletResponse.SC_NOT_FOUND, msg);
        log.warn(msg);
        return false;
    }

    String resourceName = getResourceName(path);
    String mimeType = servletContext.getMimeType(resourceName);
    response.setContentType(mimeType != null ? mimeType : FileTypesHelper.DEFAULT_MIME_TYPE);

    String cacheControl = "public, max-age=0, must-revalidate";
    int resourceCacheTime = getCacheTime(resourceName);
    if (resourceCacheTime > 0) {
        cacheControl = "max-age=" + String.valueOf(resourceCacheTime);
    }
    response.setHeader("Cache-Control", cacheControl);
    response.setDateHeader("Expires", System.currentTimeMillis() + (resourceCacheTime * 1000));

    InputStream inputStream = null;
    try {
        URLConnection connection = resourceUrl.openConnection();
        long lastModifiedTime = connection.getLastModified();
        // Remove milliseconds to avoid comparison problems (milliseconds
        // are not returned by the browser in the "If-Modified-Since"
        // header).
        lastModifiedTime = lastModifiedTime - lastModifiedTime % 1000;
        response.setDateHeader("Last-Modified", lastModifiedTime);

        if (browserHasNewestVersion(request, lastModifiedTime)) {
            response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
            return true;
        }

        inputStream = connection.getInputStream();

        copy(inputStream, response.getOutputStream());

        return true;
    } finally {
        if (inputStream != null) {
            inputStream.close();
        }
    }
}

From source file:fr.epsi.controllers.rest.LoginController.java

/**
 * Methode qui deconnecte un utilisateur
 * @param guid le guid de l'utilisateur connecte
 *///from  www  .ja va2 s  .  c  om
@RequestMapping(value = "/disconnect", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody void disconnect(@RequestParam("token") String token, HttpServletResponse resp) {

    try {
        // On recupre l'instance et on la supprime
        Users userModel = Users.getInstance();
        User user = userModel.findByGUID(token);

        if (user != null) {
            user.clearGUID();

            resp.setStatus(HttpServletResponse.SC_OK);
        } else {
            resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
        }
    } catch (Exception e) {
        resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:io.lavagna.web.security.CSFRFilter.java

private static ImmutablePair<Boolean, ImmutablePair<Integer, String>> checkCSRF(HttpServletRequest request)
        throws IOException {
    String expectedToken = (String) request.getSession().getAttribute(CSRFToken.CSRF_TOKEN);
    String token = request.getHeader(CSRF_TOKEN_HEADER);
    if (token == null) {
        token = request.getParameter(CSRF_FORM_PARAMETER);
    }/*from w  w  w  . j  av a2  s. c  o  m*/

    if (token == null) {
        return of(false, of(HttpServletResponse.SC_FORBIDDEN, "missing token in header or parameter"));
    }
    if (expectedToken == null) {
        return of(false, of(HttpServletResponse.SC_FORBIDDEN, "missing token from session"));
    }
    if (!safeArrayEquals(token.getBytes("UTF-8"), expectedToken.getBytes("UTF-8"))) {
        return of(false, of(HttpServletResponse.SC_FORBIDDEN, "token is not equal to expected"));
    }

    return of(true, null);
}