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:com.sdapp.server.LoginServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    SdLogger.getInstance().getLogger().info("Post on LoginServlet");

    /**/*from w w w . j  ava2 s .  com*/
     * Get the parameters
     */
    String username = request.getParameter("username");
    String isDeviceString = request.getParameter("isDevice");
    boolean isDevice = false;

    if (isDeviceString != null && isDeviceString.length() > 0)
        isDevice = Boolean.parseBoolean(isDeviceString);

    UserMsg user = null;
    /**
     * Sanity check
     */
    if ((username != null) && (username.length() > 0) && (true == username.contains("@"))) {
        /**
         * See if the user object exists
         */
        user = DAO.getUser(username, true);
    }

    /** Login failed */
    if (null == user) {
        /** If login failed on device, return a 403 */
        if (isDevice) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            return;
        } else {
            /** Create the response */
            response.setStatus(HttpServletResponse.SC_OK);
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            String title = "Login Failure";
            out.println(ServletUtilities.headWithTitle(title) + "<BODY BGCOLOR=\"#FDF5E6\">\n"
                    + "<H1 ALIGN=CENTER>" + title + "</H1>\n" + "<TABLE BORDER=1 ALIGN=CENTER>\n");
            /** End table */
            out.println("</TABLE>\n</BODY></HTML>");
        }
    }
    /** Login successful */
    else {
        /** Login successful */
        response.setStatus(HttpServletResponse.SC_OK);

        /** JSON response or html*/
        if (createJSONRespone) {
            /**
             * TODO: Sid fix this.
             * Cant figure out how to deserialize JSON objects on client.
             * It keeps crashing. So extracting String and passing String object.
             */
            String licensePlateString = "";
            for (LicensePlateMsg msg : user.getLicensePlateList()) {
                licensePlateString += ";" + msg.getLicensePlateNumber();
            }
            LicensePlateJsonObject msg = new LicensePlateJsonObject();
            msg.setLicensePlateList(licensePlateString);
            /** JSONify the object and bundle it with the response*/
            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(msg);
            response.setContentType("application/json");
            PrintWriter out = response.getWriter();
            out.write(json);
            out.close();
        } else {
            createHTMLSuccessResponse(response, user);
        }
    }
}

From source file:com.telefonica.euro_iaas.paasmanager.rest.auth.RestAuthenticationEntryPoint.java

/**
 * (non-Javadoc)./*from   ww w .j  a  va 2 s  .c o m*/
 * 
 * @see org.springframework.security.web.AuthenticationEntryPoint#commence(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse,
 *      org.springframework.security.core.AuthenticationException)
 */
public final void commence(final HttpServletRequest request, final HttpServletResponse response,
        final AuthenticationException authException) throws IOException, ServletException {

    // if (authException instanceof AuthenticationServiceException) {
    // LOG.error(authException);
    // response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
    // authException.getMessage());
    // }

    if (authException instanceof InsufficientAuthenticationException) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN, "Forbidden");
    } else {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
    }
}

From source file:it.marcoberri.mbmeteo.action.UploadFile.java

/**
 * Handles the HTTP/*from   w ww .  j a  v a2 s  .c  o m*/
 * <code>GET</code> method.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.sendError(HttpServletResponse.SC_FORBIDDEN);
}

From source file:fr.aliasource.webmail.server.invitation.GoingInvitationProxyImpl.java

@SuppressWarnings("unchecked")
@Override//w  w w.  j  a  va 2s .c  o m
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    IAccount ac = (IAccount) req.getSession().getAttribute("account");

    if (ac == null) {
        GWT.log("Account not found in session", null);
        resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    PostMethod pm = new PostMethod(backendUrl);
    if (req.getQueryString() != null) {
        pm.setQueryString(req.getQueryString());
    }
    Map<String, String[]> params = req.getParameterMap();
    for (String p : params.keySet()) {
        String[] val = params.get(p);
        pm.setParameter(p, val[0]);
    }

    synchronized (hc) {
        try {
            int ret = hc.executeMethod(pm);
            if (ret != HttpStatus.SC_OK) {
                log("method failed:\n" + pm.getStatusLine() + "\n" + pm.getResponseBodyAsString());
                resp.setStatus(ret);
            } else {
                InputStream is = pm.getResponseBodyAsStream();
                transfer(is, resp.getOutputStream(), false);
            }
        } catch (Exception e) {
            log("error occured on call proxyfication", e);
        } finally {
            pm.releaseConnection();
        }
    }
}

