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.google.gerrit.httpd.auth.oauth.OAuthSession.java

boolean login(HttpServletRequest request, HttpServletResponse response, OAuthServiceProvider oauth)
        throws IOException {
    log.debug("Login " + this);

    if (isOAuthFinal(request)) {
        if (!checkState(request)) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return false;
        }//from  w w  w  .  j a v  a2s.  co m

        log.debug("Login-Retrieve-User " + this);
        OAuthToken token = oauth.getAccessToken(new OAuthVerifier(request.getParameter("code")));
        user = oauth.getUserInfo(token);

        if (isLoggedIn()) {
            log.debug("Login-SUCCESS " + this);
            authenticateAndRedirect(request, response, token);
            return true;
        }
        response.sendError(SC_UNAUTHORIZED);
        return false;
    }
    log.debug("Login-PHASE1 " + this);
    redirectToken = request.getRequestURI();
    // We are here in content of filter.
    // Due to this Jetty limitation:
    // https://bz.apache.org/bugzilla/show_bug.cgi?id=28323
    // we cannot use LoginUrlToken.getToken() method,
    // because it relies on getPathInfo() and it is always null here.
    redirectToken = redirectToken.substring(request.getContextPath().length());
    response.sendRedirect(oauth.getAuthorizationUrl() + "&state=" + state);
    return false;
}

From source file:com.day.cq.wcm.foundation.forms.impl.FormsListServlet.java

/**
 * {@inheritDoc}//from  w  w  w  .j  a  va  2  s .  c  o m
 */
protected void doGet(SlingHttpServletRequest req, SlingHttpServletResponse resp, Predicate predicate)
        throws ServletException, IOException {
    try {
        JSONWriter w = new JSONWriter(resp.getWriter());
        if (req.getRequestURI().contains("/actions")) {
            resp.setContentType("application/json");
            resp.setCharacterEncoding("utf-8");

            writeActions(w);
        } else if (req.getRequestURI().contains("/constraints")) {
            resp.setContentType("application/json");
            resp.setCharacterEncoding("utf-8");

            writeConstraints(w);
        } else if (req.getRequestURI().contains("/actiondialog")) {
            final String dialogPath = this.formsManager.getDialogPathForAction(req.getParameter("id"));
            if (dialogPath != null) {
                req.getRequestDispatcher(dialogPath + ".infinity.json").forward(req, resp);
            } else {
                // if there is no dialog just return an empty dialog
                resp.setContentType("application/json");
                resp.setCharacterEncoding("utf-8");

                resp.getWriter().write("{jcr:primaryType:\"cq:WidgetCollection\"}");
            }
        } else if (req.getRequestURI().contains("/report")) {
            // we collect the information and then redirect to the bulk editor
            final String path = req.getParameter("path");
            if (path == null || path.trim().length() == 0) {
                resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Path parameter is missing.");
                return;
            }
            final Resource formStartResource = req.getResourceResolver().getResource(path);
            if (formStartResource == null) {
                resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Resource not found.");
                return;
            }
            final ValueMap vm = ResourceUtil.getValueMap(formStartResource);
            final StringBuilder sb = new StringBuilder();
            sb.append(req.getContextPath());
            sb.append("/etc/importers/bulkeditor.html?rootPath=");
            String actionPath = vm.get(FormsConstants.START_PROPERTY_ACTION_PATH, "");
            if (actionPath == null || actionPath.trim().length() == 0) {
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        "Missing '" + FormsConstants.START_PROPERTY_ACTION_PATH + "' property on node "
                                + formStartResource.getPath());
            }
            if (actionPath.endsWith("*")) {
                actionPath = actionPath.substring(0, actionPath.length() - 1);
            }
            if (actionPath.endsWith("/")) {
                actionPath = actionPath.substring(0, actionPath.length() - 1);
            }
            sb.append(FormsHelper.encodeValue(actionPath));
            sb.append("&initialSearch=true&contentMode=false&spc=true");
            final Iterator<Resource> elements = FormsHelper.getFormElements(formStartResource);
            while (elements.hasNext()) {
                final Resource element = elements.next();
                FieldHelper.initializeField(req, resp, element);
                final FieldDescription[] descs = FieldHelper.getFieldDescriptions(req, element);
                for (final FieldDescription desc : descs) {
                    if (!desc.isPrivate()) {
                        final String name = FormsHelper.encodeValue(desc.getName());
                        sb.append("&cs=");
                        sb.append(name);
                        sb.append("&cv=");
                        sb.append(name);
                    }
                }
            }
            resp.sendRedirect(sb.toString());
        }
    } catch (Exception e) {
        logger.error("Error while generating JSON list", e);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
        return;
    }
}

