Example usage for javax.servlet.http HttpServletResponse SC_NOT_FOUND

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

Introduction

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

Prototype

int SC_NOT_FOUND

To view the source code for javax.servlet.http HttpServletResponse SC_NOT_FOUND.

Click Source Link

Document

Status code (404) indicating that the requested resource is not available.

Usage

From source file:io.wcm.dam.assetservice.impl.DataVersionServlet.java

@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
        throws ServletException, IOException {
    String path = request.getResource().getPath();

    // check path is a valid DAM root folder path for asset service
    if (!damPathHandler.isAllowedDataVersionPath(path)) {
        log.debug("Path not allowed to get data version {}", path);
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;/*  www . j  a v  a  2  s. com*/
    }

    // return data version as JSON
    try {
        JSONObject jsonResponse = new JSONObject();
        jsonResponse.put("dataVersion", damPathHandler.getDataVersion());

        response.setContentType(ContentType.JSON);
        response.setCharacterEncoding(CharEncoding.UTF_8);
        response.getWriter().write(jsonResponse.toString());
    } catch (JSONException ex) {
        throw new ServletException("Unable to generate JSON.", ex);
    }
}

From source file:apps.brucelefebvre.kitchen_002dsink.components.app_002dpage.img_png.java

protected void writeLayer(SlingHttpServletRequest req, SlingHttpServletResponse resp, ImageContext c,
        Layer layer) throws IOException, RepositoryException {

    Image image = new Image(c.resource, "image");
    if (!image.hasContent()) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;//from w  w w. j  a va 2s.  c  o  m
    }

    // get style and set constraints
    image.loadStyleData(c.style);

    // get pure layer
    layer = image.getLayer(false, false, false);
    boolean modified = false;

    if (layer != null) {
        // crop
        modified = image.crop(layer) != null;

        // resize
        modified |= image.resize(layer) != null;

        // rotate
        modified |= image.rotate(layer) != null;

        // check diff (needed when return null for createLayer() )
        modified |= applyDiff(layer, c);
    }

    // don't cache images on authoring instances
    // Cache-Control: no-cache allows caching (e.g. in the browser cache) but
    // will force revalidation using If-Modified-Since or If-None-Match every time,
    // avoiding aggressive browser caching
    if (!WCMMode.DISABLED.equals(WCMMode.fromRequest(req))) {
        resp.setHeader("Cache-Control", "no-cache");
    }

    if (modified) {
        resp.setContentType("image/png");
        layer.write("image/png", 1.0, resp.getOutputStream());
    } else {
        // do not re-encode layer, just spool
        Property data = image.getData();
        InputStream in = data.getStream();
        resp.setContentLength((int) data.getLength());
        resp.setContentType(image.getMimeType());
        IOUtils.copy(in, resp.getOutputStream());
        in.close();
    }
    resp.flushBuffer();
}

From source file:net.sourceforge.subsonic.controller.AvatarController.java

public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    Avatar avatar = getAvatar(request);/*  w w  w.j  av a  2s .com*/

    if (avatar == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return null;
    }

    response.setContentType(avatar.getMimeType());
    response.getOutputStream().write(avatar.getData());
    return null;
}

From source file:com.opencredo.servlet.BookDisplayCoverController.java

protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws IllegalStateException, IOException {

    // set the content type
    response.setContentType(CONTENT_TYPE);

    // get the ID of the book -- set "bad request" if its not a valid integer
    Integer id;// w  w w.  j a va  2s . c om
    try {
        id = ServletRequestUtils.getIntParameter(request, "book");
        if (id == null)
            throw new IllegalStateException("must specify the book id");
    } catch (Exception e) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "invalid book");
        return null;
    }

    // get the book from the service
    Book book = bookService.getBook(id);

    // if the book doesn't exist then set "not found"
    if (book == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND, "no such book");
        return null;
    }

    // if the book doesn't have a picture, set "not found"
    if (book.getCoverPng() == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND, "book has no image");
        return null;
    }

    if (logger.isDebugEnabled())
        logger.debug("returning cover for book " + book.getKey() + " '" + book.getTitle() + "'" + " size: "
                + book.getCoverPng().length + " bytes");

    // send the image
    response.setContentLength(book.getCoverPng().length);
    response.getOutputStream().write(book.getCoverPng());
    response.getOutputStream().flush();

    // we already handled the response
    return null;
}

From source file:org.eclipse.virgo.snaps.core.internal.webapp.StaticResourceServlet.java

/** 
 * {@inheritDoc}/*from   w w w . j a v a  2 s .  c  o  m*/
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // As an alternative of the Tomcat's escaping utility we can use one of the following libraries:
    // - org.springframework.web.util.HtmlUtils.htmlEscape(String)
    // - org.apache.commons.lang3.StringEscapeUtils.escapeHtml4(String)
    String pathInfo = RequestUtil.filter(request.getPathInfo());
    try {
        URL resource = getServletContext().getResource(pathInfo);
        if (resource == null) {
            logger.warn("Resource {} not found", pathInfo);
            response.sendError(HttpServletResponse.SC_NOT_FOUND, "Resource '" + pathInfo + "' not found.");
        } else {
            logger.info("Resource {} found", pathInfo);
            InputStream input = null;
            try {
                input = new BufferedInputStream(resource.openStream());
                OutputStream output = response.getOutputStream();
                byte[] buffer = new byte[4096];
                int len;
                while ((len = input.read(buffer)) > 0) {
                    output.write(buffer, 0, len);
                }
                output.flush();
            } finally {
                if (input != null) {
                    IOUtils.closeQuietly(input);
                }
            }
        }
    } catch (MalformedURLException e) {
        logger.error(String.format("Malformed servlet path %s", pathInfo), e);
        throw new ServletException("Malformed servlet path " + pathInfo, e);
    }
}

