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:io.wcm.caconfig.editor.impl.ConfigDataServlet.java

@Override
protected void doGet(@NotNull SlingHttpServletRequest request, @NotNull SlingHttpServletResponse response)
        throws ServletException, IOException {
    if (!editorConfig.isEnabled()) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;//from   w  w w  .  jav  a2 s.  c om
    }

    // get parameters
    String configName = request.getParameter(RP_CONFIGNAME);
    if (StringUtils.isBlank(configName)) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }
    boolean collection = BooleanUtils.toBoolean(request.getParameter(RP_COLLECTION));

    // output configuration
    try {
        JSONObject result = getConfiguration(request.getResource(), configName, collection);
        if (result == null) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        } else {
            response.setContentType("application/json;charset=" + CharEncoding.UTF_8);
            response.getWriter().write(result.toString());
        }
    }
    /*CHECKSTYLE:OFF*/ catch (Exception ex) { /*CHECKSTYLE:ON*/
        log.error("Error getting configuration for " + configName + (collection ? "[col]" : ""), ex);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getMessage());
    }
}

From source file:edu.harvard.i2b2.fhirserver.ws.FileServlet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // Get requested file by path info.

    String requestedFile = request.getPathInfo();

    if (requestedFile.equals("/"))
        requestedFile = "/index.html";
    logger.trace("Got request:" + requestedFile);
    logger.trace("basePath:" + this.basePath);
    logger.trace("ffp:" + basePath + requestedFile);

    // Check if file is actually supplied to the request URI.
    //if (requestedFile == null) {
    // Do your thing if the file is not supplied to the request URI.
    // Throw an exception, or send 404, or show default/warning page, or just ignore it.
    //  response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
    //return;/*from  ww  w .  j a va  2 s  . c  o m*/
    //}

    // Decode the file name (might contain spaces and on) and prepare file object.
    URL url = new URL(basePath + requestedFile);
    logger.trace("url:" + url);
    File file = FileUtils.toFile(url);
    logger.trace("searching for file:" + file.getAbsolutePath());

    // Check if file actually exists in filesystem.
    if (!file.exists()) {
        // Do your thing if the file appears to be non-existing.
        // Throw an exception, or send 404, or show default/warning page, or just ignore it.
        response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
        return;
    }

    // Get content type by filename.
    String contentType = getServletContext().getMimeType(file.getName());

    // If content type is unknown, then set the default value.
    // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp
    // To add new content types, add new mime-mapping entry in web.xml.
    if (contentType == null) {
        contentType = "application/text";
    }

    // Init servlet response.
    response.reset();
    response.setBufferSize(DEFAULT_BUFFER_SIZE);
    response.setContentType(contentType);
    response.setHeader("Content-Length", String.valueOf(file.length()));
    //  response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");

    // Prepare streams.
    BufferedInputStream input = null;
    BufferedOutputStream output = null;

    try {
        // Open streams.
        input = new BufferedInputStream(new FileInputStream(file), DEFAULT_BUFFER_SIZE);
        output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);

        // Write file contents to response.
        byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
        int length;
        while ((length = input.read(buffer)) > 0) {
            output.write(buffer, 0, length);
        }
    } finally {
        // Gently close streams.
        close(output);
        close(input);
    }
}

From source file:com.twinsoft.convertigo.engine.servlets.GenericServlet.java

protected void handleStaticData(HttpServletRequest request, HttpServletResponse response) {
    String resourceUri = request.getServletPath();
    Engine.logContext.debug("Serving static ressource: " + resourceUri);

    // TODO: enhance to support content types according to file extension
    if (resourceUri.endsWith(".xml") || resourceUri.endsWith(".cxml") || resourceUri.endsWith(".pxml"))
        response.setContentType(MimeType.TextXml.value());
    else/*from w  ww.jav a 2 s .  c o m*/
        response.setContentType(MimeType.Html.value());

    try {
        InputStream is = getServletContext().getResourceAsStream(resourceUri);
        if (is == null) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND,
                    "Static resource " + resourceUri + " not found");
            return;
        }

        byte array[] = new byte[4096];

        OutputStream os = response.getOutputStream();
        while (is.available() != 0) {
            int nb = is.read(array);
            os.write(array, 0, nb);
        }
        os.flush();

    } catch (IOException e) {
        Engine.logContext.trace("Error serving static resource: " + resourceUri);
    }
}

From source file:org.magnum.dataup.VideoUpController.java

