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.octo.captcha.module.struts.image.RenderImageCaptchaAction.java

public ActionForward execute(ActionMapping actionMapping, ActionForm actionForm,
        HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {

    ImageCaptchaService service = (ImageCaptchaService) CaptchaServicePlugin.getInstance().getService();
    String captchaID = CaptchaModuleConfigHelper.getId(httpServletRequest);
    //(String) theRequest.getParameter(captchaIDParameterName);

    // call the ManageableImageCaptchaService methods
    byte[] captchaChallengeAsJpeg = null;
    ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
    try {//from   w  ww  .  ja  v a  2s.c om
        BufferedImage challenge = service.getImageChallengeForID(captchaID, httpServletRequest.getLocale());
        // the output stream to render the captcha image as jpeg into

        // a jpeg encoder
        JPEGImageEncoder jpegEncoder = JPEGCodec.createJPEGEncoder(jpegOutputStream);
        jpegEncoder.encode(challenge);
    } catch (IllegalArgumentException e) {
        // log a security warning and return a 404...
        if (log.isWarnEnabled()) {
            log.warn("There was a try from " + httpServletRequest.getRemoteAddr()
                    + " to render an URL without ID" + " or with a too long one");
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            log.error("should never pass here!");
            return actionMapping.findForward("error");
        }
    } catch (CaptchaServiceException e) {
        // log and return a 404 instead of an image...
        log.warn("Error trying to generate a captcha and " + "render its challenge as JPEG", e);
        httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
        // log.error("should never pass here!");
        return actionMapping.findForward("error");
    }

    captchaChallengeAsJpeg = jpegOutputStream.toByteArray();

    // render the captcha challenge as a JPEG image in the response
    httpServletResponse.setHeader("Cache-Control", "no-store");
    httpServletResponse.setHeader("Pragma", "no-cache");
    httpServletResponse.setDateHeader("Expires", 0);
    httpServletResponse.setContentType("image/jpeg");
    ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
    responseOutputStream.write(captchaChallengeAsJpeg);
    responseOutputStream.flush();
    responseOutputStream.close();
    // log.error("should never pass here!");
    return null;
}

From source file:com.kolich.curacao.embedded.mappers.ClasspathFileReturnMapper.java

@Override
public final void render(final AsyncContext context, final HttpServletResponse response,
        final @Nonnull File entity) throws Exception {
    // Get the path, and remove the leading slash.
    final String path = entity.getAbsolutePath().substring(1);
    final ClassLoader loader = Thread.currentThread().getContextClassLoader();
    final URL resource = loader.getResource(path);
    if (resource == null) {
        logger__.warn("Resource not found: {}", path);
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
    } else {/*  w  w  w . ja  va 2s.c  om*/
        logger__.debug("Serving resource from classpath: {}", path);
        try (final InputStream in = loader.getResourceAsStream(path);
                final OutputStream out = response.getOutputStream()) {
            IOUtils.copyLarge(in, out);
        }
    }
}

From source file:es.tid.cep.esperanza.Rules.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request/* w w  w  .ja v a 2s  . com*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    response.setContentType("application/json;charset=UTF-8");
    try {
        String ruleName = request.getPathInfo();
        ruleName = ruleName == null ? "" : ruleName.substring(1);
        logger.debug("rule asked for " + ruleName);
        EPAdministrator epa = epService.getEPAdministrator();

        if (ruleName.length() != 0) {
            EPStatement st = epa.getStatement(ruleName);
            if (st == null) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                out.printf("{\"error\":\"%s not found\"}\n", ruleName);
            } else {
                out.println(Utils.Statement2JSONObject(st));
            }
        } else {
            String[] sttmntNames = epa.getStatementNames();
            JSONArray ja = new JSONArray();
            for (String name : sttmntNames) {
                logger.debug("getting rule " + name);
                EPStatement st = epa.getStatement(name);
                ja.put(Utils.Statement2JSONObject(st));
            }
            out.println(ja.toString());
        }

    } catch (EPException epe) {
        logger.error("getting statement", epe);
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        out.printf("{\"error\":%s}\n", JSONObject.valueToString(epe.getMessage()));
    } finally {
        out.close();
    }
}

From source file:com.orange.mmp.mvc.bundle.Controller.java

@SuppressWarnings("unchecked")
@Override/*  w  w w .  j a v a2 s .c o  m*/
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    int pathInfoStart = request.getRequestURI().indexOf(urlMapping);
    if (pathInfoStart < 0) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        response.setContentLength(0);
        return null;
    }
    // Get user agent to obtain branchID
    String userAgent = request.getHeader(Constants.HTTP_HEADER_USERAGENT);
    Mobile mobile = new Mobile();
    mobile.setUserAgent(userAgent);
    Mobile[] mobiles = (Mobile[]) DaoManagerFactory.getInstance().getDaoManager().getDao("mobile").find(mobile);
    String branchId = null;//Constants.DEFAULT_BRANCH_ID;
    if (mobiles != null && mobiles.length > 0) {
        branchId = mobiles[0].getBranchId();
    } else {
        Branch branch = new Branch();
        branch.setDefault(true);
        Branch[] branches = (Branch[]) DaoManagerFactory.getInstance().getDaoManager().getDao("branch")
                .find(branch);
        if (branches != null && branches.length > 0)
            branchId = branches[0].getId();
    }

    String pathInfo = request.getRequestURI().substring(pathInfoStart + urlMapping.length());
    String requestParts[] = pathInfo.split("/");
    String widgetId = null;
    String resourceName = null;
    InputStream input = null;

    if (requestParts.length > 2) {
        widgetId = requestParts[1];
        resourceName = pathInfo.substring(widgetId.length() + 2);
    } else {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        response.setContentLength(0);
        return null;
    }

    input = WidgetManager.getInstance().getWidgetResource(resourceName, widgetId, branchId);

    if (input == null) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        response.setContentLength(0);
    } else {
        ByteArrayOutputStream resourceBuffer = new ByteArrayOutputStream();
        OutputStream output = response.getOutputStream();
        try {
            IOUtils.copy(input, resourceBuffer);
            response.setContentLength(resourceBuffer.size());
            resourceBuffer.writeTo(output);
        } catch (IOException ioe) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.setContentLength(0);
        } finally {
            if (input != null)
                input.close();
            if (output != null)
                output.close();
            if (resourceBuffer != null)
                resourceBuffer.close();
        }
    }
    return null;
}

