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:it.smartcommunitylab.aac.auth.fb.FBController.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 that was saved
 * in session. If it is not response status is UNAUTHORIZED, otherwise it
 * retrieves user data. If user is not already saved in db, then user is
 * added in db, iff email is not already used, otherwise it sends an
 * UNAUTHORIZED status and redirect user to home page without authenticating
 * him/her. If it is all ok, then it authenticates user in spring security
 * and create cookie user. Then redirects authenticated user to home page
 * where user can access protected resources.
 * //  ww  w  .ja  v a 2s  .com
 * @param request
 *            : instance of {@link HttpServletRequest}
 * @param response
 *            : instance of {@link HttpServletResponse}
 * @return redirect to home page
 */
@RequestMapping(value = "/callback", method = RequestMethod.GET)
public String confirmStateToken(HttpServletRequest request, HttpServletResponse response) {

    String code = request.getParameter("code");

    // compare state token in session and state token in response of google
    // if equals return to home
    // if not error page
    if (code == null) {
        logger.error("Error in google authentication flow");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        return "";
    } else {
        try {
            FBUser userInfo = auth.getUserInfoJson(code);
            response.setStatus(HttpServletResponse.SC_OK);
            request.getSession().setAttribute(FBAuthHelper.SESSION_FB_CHECK, "true");
            String res = String.format(
                    "redirect:/eauth/facebook?" + "target=%s" + "&id=%s" + "&first_name=%s" + "&last_name=%s",
                    URLEncoder.encode((String) request.getSession().getAttribute("redirect"), "UTF8"),
                    userInfo.getId(), userInfo.getFirst_name(), userInfo.getLast_name());
            if (StringUtils.hasText(userInfo.getEmail())) {
                res += "&email=" + userInfo.getEmail();
            }
            return res;
        } catch (IOException e) {
            logger.error("IOException .. Problem in reading user data.", e);
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        }
    }

    return "redirect:/";
}

From source file:com.thinkberg.webdav.PropPatchHandler.java

/**
 * Handle a PROPPATCH request.//from w w  w .  j a va2 s . com
 *
 * @param request  the servlet request
 * @param response the servlet response
 * @throws IOException if there is an error that cannot be handled normally
 */
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    FileObject object = VFSBackend.resolveFile(request.getPathInfo());

    try {
        if (!LockManager.getInstance().evaluateCondition(object, getIf(request)).result) {
            response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
            return;
        }
    } catch (LockException e) {
        response.sendError(SC_LOCKED);
        return;
    } catch (ParseException e) {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    if (object.exists()) {
        SAXReader saxReader = new SAXReader();
        try {
            Document propDoc = saxReader.read(request.getInputStream());
            logXml(propDoc);

            Element propUpdateEl = propDoc.getRootElement();
            List<Element> requestedProperties = new ArrayList<Element>();
            for (Object elObject : propUpdateEl.elements()) {
                Element el = (Element) elObject;
                String command = el.getName();
                if (AbstractDavResource.TAG_PROP_SET.equals(command)
                        || AbstractDavResource.TAG_PROP_REMOVE.equals(command)) {
                    for (Object propElObject : el.elements()) {
                        for (Object propNameElObject : ((Element) propElObject).elements()) {
                            Element propNameEl = (Element) propNameElObject;
                            requestedProperties.add(propNameEl);
                        }
                    }
                }
            }

            // respond as XML encoded multi status
            response.setContentType("text/xml");
            response.setCharacterEncoding("UTF-8");
            response.setStatus(SC_MULTI_STATUS);

            Document multiStatusResponse = getMultiStatusResponse(object, requestedProperties,
                    getBaseUrl(request));

            logXml(multiStatusResponse);

            // write the actual response
            XMLWriter writer = new XMLWriter(response.getWriter(), OutputFormat.createCompactFormat());
            writer.write(multiStatusResponse);
            writer.flush();
            writer.close();

        } catch (DocumentException e) {
            LOG.error("invalid request: " + e.getMessage());
            response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        }
    } else {
        LOG.error(object.getName().getPath() + " NOT FOUND");
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    }
}

From source file:ch.entwine.weblounge.test.harness.content.PageContentTest.java

/**
 * Tests for a non-existing page and makes sure that a 404 is returned.
 * //w  w  w.  ja  v  a 2  s . co  m
 * @param serverUrl
 *          the server url
 */
