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:org.abstracthorizon.proximity.webapp.controllers.RepositoryController.java

/**
 * Repository list.//from w w  w  .jav a2  s .com
 * 
 * @param request the request
 * @param response the response
 * 
 * @return the model and view
 * 
 * @throws Exception the exception
 */
public ModelAndView repositoryList(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String requestURI = request.getRequestURI()
            .substring(request.getContextPath().length() + request.getServletPath().length());
    if (requestURI.length() == 0) {
        requestURI = "/";
    }
    logger.debug("Got repository request on URI " + requestURI);
    String orderBy = request.getParameter("orderBy") == null ? "name" : request.getParameter("orderBy");
    String targetRepository = request.getParameter("repositoryId");
    String targetGroup = request.getParameter("repositoryGroupId");

    Item item = null;
    ProximityRequest pRequest = new ProximityRequest();
    pRequest.setPath(requestURI);
    pRequest.setTargetedReposId(targetRepository);
    pRequest.setTargetedReposGroupId(targetGroup);
    pRequest.setGrantee(null);
    pRequest.getAttributes().put(ProximityRequest.REQUEST_REMOTE_ADDRESS, request.getRemoteAddr());

    // issue #42, collect header information
    Enumeration headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String headerName = (String) headerNames.nextElement();
        pRequest.getAttributes().put("http." + headerName.toLowerCase(), request.getHeader(headerName));
    }

    try {
        logger.debug("Got request for " + targetRepository + " repository on URI: " + requestURI);
        item = proximity.retrieveItem(pRequest);
        logger.debug("Got response " + item.getProperties().getPath());

        if (item.getProperties().isDirectory()) {
            List items = null;
            items = proximity.listItems(pRequest);
            PropertyComparator.sort(items, new MutableSortDefinition(orderBy, true, true));
            Map result = new HashMap();
            result.put("items", items);
            result.put("orderBy", orderBy);
            result.put("requestUri", requestURI);
            result.put("requestPathList", explodeUriToList(requestURI));
            return new ModelAndView("repository/repositoryList", result);
        } else {
            // TODO: check for If-Modified-Since?
            // response.setContentType("application/octet-stream");
            response.setContentType(
                    getWebApplicationContext().getServletContext().getMimeType(item.getProperties().getName()));
            response.setContentLength((int) item.getProperties().getSize());
            response.setDateHeader("Last-Modified", item.getProperties().getLastModified().getTime());
            InputStream is = item.getStream();
            OutputStream os = response.getOutputStream();
            IOUtils.copy(is, os);
            is.close();
            return null;
        }
    } catch (ItemNotFoundException ex) {
        logger.info("Item not found on URI " + requestURI);
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return null;
    } catch (AccessDeniedException ex) {
        logger.info("Access forbidden to " + requestURI + " for " + request.getRemoteAddr(), ex);
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return null;
    }
}

From source file:com.liusoft.dlog4j.action.ActionExtend.java

/**
 * //from  w ww. j ava2s .com
 * @param mapping
 * @param form
 * @param req
 * @param res
 * @return
 * @throws Exception
 */
protected ActionForward doDefault(ActionMapping mapping, ActionForm form, HttpServletRequest req,
        HttpServletResponse res) throws Exception {
    res.sendError(HttpServletResponse.SC_NOT_FOUND, "METHOD NOT FOUND.");
    return null;
}

From source file:com.imaginary.home.cloud.api.call.RelayCall.java