From source file:com.openmeap.admin.web.servlet.WebViewServlet.java

@SuppressWarnings("unchecked")
@Override/*from  ww  w.j a v  a2s . co  m*/
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {

    logger.trace("in service");

    ModelManager mgr = getModelManager();
    GlobalSettings settings = mgr.getGlobalSettings();
    String validTempPath = settings.validateTemporaryStoragePath();
    if (validTempPath != null) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, validTempPath);
    }

    String pathInfo = request.getPathInfo();
    String[] pathParts = pathInfo.split("[/]");
    if (pathParts.length < 4) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    }
    String remove = pathParts[1] + "/" + pathParts[2] + "/" + pathParts[3];
    String fileRelative = pathInfo.replace(remove, "");

    String applicationNameString = URLDecoder.decode(pathParts[APP_NAME_INDEX], FormConstants.CHAR_ENC_DEFAULT);
    String archiveHash = URLDecoder.decode(pathParts[APP_VER_INDEX], FormConstants.CHAR_ENC_DEFAULT);

    Application app = mgr.getModelService().findApplicationByName(applicationNameString);
    ApplicationArchive arch = mgr.getModelService().findApplicationArchiveByHashAndAlgorithm(app, archiveHash,
            "MD5");

    String authSalt = app.getProxyAuthSalt();
    String authToken = URLDecoder.decode(pathParts[AUTH_TOKEN_INDEX], FormConstants.CHAR_ENC_DEFAULT);

    try {
        if (!AuthTokenProvider.validateAuthToken(authSalt, authToken)) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
        }
    } catch (DigestException e1) {
        throw new GenericRuntimeException(e1);
    }

    File fileFull = new File(
            arch.getExplodedPath(settings.getTemporaryStoragePath()).getAbsolutePath() + "/" + fileRelative);
    try {
        FileNameMap fileNameMap = URLConnection.getFileNameMap();
        String mimeType = fileNameMap.getContentTypeFor(fileFull.toURL().toString());
        response.setContentType(mimeType);
        response.setContentLength(Long.valueOf(fileFull.length()).intValue());

        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            //response.setStatus(HttpServletResponse.SC_FOUND);
            inputStream = new FileInputStream(fileFull);
            outputStream = response.getOutputStream();
            Utils.pipeInputStreamIntoOutputStream(inputStream, outputStream);
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
            response.getOutputStream().flush();
            response.getOutputStream().close();
        }
    } catch (FileNotFoundException e) {
        logger.error("Exception {}", e);
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    } catch (IOException ioe) {
        logger.error("Exception {}", ioe);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:com.ocpsoft.pretty.faces.application.PrettyRedirector.java

public void send404(final FacesContext facesContext) {
    try {/*from  www.j  av  a 2  s  .c  o  m*/
        HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    } catch (IOException e) {
        throw new PrettyException(e);
    }
}

From source file:net.myrrix.web.servlets.RecommendToAnonymousServlet.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  . ja  v a 2 s  . c  om
    }
    Iterator<String> pathComponents = SLASH.split(pathInfo).iterator();
    Pair<long[], float[]> itemIDsAndValue;
    try {
        itemIDsAndValue = 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();
    RescorerProvider rescorerProvider = getRescorerProvider();
    try {
        IDRescorer rescorer = rescorerProvider == null ? null
                : rescorerProvider.getRecommendToAnonymousRescorer(itemIDs, recommender,
                        getRescorerParams(request));
        Iterable<RecommendedItem> recommended = recommender.recommendToAnonymous(itemIDs, values,
                getHowMany(request), rescorer);
        output(request, response, recommended);
    } 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);
    } catch (IllegalArgumentException iae) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, iae.toString());
    }
}

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

