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:de.mpg.escidoc.pubman.sword.PubManDepositServlet.java

/**
 * Process the GET request. This will return an unimplemented response.
 *//*from  ww w .  ja v a  2s.c  o m*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED);
}

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

public File getFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String filePath = URLEncodeUtils.decodeUtf8(request.getParameter("p"));
    if (filePath != null) {
        if (isPermittedDirectory(filePath)) {
            return new File(filePath);
        } else {// w ww  . j  av  a2 s. c  om
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    } else {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
    }
    return null;
}

From source file:de.micromata.genome.gwiki.web.GWikiServlet.java

protected void serveStatic(String page, GWikiContext wikiContext) throws ServletException, IOException {
    String res = "/" + page;
    HttpServletResponse resp = wikiContext.getResponse();
    InputStream is = getStaticResource(res, wikiContext);
    if (is == null) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;/* w  w  w .  jav  a2 s .  c o  m*/
    }
    if (etagTimeOut > 1) {
        String etag = wikiContext.getWikiWeb().geteTagWiki();
        String ifnm = wikiContext.getRequest().getHeader("If-None-Match");
        if (StringUtils.equals(etag, ifnm) == true) {
            wikiContext.getResponse().sendError(304, "Not modified");
            return;
        }

        wikiContext.getResponse().addHeader("ETag", etag);
        long nt = new Date().getTime() + etagTimeOut;
    }
    long nt = new Date().getTime() + etagTimeOut;
    String mime = wikiContext.getWikiWeb().getDaoContext().getMimeTypeProvider().getMimeType(wikiContext, page);
    if (StringUtils.equals(mime, "application/x-shockwave-flash")) {
        resp.setHeader("Cache-Control", "cache, must-revalidate");
        resp.setHeader("Pragma", "public");
    }
    if (mime != null) {
        resp.setContentType(mime);
    }
    resp.setDateHeader("Expires", nt);
    resp.setHeader("Cache-Control", "max-age=86400, public");
    if (mime != null) {
        resp.setContentType(mime);
    }

    byte[] data = IOUtils.toByteArray(is);
    IOUtils.closeQuietly(is);
    resp.setContentLength(data.length);
    IOUtils.write(data, resp.getOutputStream());
}

From source file:com.capstone.giveout.controllers.GiftsController.java

@RequestMapping(value = Routes.GIFTS_IMAGE_PATH, method = RequestMethod.GET)
public @ResponseBody void getImage(@PathVariable("id") long id, @PathVariable("size") String size,
        HttpServletResponse response) throws IOException {
    Gift gift = gifts.findOne(id);/*from   w  w w .j a  v  a  2s.  c  o  m*/
    if (gift == null) {
        response.sendError(HttpStatus.NOT_FOUND.value());
        return;
    }

    try {
        ImageFileManager.get(GIFT_ROOT_PATH).copyImage(gift.getId(), size, response.getOutputStream());
    } catch (FileNotFoundException e) {
        response.sendError(HttpStatus.NOT_FOUND.value());
    }
}

From source file:com.bosch.cr.examples.inventorybrowser.server.CustomProxyServlet.java

@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // enforce BASIC auth on all requests
    String auth = req.getHeader("Authorization");
    if (auth == null) {
        resp.setHeader("WWW-Authenticate", "BASIC realm=\"Proxy for Bosch IoT Things\"");
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return;//from   w ww  . j ava  2 s .  c  o  m
    }

    super.service(req, resp);
}

From source file:jp.co.opentone.bsol.linkbinder.view.servlet.WebResourceServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String path = req.getPathInfo();
    if (isJavascript(path)) {
        serveResource(req, resp, javascript, path);
    } else if (isStylesheet(path)) {
        serveResource(req, resp, stylesheet, path);
    } else {//w w w.j  ava2  s.  co m
        resp.sendError(HttpServletResponse.SC_NOT_FOUND);
    }
}

From source file:com.pureinfo.tgirls.servlet.OtherCompanyInitServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    JsonBase result = new JsonBase();
    response.setContentType("text/json; charset=utf-8");
    String userId = request.getParameter("uid");
    if (StringUtils.isEmpty(userId)) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;//from ww w .  ja  v a2s .  co m
    }

    try {
        IUserMgr umgr = (IUserMgr) ArkContentHelper.getContentMgrOf(User.class);
        User currentUser = umgr.getUserByTaobaoId(userId);
        if (currentUser == null) {
            response.sendRedirect(request.getContextPath() + "/tgirls/need-login.html");
            return;
        }

        logger.info("other company init with user[" + currentUser.getTaobaoID() + "]");

        IPhotoMgr mgr = (IPhotoMgr) ArkContentHelper.getContentMgrOf(Photo.class);

        List<Photo> uploadlist = mgr.getUserUploadPublicPics(currentUser.getTaobaoID());
        if (uploadlist != null) {
            List<JSONObject> pjsonlist = new ArrayList<JSONObject>();
            Photo object = null;
            for (Iterator iterator = uploadlist.iterator(); iterator.hasNext();) {
                object = (Photo) iterator.next();
                pjsonlist.add(new JSONObject(object));
            }

            logger.debug("uploads:" + pjsonlist.size());

            result.put("uploads", pjsonlist);

            uploadlist.clear();
        }

        List<Photo> buylist = mgr.getUserBuyPublicPics(currentUser.getTaobaoID());
        if (buylist != null) {
            List<JSONObject> pjsonlist = new ArrayList<JSONObject>();
            Photo object = null;
            for (Iterator iterator = buylist.iterator(); iterator.hasNext();) {
                object = (Photo) iterator.next();
                pjsonlist.add(new JSONObject(object));
            }

            logger.debug("buys:" + pjsonlist.size());

            result.put("buys", pjsonlist);
            buylist.clear();
        }

        //            List<JSONObject> infolist = GetInformationsServlet.getInformations(currentUser.getTaobaoID());
        //            if (infolist != null) {
        //                result.put("informations", infolist);
        //            }
        result.put("uinfo", new JSONObject(currentUser));
    } catch (JSONException e) {
        logger.error("json error", e);
    } catch (PureException e) {
        logger.error("ark error", e);
    }

    // logger.debug("result:" + result.toString());
    response.getWriter().write(result.toString());
    return;
}

