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:net.big_oh.common.web.servlets.mime.MimeServlet.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    logger.info(getServletConfig().getServletName() + " invoked.  Requested mime resource: "
            + req.getParameter(REQUESTED_RESOURCE_NAME));

    // Get the name of the requested resource
    String requestedResourceName = req.getParameter(REQUESTED_RESOURCE_NAME);

    if (requestedResourceName == null || requestedResourceName.equals("")) {
        logger.error("Called " + getServletConfig().getServletName() + " without providing a parameter for '"
                + REQUESTED_RESOURCE_NAME + "'");
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;/*from  w  w w. j  av  a2  s. com*/
    }

    // Ensure that the user is allowed to access the requested resource
    if (!isCanUserAccessRequestedResource(requestedResourceName, req.getSession(true))) {
        resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    // Get a byte array representation of the resource to be returned in the
    // response
    byte[] resourceBytes = getMimeResourceBytes(requestedResourceName);

    if (resourceBytes == null || resourceBytes.length == 0) {
        logger.error("No resource found under the name \"" + requestedResourceName + "\"");
        resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // Set content length for the response
    resp.setContentLength(resourceBytes.length);

    // Get the MIME type for the resource
    String mimeType = getMimeType(requestedResourceName);

    if (mimeType == null || mimeType.equals("")) {
        logger.error("Failed to get MIME type for the requested resource.");
        resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    // Set the content type for the response
    resp.setContentType(mimeType);

    // Control the HTTP caching of the response
    // This setting controls how frequently the cached resource is
    // revalidated (which is not necessarily the same as reloaded)
    resp.setHeader("Cache-Control", "max-age=" + getMaxAgeInSeconds(requestedResourceName));

    // Use streams to return the requested resource
    ByteArrayInputStream in = new ByteArrayInputStream(resourceBytes);
    OutputStream out = resp.getOutputStream();

    byte[] buf = new byte[1024];
    int count = 0;
    while ((count = in.read(buf)) >= 0) {
        out.write(buf, 0, count);
    }

    in.close();
    out.close();

}

From source file:org.eclipse.virgo.apps.repository.web.RepositoryControllerTests.java

@Test
public void getIndexForUnknownRepository() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    MockHttpServletResponse response = new MockHttpServletResponse();

    request.setRequestURI("http://localhost:8080/org.eclipse.virgo.server.repository/my-repo");
    request.setMethod("GET");

    expect(this.repositoryManager.getIndex("my-repo")).andReturn(null);

    replay(this.repositoryManager);

    repositoryController.getIndex(request, response);

    verify(this.repositoryManager);

    assertEquals(response.getStatus(), HttpServletResponse.SC_NOT_FOUND);
}

From source file:com.jaspersoft.jasperserver.rest.services.RESTJobSummary.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServiceException {
    // Get the uri of the resource
    String url = restUtils.extractRepositoryUri(req.getPathInfo());
    if (log.isDebugEnabled()) {
        log.debug("getting job summary for " + url);
    }//w w w  . j  a  va2  s .  c  o  m
    if (url == null) {
        throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, "malformed url: " + url);
    }

    if (isValidUri(url)) {
        JobSummary[] summaries = new JobSummary[0];
        try {
            summaries = reportSchedulerService.getReportJobs(url);
        } catch (AxisFault axisFault) {
            throw new ServiceException(HttpServletResponse.SC_NOT_FOUND,
                    "could not locate jobs for report in uri: " + url + axisFault.getLocalizedMessage());
        }

        if (summaries == null) {
            restUtils.setStatusAndBody(HttpServletResponse.SC_OK, resp, "");
        } else {
            if (log.isDebugEnabled()) {
                log.debug("found " + summaries.length + "job summaries for report: " + req.getPathInfo());
            }
            restUtils.setStatusAndBody(HttpServletResponse.SC_OK, resp, generateSummeryReport(summaries));
        }
    } else
        throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, "bad report uri");
}

From source file:com.aipo.social.core.oauth2.AipoOAuth2Servlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpUtil.setNoCache(response);/*from www  .  j a va2 s . com*/
    String path = request.getPathInfo();
    if (path.endsWith(AUTHORIZE)) {
        sendOAuth2Response(response, authorizationHandler.handle(request, response));
    } else if (path.endsWith(TOKEN)) {
        // token endpoint must use POST method
        response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED,
                "The client MUST use the HTTP \"POST\" method " + "when making access token requests.");
    } else {
        response.sendError(HttpServletResponse.SC_NOT_FOUND, "Unknown URL");
    }
}

From source file:edu.harvard.iq.dataverse.NavigationWrapper.java

public String notFound() {
    return sendError(HttpServletResponse.SC_NOT_FOUND);
}

From source file:com.clican.pluto.cms.ui.servlet.VelocityResourceServlet.java

