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:info.magnolia.rendering.engine.RenderingFilterTest.java

@Test
public void testDoFilterWithNullTemplateName() throws Exception {
    MgnlContext.setInstance(new MockWebContext());

    // GIVEN//www  . jav a2s. c  om
    RenderingFilter filter = new RenderingFilter(renderingEngine, templateDefinitionRegistry);

    // WHEN
    filter.doFilter(request, response, chain);

    // THEN - doFilter could not properly be executed so when ended up with an Error.
    verify(response).sendError(HttpServletResponse.SC_NOT_FOUND);
}

From source file:eionet.cr.web.action.TabularDataServlet.java

/**
 *
 * @param message//from  w w  w.j  a v  a 2 s  .  com
 * @param request
 * @param response
 * @throws ServletException
 * @throws IOException
 */
private void handleFileNotFound(String message, HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    LOGGER.info(message);

    if (Util.isWebBrowser(request)) {
        request.setAttribute(StripesExceptionHandler.EXCEPTION_ATTR, new CRException(message));
        request.getRequestDispatcher(StripesExceptionHandler.ERROR_PAGE).forward(request, response);
    } else {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    }
}

From source file:com.google.gerrit.httpd.auth.openid.OAuthSessionOverOpenID.java

boolean login(HttpServletRequest request, HttpServletResponse response, OAuthServiceProvider oauth)
        throws IOException {
    log.debug("Login " + this);

    if (isOAuthFinal(request)) {
        if (!checkState(request)) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return false;
        }/*from  ww w. ja  v a  2s. c  o m*/

        log.debug("Login-Retrieve-User " + this);
        token = oauth.getAccessToken(new OAuthVerifier(request.getParameter("code")));
        user = oauth.getUserInfo(token);

        if (isLoggedIn()) {
            log.debug("Login-SUCCESS " + this);
            authenticateAndRedirect(request, response);
            return true;
        }
        response.sendError(SC_UNAUTHORIZED);
        return false;
    }
    log.debug("Login-PHASE1 " + this);
    redirectToken = LoginUrlToken.getToken(request);
    response.sendRedirect(oauth.getAuthorizationUrl() + "&state=" + state);
    return false;
}

From source file:com.cloudera.oryx.als.serving.web.RecommendToAnonymousServlet.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;//from   w w  w . j a va  2s .  c o m
    }
    Iterator<String> pathComponents = SLASH.split(pathInfo).iterator();
    Pair<String[], float[]> itemIDsAndValue;
    try {
        itemIDsAndValue = 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();
    float[] values = itemIDsAndValue.getSecond();

    OryxRecommender recommender = getRecommender();
    RescorerProvider rescorerProvider = getRescorerProvider();
    try {
        Rescorer rescorer = rescorerProvider == null ? null
                : rescorerProvider.getRecommendToAnonymousRescorer(itemIDs, recommender,
                        getRescorerParams(request));
        output(response, recommender.recommendToAnonymous(itemIDs, values, getHowMany(request), rescorer));
    } catch (NotReadyException nre) {
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, nre.toString());
    } catch (NoSuchItemException nsie) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND, nsie.toString());
    } catch (IllegalArgumentException iae) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, iae.toString());
    }
}

From source file:common.web.servlets.StaticFilesServlet.java