@Override
public void put(@Nonnull String requestId, @Nullable String userId, @Nonnull String[] path,
        @Nonnull HttpServletRequest req, @Nonnull HttpServletResponse resp,
        @Nonnull Map<String, Object> headers, @Nonnull Map<String, Object> parameters)
        throws RestException, IOException {
    try {/*ww w. ja  va  2  s  .  c  om*/
        if (path.length < 2) {
            throw new RestException(HttpServletResponse.SC_METHOD_NOT_ALLOWED, RestException.INVALID_OPERATION,
                    "No PUT on /relay");
        }
        ControllerRelay relay = ControllerRelay.getRelay(path[1]);

        if (relay == null) {
            throw new RestException(HttpServletResponse.SC_NOT_FOUND, RestException.NO_SUCH_OBJECT,
                    "Relay " + path[1] + " not found");
        }
        BufferedReader reader = new BufferedReader(new InputStreamReader(req.getInputStream()));
        StringBuilder source = new StringBuilder();
        String line;

        while ((line = reader.readLine()) != null) {
            source.append(line);
            source.append(" ");
        }
        JSONObject object = new JSONObject(source.toString());
        String action;

        if (object.has("action") && !object.isNull("action")) {
            action = object.getString("action");
        } else {
            throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_ACTION,
                    "An invalid action was specified (or not specified) in the PUT");
        }
        if (action.equalsIgnoreCase("update")) {
            if (userId != null) {
                throw new RestException(HttpServletResponse.SC_FORBIDDEN, RestException.USER_NOT_ALLOWED,
                        "This API call may be called only by controller relays");
            }
            update(relay, object, resp);
        } else if (action.equalsIgnoreCase("modify")) {
            if (object.has("relay")) {
                object = object.getJSONObject("relay");
            } else {
                object = null;
            }
            if (object == null) {
                throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_PUT,
                        "No location was specified in the PUT");
            }
            String name;

            if (object.has("name") && !object.isNull("name")) {
                name = object.getString("name");
            } else {
                name = relay.getName();
            }
            relay.modify(name);
            resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
        } else {
            throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_ACTION,
                    "The action " + action + " is not a valid action.");
        }
    } catch (JSONException e) {
        throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_JSON,
                "Invalid JSON in body");
    } catch (PersistenceException e) {
        e.printStackTrace();
        throw new RestException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, RestException.INTERNAL_ERROR,
                "Internal database error");
    }
}

From source file:gr.cti.android.experimentation.controller.ExperimentController.java

/**
 * Returns the information of a specific {@see Experiment}.
 *
 * @param response     the {@see HttpServletResponse}.
 * @param experimentId the Id of the {@see Experiment}.
 * @return the information of a specific {@see Experiment}.
 * @throws IOException//from  w w w  .  ja  v  a 2s  . c  om
 */
@ResponseBody
@RequestMapping(value = "/experiment/{experimentId}", method = RequestMethod.GET, produces = "application/json")
public ApiResponse getExperiment(HttpServletResponse response,
        @PathVariable(value = "experimentId") final int experimentId) throws IOException {

    final ApiResponse apiResponse = new ApiResponse();

    final Experiment storedExperiment = experimentRepository.findById(experimentId);
    if (storedExperiment != null) {
        apiResponse.setStatus(HttpServletResponse.SC_OK);
        apiResponse.setMessage("ok");
        apiResponse.setValue(storedExperiment);
        return apiResponse;
    } else {
        response.sendError(HttpServletResponse.SC_NOT_FOUND, "no experiment found with the given id");
    }
    return null;
}

From source file:org.shredzone.cilla.view.HeaderView.java

/**
 * Streams the uncropped header image.//w  w w  .j  a  v  a2  s  .co m
 */
@View(pattern = "/header/full/${header.id}-${#type}.${#suffix(header.headerImage.contentType)}")
@View(pattern = "/header/full/${header.id}.${#suffix(header.headerImage.contentType)}")
public void headerUncroppedView(@PathPart("header.id") Header header, @Optional @PathPart("#type") String type,
        HttpServletRequest req, HttpServletResponse resp) throws ViewException, CillaServiceException {
    if (!headerService.isVisible(header)) {
        throw new ErrorResponseException(HttpServletResponse.SC_FORBIDDEN);
    }

    ImageProcessing ip = null;
    if (type != null) {
        ip = imageProcessingManager.createImageProcessing(type);
        if (ip == null) {
            throw new ErrorResponseException(HttpServletResponse.SC_NOT_FOUND);
        }
    }

    ResourceDataSource ds = headerService.getFullImage(header, ip);
    streamDataSource(ds, req, resp);
}

