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.commercehub.dropwizard.BuildInfoServlet.java

private void writeValueForKey(String requestedKey, HttpServletResponse response) throws IOException {
    String value = manifestAttributes.getProperty(requestedKey);
    if (StringUtils.isNotBlank(value)) {
        response.setContentType(MediaType.TEXT_PLAIN);
        response.getWriter().print(value);
    } else {//from  w  ww.j a v a  2  s  .  c  om
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    }
}

From source file:ru.mystamps.web.controller.CollectionController.java

@GetMapping(Url.INFO_COLLECTION_BY_ID_PAGE)
public View showInfoById(@PathVariable("slug") String slug, HttpServletResponse response) throws IOException {

    if (slug == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return null;
    }//ww w . ja  v a  2 s  . c o  m

    CollectionInfoDto collection = collectionService.findBySlug(slug);
    if (collection == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return null;
    }

    RedirectView view = new RedirectView();
    view.setStatusCode(HttpStatus.MOVED_PERMANENTLY);
    view.setUrl(Url.INFO_COLLECTION_PAGE);

    return view;
}

From source file:uk.urchinly.wabi.expose.DownloadController.java

@RequestMapping(value = "/download/{assetId}", method = RequestMethod.GET)
public void download(HttpServletResponse response, @PathVariable("assetId") String assetId) throws IOException {

    Asset asset = this.assetMongoRepository.findOne(assetId);

    if (asset == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;/*from w ww . j  av  a  2 s  .c  om*/
    }

    File file = new File(appSharePath, asset.getFileName());

    if (file.canRead()) {
        this.rabbitTemplate.convertAndSend(MessagingConstants.USAGE_ROUTE,
                new UsageEvent("download asset", asset.toString()));

        response.setContentType(asset.getContentType());
        response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getName()));
        response.setContentLength((int) file.length());

        InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
        FileCopyUtils.copy(inputStream, response.getOutputStream());
    } else {
        logger.warn("File '{}' not found.", file.getAbsolutePath());
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:org.dasein.cloud.azure.tests.network.AzureIpAddressSupportTest.java

@Test(expected = InternalException.class)
public void forwardShouldThrowExceptionIfOnServerIdIsNotValid() throws CloudException, InternalException {
    new MockUp<CloseableHttpClient>() {
        @Mock(invocations = 1)/*from w w w.j a  va  2  s.co m*/
        public CloseableHttpResponse execute(Invocation inv, HttpUriRequest request) throws IOException {
            assertGet(request, EXPECTED_URL, new Header[] { new BasicHeader("x-ms-version", "2012-03-01") });
            return getHttpResponseMock(getStatusLineMock(HttpServletResponse.SC_NOT_FOUND), null,
                    new Header[] { new BasicHeader("x-ms-request-id", UUID.randomUUID().toString()) });
        }
    };

    ipAddressSupport.forward("127.0.0.1", PUBLIC_PORT, PROTOCOL, PRIVATE_PORT, VM_ID);
}

From source file:com.thinkberg.moxo.dav.PropPatchHandler.java

public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    FileObject object = getResourceManager().getFileObject(request.getPathInfo());

    try {/*  w  w  w.java2  s  . c  o  m*/
        LockManager.getInstance().checkCondition(object, getIf(request));
    } catch (LockException e) {
        if (e.getLocks() != null) {
            response.sendError(SC_LOCKED);
        } else {
            response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        }
        return;
    }

    SAXReader saxReader = new SAXReader();
    try {
        Document propDoc = saxReader.read(request.getInputStream());
        //      log(propDoc);

        response.setContentType("text/xml");
        response.setCharacterEncoding("UTF-8");
        response.setStatus(SC_MULTI_STATUS);

        if (object.exists()) {
            Document resultDoc = DocumentHelper.createDocument();
            Element multiStatusResponse = resultDoc.addElement("multistatus", "DAV:");
            Element responseEl = multiStatusResponse.addElement("response");
            try {
                URL url = new URL(getBaseUrl(request), URLEncoder.encode(object.getName().getPath(), "UTF-8"));
                log("!! " + url);
                responseEl.addElement("href").addText(url.toExternalForm());
            } catch (Exception e) {
                e.printStackTrace();
            }

            Element propstatEl = responseEl.addElement("propstat");
            Element propEl = propstatEl.addElement("prop");

            Element propertyUpdateEl = propDoc.getRootElement();
            for (Object elObject : propertyUpdateEl.elements()) {
                Element el = (Element) elObject;
                if ("set".equals(el.getName())) {
                    for (Object propObject : el.elements()) {
                        setProperty(propEl, object, (Element) propObject);
                    }
                } else if ("remove".equals(el.getName())) {
                    for (Object propObject : el.elements()) {
                        removeProperty(propEl, object, (Element) propObject);
                    }
                }
            }
            propstatEl.addElement("status").addText(DavResource.STATUS_403);

            //        log(resultDoc);

            // write the actual response
            XMLWriter writer = new XMLWriter(response.getWriter(), OutputFormat.createCompactFormat());
            writer.write(resultDoc);
            writer.flush();
            writer.close();
        } else {
            log("!! " + object.getName().getPath() + " NOT FOUND");
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    } catch (DocumentException e) {
        log("!! inavlid request: " + e.getMessage());
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
    }
}

From source file:alpine.filters.BlacklistUrlFilter.java

/**
 * Check for denied or ignored URLs being requested.
 *
 * @param request The request object.//from  w  w  w .ja  va  2  s  . c om
 * @param response The response object.
 * @param chain Refers to the {@code FilterChain} object to pass control to the next {@code Filter}.
 * @throws IOException a IOException
 * @throws ServletException a ServletException
 */
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {

    final HttpServletRequest req = (HttpServletRequest) request;
    final HttpServletResponse res = (HttpServletResponse) response;

    final String requestUri = req.getRequestURI();
    if (requestUri != null) {
        for (String url : denyUrls) {
            if (requestUri.startsWith(url.trim())) {
                res.setStatus(HttpServletResponse.SC_FORBIDDEN);
                return;
            }
        }
        for (String url : ignoreUrls) {
            if (requestUri.startsWith(url.trim())) {
                res.setStatus(HttpServletResponse.SC_NOT_FOUND);
                return;
            }
        }
    }
    chain.doFilter(request, response);
}

From source file:info.magnolia.rendering.engine.RenderingFilter.java

@Override
public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    final AggregationState aggregationState = MgnlContext.getAggregationState();

    String templateName = aggregationState.getTemplateName();
    if (StringUtils.isNotEmpty(templateName)) {
        try {/* w w  w  . ja  va2  s  .  c  o m*/
            // don't reset any existing status code, see MAGNOLIA-2005
            // response.setStatus(HttpServletResponse.SC_OK);
            if (response != MgnlContext.getWebContext().getResponse()) {
                log.warn("Context response not synced. This may lead to discrepancies in rendering.");
            }

            Node content = aggregationState.getMainContent().getJCRNode();

            // if the content isn't visible output a 404
            if (!isVisible(content, request, response, aggregationState)) {
                if (!response.isCommitted()) {
                    response.sendError(HttpServletResponse.SC_NOT_FOUND);
                } else {
                    log.info("Unable to redirect to 404 page for {}, response is already committed",
                            request.getRequestURI());
                }
                return;
            }

            render(content, templateName, response);

            try {
                response.flushBuffer();
            } catch (IOException e) {
                // don't log at error level since tomcat typically throws a
                // org.apache.catalina.connector.ClientAbortException if the user stops loading the page
                log.debug("Exception flushing response " + e.getClass().getName() + ": " + e.getMessage(), e);
            }

        } catch (RenderException e) {
            // TODO better handling of rendering exception
            // TODO dlipp: why not move this section up to the actual call to render() -> that's the only place where a RenderException could occur...
            log.error(e.getMessage(), e);
            throw new ServletException(e);
        } catch (Exception e) {
            // TODO dlipp: there's no other checked exceptions thrown in the code above - is it correct to react like that???
            log.error(e.getMessage(), e);
            if (!response.isCommitted()) {
                response.setContentType("text/html");
            }
            throw new RuntimeException(e);
        }
    } else {
        // direct request
        handleResourceRequest(aggregationState, request, response);
    }

    // TODO don't make it a dead end
    //      currently we can't process the chain because there is no content/nop servlet
    // chain.doFilter(request, response);
}