From source file:com.ctc.storefront.util.CSRFHandlerInterceptor.java

@Override
public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response,
        final Object handler) throws Exception {

    if (shouldCheckCSRFTokenForRequest(request)) {
        // This is a POST request - need to check the CSRF token
        final String sessionToken = CSRFTokenManager.getTokenForSession(request.getSession());
        final String requestToken = CSRFTokenManager.getTokenFromRequest(request);
        if (sessionToken.equals(requestToken)) {
            return true;
        } else {/*from   ww  w.  ja v a 2  s  . co  m*/
            response.sendError(HttpServletResponse.SC_FORBIDDEN, "Bad or missing CSRF value");
            return false;
        }
    } else {
        // Not a POST - allow the request
        return true;
    }
}

From source file:com.thinkberg.moxo.dav.CopyMoveBase.java

public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    boolean overwrite = getOverwrite(request);
    FileObject object = getResourceManager().getFileObject(request.getPathInfo());
    FileObject targetObject = getDestination(request);

    try {//ww  w . j  a v a  2 s .  c o m
        // check that we can write the target
        LockManager.getInstance().checkCondition(targetObject, getIf(request));
        // if we move, check that we can actually write on the source
        if ("MOVE".equals(request.getMethod())) {
            LockManager.getInstance().checkCondition(object, getIf(request));
        }
    } catch (LockException e) {
        if (e.getLocks() != null) {
            response.sendError(SC_LOCKED);
        } else {
            response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        }
        return;
    }

    if (null == targetObject) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    if (object.equals(targetObject)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    if (targetObject.exists()) {
        if (!overwrite) {
            response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
            return;
        }
        response.setStatus(HttpServletResponse.SC_NO_CONTENT);
    } else {
        FileObject targetParent = targetObject.getParent();
        if (!targetParent.exists() || !FileType.FOLDER.equals(targetParent.getType())) {
            response.sendError(HttpServletResponse.SC_CONFLICT);
        }
        response.setStatus(HttpServletResponse.SC_CREATED);
    }

    copyOrMove(object, targetObject, getDepth(request));
}

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

/**
 * Methode pour les commandes//www. j  av  a2s  .c  o  m
 * @param reference la reference du produit
 * @param quantity la quantite voulue
 * @param guid l'identifiant de l'utilisateur
 * @return Un message selon le statut de la commande
 */
@RequestMapping(value = "/order", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody Product order(@RequestParam("reference") String reference,
        @RequestParam("quantity") int quantity, @RequestParam("token") String token, HttpServletResponse resp) {

    Users userModel = Users.getInstance(); //Recupere l'instance de user

    try {
        // Si on trouve un user correspondant au guid
        if (userModel.findByGUID(token) != null) {
            Products productModel = Products.getInstance();

            // On recupere le produit par reference
            Product product = productModel.findByRef(reference);

            if (product == null || quantity <= 0 || product.getQuantity() == 0
                    || product.getQuantity() < quantity) {
                resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            } else {
                //On decremente la quantite du produit
                product.setQuantity(product.getQuantity() - quantity);

                return new Product(product.getReference(), product.getName(), quantity);
            }
        } else {
            resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
        }
        return null;
    } catch (Exception e) {
        resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return null;
    }
}

From source file:jeeves.config.springutil.JeevesAccessDeniedHandler.java

@Override
public void handle(HttpServletRequest request, HttpServletResponse response,
        AccessDeniedException accessDeniedException) throws IOException, ServletException {
    if (!response.isCommitted()) {
        if (matcher != null && matcher.matches(request)) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN, accessDeniedException.getMessage());
        }/*from   w ww  .ja v a 2 s  .  co  m*/
        if (_errorPage != null) {
            request.setAttribute(WebAttributes.ACCESS_DENIED_403, accessDeniedException);
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            final String referer = _escaper.escape(request.getRequestURI());
            RequestDispatcher dispatcher = request.getRequestDispatcher(_errorPage + "?referer=" + referer);
            dispatcher.forward(request, response);
        } else {
            response.sendError(HttpServletResponse.SC_FORBIDDEN, accessDeniedException.getMessage());
        }
    }
}