private void testNonExistingPage(String serverUrl) throws Exception {
    logger.info("Preparing test of non-existing page content");

    String requestUrl = UrlUtils.concat(serverUrl, requestPath, "does-not-exist", "index.html");

    logger.info("Sending request to {}", requestUrl);
    HttpGet request = new HttpGet(requestUrl);

    // Send and the request and examine the response
    logger.debug("Sending request to {}", request.getURI());
    HttpClient httpClient = new DefaultHttpClient();
    try {
        HttpResponse response = TestUtils.request(httpClient, request, null);
        assertEquals(HttpServletResponse.SC_NOT_FOUND, response.getStatusLine().getStatusCode());
        TestUtils.parseTextResponse(response);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:com.xpn.xwiki.web.DeleteAttachmentAction.java

/**
 * {@inheritDoc}/* ww w  .j  a v  a 2s  .  c o m*/
 * 
 * @see com.xpn.xwiki.web.XWikiAction#action(com.xpn.xwiki.XWikiContext)
 */
@Override
public boolean action(XWikiContext context) throws XWikiException {
    // CSRF prevention
    if (!csrfTokenCheck(context)) {
        return false;
    }

    XWikiRequest request = context.getRequest();
    XWikiResponse response = context.getResponse();
    XWikiDocument doc = context.getDoc();
    XWikiAttachment attachment = null;
    XWiki xwiki = context.getWiki();
    String filename;

    // Delete from the trash
    if (request.getParameter("trashId") != null) {
        long trashId = NumberUtils.toLong(request.getParameter("trashId"));
        DeletedAttachment da = xwiki.getAttachmentRecycleBinStore().getDeletedAttachment(trashId, context,
                true);
        // If the attachment hasn't been previously deleted (i.e. it's not in the deleted attachment store) then
        // don't try to delete it and instead redirect to the attachment list.
        if (da != null) {
            com.xpn.xwiki.api.DeletedAttachment daapi = new com.xpn.xwiki.api.DeletedAttachment(da, context);
            if (!daapi.canDelete()) {
                throw new XWikiException(XWikiException.MODULE_XWIKI_ACCESS,
                        XWikiException.ERROR_XWIKI_ACCESS_DENIED,
                        "You are not allowed to delete an attachment from the trash "
                                + "immediately after it has been deleted from the wiki");
            }
            if (!da.getDocName().equals(doc.getFullName())) {
                throw new XWikiException(XWikiException.MODULE_XWIKI_APP,
                        XWikiException.ERROR_XWIKI_APP_URL_EXCEPTION,
                        "The specified trash entry does not match the current document");
            }
            // TODO: Add a confirmation check
            xwiki.getAttachmentRecycleBinStore().deleteFromRecycleBin(trashId, context, true);
        }
        sendRedirect(response, Utils.getRedirect("attach", context));
        return false;
    }

    if (context.getMode() == XWikiContext.MODE_PORTLET) {
        filename = request.getParameter("filename");
    } else {
        // Note: We use getRequestURI() because the spec says the server doesn't decode it, as
        // we want to use our own decoding.
        String requestUri = request.getRequestURI();
        filename = Util.decodeURI(requestUri.substring(requestUri.lastIndexOf("/") + 1), context);
    }

    XWikiDocument newdoc = doc.clone();

    // An attachment can be indicated either using an id, or using the filename.
    if (request.getParameter("id") != null) {
        int id = NumberUtils.toInt(request.getParameter("id"));
        if (newdoc.getAttachmentList().size() > id) {
            attachment = newdoc.getAttachmentList().get(id);
        }
    } else {
        attachment = newdoc.getAttachment(filename);
    }

    // No such attachment
    if (attachment == null) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        VelocityContext vcontext = (VelocityContext) context.get("vcontext");
        if (vcontext != null) {
            vcontext.put("message",
                    context.getMessageTool().get("core.action.deleteAttachment.failed", filename));
            vcontext.put("details",
                    context.getMessageTool().get("platform.core.action.deleteAttachment.noAttachment"));
        }
        return true;
    }

    newdoc.setAuthor(context.getUser());

    // Set "deleted attachment" as the version comment.
    ArrayList<String> params = new ArrayList<String>();
    params.add(filename);
    if (attachment.isImage(context)) {
        newdoc.setComment(context.getMessageTool().get("core.comment.deleteImageComment", params));
    } else {
        newdoc.setComment(context.getMessageTool().get("core.comment.deleteAttachmentComment", params));
    }

    try {
        newdoc.deleteAttachment(attachment, context);

        // Needed to counter a side effect: the attachment is deleted from the newdoc.originalDoc as well
        newdoc.setOriginalDocument(doc);

        // Also save the document and attachment metadata
        context.getWiki().saveDocument(newdoc, context);
    } catch (Exception ex) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        VelocityContext vcontext = (VelocityContext) context.get("vcontext");
        if (vcontext != null) {
            vcontext.put("message",
                    context.getMessageTool().get("core.action.deleteAttachment.failed", filename));
            vcontext.put("details", ExceptionUtils.getRootCauseMessage(ex));
        }
        return true;
    }

    // forward to attach page
    String redirect = Utils.getRedirect("attach", context);
    sendRedirect(response, redirect);

    return false;
}