@SuppressWarnings("unchecked")
@Override// w  w  w.j  a v a  2s. co m
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String prefix = request.getContextPath() + request.getServletPath();
    if (request.getRequestURI().startsWith(prefix)) {
        String path = request.getRequestURI().replaceFirst(prefix, "");
        if (path.startsWith("/")) {
            path = path.substring(1, path.indexOf(";"));
        }
        // request.getSession().setAttribute("propertyDescriptionList", new
        // ArrayList<PropertyDescription>());
        Writer w = new OutputStreamWriter(response.getOutputStream(), "utf-8");
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        InputStream is = null;
        try {
            is = Thread.currentThread().getContextClassLoader().getResourceAsStream(path);
            byte[] data = new byte[is.available()];
            is.read(data);
            String content = new String(data, "utf-8");
            Template t = null;
            VelocityContext velocityContext = new VelocityContext();
            HttpSession session = request.getSession();
            Enumeration<String> en = session.getAttributeNames();
            while (en.hasMoreElements()) {
                String name = en.nextElement();
                velocityContext.put(name, session.getAttribute(name));
            }
            SimpleNode node = RuntimeSingleton.getRuntimeServices().parse(content, path);
            t = new Template();
            t.setName(path);
            t.setRuntimeServices(RuntimeSingleton.getRuntimeServices());
            t.setData(node);
            t.initDocument();
            Writer wr = new OutputStreamWriter(os);
            t.merge(velocityContext, wr);
            wr.flush();
            byte[] datas = os.toByteArray();
            String s = new String(datas);
            log.info(s);
        } catch (Exception e) {
            log.error("", e);
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        } finally {
            if (w != null) {
                w.close();
            }
            if (is != null) {
                is.close();
            }
        }
    } else {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    }

}

From source file:org.gooru.insights.api.spring.exception.InsightsExceptionResolver.java

public ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
        Exception ex) {//from w  w  w  .  j  a v  a  2s.  c o  m
    ResponseParamDTO<Map<Object, Object>> responseDTO = new ResponseParamDTO<Map<Object, Object>>();
    Map<Object, Object> errorMap = new HashMap<Object, Object>();
    Integer statusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    String traceId = request.getAttribute("traceId") != null ? request.getAttribute("traceId").toString()
            : DEFAULT_TRACEID;
    if (ex instanceof BadRequestException) {
        statusCode = HttpServletResponse.SC_BAD_REQUEST;
    } else if (ex instanceof AccessDeniedException) {
        statusCode = HttpServletResponse.SC_FORBIDDEN;
    } else if (ex instanceof NotFoundException) {
        statusCode = HttpServletResponse.SC_NOT_FOUND;
    } else {
        statusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    }

    if (statusCode.toString().startsWith(Numbers.FOUR.getNumber())) {
        InsightsLogger.debug(traceId, ex);
        errorMap.put(DEVELOPER_MESSAGE, ex.getMessage());
    } else if (statusCode.toString().startsWith(Numbers.FIVE.getNumber())) {
        InsightsLogger.error(traceId, ex);
        errorMap.put(DEVELOPER_MESSAGE, DEFAULT_ERROR);
    } else if (statusCode.equals(HttpServletResponse.SC_NO_CONTENT)) {
        InsightsLogger.error(traceId, ex);
        errorMap.put(DEVELOPER_MESSAGE, CONTENT_UNAVAILABLE);
    }
    errorMap.put(STATUS_CODE, statusCode);
    errorMap.put(MAIL_To, SUPPORT_EMAIL_ID);

    response.setStatus(statusCode);
    responseDTO.setMessage(errorMap);
    return new ModelAndView(modelAttributes.VIEW_NAME.getAttribute(),
            modelAttributes.RETURN_NAME.getAttribute(),
            new JSONSerializer().exclude(ApiConstants.EXCLUDE_CLASSES).deepSerialize(responseDTO));

}

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

@RequestMapping(value = VideoSvcApi.VIDEO_SVC_PATH + "/{id}", method = RequestMethod.GET)
public @ResponseBody Video getVideoById(@PathVariable("id") long id, HttpServletResponse response) {
    Video v = videos.findOne(id);//from w  w  w  . j a v a2s . c o m
    if (v == null) {
        sendError(response, HttpServletResponse.SC_NOT_FOUND, "Video not found");
    }
    return v;
}

From source file:cz.muni.fi.pa165.deliverysystemweb.CourierActionBean.java

public Resolution view() {
    String id = getContext().getRequest().getParameter("id");

    Long l_id;/*w  w  w . j  a  v  a 2  s  . c  om*/
    try {
        l_id = Long.valueOf(id);
    } catch (NumberFormatException ex) {
        return new ErrorResolution(HttpServletResponse.SC_BAD_REQUEST);
    }

    try {
        courierDTO = courierService.findCourier(l_id);
    } catch (DataAccessException ex) {
        return new ErrorResolution(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }

    if (courierDTO == null) {
        return new ErrorResolution(HttpServletResponse.SC_NOT_FOUND);
    }
    return new ForwardResolution("/courier/view.jsp");
}

From source file:net.myrrix.web.servlets.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 v  a2s . com
    }
    Iterator<String> pathComponents = SLASH.split(pathInfo).iterator();
    long toItemID;
    Pair<long[], float[]> itemIDsAndValue;
    try {
        toItemID = Long.parseLong(pathComponents.next());
        itemIDsAndValue = RecommendToAnonymousServlet.parseItemValuePairs(pathComponents);
    } catch (NoSuchElementException nsee) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, nsee.toString());
        return;
    } catch (NumberFormatException nfe) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, nfe.toString());
        return;
    }

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

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

    MyrrixRecommender 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());
    } catch (TasteException te) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, te.toString());
        getServletContext().log("Unexpected error in " + getClass().getSimpleName(), te);
    }
}