From source file:fr.aliasource.webmail.server.export.ExportConversationImpl.java

/**
 * The actual business logic./*from  w  w w  .  ja  v a2  s  . co  m*/
 * 
 * @param requ
 *            the request object
 * @param resp
 *            the response object
 * @throws IOException
 * @throws ServletException
 */
public void service(HttpServletRequest req, HttpServletResponse response) throws IOException, ServletException {
    logger.info("Export conversation called.");

    IAccount account = (IAccount) req.getSession().getAttribute("account");

    if (account == null) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }
    String uri = req.getRequestURI();
    String convAndMessageIds = extractConversationIdFromRequestURI(uri);
    MessageId messageId = getMessageIdPart(convAndMessageIds);
    ConversationId conversationId = getConversationIdPart(convAndMessageIds);

    String folder = conversationId.getSourceFolder();

    logger.info("Conversation id: " + conversationId.getConversationId() + " folder: " + folder + " uri: " + uri
            + "Message id: " + messageId);

    Folder f = new Folder(folder, folder);
    ConversationReference cr = account.findConversation(conversationId);
    ClientMessage[] cm = null;
    if (messageId == null) {
        cm = account.fetchMessages(f, cr.getMessageIds());
    } else {
        cm = account.fetchMessages(f, Arrays.asList(messageId));
    }

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ConversationExporter exporter = new ConversationExporter(
            req.getContextPath() + "/minig/images/logo_print.jpg");
    try {
        if (req.getRequestURI().endsWith(".html")) {
            exporter.exportToHtml(account, cr, cm, baos);
            response.setContentType("text/html");
        } else {
            exporter.exportToPdf(account, cr, cm, baos);
            response.setContentType("application/pdf");
        }
    } catch (ConversationExporterException e) {
        logger.error("Cannot render conversation", e);
        throw new ServletException(e);
    }

    response.setHeader("Expires", "0");
    response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
    response.setHeader("Pragma", "public");

    response.setContentLength(baos.size());
    ServletOutputStream out = response.getOutputStream();
    baos.writeTo(out);
    out.flush();

}

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

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./* w w  w . jav  a 2  s . c om*/
 *
 * @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");
    try {
        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();
            return;
        }
        Integer userId = Integer.parseInt(session.getAttribute("UID").toString());
        List<String> errorMsgs = new ArrayList<>();

        if (StringUtils.isEmpty(request.getParameter("from"))) {
            errorMsgs.add("from date parameter is missing");
        }
        if (StringUtils.isEmpty(request.getParameter("to"))) {
            errorMsgs.add("to date parameter is missing");
        }

        if (!errorMsgs.isEmpty()) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            Map<String, Object> responseMap = new HashMap<>();
            responseMap.put("error", errorMsgs);
            response.getWriter().write(AppConstants.GSON.toJson(responseMap));
            response.getWriter().flush();
            return;
        }

        LocalDate fromDate = null;
        LocalDate toDate = null;
        //Dates have to follow the format: 2011-12-03
        try {
            fromDate = LocalDate.parse(request.getParameter("from"));
        } catch (DateTimeParseException ex) {
            errorMsgs.add("from parameter is not in the required yyyy-mm-dd format");
            logger.log(Level.SEVERE, "", ex);
        }

        try {
            toDate = LocalDate.parse(request.getParameter("to"));
        } catch (DateTimeParseException ex) {
            errorMsgs.add("to parameter is not in the required yyyy-mm-dd format");
            logger.log(Level.SEVERE, "", ex);
        }
        if (!errorMsgs.isEmpty()) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            Map<String, Object> responseMap = new HashMap<>();
            responseMap.put("error", errorMsgs);
            response.getWriter().write(AppConstants.GSON.toJson(responseMap));
            response.getWriter().flush();
            return;
        }

        JSONObject scheduledEntities = ScheduleDAO.getScheduledEntities(userId, fromDate, toDate);
        response.setStatus(HttpServletResponse.SC_OK);
        response.getWriter().write(AppConstants.GSON.toJson(scheduledEntities));
        response.getWriter().flush();
    } catch (SQLException ex) {
        Logger.getLogger(GetScheduledEntitiesServlet.class.getName()).log(Level.SEVERE, null, ex);
    }

}