Example usage for javax.servlet.http HttpServletResponse sendError

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

Introduction

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

Prototype

public void sendError(int sc) throws IOException;

Source Link

Document

Sends an error response to the client using the specified status code and clears the buffer.

Usage

From source file:org.codehaus.groovy.grails.plugins.springsecurity.IpAddressFilter.java

/**
 * {@inheritDoc}//  w  w w  . j a  v  a  2 s  . c  o  m
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse,
 *    javax.servlet.FilterChain)
 */
public void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain)
        throws IOException, ServletException {

    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;

    if (!isAllowed(request)) {
        // send 404 to hide the existence of the resource
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    chain.doFilter(request, response);
}

From source file:com.haulmont.cuba.restapi.RestFileDownloadController.java

private void error(HttpServletResponse response) throws IOException {
    if (!response.isCommitted())
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
}

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

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

    if (object.exists()) {
        if (FileType.FOLDER.equals(object.getType())) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            return;
        }//from w  w  w . j  av a2  s  .c om

        setHeader(response, object.getContent());

        InputStream is = object.getContent().getInputStream();
        OutputStream os = response.getOutputStream();
        Util.copyStream(is, os);
        is.close();
    } else {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    }
}

From source file:net.duckling.ddl.web.controller.BaseController.java

/**
 * ?404/*w w w .j  a  v  a2s .  c  om*/
 * @param request   HttpRequest
 * @param response   HttpResponse
 * @param inTeam   true??false???
 */
protected void notFound(HttpServletRequest request, HttpServletResponse response, boolean inTeam) {
    if (!inTeam) {
        request.setAttribute("accessMain", Boolean.TRUE);
    }
    try {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    } catch (IOException e) {
        LOGGER.debug("Error founded in not found :", e);
    }
}

From source file:com.enonic.cms.server.service.servlet.CmsDispatcherServlet.java

protected void doService(HttpServletRequest req, HttpServletResponse res) throws Exception {

    HttpMethod requestMethod = HttpMethod.valueOf(req.getMethod());

    if (!ALLOWED_HTTP_METHODS.contains(requestMethod)) {
        res.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        return;/*from w w  w  . j a v  a2  s.c o m*/
    }

    startContextIfNeeded();
    if (upgradeIsNeeded(res)) {
        return;
    }

    ServletRequestAccessor.setRequest(req);
    // resolve and set original url if not set
    if (req.getAttribute(Attribute.ORIGINAL_URL) == null) {
        final String originalUrl = OriginalUrlResolver.get().resolveOriginalUrl(req);
        req.setAttribute(Attribute.ORIGINAL_URL, originalUrl);
    }

    if (LOG.isDebugEnabled()) {
        StringBuffer msg = new StringBuffer();
        msg.append("Dispatching request to URL: " + req.getRequestURL());
        LOG.debug(msg.toString());
    }

    super.doService(req, res);
}

From source file:com.wavemaker.runtime.FileController.java

protected void handleError(HttpServletResponse response, String errorMessage, int code) throws IOException {

    response.sendError(code);
    /*Writer outputWriter = response.getWriter();
    outputWriter.write(errorMessage); */
}

From source file:com.mirth.connect.server.servlets.ChannelStatisticsServlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // MIRTH-1745
    response.setCharacterEncoding("UTF-8");

    if (!isUserLoggedIn(request)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
    } else {//ww w .ja v  a 2s.c o m
        try {
            ChannelStatisticsController statisticsController = ControllerFactory.getFactory()
                    .createChannelStatisticsController();
            ObjectXMLSerializer serializer = new ObjectXMLSerializer();
            PrintWriter out = response.getWriter();
            Operation operation = Operations.getOperation(request.getParameter("op"));
            String channelId = request.getParameter("id");
            Map<String, Object> parameterMap = new HashMap<String, Object>();
            parameterMap.put("channelId", channelId);

            if (operation.equals(Operations.CHANNEL_STATS_GET)) {
                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    response.setContentType(APPLICATION_XML);
                    serializer.toXML(statisticsController.getStatistics(channelId), out);
                }
            } else if (operation.equals(Operations.CHANNEL_STATS_CLEAR)) {
                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    boolean deleteReceived = Boolean.valueOf(request.getParameter("deleteReceived"));
                    boolean deleteFiltered = Boolean.valueOf(request.getParameter("deleteFiltered"));
                    boolean deleteQueued = Boolean.valueOf(request.getParameter("deleteQueued"));
                    boolean deleteSent = Boolean.valueOf(request.getParameter("deleteSent"));
                    boolean deleteErrored = Boolean.valueOf(request.getParameter("deleteErrored"));
                    boolean deleteAlerted = Boolean.valueOf(request.getParameter("deleteAlerted"));
                    statisticsController.clearStatistics(channelId, deleteReceived, deleteFiltered,
                            deleteQueued, deleteSent, deleteErrored, deleteAlerted);
                }
            }
        } catch (RuntimeIOException rio) {
            logger.debug(rio);
        } catch (Throwable t) {
            logger.error(ExceptionUtils.getStackTrace(t));
            throw new ServletException(t);
        }
    }
}

