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.basicservice.controller.UserController.java

@RequestMapping(method = RequestMethod.GET)
@ResponseBody/*  www  . ja v a 2  s .  c  o m*/
public User findLoggedinUser(
        @CookieValue(value = Constants.AUTHENTICATED_USER_ID_COOKIE, required = false) UUIDValidatedString userIdCookie,
        HttpServletResponse response) {
    User user = userService.getUserFromValidatedSessionId(userIdCookie);
    if (user != null) {
        return user;
    } else {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return null;
    }
}

From source file:eu.planets_project.tb.impl.data.util.TBDigitalObjectContentResolver.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    InputStream is = null;/*from w ww.  j  ava2  s .  c o  m*/
    String id = request.getParameter(ID_PARAMETER_NAME);

    try {
        if (id == null)
            throw new DigitalObjectNotFoundException("id is null");

        // Fix up any encoding issues:
        id = PDURI.encodePlanetsUriStringAsUri(id).toASCIIString();

        DigitalObjectRefBean digoRef = dh.get(id);
        if (digoRef == null)
            throw new DigitalObjectNotFoundException("digital object " + id + " not found");

        // set the metadata if it's contained within the digital object
        DigitalObject object = digoRef.getDigitalObject();
        for (Metadata md : object.getMetadata()) {
            if (md.getName().equals(MIME_TYPE_METADATA_NAME))
                response.setContentType(md.getContent());
        }

        is = digoRef.getContentAsStream();

        // read from input stream and write to client
        int bytesRead = 0;
        byte[] buffer = new byte[BUFFER_SIZE];
        while ((bytesRead = is.read(buffer)) != -1) {
            response.getOutputStream().write(buffer, 0, bytesRead);
        }
    } catch (DigitalObjectNotFoundException e) {
        log.info(e.getMessage(), e);
        response.sendError(HttpServletResponse.SC_NOT_FOUND, "object not found with id=" + id);
    } finally {
        if (is != null)
            is.close();
    }
}

From source file:org.jasig.portlet.announcements.controller.RssFeedController.java

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

    response.setContentType(CONTENT_TYPE);

    Long topicId;//from   ww  w . j ava 2 s. c  om
    try {
        topicId = Long.valueOf(ServletRequestUtils.getIntParameter(request, "topic"));
        if (topicId == null) {
            throw new IllegalStateException("Must specify the topic id");
        }
    } catch (Exception e) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Must specify topic id");
        return null;
    }

    Topic t = null;
    try {
        t = announcementService.getTopic(topicId);
    } catch (PortletException e) {
        e.printStackTrace();
    }

    if (t == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND, "no such topic");
        return null;
    }

    if (!t.isAllowRss()) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN, "This topic is not available as RSS");
        return null;
    }

    // fetch and sort the announcements
    List<Announcement> announcements = new ArrayList<Announcement>();
    announcements.addAll(t.getPublishedAnnouncements());

    Collections.sort(announcements);

    // create the feed
    SyndFeed feed = new SyndFeedImpl();
    feed.setFeedType("rss_2.0");
    feed.setTitle(t.getTitle());
    feed.setLink(request.getRequestURL().append("?topic=").append(topicId.toString()).toString());
    feed.setDescription(t.getDescription());

    List<SyndEntry> entries = new ArrayList<SyndEntry>();
    SyndEntry entry;
    SyndContent description;

    for (Announcement a : announcements) {
        entry = new SyndEntryImpl();
        entry.setTitle(a.getTitle());
        entry.setAuthor(a.getAuthor());
        if (a.getLink() != null)
            entry.setLink(a.getLink());
        entry.setPublishedDate(a.getStartDisplay());
        description = new SyndContentImpl();
        description.setType("text/plain");
        description.setValue(a.getMessage());
        entry.setDescription(description);
        entries.add(entry);
    }

    feed.setEntries(entries);

    SyndFeedOutput output = new SyndFeedOutput();
    String out;
    try {
        out = output.outputString(feed);
    } catch (FeedException e) {
        e.printStackTrace();
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error generating feed");
        return null;
    }

    response.setContentLength(out.length());
    response.getOutputStream().print(out);
    response.getOutputStream().flush();

    return null;

}

From source file:org.shept.services.jcaptcha.ImageCaptchaServlet.java