From source file:org.dspace.app.webui.cris.servlet.ResearcherPictureServlet.java

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

    String idString = req.getPathInfo();
    String[] pathInfo = idString.split("/", 2);
    String authorityKey = pathInfo[1];

    Integer id = ResearcherPageUtils.getRealPersistentIdentifier(authorityKey, ResearcherPage.class);

    if (id == null) {

        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;/*www .ja  v  a 2s .co  m*/
    }

    ResearcherPage rp = ResearcherPageUtils.getCrisObject(id, ResearcherPage.class);
    File file = new File(ConfigurationManager.getProperty(CrisConstants.CFG_MODULE, "researcherpage.file.path")
            + File.separatorChar + JDynATagLibraryFunctions.getFileFolder(rp.getPict().getValue())
            + File.separatorChar + JDynATagLibraryFunctions.getFileName(rp.getPict().getValue()));

    InputStream is = null;
    try {
        is = new FileInputStream(file);

        response.setContentType(req.getSession().getServletContext().getMimeType(file.getName()));
        Long len = file.length();
        response.setContentLength(len.intValue());
        response.setHeader("Content-Disposition", "attachment; filename=" + file.getName());
        FileCopyUtils.copy(is, response.getOutputStream());
        response.getOutputStream().flush();
    } finally {
        if (is != null) {
            IOUtils.closeQuietly(is);
        }

    }

}

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

protected void upload(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {//w w w  .j  a va 2  s  .  c  o m
        if (!ServletFileUpload.isMultipartContent(request)) {
            response.sendError(response.SC_BAD_REQUEST);
            return;
        }

        String media = null, type = null;
        FileItemFactory fiF = new DiskFileItemFactory();
        ServletFileUpload sfU = new ServletFileUpload(fiF);
        List<FileItem> fileItems = new LinkedList<FileItem>();
        Iterator i = sfU.parseRequest(request).iterator();

        while (i.hasNext()) {
            FileItem item = (FileItem) i.next();
            if (item.isFormField()) {
                if (item.getFieldName().equals("media"))
                    media = item.getString();
                else if (item.getFieldName().equals("type"))
                    type = item.getString();
            } else if (item.getName().matches(zipExtRegex)) {
                processZipFileItem(fiF, item, fileItems);
            } else if (uploadFileNameFilter.accept(null, item.getName())) {
                fileItems.add(item);
            }
        }

        if (fileItems.size() == 0) {
            setTextResponse(response, response.SC_BAD_REQUEST, "No files provided to upload");
            return;
        }

        processFileItemList(fileItems, media, type);

        int len = fileItems.size();
        setTextResponse(response, response.SC_OK,
                "Successfully uploaded " + len + " file" + (len > 1 ? "s" : ""));
    } catch (FileNotFoundException fnfE) {
        setTextResponse(response, response.SC_NOT_FOUND, fnfE.getMessage());
    } catch (IllegalArgumentException iaE) {
        setTextResponse(response, response.SC_BAD_REQUEST, iaE.getMessage());
    } catch (FileUploadException fuE) {
        setTextResponse(response, response.SC_INTERNAL_SERVER_ERROR, fuE.getMessage());
    }
}

From source file:com.capstone.giveout.controllers.GiftsController.java

@PreAuthorize("hasRole(mobile)")
@RequestMapping(value = Routes.GIFTS_UPDATE_IMAGE_PATH, method = RequestMethod.POST)
public @ResponseBody Gift updateImages(@PathVariable("id") long id, @RequestParam("image") MultipartFile image,
        Principal p, HttpServletResponse response) throws IOException {
    Gift gift = gifts.findOne(id);//from   ww w. j a v a2  s  .c om
    if (gift == null) {
        response.sendError(HttpStatus.NOT_FOUND.value());
        return null;
    }

    gift.allowAccessToGiftChain = true;

    User currentUser = users.findByUsername(p.getName());
    if (gift.getUser().getId() != currentUser.getId()) {
        response.sendError(HttpStatus.UNAUTHORIZED.value(), "You are not the owner of this gift");
        return null;
    }

    saveImages(gift, image);
    return gift;
}