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.activecq.experiments.pageimage.impl.PageImageServletImpl.java

@Override
protected void writeLayer(SlingHttpServletRequest slingRequest, SlingHttpServletResponse slingResponse,
        ImageContext imageContext, Layer layer) throws IOException, RepositoryException {

    final Image image = new Image(imageContext.resource);

    final String width = this.getDimension(PageImage.WIDTH, slingRequest);
    final String height = this.getDimension(PageImage.HEIGHT, slingRequest);

    final Resource pageImage = imageContext.resource.getParent();
    final ValueMap pageImageProperties = pageImage.adaptTo(ValueMap.class);

    image.set(Image.PN_REFERENCE, pageImageProperties.get(Image.PN_REFERENCE, String.class));

    if (isAllowedDimension(width, height, imageContext.resource)) {
        image.set(Image.PN_WIDTH, width);
        image.set(Image.PN_HEIGHT, height);
    }/*from w ww . ja va2  s  . c  o  m*/

    if (!image.hasContent()) {
        slingResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

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

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

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

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

        // apply diff if needed (because we create the layer inline)
        modified |= applyDiff(layer, imageContext);
    }

    if (modified) {
        // If the image is modified then adjust accordingly and write to the output stream
        String mimeType = image.getMimeType();

        if (ImageHelper.getExtensionFromType(mimeType) == null) {
            mimeType = DEFAULT_IMAGE_MIMETYPE;
        }

        slingResponse.setContentType(mimeType);
        layer.write(mimeType, mimeType.equals(GIF_IMAGE_MIMETYPE) ? 255 : 1.0, slingResponse.getOutputStream());
    } else {
        // Image has not been modified (crop, rotate, size) so simply original image data to output stream
        final Property data = image.getData();
        final InputStream in = data.getBinary().getStream();

        slingResponse.setContentLength((int) data.getLength());
        slingResponse.setContentType(image.getMimeType());

        IOUtils.copy(in, slingResponse.getOutputStream());
        in.close();
    }

    slingResponse.flushBuffer();
}

From source file:de.mpg.mpdl.inge.pidcache.web.MainServlet.java

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    logger.info("PID cache GET request");

    try {/*from   w  w w  . j a  va  2 s  . co m*/

        if (!authenticate(req, resp)) {
            logger.warn("Unauthorized request from " + req.getRemoteHost());
            return;
        }

        PidCacheService pidCacheService = new PidCacheService();

        if (GwdgPidService.GWDG_PIDSERVICE_VIEW.equals(req.getPathInfo())
                || GwdgPidService.GWDG_PIDSERVICE_VIEW.concat("/").equals(req.getPathInfo())) {
            if (req.getParameter("pid") == null) {
                resp.sendError(HttpServletResponse.SC_NO_CONTENT, "PID parameter failed.");
            }
            resp.getWriter().append(pidCacheService.retrieve(req.getParameter("pid")));
        } else if (GwdgPidService.GWDG_PIDSERVICE_FIND.equals(req.getPathInfo())
                || GwdgPidService.GWDG_PIDSERVICE_FIND.concat("/").equals(req.getPathInfo())) {
            if (req.getParameter("url") == null) {
                resp.sendError(HttpServletResponse.SC_NO_CONTENT, "URL parameter failed.");
            }
            resp.getWriter().append(pidCacheService.search(req.getParameter("url")));
        } else if ("/cache/size".equals(req.getPathInfo())) {
            resp.getWriter().append("There are " + pidCacheService.getCacheSize() + " PID stored in cache");
        } else if ("/queue/size".equals(req.getPathInfo())) {
            resp.getWriter().append("There are " + pidCacheService.getQueueSize() + " PID actually in queue");
        } else {
            resp.sendError(HttpServletResponse.SC_NOT_FOUND, req.getPathInfo());
        }
    } catch (Exception e) {
        throw new ServletException("Error processing request", e);
    }
}