@SuppressWarnings("unchecked")
protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
        throws ServletException, IOException {
    BufferedImage challenge = null;
    try {/*  www. java  2 s.c  o  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 = httpServletRequest.getSession().getId();

        // If we have an explicit configuration for an ImageService we use this
        // else we use the predefined default
        ImageCaptchaService captchaService = CaptchaServiceSingleton.getInstance();
        Map services = ctx.getBeansOfType(ImageCaptchaService.class);
        // there must be exactly on service configured
        if (services.size() == 1) {
            for (Iterator iterator = services.values().iterator(); iterator.hasNext();) {
                captchaService = (ImageCaptchaService) iterator.next();
            }
        }

        // call the ImageCaptchaService getChallenge method
        challenge = captchaService.getImageChallengeForID(captchaId, httpServletRequest.getLocale());

    } catch (IllegalArgumentException e) {
        httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    } catch (CaptchaServiceException e) {
        httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }
    // flush it 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();
    ImageIO.write(challenge, "jpeg", responseOutputStream);
    responseOutputStream.flush();
    responseOutputStream.close();
}

From source file:com.cloudera.oryx.als.serving.web.EstimateForAnonymousServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

    CharSequence pathInfo = request.getPathInfo();
    if (pathInfo == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No path");
        return;/* w  w w. j a  va2s. c  o  m*/
    }
    Iterator<String> pathComponents = SLASH.split(pathInfo).iterator();
    String toItemID;
    Pair<String[], float[]> itemIDsAndValue;
    try {
        toItemID = pathComponents.next();
        itemIDsAndValue = RecommendToAnonymousServlet.parseItemValuePairs(pathComponents);
    } catch (NoSuchElementException nsee) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, nsee.toString());
        return;
    }

    if (itemIDsAndValue.getFirst().length == 0) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No items");
        return;
    }

    String[] itemIDs = itemIDsAndValue.getFirst();
    unescapeSlashHack(itemIDs);
    float[] values = itemIDsAndValue.getSecond();

    OryxRecommender recommender = getRecommender();
    try {
        float estimate = recommender.estimateForAnonymous(toItemID, itemIDs, values);
        Writer out = response.getWriter();
        out.write(Float.toString(estimate));
        out.write('\n');
    } catch (NotReadyException nre) {
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, nre.toString());
    } catch (NoSuchItemException nsie) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND, nsie.toString());
    }
}

From source file:jp.terasoluna.fw.web.struts.actions.LogoffAction.java

/**
 * ?OIt???s?BHTTPZbV?A//from  w  w w . j a v  a 2s.  co m
 * parameter??J?
 * ANVtH??[hZbg?B
 * parameter?????A?i404?jG?[?B
 *
 * @param mapping ANV}bsO
 * @param form ANVtH?[
 * @param req HTTPNGXg
 * @param res HTTPX|X
 * @return J?ANVtH??[h
 */
@Override
public ActionForward doExecute(ActionMapping mapping, ActionForm form, HttpServletRequest req,
        HttpServletResponse res) {
    if (log.isDebugEnabled()) {
        log.debug("doExecute() called.");
    }

    // pZbV
    HttpSession session = req.getSession(false);
    if (session != null) {
        session.invalidate();
    }

    // parameter??itH??[h??j
    String path = mapping.getParameter();

    if (path == null) {
        // parameter?????A?i404?jG?[p
        try {
            res.sendError(HttpServletResponse.SC_NOT_FOUND);
        } catch (IOException e) {
            log.error("Error page(404) forwarding failed.");

            throw new SystemException(e, FORWARD_ERRORPAGE_ERROR);
        }
        return null;
    }

    // ANVtH??[h??
    ActionForward retVal = new ActionForward(path);

    return retVal;
}

From source file:com.cognifide.cq.cqsm.core.servlets.ScriptRunServlet.java

@Override
protected void doPost(final SlingHttpServletRequest request, final SlingHttpServletResponse response)
        throws ServletException, IOException {
    ResourceResolver resolver = request.getResourceResolver();
    final String searchPath = request.getParameter("file");
    final String modeName = request.getParameter("mode");

    if (StringUtils.isEmpty(searchPath)) {
        ServletUtils.writeMessage(response, "error", "Please set the script file name: -d \"file=[name]\"");
        return;/*from  w w  w .j a  v a  2  s .co  m*/
    }

    if (StringUtils.isEmpty(modeName)) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        ServletUtils.writeMessage(response, "error", "Running mode not specified.");
        return;
    }

    final Script script = scriptFinder.find(searchPath, resolver);
    if (script == null) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        ServletUtils.writeMessage(response, "error", String.format("Script not found: %s", searchPath));
        return;
    }

    try {
        final Mode mode = Mode.fromString(modeName, Mode.DRY_RUN);
        final Progress progressLogger = scriptManager.process(script, mode, resolver);

        if (progressLogger.isSuccess()) {
            ServletUtils.writeJson(response, ProgressHelper.toJson(progressLogger.getEntries()));
        } else {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            ServletUtils.writeJson(response, ProgressHelper.toJson(progressLogger.getLastError()));
        }

    } catch (RepositoryException e) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        ServletUtils.writeMessage(response, "error", String
                .format("Script cannot be executed because of" + " repository error: %s", e.getMessage()));
    }
}

