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.cloud.servlet.StaticResourceServlet.java

@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    final File requestedFile = getRequestedFile(req);
    if (!requestedFile.exists() || !requestedFile.isFile()) {
        resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return;/*from  w  w w  .  j av  a2  s  .  c  o m*/
    }
    final String etag = getEtag(requestedFile);
    if (etag.equals(req.getHeader("If-None-Match"))) {
        resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }
    // have to send data, either compressed or the original
    final File compressedStatic = getCompressedVersion(requestedFile);
    InputStream fileContent = null;
    try {
        resp.setContentType(getContentType(requestedFile.getName()));
        resp.setHeader("ETag", etag);
        resp.setStatus(HttpServletResponse.SC_OK);
        if (isClientCompressionSupported(req) && compressedStatic.exists()) {
            // gzip compressed
            resp.setHeader("Content-Encoding", "gzip");
            resp.setContentLength((int) compressedStatic.length());
            fileContent = new FileInputStream(compressedStatic);
        } else {
            // uncompressed
            resp.setContentLength((int) requestedFile.length());
            fileContent = new FileInputStream(requestedFile);
        }
        IOUtils.copy(fileContent, resp.getOutputStream());
    } finally {
        IOUtils.closeQuietly(fileContent);
    }
}

From source file:org.fenixedu.bennu.spring.portal.PortalHandlerInterceptor.java

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
    PortalHandlerMethod handlerMethod = (PortalHandlerMethod) handler;
    if (handlerMethod.getFunctionality() == null) {
        // The requested controller does not map to a functionality
        return true;
    }/*  ww  w.  j  a v a2 s  .  com*/
    // If no functionality is selected, look it up from the current request
    if (BennuPortalDispatcher.getSelectedFunctionality(request) == null) {
        MenuFunctionality functionality = MenuFunctionality.findFunctionality(SpringPortalBackend.BACKEND_KEY,
                handlerMethod.getFunctionality().getKey());
        if (functionality == null) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND,
                    "The selected functionality is not configured");
            return false;
        }
        if (!functionality.isAvailableForCurrentUser()) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            return false;
        }
        BennuPortalDispatcher.selectFunctionality(request, functionality);
    }
    return true;
}

From source file:com.ningpai.common.util.CaptchaController.java

@RequestMapping("/captcha")
public void writeCaptcha(HttpServletRequest request, HttpServletResponse response) {
    byte[] captchaChallengeAsJpeg = null;
    // the output stream to render the captcha image as jpeg into
    ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
    try {/* w  ww. j  a va  2 s.co m*/
        // get the session id that will identify the generated captcha.
        // the same id must be used to validate the response, the session id is a good candidate!
        String captchaId = request.getSession().getId();
        BufferedImage challenge = captchaService.getImageChallengeForID(captchaId, request.getLocale());
        try {
            ImageIO.write(challenge, CAPTCHA_IMAGE_FORMAT, jpegOutputStream);
        } catch (IOException e) {
        }
    } catch (IllegalArgumentException e) {
        try {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        } catch (IOException e1) {
        }
        return;
    } catch (CaptchaServiceException e) {
        try {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } catch (IOException e1) {
        }
        return;
    }

    captchaChallengeAsJpeg = jpegOutputStream.toByteArray();

    // flush it in the response
    response.setHeader("Cache-Control", "no-store");
    response.setHeader("Pragma", "no-cache");
    response.setDateHeader("Expires", 0);
    response.setContentType("image/" + CAPTCHA_IMAGE_FORMAT);

    ServletOutputStream responseOutputStream;
    try {
        responseOutputStream = response.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();
    } catch (IOException e) {
    }

}

From source file:com.commsen.apropos.web.servlet.DownloadPropertiesServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String name = req.getParameter("name");
    if (StringUtils.isBlank(name)) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing package name!");
        return;//from   ww  w. ja v  a2  s. co  m
    }

    PropertyPackage propertyPackage = PropertiesManager.getPropertyPackage(name.trim());
    StringEscapeUtils.escapeHtml(name);
    if (propertyPackage == null) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND,
                "Property package called " + StringEscapeUtils.escapeHtml(name) + " was not found!");
        return;
    }

    String type = req.getParameter("type");
    if (StringUtils.isBlank(type)) {
        type = "properties";
    }

    if (type.toLowerCase().equals("properties")) {
        resp.setContentType("text/plain; charset=ASCI");
        propertyPackage.asProperties().store(resp.getOutputStream(),
                "Property file obtained from " + req.getLocalName());
    } else if (type.toLowerCase().equals("xml")) {
        resp.setContentType("text/xml; charset=UTF-8");
        propertyPackage.asProperties().storeToXML(resp.getOutputStream(),
                "Property file obtained from " + req.getRequestURI());
    } else {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST,
                "Unsupported type: " + StringEscapeUtils.escapeHtml(type) + " !");
        return;
    }

}