From source file:org.appverse.web.framework.backend.api.helpers.security.RPCTimeoutRedirectFilter.java

@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {
    try {//from  w  w w. jav a2 s.  c  o  m
        chain.doFilter(request, response);

        logger.debug("Chain processed normally");
    } catch (IOException ex) {
        throw ex;
    } catch (Exception ex) {
        Throwable[] causeChain = throwableAnalyzer.determineCauseChain(ex);
        RuntimeException ase = (AuthenticationException) throwableAnalyzer
                .getFirstThrowableOfType(AuthenticationException.class, causeChain);

        if (ase == null) {
            ase = (AccessDeniedException) throwableAnalyzer.getFirstThrowableOfType(AccessDeniedException.class,
                    causeChain);
        }

        if (ase != null) {
            if (ase instanceof AuthenticationException) {
                String rpcContentType = ((HttpServletRequest) request).getHeader("Content-Type");

                if (rpcContentType != null && rpcContentType.contains(GWT_RPC_CONTENT_TYPE)) {
                    logger.info("gwt-rpc call detected, send {} error code",
                            this.customSessionExpiredErrorCode);
                    HttpServletResponse resp = (HttpServletResponse) response;
                    resp.sendError(this.customSessionExpiredErrorCode);
                } else {
                    logger.info("Redirect to login page");
                    throw ase;
                }
            } else if (ase instanceof AccessDeniedException) {

                if (authenticationTrustResolver
                        .isAnonymous(SecurityContextHolder.getContext().getAuthentication())) {
                    logger.info("User session expired or not logged in yet");

                    if (SecurityContextHolder.getContext().getAuthentication() == null) {
                        logger.debug("SecurityContextHolder.getContext().getAuthentication() is NULL"
                                + SecurityContextHolder.getContext().getAuthentication());
                    } else {
                        logger.debug(new StringBuffer().append(
                                "SecurityContextHolder.getContext().getAuthentication().getPrincipal(): ")
                                .append(SecurityContextHolder.getContext().getAuthentication().getPrincipal())
                                .toString());
                        logger.debug(new StringBuffer().append(
                                "SecurityContextHolder.getContext().getAuthentication().getAuthorities(): ")
                                .append(SecurityContextHolder.getContext().getAuthentication().getAuthorities())
                                .toString());
                        logger.debug(new StringBuffer().append(
                                "SecurityContextHolder.getContext().getAuthentication().getCredentials(): ")
                                .append(SecurityContextHolder.getContext().getAuthentication().getCredentials())
                                .toString());
                        logger.debug(new StringBuffer()
                                .append("SecurityContextHolder.getContext().getAuthentication().getDetails(): ")
                                .append(SecurityContextHolder.getContext().getAuthentication().getDetails())
                                .toString());
                        logger.debug(new StringBuffer().append(
                                "SecurityContextHolder.getContext().getAuthentication().isAuthenticated(): ")
                                .append(SecurityContextHolder.getContext().getAuthentication()
                                        .isAuthenticated())
                                .toString());
                    }

                    String rpcContentType = ((HttpServletRequest) request).getHeader("Content-Type");

                    if (rpcContentType != null && rpcContentType.contains(GWT_RPC_CONTENT_TYPE)) {
                        logger.info("gwt-rpc call detected, send {} error code",
                                this.customSessionExpiredErrorCode);
                        HttpServletResponse resp = (HttpServletResponse) response;
                        resp.sendError(this.customSessionExpiredErrorCode);

                    } else {
                        logger.info("Redirect to login page");
                        throw ase;
                    }
                } else {
                    throw ase;
                }
            }
        }

    }
}

From source file:RestrictUserIP.java

public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    PrintWriter out;//from  w w w . j  ava  2  s .c  o m
    /**
     * Status code (401) indicating that the request requires HTTP
     * authentication.
     */
    if (req.getRemoteAddr().equals("142.3.28.87")) {
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    }
    resp.setContentType("text/html");
    out = resp.getWriter();
    out.println("<HTML>");
    out.println("<BODY>");
    out.println("<H1>");
    out.println("Hello!");
    out.println("<BR>");
    out.println("Your IP Address: " + req.getRemoteAddr());
    out.println("</H1>");
    out.println("</body>");
    out.println("</html>");
    out.close();
}

From source file:com.carolinarollergirls.scoreboard.jetty.LoadXmlScoreBoard.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    super.doPost(request, response);

    try {/*  www .ja  va2s .c  o m*/
        if (!ServletFileUpload.isMultipartContent(request)) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }

        ServletFileUpload sfU = new ServletFileUpload();
        FileItemIterator items = sfU.getItemIterator(request);
        while (items.hasNext()) {
            FileItemStream item = items.next();
            if (!item.isFormField()) {
                InputStream stream = item.openStream();
                Document doc = editor.toDocument(stream);
                stream.close();
                handleDocument(request, response, doc);
                return;
            }
        }

        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No XML uploaded");
    } catch (FileUploadException fuE) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, fuE.getMessage());
    } catch (JDOMException jE) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, jE.getMessage());
    }
}