@RequestMapping(value = VideoSvcApi.VIDEO_DATA_PATH, method = RequestMethod.POST)
public @ResponseBody VideoStatus setVideoData(@PathVariable(VideoSvcApi.ID_PARAMETER) long id,
        @RequestParam(VideoSvcApi.DATA_PARAMETER) MultipartFile videoData, HttpServletResponse resp) {
    if (videos.containsKey(id)) {
        Video v = videos.get(id);// w  w w  . ja  va 2s .  co m
        try {
            saveVideo(v, videoData);
            return new VideoStatus(VideoState.READY);
        } catch (IOException e) {
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    } else {
        resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
    }
    return null;
}

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

@GetMapping(Url.INFO_COUNTRY_PAGE)
public String showInfoBySlug(@Country @PathVariable("slug") LinkEntityDto country, Model model,
        Locale userLocale, HttpServletResponse response) throws IOException {

    if (country == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return null;
    }//from  w w  w .  j  a  v a 2s  . c o m

    String slug = country.getSlug();
    String name = country.getName();

    String lang = LocaleUtils.getLanguageOrNull(userLocale);
    List<SeriesInfoDto> series = seriesService.findByCountrySlug(slug, lang);

    model.addAttribute("countrySlug", slug);
    model.addAttribute("countryName", name);
    model.addAttribute("seriesOfCountry", series);

    return "country/info";
}

From source file:io.wcm.caravan.io.http.impl.CaravanHttpClientHystrixTest.java

@Before
public void setUp() {

    ArchaiusConfig.initialize();//from  w  w w.  j a  v a 2  s  . co m
    context.registerInjectActivateService(new CaravanHttpClientConfig(),
            Collections.singletonMap(CaravanHttpClientConfig.SERVLET_CLIENT_ENABLED, true));
    context.registerInjectActivateService(new SimpleLoadBalancerFactory());
    context.registerInjectActivateService(new LoadBalancerCommandFactory());
    context.registerInjectActivateService(new HttpClientFactoryImpl());
    context.registerInjectActivateService(new ServletHttpClient());
    context.registerInjectActivateService(new ApacheHttpClient());
    context.registerInjectActivateService(new RibbonHttpClient());
    underTest = context.registerInjectActivateService(new CaravanHttpClientImpl());

    host = "localhost:" + server.port();

    server.stubFor(get(urlEqualTo(HTTP_200_URI)).willReturn(aResponse()
            .withHeader("Content-Type", "text/plain;charset=" + CharEncoding.UTF_8).withBody("success")));
    server.stubFor(
            get(urlEqualTo(HTTP_404_URI)).willReturn(aResponse().withStatus(HttpServletResponse.SC_NOT_FOUND)));
    server.stubFor(get(urlEqualTo(HTTP_500_URI))
            .willReturn(aResponse().withStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)));

    context.registerInjectActivateService(new CaravanHttpServiceConfig(),
            ImmutableMap.<String, Object>builder()
                    .put(CaravanHttpServiceConfig.SERVICE_ID_PROPERTY, SERVICE_NAME)
                    .put(CaravanHttpServiceConfig.RIBBON_HOSTS_PROPERTY, host)
                    .put(CaravanHttpServiceConfig.RIBBON_MAXAUTORETRIES_PROPERTY, 0)
                    .put(CaravanHttpServiceConfig.RIBBON_MAXAUTORETRIESNEXTSERVER_PROPERTY, 0)
                    .put(CaravanHttpServiceConfig.HYSTRIX_CIRCUITBREAKER_REQUESTVOLUMETHRESHOLD_PROPERTY, 20)
                    .put(CaravanHttpServiceConfig.HYSTRIX_CIRCUITBREAKER_ERRORTHRESHOLDPERCENTAGE_PROPERTY, 50)
                    .build());
}

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

@GetMapping(Url.INFO_CATEGORY_PAGE)
public String showInfoBySlug(@Category @PathVariable("slug") LinkEntityDto category, Model model,
        Locale userLocale, HttpServletResponse response) throws IOException {

    if (category == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return null;
    }/*w  w  w  .  j a  v  a 2s  . c  o m*/

    String slug = category.getSlug();
    String name = category.getName();

    String lang = LocaleUtils.getLanguageOrNull(userLocale);
    List<SeriesInfoDto> series = seriesService.findByCategorySlug(slug, lang);

    model.addAttribute("categorySlug", slug);
    model.addAttribute("categoryName", name);
    model.addAttribute("seriesOfCategory", series);

    return "category/info";
}

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

