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:com.haulmont.cuba.web.controllers.LogDownloadController.java

@RequestMapping(value = "/log/{file:[a-zA-Z0-9\\.\\-_]+}", method = RequestMethod.GET)
public void getLogFile(HttpServletResponse response, @RequestParam(value = "s") String sessionId,
        @RequestParam(value = "full", required = false) Boolean downloadFull,
        @PathVariable(value = "file") String logFileName) throws IOException {
    UserSession userSession = getSession(sessionId, response);
    if (userSession == null)
        return;/*from   www . j av a2  s. co  m*/

    if (!userSession.isSpecificPermitted("cuba.gui.administration.downloadlogs")) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    // security check, handle only valid file name
    String filename = FilenameUtils.getName(logFileName);

    try {
        File logFile = logControl.getLogFile(filename);

        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setHeader("Content-Type", "application/zip");
        response.setHeader("Pragma", "no-cache");

        response.setHeader("Content-Disposition", "attachment; filename=" + filename + ".zip");

        OutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();

            if (BooleanUtils.isTrue(downloadFull)) {
                LogArchiver.writeArchivedLogToStream(logFile, outputStream);
            } else {
                LogArchiver.writeArchivedLogTailToStream(logFile, outputStream);
            }
        } catch (RuntimeException | IOException ex) {
            log.error("Unable to download file", ex);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } finally {
            IOUtils.closeQuietly(outputStream);
        }

    } catch (LogFileNotFoundException e) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
    }
}

From source file:com.haulmont.cuba.portal.controllers.LogDownloadController.java

@RequestMapping(value = "/log/{file:[a-zA-Z0-9\\.\\-_]+}", method = RequestMethod.GET)
public void getLogFile(HttpServletResponse response, @RequestParam(value = "s") String sessionId,
        @RequestParam(value = "full", required = false) Boolean downloadFull,
        @PathVariable(value = "file") String logFileName) throws IOException {
    UserSession userSession = getSession(sessionId, response);
    if (userSession == null)
        return;//  w w w .  j  a  v a  2s .  c  o  m

    if (!userSession.isSpecificPermitted("cuba.gui.administration.downloadlogs")) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    // security check, handle only valid file name
    String filename = FilenameUtils.getName(logFileName);

    try {
        File logFile = logControl.getLogFile(filename);

        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setHeader("Content-Type", "application/zip");
        response.setHeader("Pragma", "no-cache");

        response.setHeader("Content-Disposition", "attachment; filename=" + filename);

        OutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();

            if (BooleanUtils.isTrue(downloadFull)) {
                LogArchiver.writeArchivedLogToStream(logFile, outputStream);
            } else {
                LogArchiver.writeArchivedLogTailToStream(logFile, outputStream);
            }
        } catch (RuntimeException | IOException ex) {
            log.error("Unable to assemble zipped log file", ex);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } finally {
            IOUtils.closeQuietly(outputStream);
        }

    } catch (LogFileNotFoundException e) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
    }
}

From source file:org.openmrs.module.openhmis.cashier.web.controller.ReceiptController.java

private boolean validateBill(Integer billId, Bill bill, HttpServletResponse response) throws IOException {
    if (bill == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND,
                "Could not find bill with bill Id '" + billId + "'");

        return false;
    }/*from  w w w .  jav a  2s  .  co  m*/

    if (bill.isReceiptPrinted() && !Context.hasPrivilege(PrivilegeConstants.REPRINT_RECEIPT)) {
        if (StringUtils.isEmpty(bill.getReceiptNumber())) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN,
                    "You do not have permission to reprint receipt '" + bill.getReceiptNumber() + "'");
        } else {
            response.sendError(HttpServletResponse.SC_FORBIDDEN,
                    "You do not have permission to reprint bill '" + billId + "'");
        }

        return false;
    }

    return true;
}

From source file:alpine.filters.WhitelistUrlFilter.java