From source file:edu.cornell.mannlib.vitro.webapp.controller.individual.IndividualController.java

private ResponseValues doNotFound() {
    Map<String, Object> body = new HashMap<String, Object>();
    body.put("title", "Individual Not Found");
    body.put("errorMessage", "The individual was not found in the system.");

    return new TemplateResponseValues(TEMPLATE_HELP, body, HttpServletResponse.SC_NOT_FOUND);
}

From source file:net.bhira.sample.api.controller.CompanyController.java

/**
 * Fetch the instance of {@link net.bhira.sample.model.Company} represented by given companyId
 * and return it as JSON object.//from  w  w w  .  j av a2  s.  c  om
 * 
 * @param companyId
 *            the ID for {@link net.bhira.sample.model.Company}.
 * @param response
 *            the http response to which the results will be written.
 * @return an instance of {@link net.bhira.sample.model.Company} as JSON.
 */
@RequestMapping(value = "/company/{companyId}", method = RequestMethod.GET)
@ResponseBody
public Callable<String> getCompany(@PathVariable long companyId, HttpServletResponse response) {
    return new Callable<String>() {
        public String call() throws Exception {
            String body = "";
            try {
                LOG.debug("servicing GET company/{}", companyId);
                Company company = companyService.load(companyId);
                LOG.debug("GET company/{}, found = {}", companyId, company != null);
                if (company == null) {
                    response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                } else {
                    body = JsonUtil.createGson().toJson(company);
                }
            } catch (Exception ex) {
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                body = ex.getLocalizedMessage();
                LOG.warn("Error loading company/{}. {}", companyId, body);
                LOG.debug("Load error stacktrace: ", ex);
            }
            return body;
        }
    };
}

From source file:com.haulmont.cuba.restapi.DataServiceController.java

@RequestMapping(value = "/api/find.{type}", method = RequestMethod.GET)
public void find(@PathVariable String type, @RequestParam(value = "e") String entityRef,
        @RequestParam(value = "s") String sessionId,
        @RequestParam(value = "dynamicAttributes", required = false) Boolean dynamicAttributes,
        HttpServletRequest request, HttpServletResponse response)
        throws IOException, InvocationTargetException, NoSuchMethodException, IllegalAccessException {

    if (!connect(sessionId, response))
        return;//from   w  w  w  .  j a v a 2 s  .  c  o m

    try {
        EntityLoadInfo loadInfo = EntityLoadInfo.parse(entityRef);
        if (loadInfo == null) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }
        MetaClass metaClass = loadInfo.getMetaClass();
        if (!readPermitted(metaClass)) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            return;
        }

        Object objectId = loadInfo.getId();

        LoadContext loadCtx = new LoadContext(metaClass);
        loadCtx.setLoadDynamicAttributes(Boolean.TRUE.equals(dynamicAttributes));
        loadCtx.setId(objectId);
        if (loadInfo.getViewName() != null) {
            loadCtx.setView(loadInfo.getViewName());
        } else {
            View view = metadata.getViewRepository().getView(metaClass, View.LOCAL);
            loadCtx.setView(new View(view, "local-with-system-props", true));
        }

        Entity entity = dataService.load(loadCtx);
        if (entity == null) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        } else {
            Converter converter = conversionFactory.getConverter(type);
            String result = converter.process(entity, metaClass, loadCtx.getView());
            writeResponse(response, result, converter.getMimeType());
        }
    } catch (Throwable e) {
        sendError(request, response, e);
    } finally {
        authentication.end();
    }
}

From source file:com.nesscomputing.httpserver.jetty.ClasspathResourceHandler.java