From source file:com.janrain.backplane2.server.dao.redis.RedisBackplaneMessageDAO.java

@NotNull
@Override/* ww  w .  jav  a2  s  . c  om*/
public BackplaneMessage retrieveBackplaneMessage(@NotNull String messageId, @NotNull Token token)
        throws BackplaneServerException, TokenException {

    BackplaneMessage message = get(messageId);

    if (message == null || !token.getScope().isMessageInScope(message)) {
        // don't disclose that the messageId exists if not in scope
        throw new TokenException("Message id '" + messageId + "' not found", HttpServletResponse.SC_NOT_FOUND);
    } else {
        return message;
    }
}

From source file:com.cognifide.cq.cqsm.core.servlets.ScriptReplicationServlet.java

@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
        throws ServletException, IOException {
    ResourceResolver resolver = request.getResourceResolver();

    final String searchPath = request.getParameter("fileName");
    final String run = request.getParameter("run");

    if (StringUtils.isEmpty(searchPath)) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        ServletUtils.writeMessage(response, "error", "File name parameter is required");
        return;/* w  ww .  j  ava2 s  . com*/
    }

    final Script script = scriptFinder.find(searchPath, resolver);
    if (script == null) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        ServletUtils.writeMessage(response, "error", String.format("Script cannot be found: %s", searchPath));
        return;
    }

    final String scriptPath = script.getPath();

    try {
        final ModifiableScript modifiableScript = new ModifiableScriptWrapper(resolver, script);
        if (PUBLISH_RUN.equals(run)) {
            modifiableScript.setPublishRun(true);
        }
        scriptReplicator.replicate(script, resolver);

        ServletUtils.writeMessage(response, "success",
                String.format("Script '%s' replicated successfully", scriptPath));
    } catch (PersistenceException e) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        ServletUtils.writeMessage(response, "error",
                String.format("Script '%s' cannot be processed because of" + " repository error: %s",
                        scriptPath, e.getMessage()));
    } catch (ExecutionException e) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        ServletUtils.writeMessage(response, "error",
                String.format("Script '%s' cannot be processed: %s", scriptPath, e.getMessage()));
    } catch (ReplicationException e) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        ServletUtils.writeMessage(response, "error",
                String.format("Script '%s' cannot be replicated: %s", scriptPath, e.getMessage()));
    }
}

From source file:gallery.web.controller.wallpaper.WallpaperResizeController.java

@RequestMapping(value = "/{resolutionX}x{resolutionY}/{wallpaper:.*}", method = RequestMethod.GET)
public void resizeWallpaper(@PathVariable("resolutionX") Integer resolutionX,
        @PathVariable("resolutionY") Integer resolutionY, @PathVariable("wallpaper") String wallpaper,
        HttpServletResponse response) {/*from w  w  w .j a  va 2 s . c  o  m*/
    if (resolutionX > 0 && resolutionY > 0 && resolutionService.getRowCount(RESOLUTION_WIDTH_HEIGHT,
            new Object[] { resolutionX, resolutionY }) == 1) {
        try {
            statisticService.increaseStat(resolutionX + "x" + resolutionY + ":start_resize", 1);
            IOutputStreamHolder osh = HttpResponseOutputStreamHolder.getInstance(response);
            if (wallpaperService.getResizedWallpaperStream(wallpaper, resolutionX, resolutionY, osh)) {
                statisticService.increaseStat(resolutionX + "x" + resolutionY + ":finish_resize", 1);
            } else {
                //error handling
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
            }
            osh.closeAndFlushOutputStream();
        } catch (IOException ex) {
            logger.error("while resizing image and writing it to output stream(response) ");
        }
        return;
    }
    try {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    } catch (IOException ex) {
        logger.error("while sending a not found status ");
    }
}