From source file:de.betterform.agent.web.resources.ResourceServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String requestUri = req.getRequestURI();
    String resourcePath = RESOURCE_FOLDER + getResourcePath(requestUri);
    URL url = ResourceServlet.class.getResource(resourcePath);
    if (LOG.isTraceEnabled()) {
        LOG.trace("Request URI: " + requestUri);
        LOG.trace("resource fpath: " + resourcePath);
    }/*  ww  w.  j  av  a 2 s.c  om*/

    if (url == null) {
        boolean error = true;

        if (requestUri.endsWith(".js")) {
            //try optimized version first
            if (requestUri.contains("scripts/betterform/betterform-")) {
                if (ResourceServlet.class.getResource(resourcePath) == null) {
                    resourcePath = resourcePath.replace("betterform-", "BfRequired");
                    if (ResourceServlet.class.getResource(resourcePath) != null) {
                        error = false;
                    }
                }
            }
        }

        if (error) {
            if (LOG.isWarnEnabled()) {
                LOG.warn("Resource " + resourcePath + " not found");
            }
            resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Resource " + resourcePath + " not found");
            return;
        }

    }

    if (LOG.isTraceEnabled()) {
        LOG.trace("Streaming resource " + resourcePath);
    }

    InputStream inputStream = null;

    try {
        if (exploded) {
            String path = ResourceServlet.class.getResource(resourcePath).getPath();
            inputStream = new FileInputStream(new File(path));
            if (LOG.isTraceEnabled()) {
                LOG.trace("loading reources form file: " + path);
            }
        } else {
            inputStream = ResourceServlet.class.getResourceAsStream(resourcePath);
        }

        String mimeType = getResourceContentType(resourcePath);
        if (mimeType == null) {
            mimeType = getServletContext().getMimeType(resourcePath);
        }

        if (mimeType == null) {
            if (LOG.isTraceEnabled()) {
                LOG.trace("MimeType for " + resourcePath + " not found. Sending 'not found' response");
            }
            resp.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
                    "MimeType for " + resourcePath + " not found. Sending 'not found' response");
            return;
        }

        resp.setContentType(mimeType);
        resp.setStatus(HttpServletResponse.SC_OK);
        setCaching(req, resp);
        streamResource(req, resp, mimeType, inputStream);

        if (LOG.isTraceEnabled()) {
            LOG.trace("Resource " + resourcePath + " streamed succesfully");
        }
    } catch (Exception exception) {
        LOG.error("Error in streaming resource " + resourcePath + ". Exception is " + exception.getMessage());
    } finally {
        if (inputStream != null) {
            inputStream.close();
        }

        resp.getOutputStream().flush();
        resp.getOutputStream().close();
    }
}

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

/**
 * <p>//from  w  w w.  j av a  2  s.  c  o  m
 *  ZbVfBNg???B<br>
 *  ZbV???AZbVfBNg??
 *  p??[^??J?ANVtH??[hZbg?B<br>
 *  p??[^?????A(404)G?[?B<br>
 *  ZbV???AVXeON?B
 * </p>
 * @param mapping ANV}bsO
 * @param form ANVtH?[
 * @param req HTTPNGXg
 * @param res HTTPX|X
 * @return J?ANVtH??[h?B
 */
@Override
public ActionForward doExecute(ActionMapping mapping, ActionForm form, HttpServletRequest req,
        HttpServletResponse res) {

    if (log.isDebugEnabled()) {
        log.debug("doExecute() called.");
    }

    // pZbVON
    HttpSession session = req.getSession(false);
    if (session == null) {
        log.error("HttpSession is not available.");
        throw new SystemException(null, SESSION_NOT_FOUND_ERROR);
    }

    // ZbVID?AZbVfBNg???B
    FileUtil.makeSessionDirectory(session.getId());

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

    if (path == null) {
        // p??[^?????A(404)G?[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;
    }

    // J
    ActionForward retVal = new ActionForward(path);
    return retVal;
}

From source file:com.zimbra.cs.service.admin.StatsImageServlet.java