/**
 * Check for allowed URLs being requested.
 *
 * @param request The request object./*  www.ja  v a2 s  . c o m*/
 * @param response The response object.
 * @param chain Refers to the {@code FilterChain} object to pass control to the next {@code Filter}.
 * @throws IOException a IOException
 * @throws ServletException a ServletException
 */
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {

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

    final String requestUri = req.getRequestURI();
    if (requestUri != null) {
        boolean allowed = false;
        for (String url : allowUrls) {
            if (requestUri.equals("/")) {
                if (url.trim().equals("/")) {
                    allowed = true;
                }
            } else if (requestUri.startsWith(url.trim())) {
                allowed = true;
            }
        }
        if (!allowed) {
            res.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
    }
    chain.doFilter(request, response);
}

From source file:info.magnolia.imaging.ImagingServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    final String generatorName = getImageGeneratorName(request);
    final ImageGenerator generator = getGenerator(generatorName);
    if (generator == null) {
        throw new IllegalArgumentException("No ImageGenerator with name " + generatorName);
    }/*w w w .j  av a  2 s .  c  o  m*/

    final ParameterProviderFactory parameterProviderFactory = generator.getParameterProviderFactory();
    final ParameterProvider p = parameterProviderFactory.newParameterProviderFor(request);

    if (validateFileExtension) {
        String outputFormat = generator.getOutputFormat(p).getFormatName();
        String requestedPath = StringUtils.substringAfterLast(request.getPathInfo(), "/"); // don't take part of node name as extension, we support dots in node names!
        String requestedFormat = StringUtils.substringAfterLast(requestedPath, ".");
        if (!StringUtils.equals(outputFormat, requestedFormat)) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
    }

    try {
        // TODO -- mimetype etc.
        final ImageStreamer streamer = getStreamer(parameterProviderFactory);
        streamer.serveImage(generator, p, response.getOutputStream());

        response.flushBuffer();
        // IOUtils.closeQuietly(response.getOutputStream());
    } catch (ImagingException e) {
        throw new ServletException(e); // TODO
    }
}

From source file:com.jaspersoft.jasperserver.rest.services.RESTReport.java

/**
 * The get method get resources of a produced report
 * Urls in this case look like /report/uniqueidentifier?file=filename
 *//*from w  w w . j  a  va 2  s. com*/
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServiceException {
    // Get the uri of the resource
    String uuid = restUtils.extractRepositoryUri(req.getPathInfo());
    if (uuid.startsWith("/"))
        uuid = uuid.substring(1);

    // Find the report in session...
    HttpSession session = req.getSession();
    Report report = (Report) session.getAttribute(uuid);

    if (report == null) {
        restUtils.setStatusAndBody(HttpServletResponse.SC_NOT_FOUND, resp,
                "Report not found (uuid not found in session)");
        return;
    }

    String file = req.getParameter("file");
    if (file != null) {
        if (!report.getAttachments().containsKey(file)) {
            restUtils.setStatusAndBody(HttpServletResponse.SC_NOT_FOUND, resp,
                    "Report not found (requested file not available for this report)");
            return;
        } else {
            DataSource ds = (DataSource) report.getAttachments().get(file);
            restUtils.sendFile(ds, resp);
            return;
        }
    } else {
        // Send the report description...
        // Please not that here we may decide to send back a final format based on the accepted
        // content type....
        resp.setContentType("text/xml; charset=UTF-8");
        restUtils.setStatusAndBody(HttpServletResponse.SC_OK, resp, report.toXml());
    }
}

From source file:csns.web.controller.DownloadController.java