From source file:controller.IndicadoresMontoRestController.java

@RequestMapping(value = "/{idi}/municipios/{idm}", method = RequestMethod.GET, produces = "application/xml")
public String getXML(@PathVariable("idi") String idi, @PathVariable("idm") int idm, HttpServletRequest request,
        HttpServletResponse response) {/*from  ww w  .j  a v a2  s  .  com*/

    XStream XML = new XStream();
    List<DatosRegistrosIdMunicipio> listaFinal;
    List<Registros> listaRegistros;
    RegistrosDAO tablaRegistros;
    tablaRegistros = new RegistrosDAO();
    /*
    *obtenemos la lista Registros
    */
    try {
        listaRegistros = tablaRegistros.selectAllResgistrosByIdIndicadorAndMunicipio(idi, idm);
        if (listaRegistros.isEmpty()) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            Error e = new Error();
            e.setTypeAndDescription("Warning",
                    "No existen registros del indicador:" + idi + " asociados al municipio con id:" + idm);
            XML.alias("message", Error.class);
            return XML.toXML(e);
        }
    } catch (HibernateException ex) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        Error e = new Error();
        e.setTypeAndDescription("errorServer", ex.getMessage());
        XML.alias("message", Error.class);
        return XML.toXML(e);
    }
    listaFinal = new ArrayList<>();
    for (Registros r : listaRegistros) {
        listaFinal.add(new DatosRegistrosIdMunicipio(r.getIdRegistros(), r.getAnio(), r.getCantidad()));
    }

    response.setStatus(HttpServletResponse.SC_OK);
    XML.alias("registro", DatosRegistrosIdMunicipio.class);
    return XML.toXML(listaFinal);
}

From source file:com.asual.summer.sample.web.TechnologyController.java

@RequestMapping("/image/{value}")
public void image(@PathVariable("value") String value, HttpServletResponse response) throws IOException {
    Image image = Technology.findImage(value);
    if (image != null) {
        response.setContentLength(image.getBytes().length);
        response.setContentType(image.getContentType());
        response.getOutputStream().write(image.getBytes());
    } else {//from  w ww. j  a v  a  2  s .  c om
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
    }
    response.getOutputStream().flush();
    response.getOutputStream().close();
}