From source file:com.sg.rest.SpringSecurityTest.java

@Test
public void testNonExistentResourceWhichStartsFromPublicPath() throws Exception {
    mockMvc.perform(get(RequestPath.TEST_REQUEST + PATH_DO_NOT_EXIST))
            .andExpect(status().is(HttpServletResponse.SC_NOT_FOUND)).andExpect(content().bytes(new byte[0]));
}

From source file:org.wiredwidgets.cow.server.web.TasksController.java

/**
 * Retrieve a single task by its ID/*from ww  w.j  a va 2s  . co  m*/
 *
 * @param id the task ID
 * @return the Task object as XML
 */
@RequestMapping("/active/{id}")
@ResponseBody
public Task getTask(@PathVariable("id") String id, HttpServletResponse response) {
    Task task = taskService.getTask(Long.valueOf(id));
    if (task == null) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return null;
    } else {
        return task;
    }
}

From source file:eu.dasish.annotation.backend.rest.PrincipalResource.java

/**
 * /*w  ww  .ja v a2 s .c  o  m*/
 * @param externalIdentifier the external UUID of a principal.
 * @return the {@link Principal} element representing the principal object with the "externalIdentifier".
 * @throws IOException is sending an error fails.
 */
@GET
@Produces(MediaType.TEXT_XML)
@Path("{principalid}")
@Transactional(readOnly = true)
public JAXBElement<Principal> getPrincipal(@PathParam("principalid") String externalIdentifier)
        throws IOException {
    Map params = new HashMap<String, String>();
    params.put("externalId", externalIdentifier);
    try {
        Principal result = (Principal) (new RequestWrappers(this)).wrapRequestResource(params,
                new GetPrincipal());
        return (result != null) ? (new ObjectFactory().createPrincipal(result))
                : (new ObjectFactory().createPrincipal(new Principal()));
    } catch (NotInDataBaseException e) {
        httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
        return new ObjectFactory().createPrincipal(new Principal());
    } catch (ForbiddenException e2) {
        httpServletResponse.sendError(HttpServletResponse.SC_FORBIDDEN, e2.getMessage());
        return new ObjectFactory().createPrincipal(new Principal());
    }
}

From source file:org.alfresco.module.demoscripts.RandomSelectWebScript.java

protected NodeRef getNodeRef(WebScriptRequest req) {
    // NOTE: This web script must be executed in a HTTP Servlet environment
    if (!(req instanceof WebScriptServletRequest)) {
        throw new WebScriptException("Content retrieval must be executed in HTTP Servlet environment");
    }/* w  ww.  j  a  va 2 s  .co  m*/
    HttpServletRequest httpReq = ((WebScriptServletRequest) req).getHttpServletRequest();

    // locate the root path
    String path = httpReq.getParameter("path");
    if (path == null) {
        path = "/images";
    }
    if (path.startsWith("/")) {
        path = path.substring(1);
    }

    // build a path elements list
    List<String> pathElements = new ArrayList<String>();
    StringTokenizer tokenizer = new StringTokenizer(path, "/");
    while (tokenizer.hasMoreTokens()) {
        String childName = tokenizer.nextToken();
        pathElements.add(childName);
    }

    // look up the child
    NodeRef nodeRef = null;
    try {
        NodeRef companyHomeRef = repository.getCompanyHome();
        nodeRef = registry.getFileFolderService().resolveNamePath(companyHomeRef, pathElements).getNodeRef();
    } catch (Exception ex) {
        throw new WebScriptException(HttpServletResponse.SC_NOT_FOUND, "Unable to locate path");
    }
    if (nodeRef == null) {
        throw new WebScriptException(HttpServletResponse.SC_NOT_FOUND, "Unable to locate path");
    }

    return nodeRef;
}