From source file:com.rhythm.louie.info.DownloadServlet.java

private void downloadFile(HttpServletRequest request, HttpServletResponse response, String filePath)
        throws IOException {
    if (filePath.isEmpty()) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;/*from w ww  .  ja v a2 s. co m*/
    }
    File file = new File(filePath);
    int length = 0;
    try (ServletOutputStream outStream = response.getOutputStream()) {
        ServletContext context = getServletConfig().getServletContext();

        String mimetype = context.getMimeType(filePath);

        // sets response content type
        if (mimetype == null) {
            mimetype = "application/octet-stream";
        }
        response.setContentType(mimetype);
        response.setContentLength((int) file.length());
        String fileName = (new File(filePath)).getName();

        // sets HTTP header
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

        byte[] byteBuffer = new byte[4096];
        // reads the file's bytes and writes them to the response stream
        try (DataInputStream in = new DataInputStream(new FileInputStream(file))) {
            // reads the file's bytes and writes them to the response stream
            while ((in != null) && ((length = in.read(byteBuffer)) != -1)) {
                outStream.write(byteBuffer, 0, length);
            }
        }
    }
}

From source file:org.geoserver.ows.AbstractURLPublisher.java

protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    URL url = getUrl(request);/*from  ww  w.ja  v a2  s  .  c  o  m*/

    // if not found return a 404
    if (url == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return null;
    }

    File file = DataUtilities.urlToFile(url);
    if (file != null && file.exists() && file.isDirectory()) {
        String uri = request.getRequestURI().toString();
        uri += uri.endsWith("/") ? "index.html" : "/index.html";

        response.addHeader("Location", uri);
        response.sendError(HttpServletResponse.SC_MOVED_TEMPORARILY);

        return null;
    }

    // set the mime if known by the servlet container, set nothing otherwise
    // (Tomcat behaves like this when it does not recognize the file format)
    String mime = getServletContext().getMimeType(new File(url.getFile()).getName());
    if (mime != null) {
        response.setContentType(mime);
    }

    // set the content length and content type
    URLConnection connection = null;
    InputStream input = null;
    try {
        connection = url.openConnection();
        long length = connection.getContentLength();
        if (length > 0 && length <= Integer.MAX_VALUE) {
            response.setContentLength((int) length);
        }

        long lastModified = connection.getLastModified();
        if (lastModified > 0) {
            SimpleDateFormat format = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss", Locale.ENGLISH);
            format.setTimeZone(TimeZone.getTimeZone("GMT"));
            String formatted = format.format(new Date(lastModified)) + " GMT";
            response.setHeader("Last-Modified", formatted);
        }

        // Guessing the charset (and closing the stream)
        EncodingInfo encInfo = null;
        OutputStream output = null;
        final byte[] b4 = new byte[4];
        int count = 0;
        // open the output
        input = connection.getInputStream();

        // Read the first four bytes, and determine charset encoding
        count = input.read(b4);
        encInfo = XmlCharsetDetector.getEncodingName(b4, count);
        response.setCharacterEncoding(encInfo.getEncoding() != null ? encInfo.getEncoding() : "UTF-8");

        // send out the first four bytes read
        output = response.getOutputStream();
        output.write(b4, 0, count);

        // copy the content to the output
        byte[] buffer = new byte[8192];
        int n = -1;
        while ((n = input.read(buffer)) != -1) {
            output.write(buffer, 0, n);
        }
    } finally {
        if (input != null)
            input.close();
    }

    return null;
}

From source file:org.wallride.web.controller.admin.tag.TagSelect2Controller.java

@RequestMapping(value = "/{language}/tags/select/{id}", method = RequestMethod.GET)
public @ResponseBody DomainObjectSelect2Model select(@PathVariable String language, @PathVariable Long id,
        HttpServletResponse response) throws IOException {
    Tag tag = tagService.getTagById(id, language);
    if (tag == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return null;
    }/*from   w  w w. ja  v  a 2s .com*/

    DomainObjectSelect2Model model = new DomainObjectSelect2Model(tag.getName(), tag.getName());
    return model;
}

From source file:com.tdclighthouse.prototype.servlets.JLatexServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String latexExpression = req.getParameter(LATEX_PARAM);
    latexExpression = StringEscapeUtils.unescapeXml(latexExpression);

    if (latexExpression != null && !"".equals(latexExpression)) {
        BufferedImage image = generateImage(latexExpression);
        resp.setContentType(MIME_TYPE);/* w w  w .  ja v a2  s.c om*/
        ImageIO.write(image, IMAGE_TYPE, resp.getOutputStream());
    } else {
        resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
    }
}

From source file:org.wallride.web.controller.admin.user.UserSelect2Controller.java

@RequestMapping(value = "/{language}/users/select/{id}", method = RequestMethod.GET)
public @ResponseBody DomainObjectSelect2Model select(@PathVariable String language, @PathVariable Long id,
        HttpServletResponse response) throws IOException {
    User user = userService.getUserById(id);
    if (user == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return null;
    }//from   w w  w .  j a v  a  2s .c  om

    DomainObjectSelect2Model model = new DomainObjectSelect2Model(user.getId(), user.toString());
    return model;
}