/** 
 * Handles the HTTP <code>GET</code> method.
 * @param request servlet request//from   w  w  w.j  ava2  s.  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 {
    String name = getResourceName(request.getPathInfo());

    if (name == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND, "Not Found");
        return;
    }

    File file = new File(realPath, name);

    if (!file.exists()) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND, "Not Found");
        return;
    }

    //delete after testing
    //synchronized(semaphore){
    long time = System.nanoTime();
    if (logger.isDebugEnabled()) {
        logger.debug("get resource=" + name);
        logger.debug("get file=" + file.getAbsolutePath());
    }
    OutputStream os = response.getOutputStream();
    //if (useNew){
    //   FileUtils.loadFromFileNew(file, os);
    //} else {
    FileUtils.loadFromFileOld(file, os);
    //}
    os.flush();
    os.close();

    time = System.nanoTime() - time;
    //if (useNew){
    //logger.info("proceed time new = "+time+"; avg = "+(servTimeNew/servQuantityNew)+"; count="+servQuantityNew+"; size = "+servSizeNew);
    //   newStat.increaseCount();
    //   newStat.increaseSize(file.length());
    //   newStat.increaseTime(time);
    //   useNew = false;
    //} else {
    //logger.info("proceed time old = "+time+"; avg = "+(servTimeOld/servQuantityOld)+"; count="+servQuantityOld+"; size = "+servSizeOld);
    oldStat.increaseCount();
    oldStat.increaseSize(file.length());
    oldStat.increaseTime(time);
    //   useNew = true;
    //}
    //}
}

From source file:net.contextfw.web.application.internal.service.InitHandler.java

public final void handleRequest(final UriMapping mapping, final List<Class<? extends Component>> chain,
        final HttpServlet servlet, final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {

    if (watcher != null && watcher.hasChanged()) {
        logger.debug("Reloading resources");
        cleaner.clean();// w ww.j av  a2s  .co  m
        internalDevelopmentTools.reloadResources();
    }

    response.addHeader("Expires", "Sun, 19 Nov 1978 05:00:00 GMT");
    response.addHeader("Last-Modified", new Date().toString());
    response.addHeader("Cache-Control", "no-store, no-cache, must-revalidate");
    response.addHeader("Cache-Control", "post-check=0, pre-check=0");
    response.addHeader("Pragma", "no-cache");

    if (chain == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    } else {

        WebApplicationPage page = pageScope.createPage(servlet, request, response);
        final MutableBoolean expired = new MutableBoolean(false);
        storage.initialize(page, request, System.currentTimeMillis() + HOUR,
                new ScopedWebApplicationExecution() {
                    @Override
                    public void execute(net.contextfw.web.application.WebApplication application) {
                        try {
                            WebApplicationPage page = (WebApplicationPage) application;
                            WebApplication app = webApplicationProvider.get();
                            app.setInitializerChain(chain);
                            page.setWebApplication(app);
                            listeners.beforeInitialize();
                            page.getWebApplication().initState(mapping);
                            listeners.afterInitialize();
                            listeners.beforeRender();
                            expired.setValue(page.getWebApplication().sendResponse());
                            listeners.afterRender();
                        } catch (Exception e) {
                            // TODO Fix this construct with test
                            if (e instanceof MetaComponentException) {
                                ErrorResolution resolution = ((MetaComponentException) e).getResolution();
                                try {
                                    if (resolution == ErrorResolution.SEND_NOT_FOUND_ERROR) {
                                        response.sendError(HttpServletResponse.SC_NOT_FOUND);
                                    } else if (resolution == ErrorResolution.SEND_BAD_REQUEST_ERROR) {
                                        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
                                    }
                                } catch (IOException e1) {
                                    throw new WebApplicationException(e1);
                                }
                            }
                            listeners.onException(e);
                        } finally {
                            pageScope.deactivateCurrentPage();
                        }

                    }
                });
        // Setting expiration here so that long page
        // processing is
        // not
        // penalizing client
        if (expired.booleanValue()) {
            storage.remove(page.getHandle(), request);
        } else {
            storage.refresh(page.getHandle(), request, System.currentTimeMillis() + initialMaxInactivity);
        }
    }
}

From source file:org.chimi.s4s.controller.FileDownloadController.java

private void checkAndSend(boolean requestImageInline, HttpServletRequest request, HttpServletResponse response,
        FileSource file) throws IOException {
    if (file == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;// ww  w .j  a  v a 2s .  c o  m
    }
    if (requestImageInline && !file.isImage()) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }
    if (checkModifiedRequest(request)) {
        response.setStatus(304);
        response.setContentType(file.getMimeType());
        cacheStrategy.setCacheOption(file, response);
        return;
    }
    sendFile(requestImageInline, file, request, response);
}

From source file:net.danielkvasnicka.flower.FlowerDispatcherServlet.java

/**
 * @see Servlet#service(ServletRequest, ServletResponse)
 *//*from  w  ww  . j  a  v  a  2s  . c o  m*/
@Override
public void service(final ServletRequest request, final ServletResponse response)
        throws ServletException, IOException {

    // get the URL mapping bean
    final UrlMappingHolder urlMappingHolder = (UrlMappingHolder) this.appCtx
            .getBean(Constants.URL_MAPPING_HOLDER_BEAN_NAME);

    final HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    final HttpServletResponse httpServletResponse = (HttpServletResponse) response;

    // get the mapping
    final Map<String, String> urlMapping = urlMappingHolder.getUrlMapping();

    // get the current url and use it together with the mapping to retreive the bean metadata
    final String url = httpServletRequest.getRequestURI()
            .substring(httpServletRequest.getContextPath().length());
    final WebAccessibleBeanMetadata beanMetadata = this.webAccessibleBeanResolver.resolve(urlMapping, url);

    // no bean has been found for this URL
    if (beanMetadata == null) {
        httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND,
                "No web accessible bean has been found for this URL.");
        return;
    }

    // we get the bean and inject the params
    final WebAccessibleBean bean = (WebAccessibleBean) this.appCtx.getBean(beanMetadata.name);
    bean.setParameters(beanMetadata.parameters);

    // we add GET/POST params, which OVERWRITES the REST params
    for (final Object key : httpServletRequest.getParameterMap().keySet()) {
        bean.getParameters().put(key.toString(), httpServletRequest.getParameter(key.toString()));
    }

    // we run the desired method and send the response
    try {
        final Method method = bean.getClass().getMethod(beanMetadata.methodName);
        final Response beanResponse = (Response) method.invoke(bean);
        beanResponse.send(httpServletRequest, httpServletResponse);

    } catch (SecurityException e) {
        throw new FlowerRuntimeException(e);
    } catch (NoSuchMethodException e) {
        httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND,
                "Method '" + beanMetadata.methodName + "' not found on " + bean.getClass().getName());
        return;
    } catch (IllegalArgumentException e) {
        throw new FlowerRuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new FlowerRuntimeException(e);
    } catch (InvocationTargetException e) {
        throw new FlowerRuntimeException(e);
    }
}

From source file:org.openmrs.module.webservices.rest.web.v1_0.controller.openmrs1_8.ChangePasswordController1_8.java

@ExceptionHandler(NullPointerException.class)
@ResponseBody//from  w w  w .  ja v  a 2s.c  o  m
public SimpleObject handleNotFound(NullPointerException exception, HttpServletRequest request,
        HttpServletResponse response) {
    response.setStatus(HttpServletResponse.SC_NOT_FOUND);
    return RestUtil.wrapErrorResponse(exception, "User not found");
}

From source file:org.magnum.mobilecloud.video.AFilledController.java

private void setLike(long id, String user, HttpServletResponse res, boolean isLike) {
    Video v = videos.findOne(id);/*from w w w.  j  a  v  a 2 s .  c o m*/
    int code = HttpServletResponse.SC_OK;
    if (v == null) {
        code = HttpServletResponse.SC_NOT_FOUND;
    } else {
        if (isLike ? v.addLikedUser(user) : v.removeLikedUser(user)) {
            videos.save(v);
        } else {
            code = HttpServletResponse.SC_BAD_REQUEST;
        }
    }
    res.setStatus(code);
}