@RequestMapping(value = "/download", params = "fileId")
public String downloadFile(@RequestParam Long fileId, HttpServletResponse response, ModelMap models)
        throws IOException {
    File file = fileDao.getFile(fileId);

    if (file.isDeleted()) {
        models.put("message", "error.file.deleted");
        return "error";
    }//from   w w w . ja  v  a2  s.c o m

    if (!fileIO.getDiskFile(file).exists()) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return null;
    }

    String contentType = contentTypes.getProperty(file.getFileExtension().toLowerCase());
    if (contentType == null)
        contentType = file.getType();

    response.setContentType(contentType);
    response.setHeader("Content-Length", file.getSize().toString());
    response.setHeader("Content-Disposition",
            "inline; filename=" + file.getName().replaceAll(replaceRegex, "_"));

    fileIO.copy(file, response.getOutputStream());

    String username = SecurityUtils.isAnonymous() ? "guest" : SecurityUtils.getUser().getUsername();
    logger.info(username + " downloaded " + file.getId());

    return null;
}

From source file:com.adeptj.runtime.servlet.ErrorPages.java

static void renderErrorPage(HttpServletRequest req, HttpServletResponse resp) {
    String statusCode = StringUtils.substringAfterLast(req.getRequestURI(), Constants.SLASH);
    if (StringUtils.equals(TEMPLATE_ERROR, req.getRequestURI())) {
        ErrorPages.renderGenericErrorPage(req, resp);
    } else if (StringUtils.equals(STATUS_500, statusCode)) {
        ErrorPages.render500Page(req, resp);
    } else if (RequestUtil.hasException(req) && StringUtils.equals(STATUS_500, statusCode)) {
        ErrorPages.render500PageWithExceptionTrace(req, resp);
    } else if (Configs.of().undertow().getStringList(KEY_STATUS_CODES).contains(statusCode)) {
        ErrorPages.renderErrorPageForStatusCode(req, resp, statusCode);
    } else {/*from   w ww . j a  v  a2 s  .  c  o  m*/
        ResponseUtil.sendError(resp, HttpServletResponse.SC_NOT_FOUND);
    }
}

From source file:de.thischwa.pmcms.server.ZipProxyServlet.java

@Override
protected void doRequest(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    String reqPath = req.getPathInfo();
    if (reqPath.startsWith("/"))
        reqPath = reqPath.substring(1);//from  w  ww  .j  a v  a 2  s.co  m

    ZipEntry entry = zipInfo.get(reqPath);
    if (entry == null) {
        logger.debug(Utils.join("Requested path not found: [", reqPath, "]"));
        resp.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }
    logger.debug(Utils.join("Requested path: [", reqPath, "]"));

    ServletUtils.establishContentType(reqPath, resp);

    InputStream in = null;
    try {
        in = new BufferedInputStream(zipFile.getInputStream(entry));
        IOUtils.copy(in, resp.getOutputStream());
        logger.debug("Rendered: " + reqPath);
    } catch (FileNotFoundException e) {
        logger.error("zipped resource not found: " + reqPath);
    } finally {
        IOUtils.closeQuietly(in);
    }
}

From source file:io.adeptj.runtime.servlet.ErrorPages.java

static void renderErrorPage(HttpServletRequest req, HttpServletResponse resp) {
    String statusCode = StringUtils.substringAfterLast(req.getRequestURI(), SLASH);
    if (StringUtils.equals(TEMPLATE_ERROR, req.getRequestURI())) {
        ErrorPages.renderGenericErrorPage(req, resp);
    } else if (StringUtils.equals(STATUS_500, statusCode)) {
        ErrorPages.render500Page(req, resp);
    } else if (RequestUtil.hasException(req) && StringUtils.equals(STATUS_500, statusCode)) {
        ErrorPages.render500PageWithExceptionTrace(req, resp);
    } else if (Configs.of().undertow().getStringList(KEY_STATUS_CODES).contains(statusCode)) {
        ErrorPages.renderErrorPageForStatusCode(req, resp, statusCode);
    } else {//w ww.j  av  a2  s  .c om
        ResponseUtil.sendError(resp, HttpServletResponse.SC_NOT_FOUND);
    }
}