public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    AuthToken authToken = getAdminAuthTokenFromCookie(req, resp);
    if (authToken == null)
        return;//w ww.j  a v  a2  s  . c  om

    String imgName = null;
    InputStream is = null;
    boolean imgAvailable = true;
    boolean localServer = false;
    boolean systemWide = false;

    String serverAddr = "";

    String noDefaultImg = req.getParameter("nodef");
    boolean noDefault = false;
    if (noDefaultImg != null && !noDefaultImg.equals("") && noDefaultImg.equals("1")) {
        noDefault = true;
    }
    String reqPath = req.getRequestURI();
    try {

        //check if this is the logger host, otherwise proxy the request to the logger host 
        String serviceHostname = Provisioning.getInstance().getLocalServer()
                .getAttr(Provisioning.A_zimbraServiceHostname);
        String logHost = Provisioning.getInstance().getConfig().getAttr(Provisioning.A_zimbraLogHostname);
        if (!serviceHostname.equalsIgnoreCase(logHost)) {
            StringBuffer url = new StringBuffer("https");
            url.append("://").append(logHost).append(':').append(LC.zimbra_admin_service_port.value());
            url.append(reqPath);
            String queryStr = req.getQueryString();
            if (queryStr != null)
                url.append('?').append(queryStr);

            // create an HTTP client with the same cookies
            HttpState state = new HttpState();
            try {
                state.addCookie(new org.apache.commons.httpclient.Cookie(logHost,
                        ZimbraCookie.COOKIE_ZM_ADMIN_AUTH_TOKEN, authToken.getEncoded(), "/", null, false));
            } catch (AuthTokenException ate) {
                throw ServiceException.PROXY_ERROR(ate, url.toString());
            }
            HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
            client.setState(state);
            GetMethod get = new GetMethod(url.toString());
            try {
                int statusCode = HttpClientUtil.executeMethod(client, get);
                if (statusCode != HttpStatus.SC_OK)
                    throw ServiceException.RESOURCE_UNREACHABLE(get.getStatusText(), null);

                resp.setContentType("image/gif");
                ByteUtil.copy(get.getResponseBodyAsStream(), true, resp.getOutputStream(), false);
                return;
            } catch (HttpException e) {
                throw ServiceException.RESOURCE_UNREACHABLE(get.getStatusText(), e);
            } catch (IOException e) {
                throw ServiceException.RESOURCE_UNREACHABLE(get.getStatusText(), e);
            } finally {
                get.releaseConnection();
            }
        }
    } catch (Exception ex) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Image not found");
        return;
    }
    try {

        if (reqPath == null || reqPath.length() == 0) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }

        if (mLog.isDebugEnabled())
            mLog.debug("received request to:(" + reqPath + ")");

        String reqParts[] = reqPath.split("/");

        String reqFilename = reqParts[3];
        imgName = LC.stats_img_folder.value() + File.separator + reqFilename;
        try {
            is = new FileInputStream(imgName);
        } catch (FileNotFoundException ex) {//unlikely case - only if the server's files are broken
            if (is != null)
                is.close();
            if (!noDefault) {
                imgName = LC.stats_img_folder.value() + File.separator + IMG_NOT_AVAIL;
                is = new FileInputStream(imgName);

            } else {
                resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Image not found");
                return;
            }
        }
    } catch (Exception ex) {
        if (is != null)
            is.close();

        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "FNF image File not found");
        return;
    }
    resp.setContentType("image/gif");
    ByteUtil.copy(is, true, resp.getOutputStream(), false);
}

From source file:org.everit.authentication.http.session.ecm.tests.SessionAuthenticationComponentTest.java

private void logoutGet(final HttpContext httpContext) throws ClientProtocolException, IOException {
    HttpClient httpClient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(logoutUrl);
    HttpResponse httpResponse = httpClient.execute(httpGet, httpContext);
    Assert.assertEquals(HttpServletResponse.SC_NOT_FOUND, httpResponse.getStatusLine().getStatusCode());

    HttpUriRequest currentReq = (HttpUriRequest) httpContext.getAttribute(ExecutionContext.HTTP_REQUEST);
    HttpHost currentHost = (HttpHost) httpContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
    String currentUrl = (currentReq.getURI().isAbsolute()) ? currentReq.getURI().toString()
            : (currentHost.toURI() + currentReq.getURI());
    Assert.assertEquals(loggedOutUrl, currentUrl);
}

From source file:org.gc.GoogleController.java

/**
 * This rest web service is the one that google called after login (callback url).
 * First it retrieve code and token that google sends back. 
 * It checks if code and token are not null, then if token is the same as the one saved in session.
 * If it is not then response status is UNAUTHORIZED, otherwise it retrieves user data.
 * //w w  w .  j  av  a 2  s.  co m
 * Then redirects authenticated user to home page where user can access protected resources.
 * 
 * @param request : instance of {@link HttpServletRequest}
 * @param response : instance of {@link HttpServletResponse}
 * @return redirect to home page
 */
@RequestMapping(value = "/callback", method = RequestMethod.GET, produces = "application/json")
public String confirmStateToken(HttpServletRequest request, HttpServletResponse response) {

    logger.info("****** Google callback ******");
    String code = request.getParameter("code");
    String token = request.getParameter("state");
    String session_token = "";
    if (request.getSession().getAttribute("state") != null) {
        session_token = request.getSession().getAttribute("state").toString();
    }

    logger.info("request code: " + code);
    logger.info("request token: " + token);
    logger.info("request session token: " + session_token);

    //compare state token in session and state token in response of google
    //if equals return to home
    //if not error page
    if ((code == null || token == null) && (!token.equals(session_token))) {
        logger.info("Error: You have to sign in!");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    } else {
        try {
            //init analytics
            auth.getUserAnalytics(code);

            response.setStatus(HttpServletResponse.SC_OK);

        } catch (IOException e) {
            logger.info("IOException .. Problem in reading user data.");
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        }
    }

    return "redirect:/";
}