@RequestMapping(value = VideoSvcApi.VIDEO_SVC_PATH + "/{id}/like", method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.OK)/*  ww  w  .  ja v  a2 s  .c  o  m*/
public void likeVideo(@PathVariable("id") long id, HttpServletResponse response, Principal p) {
    Video v = videos.findOne(id);
    if (v == null) {
        sendError(response, HttpServletResponse.SC_NOT_FOUND, "Video not found");
        return;
    }
    if (!v.likeVideo(p.getName())) {
        sendError(response, HttpServletResponse.SC_BAD_REQUEST, "Video already liked by user");
        return;
    }
    videos.save(v);
}

From source file:edu.northwestern.bioinformatics.studycalendar.web.subject.SubjectCentricScheduleController.java

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    Subject subject = interpretUsingIdOrGridId(request, "subject", subjectDao);

    // Try assignment
    if (subject == null) {
        StudySubjectAssignment assignment = interpretUsingIdOrGridId(request, "assignment",
                studySubjectAssignmentDao);
        if (assignment != null)
            subject = assignment.getSubject();
    }//from   w ww  . jav a 2 s.  c  o m
    // Try calendar
    if (subject == null) {
        ScheduledCalendar calendar = interpretUsingIdOrGridId(request, "calendar", scheduledCalendarDao);
        if (calendar != null)
            subject = calendar.getAssignment().getSubject();
    }

    if (subject == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND, "No matching subject found");
        return null;
    }

    List<UserStudySubjectAssignmentRelationship> assignments = new ArrayList<UserStudySubjectAssignmentRelationship>(
            subject.getAssignments().size());
    for (StudySubjectAssignment ssa : subject.getAssignments()) {
        assignments.add(new UserStudySubjectAssignmentRelationship(applicationSecurityManager.getUser(), ssa));
    }
    MultipleAssignmentScheduleView schedule = new MultipleAssignmentScheduleView(assignments, nowFactory);

    ModelMap model = new ModelMap("schedule", schedule);
    model.addAttribute(subject);
    model.addAttribute("schedulePreview", false);
    model.addAttribute("canUpdateSchedule", canUpdateSchedule(assignments));
    model.addAttribute("todayDate", FormatTools.getLocal().formatDate(Calendar.getInstance().getTime()));
    return new ModelAndView("subject/schedule", model);
}

From source file:eu.dasish.annotation.backend.rest.CachedRepresentationResource.java

/**
 * /*from  w w  w  .  j av  a2s . c  o m*/
 * @param externalId the external UUID of a cached representation.
 * @return a {@link CachedRepresentationInfo} object representing the metadata for the cached representation with the "externalId".
 * @throws IOException if sending an error fails.
 */
@GET
@Produces(MediaType.TEXT_XML)
@Path("{cachedid: " + BackendConstants.regExpIdentifier + "}/metadata")
@Transactional(readOnly = true)
public JAXBElement<CachedRepresentationInfo> getCachedRepresentationInfo(
        @PathParam("cachedid") String externalId) throws IOException {
    Map params = new HashMap();
    try {
        CachedRepresentationInfo result = (CachedRepresentationInfo) (new RequestWrappers(this))
                .wrapRequestResource(params, new GetCachedRepresentationInfo(), Resource.CACHED_REPRESENTATION,
                        Access.READ, externalId);
        if (result != null) {
            return (new ObjectFactory()).createCachedRepresentationInfo(result);
        } else {
            return (new ObjectFactory()).createCachedRepresentationInfo(new CachedRepresentationInfo());
        }
    } catch (NotInDataBaseException e1) {
        httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND, e1.getMessage());
        return new ObjectFactory().createCachedRepresentationInfo(new CachedRepresentationInfo());
    } catch (ForbiddenException e2) {
        httpServletResponse.sendError(HttpServletResponse.SC_FORBIDDEN, e2.getMessage());
        return new ObjectFactory().createCachedRepresentationInfo(new CachedRepresentationInfo());
    }
}

From source file:cc.kune.core.server.manager.file.FileDownloadManagerUtils.java

/**
 * Return not found404.//from   w w w .  j  a v  a 2  s.  c o  m
 * 
 * @param resp
 *          the resp
 * @throws IOException
 *           Signals that an I/O exception has occurred.
 */
public static void returnNotFound404(final HttpServletResponse resp) throws IOException {
    resp.getWriter().println("Content not found");
    resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
}