From source file:com.cradiator.TeamCityStatusPlugin.BuildMonitorController.java

private ModelAndView showProject(String projectId, HttpServletResponse response) throws IOException {
    SProject project = projectManager.findProjectById(projectId);
    if (project == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND, "no project with id " + projectId);
        return null;
    }/*from   w w w.java 2 s . c  o m*/
    return modelWithView("project-status.jsp").addObject("project", new ProjectMonitorViewState(project));
}

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

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

    // check if asset path is valid
    if (!damPathHandler.isAllowedAssetPath(assetPath)) {
        log.debug("Asset path not allowed {}", assetPath);
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;/*from w w  w .j ava2s  . c om*/
    }

    // get media handler
    MediaHandler mediaHandler = request.getResource().adaptTo(MediaHandler.class);
    if (mediaHandler == null) {
        log.debug("Unable to get media handler for {}", assetPath);
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // build list of asset service requests with optional input parameters
    List<AssetRequest> requests = getAssetRequests(assetPath, request);

    // resolve asset service requests
    List<Media> mediaList = resolveMedia(requests, mediaHandler);
    if (mediaList.size() == 0) {
        log.debug("No matching assets/renditions found for {}; requests: {}", assetPath, requests);
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // output result json
    try {
        JSONArray resultJson = toResultJson(mediaList);
        response.setContentType(ContentType.JSON);
        response.setCharacterEncoding(CharEncoding.UTF_8);
        response.getWriter().write(resultJson.toString());
    } catch (JSONException ex) {
        throw new ServletException("Unable to generate JSON.", ex);
    }
}

From source file:me.chester.myretweetedtweets.RetrieveTweetsServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String path = request.getPathInfo();
    String callback = request.getParameter("callback");
    PrintWriter out = response.getWriter();
    if (path != null && path.length() > 1) {
        try {//  w  w w. ja  va 2  s  .c  o m
            long id = Long.parseLong(path.substring(1));
            String json = getJsonWithCache(id, callback);
            response.setContentType("application/json");
            out.write(json);
            return;
        } catch (NumberFormatException e) {
            // Invalid id, will be treated as 404-not-found below
        } catch (EntityNotFoundException e) {
            // Invalid id, will be treated as 404-not-found below
        } catch (TwitterException e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            out.write("Error retrieving tweets. Maybe you should re-authorize?");
        } catch (CacheException e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            out.write("Error with Memcache. We are all doomed.");
        }
    }
    response.setStatus(HttpServletResponse.SC_NOT_FOUND);
    out.write("Invalid URL. Try authorizing again to get a valid one");
}

From source file:io.wcm.wcm.ui.extjs.provider.AbstractPageProvider.java

@Override
protected final void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
        throws ServletException, IOException {

    // determine root resource
    Resource rootResource = getRootResource(request);
    if (rootResource == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;// ww  w .  j ava2 s . com
    }

    response.setContentType(ContentType.JSON);

    try {
        PageFilter pageFilter = getPageFilter(request);
        JSONArray jsonContent = getJsonContent(rootResource, pageFilter);
        response.getWriter().write(jsonContent.toString());
    } catch (Throwable ex) {
        log.error("Unexpected error, rethrow as servlet exception.", ex);
        throw new ServletException(ex);
    }
}

From source file:jetbrains.buildServer.torrent.web.DownloadTorrentController.java

@Override
protected ModelAndView doHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response)
        throws Exception {
    String buildIdParam = request.getParameter("buildId");
    String path = request.getParameter("file");
    String torrentPath = path + TorrentUtil.TORRENT_FILE_SUFFIX;

    File torrentFile = null;/*w  w w. j  a  va 2s.  c o  m*/
    long buildId = Long.parseLong(buildIdParam);
    SBuild build = myBuildsManager.findBuildInstanceById(buildId);
    if (build != null) {
        torrentFile = myTorrentsManager.getTorrentFile(build, torrentPath);
        if (!torrentFile.isFile()) {
            torrentFile = null;
        }
    }

    if (torrentFile == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    } else {
        response.setContentType(WebUtil.getMimeType(request, torrentFile.getName()));
        // force set content-disposition to attachment
        WebUtil.setContentDisposition(request, response, torrentFile.getName(), false);
        ServletOutputStream output = response.getOutputStream();
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(torrentFile);
            StreamUtil.copyStreamContent(fis, output);
        } finally {
            FileUtil.close(fis);
            output.close();
        }
    }

    return null;
}

From source file:org.onlab.stc.MonitorWebSocketServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String uri = req.getRequestURI();
    uri = uri.length() <= 1 ? "/index.html" : uri;
    InputStream resource = getClass().getResourceAsStream(uri);
    if (resource == null) {
        resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
    } else {/*from ww  w  .j a va2 s  .co  m*/
        byte[] entity = ByteStreams.toByteArray(resource);
        resp.setStatus(HttpServletResponse.SC_OK);
        resp.setContentType(contentType(uri).toString());
        resp.setContentLength(entity.length);
        resp.getOutputStream().write(entity);
    }
}