public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    SAXReader saxReader = new SAXReader();
    try {//from w  w  w  . j a  va2 s . c  o m
        Document propDoc = saxReader.read(request.getInputStream());
        // log(propDoc);
        Element propFindEl = propDoc.getRootElement();
        Element propEl = (Element) propFindEl.elementIterator().next();
        String propElName = propEl.getName();

        List<String> requestedProperties = new ArrayList<String>();
        boolean ignoreValues = false;
        if (TAG_PROP.equals(propElName)) {
            for (Object id : propEl.elements()) {
                requestedProperties.add(((Element) id).getName());
            }
        } else if (TAG_ALLPROP.equals(propElName)) {
            requestedProperties = DavResource.ALL_PROPERTIES;
        } else if (TAG_PROPNAMES.equals(propElName)) {
            requestedProperties = DavResource.ALL_PROPERTIES;
            ignoreValues = true;
        }

        FileObject object = getResourceManager().getFileObject(request.getPathInfo());
        if (object.exists()) {
            // respond as XML encoded multi status
            response.setContentType("text/xml");
            response.setCharacterEncoding("UTF-8");
            response.setStatus(SC_MULTI_STATUS);

            Document multiStatusResponse = getMultiStatusRespons(object, requestedProperties,
                    getBaseUrl(request), getDepth(request), ignoreValues);
            //log(multiStatusResponse);

            // write the actual response
            XMLWriter writer = new XMLWriter(response.getWriter(), OutputFormat.createCompactFormat());
            writer.write(multiStatusResponse);
            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:eu.dasish.annotation.backend.rest.NotebookResource.java

/**
 * //from  ww w  .ja v a2s.  c om
 * @param accessMode a string, representing an access mode: "none", "read", "write", "all".
 * @return the {@link NotebookInfoList} element containing the list of {@link NotebookInfo} elements
 * of all the notebooks to which the in-logged principal has "access" access.
 * @throws IOException if sending an error fails.
 */
@GET
@Produces(MediaType.APPLICATION_XML)
@Path("")
@Transactional(readOnly = true)
public JAXBElement<NotebookInfoList> getNotebookInfos(@QueryParam("access") String accessMode)
        throws IOException {
    dbDispatcher.setResourcesPaths(this.getRelativeServiceURI());
    Number remotePrincipalID = this.getPrincipalID();
    if (accessMode.equalsIgnoreCase("read") || accessMode.equalsIgnoreCase("write")) {
        NotebookInfoList notebookInfos = dbDispatcher.getNotebooks(remotePrincipalID,
                Access.fromValue(accessMode));
        return new ObjectFactory().createNotebookInfoList(notebookInfos);
    } else {
        this.INVALID_ACCESS_MODE(accessMode);
        httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND, "ivalide mode acess " + accessMode);
        return new ObjectFactory().createNotebookInfoList(new NotebookInfoList());
    }
}

From source file:org.wallride.web.support.MediaHttpRequestHandler.java

@Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    checkAndPrepare(request, response, true);

    Map<String, Object> pathVariables = (Map<String, Object>) request
            .getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
    String key = (String) pathVariables.get("key");

    Media media = mediaService.getMedia(key);
    int width = ServletRequestUtils.getIntParameter(request, "w", 0);
    int height = ServletRequestUtils.getIntParameter(request, "h", 0);
    int mode = ServletRequestUtils.getIntParameter(request, "m", 0);

    Resource resource = readResource(media, width, height, Media.ResizeMode.values()[mode]);

    if (resource == null) {
        logger.debug("No matching resource found - returning 404");
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;/*from   w  w w  .ja va  2 s  .  com*/
    }
    if (new ServletWebRequest(request, response).checkNotModified(resource.lastModified())) {
        logger.debug("Resource not modified - returning 304");
        return;
    }

    long length = resource.contentLength();
    if (length > Integer.MAX_VALUE) {
        throw new IOException("Resource content too long (beyond Integer.MAX_VALUE): " + resource);
    }

    response.setContentLength((int) length);
    response.setContentType(media.getMimeType());
    if (!"image".equals(MediaType.parseMediaType(media.getMimeType()).getType())) {
        response.setHeader("Content-Disposition",
                "attachment;filename*=utf-8''" + URLEncoder.encode(media.getOriginalName(), "UTF-8"));
    }

    FileCopyUtils.copy(resource.getInputStream(), response.getOutputStream());
}