From source file:net.sourceforge.vulcan.web.ProjectFileServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    final String pathInfo = request.getPathInfo();

    if (isBlank(pathInfo)) {
        response.sendRedirect(request.getContextPath());
        return;//from   www.j  a v a 2 s. co  m
    }

    final PathInfo projPathInfo = getProjectNameAndBuildNumber(pathInfo);

    if (isBlank(projPathInfo.projectName)) {
        response.sendRedirect(request.getContextPath());
        return;
    }

    final ProjectConfigDto projectConfig;

    try {
        projectConfig = projectManager.getProjectConfig(projPathInfo.projectName);
    } catch (NoSuchProjectException e) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    final String requestURI = request.getRequestURI();

    if (projPathInfo.buildNumber < 0) {
        redirectWithBuildNumber(response, projPathInfo, requestURI);
        return;
    }

    final ProjectStatusDto buildOutcome = buildManager.getStatusByBuildNumber(projPathInfo.projectName,
            projPathInfo.buildNumber);

    if (buildOutcome == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND,
                "No such build " + projPathInfo.buildNumber + " for project Project.");
        return;
    }

    final String workDir;

    if (StringUtils.isNotBlank(buildOutcome.getWorkDir())) {
        workDir = buildOutcome.getWorkDir();
    } else {
        workDir = projectConfig.getWorkDir();
    }

    final File file = getFile(workDir, pathInfo, true);

    if (!file.exists()) {
        if (shouldFallback(request, workDir, file)) {
            response.sendRedirect(getFallbackParentPath(request, workDir));
            return;
        }
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    } else if (!file.canRead()) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    } else if (file.isDirectory()) {
        if (!pathInfo.endsWith("/")) {
            response.sendRedirect(requestURI + "/");
            return;
        }

        final File[] files = getDirectoryListing(file);

        request.setAttribute(Keys.DIR_PATH, pathInfo);
        request.setAttribute(Keys.FILE_LIST, files);

        request.getRequestDispatcher(Keys.FILE_LIST_VIEW).forward(request, response);
        return;
    }

    setContentType(request, response, pathInfo);

    final Date lastModifiedDate = new Date(file.lastModified());

    if (!checkModifiedSinceHeader(request, lastModifiedDate)) {
        response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    response.setStatus(HttpServletResponse.SC_OK);

    setLastModifiedDate(response, lastModifiedDate);

    response.setContentLength((int) file.length());

    final FileInputStream fis = new FileInputStream(file);
    final ServletOutputStream os = response.getOutputStream();

    sendFile(fis, os);
}

From source file:com.epam.catgenome.controller.util.MultipartFileSender.java