From source file:apps.loyalty.components.variable_002dimage.img_GET.java

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

    Image image = new Image(c.resource);
    image.setItemName(Image.NN_FILE, "image");
    image.setItemName(Image.PN_REFERENCE, "imageReference");
    if (!image.hasContent()) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;// w ww  . j av  a 2  s .  c o  m
    }

    // get style and set constraints
    image.set(Image.PN_MIN_WIDTH, c.properties.get("minWidth", ""));
    image.set(Image.PN_MIN_HEIGHT, c.properties.get("minHeight", ""));
    image.set(Image.PN_MAX_WIDTH, c.properties.get("maxWidth", ""));
    image.set(Image.PN_MAX_HEIGHT, c.properties.get("maxHeight", ""));

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

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

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

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

    UserProperties u = req.getResourceResolver().adaptTo(UserProperties.class);
    String name = u.getProperty(UserProperties.DISPLAY_NAME);
    if (name == null) {
        name = u.getAuthorizableID();
    }
    String prefix = c.properties.get("prefix", "");
    String suffix = c.properties.get("suffix", "");

    Font font = new Font("helvetica", 24);
    layer.setPaint(java.awt.Color.WHITE);
    int x = c.properties.get("x", 0);
    int y = c.properties.get("y", 0);
    layer.drawText(x, y, 0, 0, prefix + name + suffix, font, AbstractFont.ALIGN_LEFT, 0, 0);
    modified = true;

    if (modified) {
        resp.setContentType(c.requestImageType);
        layer.write(c.requestImageType, 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());
        String contentType = image.getMimeType();
        if (contentType.equals("application/octet-stream")) {
            contentType = c.requestImageType;
        }
        resp.setContentType(contentType);
        IOUtils.copy(in, resp.getOutputStream());
        in.close();
    }
    resp.flushBuffer();
}

From source file:libs.foundation.components.page.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  .ja v  a  2s .com*/
    }

    // 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);
    }
    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:org.shredzone.commons.gravatar.GravatarCacheServlet.java

@Override
protected void doService(HttpServletRequest req, HttpServletResponse resp) throws Exception {
    Matcher m = HASH_PATTERN.matcher(req.getPathInfo());
    if (!m.matches()) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;//  w w  w.j a  v  a2  s.  com
    }

    String hash = m.group(1);

    GravatarService gs = getWebApplicationContext().getBean("gravatarService", GravatarService.class);
    File gravatarFile = gs.fetchGravatar(hash);

    long modifiedSinceTs = -1;
    try {
        modifiedSinceTs = req.getDateHeader("If-Modified-Since");
    } catch (IllegalArgumentException ex) {
        // As stated in RFC2616 Sec. 14.25, an invalid date will just be ignored.
    }

    if (modifiedSinceTs >= 0 && (modifiedSinceTs / 1000L) == (gravatarFile.lastModified() / 1000L)) {
        // The image has not been modified since last request
        resp.sendError(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    long size = gravatarFile.length();
    if (size > 0 && size <= Integer.MAX_VALUE) {
        // Cast to int is safe
        resp.setContentLength((int) size);
    }

    resp.setContentType("image/png");
    resp.setDateHeader("Date", System.currentTimeMillis());
    resp.setDateHeader("Last-Modified", gravatarFile.lastModified());

    try (InputStream in = new FileInputStream(gravatarFile)) {
        FileCopyUtils.copy(in, resp.getOutputStream());
    }
}

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

/**
 * //from  ww w  . j  ava 2s  .c o m
 * @return a message string containing the number of the version of the backend.
 * @throws IOException if getting a principal or sending an error fails.
 */
@GET
@Produces(MediaType.TEXT_PLAIN)
@Path("version")
@Transactional(readOnly = true)
public String getVersion() throws IOException {
    Number principalID = this.getPrincipalID();
    String retVal = "?.?";
    ResourceBundle rb;
    try {
        rb = ResourceBundle.getBundle("projectinfo");
        retVal = rb.getString("application.version");
    } catch (MissingResourceException e) {
        httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
    }
    return "DWAN backend " + retVal;
}

From source file:net.zcarioca.jmx.servlet.handlers.RestRequestHandler.java

public void respond(HttpServletRequest request, HttpServletResponse response) throws IOException {
    try {//from   w  w  w.j  a va 2 s  .c  om
        Object value = getResponse(request);

        if (value != null) {
            response.setContentType(MediaType.APPLICATION_JSON);
            response.setCharacterEncoding("UTF-8");

            BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
            ObjectMapper mapper = new ObjectMapper();
            mapper.writeValue(out, value);

            out.flush();
            out.close();
        } else {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    } catch (InvalidObjectException exc) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
    } catch (IOException exc) {
        throw exc;
    } catch (Exception exc) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:com.collective.celos.servlet.JSONWorkflowServlet.java

protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException {
    String id = req.getParameter(CelosClient.ID_PARAM);
    try {/*from   w w w  .  j  a v  a2 s .  c  o m*/
        if (id == null) {
            res.sendError(HttpServletResponse.SC_BAD_REQUEST, CelosClient.ID_PARAM + " parameter missing.");
            return;
        }
        Scheduler scheduler = getOrCreateCachedScheduler();
        Workflow wf = scheduler.getWorkflowConfiguration().findWorkflow(new WorkflowID(id));
        if (wf == null) {
            res.sendError(HttpServletResponse.SC_NOT_FOUND, "Workflow not found: " + id);
        } else {
            ScheduledTime time = getRequestTime(req);
            try (StateDatabaseConnection connection = getStateDatabase().openConnection()) {
                List<SlotState> slotStates = scheduler.getSlotStates(wf,
                        scheduler.getWorkflowStartTime(wf, time), time, connection);
                ObjectNode object = createJSONObject(slotStates);
                writer.writeValue(res.getOutputStream(), object);
            }
        }
    } catch (Exception e) {
        throw new ServletException(e);
    }
}