@Override
public void handle(final String target, final Request baseRequest, final HttpServletRequest request,
        final HttpServletResponse response) throws IOException, ServletException {
    if (baseRequest.isHandled()) {
        return;//from  w  w w  .ja va  2  s.c  o m
    }

    String pathInfo = request.getPathInfo();

    // Only serve the content if the request matches the base path.
    if (pathInfo == null || !pathInfo.startsWith(basePath)) {
        return;
    }

    pathInfo = pathInfo.substring(basePath.length());

    if (!pathInfo.startsWith("/") && !pathInfo.isEmpty()) {
        // basepath is /foo and request went to /foobar --> pathInfo starts with bar
        // basepath is /foo and request went to /foo --> pathInfo should be /index.html
        return;
    }

    // Allow index.html as welcome file
    if ("/".equals(pathInfo) || "".equals(pathInfo)) {
        pathInfo = "/index.html";
    }

    boolean skipContent = false;

    // When a request hits this handler, it will serve something. Either data or an error.
    baseRequest.setHandled(true);

    final String method = request.getMethod();
    if (!StringUtils.equals(HttpMethods.GET, method)) {
        if (StringUtils.equals(HttpMethods.HEAD, method)) {
            skipContent = true;
        } else {
            response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            return;
        }
    }

    // Does the request contain an IF_MODIFIED_SINCE header?
    final long ifModifiedSince = request.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE);
    if (ifModifiedSince > 0 && startupTime <= ifModifiedSince / 1000 && !is304Disabled) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    InputStream resourceStream = null;

    try {
        if (pathInfo.startsWith("/")) {
            final String resourcePath = resourceLocation + pathInfo;
            resourceStream = getClass().getResourceAsStream(resourcePath);
        }

        if (resourceStream == null) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        final Buffer mime = MIME_TYPES.getMimeByExtension(request.getPathInfo());
        if (mime != null) {
            response.setContentType(mime.toString("ISO8859-1"));
        }

        response.setDateHeader(HttpHeaders.LAST_MODIFIED, startupTime * 1000L);

        if (skipContent) {
            return;
        }

        // Send the content out. Lifted straight out of ResourceHandler.java

        OutputStream out = null;
        try {
            out = response.getOutputStream();
        } catch (IllegalStateException e) {
            out = new WriterOutputStream(response.getWriter());
        }

        if (out instanceof AbstractHttpConnection.Output) {
            ((AbstractHttpConnection.Output) out).sendContent(resourceStream);
        } else {
            ByteStreams.copy(resourceStream, out);
        }
    } finally {
        IOUtils.closeQuietly(resourceStream);
    }
}

From source file:com.eryansky.common.web.servlet.RemoteContentServlet.java

private void fetchContentByJDKConnection(HttpServletResponse response, String contentUrl) throws IOException {

    HttpURLConnection connection = (HttpURLConnection) new URL(contentUrl).openConnection();
    // Socket/* ww w.  j a  va 2s  .  co  m*/
    connection.setReadTimeout(TIMEOUT_SECONDS * 1000);
    try {
        connection.connect();

        // ?
        InputStream input;
        try {
            input = connection.getInputStream();
        } catch (FileNotFoundException e) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, contentUrl + " is not found.");
            return;
        }

        // Header
        response.setContentType(connection.getContentType());
        if (connection.getContentLength() > 0) {
            response.setContentLength(connection.getContentLength());
        }

        // 
        OutputStream output = response.getOutputStream();
        try {
            // byte?InputStreamOutputStream, ?4k.
            IOUtils.copy(input, output);
            output.flush();
        } finally {
            // ??InputStream.
            IOUtils.closeQuietly(input);
        }
    } finally {
        connection.disconnect();
    }
}

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

/**
 * Action???????? //w w  w  . j a  v  a2  s  .c  o m
 * 1.??eventSubmit_XxxxdoXxxx
 * 2.?__method?do
 */
public final ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest req,
        HttpServletResponse res) throws Exception {
    ActionForward af = beforeExecute(mapping, form, req, res);
    if (af != null)
        return af;

    String param = null;
    String value = null;

    String __method = req.getParameter(METHOD_IDENT_PARAM);
    if (StringUtils.isNotBlank(__method)) {
        param = METHOD_PREFIX + __method;
    } else {
        for (Enumeration params = req.getParameterNames(); params.hasMoreElements();) {
            String t_param = (String) params.nextElement();
            if (t_param.startsWith(SUBMIT_BUTTON_PREFIX)) {
                value = req.getParameter(t_param);
                param = METHOD_PREFIX + t_param.substring(SUBMIT_BUTTON_PREFIX.length());
                break;
            }
        }
    }

    if (param == null)
        param = "doDefault";

    try {
        return callActionMethod(mapping, form, req, res, param, value);
    } catch (InvocationTargetException e) {
        Throwable t = e.getCause();
        if (t instanceof IllegalAccessException) {
            res.sendError(HttpServletResponse.SC_FORBIDDEN);
            return null;
        }
        log.error("Exception occur when calling " + param + " in action:" + getClass().getName(), t);
        if (t instanceof Exception)
            throw (Exception) t;
        else
            throw new Exception(t);
    } catch (NoSuchMethodException e) {
        res.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
        return null;
    } finally {
        afterExecute(mapping, form, req, res);
    }
}