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:gov.nih.nci.cabig.caaers.web.filters.CsrfPreventionFilter.java

public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
        throws ServletException, IOException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) resp;
    initializeCsfrToken(request);//www.j a v a2  s.  c  o  m

    if (request.getMethod().toUpperCase().equals("POST") && !isAllowedURI(request.getRequestURI())) {
        boolean isValidRequest = isValidCsrfToken(request);
        if (!isValidRequest) {
            response.sendError(403);
            return;
        }
    }

    chain.doFilter(request, response);
}

From source file:com.ewcms.component.checkcode.web.ImageCaptchaServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
    try {/* w ww  . j ava 2s .com*/
        String captchaId = request.getSession().getId();
        createCheckCodeImage(captchaId, request.getLocale(), jpegOutputStream);
    } catch (IllegalArgumentException e) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    } catch (CaptchaServiceException e) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    initResponseHeader(response);
    responseImage(response, jpegOutputStream.toByteArray());
    jpegOutputStream.close();
}

From source file:com.javaetmoi.core.spring.vfs.Vfs2ResourceHttpRequestHandler.java

@Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    checkAndPrepare(request, response, true);

    // check whether a matching resource exists
    Resource resource = getResource(request);
    if (resource == null) {
        logger.debug("No matching resource found - returning 404");
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;//  w w w.  j  a  v a2 s  .c  o m
    }

    // check the resource's media type
    MediaType mediaType = getMediaType(resource);
    if (mediaType != null) {
        if (logger.isDebugEnabled()) {
            logger.debug("Determined media type '" + mediaType + "' for " + resource);
        }
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("No media type found for " + resource + " - not sending a content-type header");
        }
    }

    // header phase
    // Use a Vfs2Resource when asset are probided by the JBoss 5 Virtaul File System
    URL url = resource.getURL();
    if (url.getProtocol().startsWith(ResourceUtils.URL_PROTOCOL_VFS)) {
        resource = new Vfs2Resource(Vfs2Utils.getRoot(url));
    }

    if (new ServletWebRequest(request, response).checkNotModified(resource.lastModified())) {
        logger.debug("Resource not modified - returning 304");
        return;
    }
    setHeaders(response, resource, mediaType);

    // content phase
    if (METHOD_HEAD.equals(request.getMethod())) {
        logger.trace("HEAD request - skipping content");
        return;
    }
    writeContent(response, resource);
}

From source file:com.sammyun.controller.console.CommonController.java

/**
 * ??//from   www  . j  ava2s .c  o m
 */