public void serveResource() throws IOException {
    if (response == null || request == null) {
        return;/*from   www  . ja  va2 s.com*/
    }

    if (!Files.exists(filepath)) {
        logger.error("File doesn't exist at URI : {}", filepath.toAbsolutePath().toString());
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    Long length = Files.size(filepath);
    String fileName = filepath.getFileName().toString();
    FileTime lastModifiedObj = Files.getLastModifiedTime(filepath);

    if (StringUtils.isEmpty(fileName) || lastModifiedObj == null) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }
    long lastModified = LocalDateTime
            .ofInstant(lastModifiedObj.toInstant(), ZoneId.of(ZoneOffset.systemDefault().getId()))
            .toEpochSecond(ZoneOffset.UTC);
    //String contentType = MimeTypeUtils.probeContentType(filepath);
    String contentType = null;

    // Validate request headers for caching ---------------------------------------------------
    if (!validateHeadersCaching(fileName, lastModified)) {
        return;
    }

    // Validate request headers for resume ----------------------------------------------------
    if (!validateHeadersResume(fileName, lastModified)) {
        return;
    }

    // Validate and process range -------------------------------------------------------------
    Range full = new Range(0, length - 1, length);
    List<Range> ranges = processRange(length, fileName, full);
    if (ranges == null) {
        return;
    }

    // Prepare and initialize response --------------------------------------------------------

    // Get content type by file name and set content disposition.
    String disposition = "inline";

    // If content type is unknown, then set the default value.
    // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp
    // To add new content types, add new mime-mapping entry in web.xml.
    if (contentType == null) {
        contentType = "application/octet-stream";
    } else if (!contentType.startsWith("image")) {
        // Else, expect for images, determine content disposition. If content type is supported by
        // the browser, then set to inline, else attachment which will pop a 'save as' dialogue.
        String accept = request.getHeader("Accept");
        disposition = accept != null && HttpUtils.accepts(accept, contentType) ? "inline" : "attachment";
    }
    logger.debug("Content-Type : {}", contentType);
    // Initialize response.
    response.reset();
    response.setBufferSize(DEFAULT_BUFFER_SIZE);
    response.setHeader("Content-Type", contentType);
    response.setHeader("Content-Disposition", disposition + ";filename=\"" + fileName + "\"");
    logger.debug("Content-Disposition : {}", disposition);
    response.setHeader("Accept-Ranges", "bytes");
    response.setHeader("ETag", fileName);
    response.setDateHeader("Last-Modified", lastModified);
    response.setDateHeader("Expires", System.currentTimeMillis() + DEFAULT_EXPIRE_TIME);

    // Send requested file (part(s)) to client ------------------------------------------------

    // Prepare streams.
    try (InputStream input = new BufferedInputStream(Files.newInputStream(filepath));
            OutputStream output = response.getOutputStream()) {

        if (ranges.isEmpty() || ranges.get(0) == full) {

            // Return full file.
            logger.info("Return full file");
            response.setContentType(contentType);
            response.setHeader(CONTENT_RANGE_HEADER, "bytes " + full.start + "-" + full.end + "/" + full.total);
            response.setHeader("Content-Length", String.valueOf(full.length));
            Range.copy(input, output, length, full.start, full.length);

        } else if (ranges.size() == 1) {

            // Return single part of file.
            Range r = ranges.get(0);
            logger.info("Return 1 part of file : from ({}) to ({})", r.start, r.end);
            response.setContentType(contentType);
            response.setHeader(CONTENT_RANGE_HEADER, "bytes " + r.start + "-" + r.end + "/" + r.total);
            response.setHeader("Content-Length", String.valueOf(r.length));
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206.

            // Copy single part range.
            Range.copy(input, output, length, r.start, r.length);

        } else {

            // Return multiple parts of file.
            response.setContentType("multipart/byteranges; boundary=" + MULTIPART_BOUNDARY);
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206.

            // Cast back to ServletOutputStream to get the easy println methods.
            ServletOutputStream sos = (ServletOutputStream) output;

            // Copy multi part range.
            for (Range r : ranges) {
                logger.info("Return multi part of file : from ({}) to ({})", r.start, r.end);
                // Add multipart boundary and header fields for every range.
                sos.println();
                sos.println("--" + MULTIPART_BOUNDARY);
                sos.println("Content-Type: " + contentType);
                sos.println("Content-Range: bytes " + r.start + "-" + r.end + "/" + r.total);

                // Copy single part range of multi part range.
                Range.copy(input, output, length, r.start, r.length);
            }

            // End with multipart boundary.
            sos.println();
            sos.println("--" + MULTIPART_BOUNDARY + "--");
        }
    }

}

From source file:fr.norad.servlet.sample.html.template.IndexTemplateServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    if (template == null) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;//from ww  w  .j a  v a 2  s . c  o  m
    }

    HashMap<String, String> hashMap = new HashMap<>(properties);
    String contextPath = req.getContextPath();
    if (contextPathSuffix != null && !contextPathSuffix.equals("")) {
        contextPath += contextPathSuffix;
    }
    hashMap.put("contextPath", contextPath);
    hashMap.put("fullWebPath", req.getRequestURL().toString().replace(req.getRequestURI(), contextPath));

    String response = StrSubstitutor.replace(template, hashMap);

    resp.setStatus(200);
    resp.setContentType("text/html; charset=utf-8");
    resp.getWriter().write(response);
}