@RequestMapping("/unauthorized")
public String unauthorized(HttpServletRequest request, HttpServletResponse response) {
    String requestType = request.getHeader("X-Requested-With");
    if (requestType != null && requestType.equalsIgnoreCase("XMLHttpRequest")) {
        response.addHeader("loginStatus", "unauthorized");
        try {
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    return "/console/common/unauthorized";
}

From source file:eu.trentorise.smartcampus.communicatorservice.controller.NotificationController.java

@RequestMapping(method = RequestMethod.POST, value = "user/notification/sync")
public @ResponseBody ResponseEntity<SyncData> syncDataByUser(HttpServletRequest request,
        HttpServletResponse response, @RequestParam long since, @RequestBody Map<String, Object> obj)
        throws IOException, ClassNotFoundException, DataException {
    String userId = getUserId();//www. j  a  va 2 s  . c om
    if (userId == null) {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    }
    SyncDataRequest syncReq = Util.convertRequest(obj, since);
    SyncData out = notificationManager.synchronizeByUser(userId, syncReq.getSyncData());
    return new ResponseEntity<SyncData>(out, HttpStatus.OK);
}

From source file:eu.trentorise.smartcampus.communicatorservice.controller.NotificationController.java

@RequestMapping(method = RequestMethod.POST, value = "app/{capp}/notification/sync")
public @ResponseBody ResponseEntity<SyncData> syncDataByApp(@PathVariable("capp") String capp,
        HttpServletRequest request, HttpServletResponse response, @RequestParam long since,
        @RequestBody Map<String, Object> obj) throws IOException, ClassNotFoundException, DataException {
    String userId = getUserId();//from  ww w.  j a va2s  .co m
    if (userId == null) {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    }
    SyncDataRequest syncReq = Util.convertRequest(obj, since);
    SyncData out = notificationManager.synchronizeByApp(userId, capp, syncReq.getSyncData());
    return new ResponseEntity<SyncData>(out, HttpStatus.OK);
}

From source file:org.magnum.dataup.SimpleVideoSvcController.java

@RequestMapping(value = "/video/{id}/data", method = RequestMethod.POST)
public @ResponseBody VideoStatus setVideoData(@PathVariable("id") long id,
        @RequestParam("data") MultipartFile videoData, HttpServletResponse response) throws IOException {
    VideoStatus status = new VideoStatus(VideoState.READY);
    //don't have the video: return 404 - the client should receive a 404 error and throw an exception
    if (!videos.containsKey(id)) {
        //   response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return status; // if the id is invalid, the status won't be checked by the client
    }//  w w w. j a v a 2s.  c  o m

    videoFileManager = (null == videoFileManager) ? VideoFileManager.get() : videoFileManager;
    videoFileManager.saveVideoData(videos.get(id), videoData.getInputStream());
    //succesful: status.state == VideoState.READY            
    return status;
}

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

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

    try {/*from   w w  w .  ja v  a  2s .  c o m*/
        if ("/set".equals(request.getPathInfo()))
            set(request, response);
        else if (!response.isCommitted())
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
    } catch (JDOMException jE) {
        ScoreBoardManager.printMessage("XmlScoreBoardServlet ERROR: " + jE.getMessage());
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:com.edgenius.wiki.webapp.action.BaseAction.java

protected void sendHttpResponseCode(int httpResponseCode) {
    HttpServletResponse response = getResponse();
    try {/*from   w  ww .j  a  v a2s .co m*/
        response.sendError(httpResponseCode);
    } catch (IOException e) {
        log.error("Unable to send HttpResponseCode:" + httpResponseCode, e);
    }
}

From source file:com.openedit.modules.edit.BaseEditorModule.java

public void check404(WebPageRequest inReq) throws Exception {
    PageManager pageManager = getPageManager();
    boolean exist = inReq.getPage().exists();
    if (exist) {// www .  j a  va2 s . com
        Page page = inReq.getPage();
        //If link does not exists. Then put a real welcome page on there so that fallback will work
        if (page.isFolder()) {
            String isVirtual = inReq.getPage().get("virtual");
            if (Boolean.parseBoolean(isVirtual)) {
                return;
            }
            //Loop over the various starting pages. 
            page = findWelcomePage(page);
            URLUtilities util = new URLUtilities(inReq.getRequest(), inReq.getResponse());

            String requestedPath = util.getOriginalPath();
            inReq.redirect(page.getPath());

        }
        return;
    }

    PageStreamer streamer = inReq.getPageStreamer();
    if (streamer != null) {
        streamer.getWebPageRequest().putPageValue("pathNotFound", inReq.getPath());
    }
    String isVirtual = inReq.getPage().get("virtual");
    if (Boolean.parseBoolean(isVirtual)) {
        return;
    }

    URLUtilities utils = (URLUtilities) inReq.getPageValue(PageRequestKeys.URL_UTILITIES);

    if (utils != null) {
        //redirecting only works relative to a webapp
        if (streamer != null) {
            streamer.getWebPageRequest().putPageValue("forcedDestinationPath",
                    utils.requestPathWithArgumentsNoContext());
        }
    }

    if (!inReq.getPage().isHtml()) {
        HttpServletResponse response = inReq.getResponse();
        if (response != null) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            inReq.setHasRedirected(true);
            return;
        }
    }

    if (inReq.getContentPage().getPath().equals(inReq.getPath())) {
        if (inReq.getPage().isHtml() && inReq.isEditable()) {
            String path = inReq.findValue("404wizardpage");
            if (path == null) {
                path = "/system/nopagefound.html";
            }
            Page wizard = pageManager.getPage(path);
            if (wizard.exists()) {
                inReq.getPageStreamer().include(wizard);
                inReq.setHasRedirected(true);
                return;
            }
        }
        //log.info( "Could not use  add page wizard. 404 error on: " + inReq.getPath() );
        String errorpage = inReq.getContentPage().getProperty("error404"); //"/error404.html";
        errorpage = errorpage != null ? errorpage : ERROR404_HTML;
        Page p404 = pageManager.getPage(errorpage);
        if (p404.exists()) {
            HttpServletResponse response = inReq.getResponse();
            if (response != null) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            }
            inReq.putProtectedPageValue("content", p404);
            //inReq.forward(p404.getPath());
            return;
        } else {
            log.error("Could not report full 404 error on: " + inReq.getPath()
                    + ". Make sure the 404 error page exists " + p404.getPath());
            //other users will get the standard file not found error
            HttpServletResponse response = inReq.getResponse();
            if (response != null) {
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
                inReq.setHasRedirected(true);
            }
        }
    } else {
        inReq.getWriter().write("404 on " + inReq.getPath());
        inReq.getWriter().flush();
        inReq.setHasRedirected(true);

    }
}