List of usage examples for javax.servlet.http HttpServletResponse SC_NOT_FOUND
int SC_NOT_FOUND
To view the source code for javax.servlet.http HttpServletResponse SC_NOT_FOUND.
Click Source Link
From source file:com.ms.app.web.comset.controller.ComsetController.java
private WebResult goto404() { response.setStatus(HttpServletResponse.SC_NOT_FOUND); return null; }
From source file:com.sitewhere.web.rest.controllers.UsersController.java
/** * Get a user by unique username./* ww w. j a va2 s . c om*/ * * @param username * @return * @throws SiteWhereException */ @RequestMapping(value = "/{username:.+}", method = RequestMethod.GET) @ResponseBody @ApiOperation(value = "Get user by username") @PreAuthorize(value = SiteWhereRoles.PREAUTH_REST_AND_USER_ADMIN) @Documented(examples = { @Example(stage = Stage.Response, json = Users.CreateUserResponse.class, description = "getUserByUsernameResponse.md") }) public User getUserByUsername( @ApiParam(value = "Unique username", required = true) @PathVariable String username) throws SiteWhereException { Tracer.start(TracerCategory.RestApiCall, "getUserByUsername", LOGGER); try { IUser user = getUserManagement().getUserByUsername(StringEscapeUtils.unescapeHtml(username)); if (user == null) { throw new SiteWhereSystemException(ErrorCode.InvalidUsername, ErrorLevel.ERROR, HttpServletResponse.SC_NOT_FOUND); } return User.copy(user); } finally { Tracer.stop(LOGGER); } }
From source file:org.onehippo.forge.camel.demo.rest.services.AbstractRestUpdateResource.java
/** * Invoke Solr Update Service based on the given <code>action</code> and <code>id</code>. * @param action Update action name. It should be either 'addOrReplace' or 'delete'. * @param handleUuid The document handle identifier. * @return//w w w . j av a2s . c om */ @POST @Path("/") public Response update(@QueryParam("action") @DefaultValue(INDEX_ACTION) String action, @QueryParam("id") String handleUuid) { log.info("Updating ('{}') document from search index: {}", action, handleUuid); if (StringUtils.isNotEmpty(handleUuid)) { try { HstRequestContext requestContext = RequestContextProvider.get(); if (INDEX_ACTION.equals(action)) { Node node = requestContext.getSession().getNodeByIdentifier(handleUuid); HippoBean bean = (HippoBean) getObjectConverter(requestContext).getObject(node); if (bean instanceof BaseHippoDocument) { BaseHippoDocument document = (BaseHippoDocument) bean; JSONObject payload = createDocumentAddPayload(document); if (payload != null) { HttpResponse httpResponse = invokeUpdateService(action, payload); if (httpResponse.getStatusLine().getStatusCode() != HttpServletResponse.SC_OK) { return Response.status(httpResponse.getStatusLine().getStatusCode()).build(); } } } else { log.warn("The bean from '{}' is not a BaseHippoDocument.", handleUuid); } } else if (DELETE_ACTION.equals(action)) { JSONObject payload = createDocumentDeletePayload(handleUuid); HttpResponse httpResponse = invokeUpdateService(action, payload); final int status = httpResponse.getStatusLine().getStatusCode(); if (status >= HttpServletResponse.SC_BAD_REQUEST) { if (status == HttpServletResponse.SC_NOT_FOUND || status == HttpServletResponse.SC_GONE) { log.info("The document is not found or no more exists: '{}'.", handleUuid); } else if (status != HttpServletResponse.SC_OK) { return Response.status(httpResponse.getStatusLine().getStatusCode()).build(); } } } else { log.warn("Unknown action: '{}'.", action); } } catch (ItemNotFoundException e) { log.warn("The news is not found by the identifier: '{}'", handleUuid); } catch (Exception e) { if (log.isDebugEnabled()) { log.warn("Failed to find news by identifier.", e); } else { log.warn("Failed to find news by identifier. {}", e.toString()); } throw new WebApplicationException(e, buildServerErrorResponse(e)); } } return Response.ok().build(); }
From source file:com.sun.syndication.propono.atom.server.AtomServlet.java
/** * Handles an Atom GET by calling handler and writing results to response. *//*from www. j ava 2 s .c om*/ protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { log.debug("Entering"); AtomHandler handler = createAtomRequestHandler(req, res); String userName = handler.getAuthenticatedUsername(); if (userName != null) { AtomRequest areq = new AtomRequestImpl(req); try { if (handler.isAtomServiceURI(areq)) { // return an Atom Service document AtomService service = handler.getAtomService(areq); Document doc = service.serviceToDocument(); res.setContentType("application/atomsvc+xml; charset=utf-8"); Writer writer = res.getWriter(); XMLOutputter outputter = new XMLOutputter(); outputter.setFormat(Format.getPrettyFormat()); outputter.output(doc, writer); writer.close(); res.setStatus(HttpServletResponse.SC_OK); } else if (handler.isCategoriesURI(areq)) { Categories cats = handler.getCategories(areq); res.setContentType("application/xml"); Writer writer = res.getWriter(); Document catsDoc = new Document(); catsDoc.setRootElement(cats.categoriesToElement()); XMLOutputter outputter = new XMLOutputter(); outputter.output(catsDoc, writer); writer.close(); res.setStatus(HttpServletResponse.SC_OK); } else if (handler.isCollectionURI(areq)) { // return a collection Feed col = handler.getCollection(areq); col.setFeedType(FEED_TYPE); WireFeedOutput wireFeedOutput = new WireFeedOutput(); Document feedDoc = wireFeedOutput.outputJDom(col); res.setContentType("application/atom+xml; charset=utf-8"); Writer writer = res.getWriter(); XMLOutputter outputter = new XMLOutputter(); outputter.setFormat(Format.getPrettyFormat()); outputter.output(feedDoc, writer); writer.close(); res.setStatus(HttpServletResponse.SC_OK); } else if (handler.isEntryURI(areq)) { // return an entry Entry entry = handler.getEntry(areq); if (entry != null) { res.setContentType("application/atom+xml; type=entry; charset=utf-8"); Writer writer = res.getWriter(); Atom10Generator.serializeEntry(entry, writer); writer.close(); } else { res.setStatus(HttpServletResponse.SC_NOT_FOUND); } } else if (handler.isMediaEditURI(areq)) { AtomMediaResource entry = handler.getMediaResource(areq); res.setContentType(entry.getContentType()); res.setContentLength((int) entry.getContentLength()); Utilities.copyInputToOutput(entry.getInputStream(), res.getOutputStream()); res.getOutputStream().flush(); res.getOutputStream().close(); } else { res.setStatus(HttpServletResponse.SC_NOT_FOUND); } } catch (AtomException ae) { res.sendError(ae.getStatus(), ae.getMessage()); log.debug("ERROR processing GET", ae); } catch (Exception e) { res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); log.debug("ERROR processing GET", e); } } else { res.setHeader("WWW-Authenticate", "BASIC realm=\"AtomPub\""); res.sendError(HttpServletResponse.SC_UNAUTHORIZED); } log.debug("Exiting"); }
From source file:org.piraso.server.spring.web.PirasoServlet.java
private void stopService(HttpServletResponse response, User user) throws IOException { ResponseLoggerService service = getRegistry().getLogger(user); if (service == null) { response.sendError(HttpServletResponse.SC_NOT_FOUND, String.format("Service for user '%s' not found.", user.toString())); return;/*w w w.j a v a2 s .c o m*/ } if (!service.isAlive()) { response.sendError(HttpServletResponse.SC_CONFLICT, String.format("Service for user '%s' not active.", user.toString())); getRegistry().removeUser(user); return; } try { // gracefully stop the service service.stopAndWait(stopTimeout); if (service.isAlive()) { response.sendError(HttpServletResponse.SC_REQUEST_TIMEOUT, String.format("Service for user '%s' stop timeout.", user.toString())); } } catch (InterruptedException ignored) { } }
From source file:eu.dasish.annotation.backend.rest.PrincipalResource.java
/** * //from w w w .j a v a 2 s. c om * @param email the e-mail of a principal. * @return a {@link Principal} representing the principal with the "email", * if such a principal is found; otherwise "SC_NOT_FOUND" error is sent. * @throws IOException if sending an error fails. */ @GET @Produces(MediaType.TEXT_XML) @Path("info") @Transactional(readOnly = true) public JAXBElement<Principal> getPrincipalByInfo(@QueryParam("email") String email) throws IOException { Map params = new HashMap<String, String>(); params.put("email", email); try { Principal result = (Principal) (new RequestWrappers(this)).wrapRequestResource(params, new GetPrincipalByInfo()); return (result != null) ? (new ObjectFactory().createPrincipal(result)) : (new ObjectFactory().createPrincipal(new Principal())); } catch (NotInDataBaseException e) { httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage()); return new ObjectFactory().createPrincipal(new Principal()); } catch (ForbiddenException e2) { httpServletResponse.sendError(HttpServletResponse.SC_FORBIDDEN, e2.getMessage()); return new ObjectFactory().createPrincipal(new Principal()); } }
From source file:com.sun.socialsite.web.rest.servlets.UploadServlet.java
/** * Note: using SuppressWarnings annotation because the Commons FileUpload API is * not genericized./*w ww. j a v a 2 s . c om*/ */ @Override @SuppressWarnings(value = "unchecked") protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { // ensure calling app/gadget has perm to use SocialSite API SecurityToken token = new AuthInfo(req).getSecurityToken(); Factory.getSocialSite().getPermissionManager().checkPermission(requiredPerm, token); GroupManager gmgr = Factory.getSocialSite().getGroupManager(); ProfileManager pmgr = Factory.getSocialSite().getProfileManager(); int errorCode = -1; Group group = null; Profile profile = null; // parse URL to get route and subjectId String route = null; String subjectId = ""; if (req.getPathInfo() != null) { String[] pathInfo = req.getPathInfo().split("/"); route = pathInfo[1]; subjectId = pathInfo[2]; } // first, figure out destination profile or group and check the // caller's permission to upload an image for that profile or group if ("profile".equals(route)) { if (token.getViewerId().equals(subjectId)) { profile = pmgr.getProfileByUserId(subjectId); } else { errorCode = HttpServletResponse.SC_UNAUTHORIZED; } } else if ("group".equals(route)) { group = gmgr.getGroupByHandle(subjectId); if (group != null) { // ensure called is group ADMIN or founder Profile viewer = pmgr.getProfileByUserId(token.getViewerId()); GroupRelationship grel = gmgr.getMembership(group, viewer); if (grel == null || (grel.getRelcode() != GroupRelationship.Relationship.ADMIN && grel.getRelcode() != GroupRelationship.Relationship.FOUNDER)) { } else { errorCode = HttpServletResponse.SC_UNAUTHORIZED; } } else { // group not found errorCode = HttpServletResponse.SC_NOT_FOUND; } } // next, parse out the image and save it in profile or group if (errorCode != -1 && group == null && profile == null) { errorCode = HttpServletResponse.SC_NOT_FOUND; } else if (errorCode == -1) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); FileItem fileItem = null; List<FileItem> items = (List<FileItem>) upload.parseRequest(req); if (items.size() > 0) { fileItem = items.get(0); } if ((fileItem != null) && (types.contains(fileItem.getContentType()))) { // read incomining image via Commons Upload InputStream is = fileItem.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); Utilities.copyInputToOutput(is, baos); byte[] byteArray = baos.toByteArray(); // save it in the profile or group indicated if (profile != null) { profile.setImageType(fileItem.getContentType()); profile.setImage(byteArray); pmgr.saveProfile(profile); Factory.getSocialSite().flush(); } else if (group != null) { group.setImageType(fileItem.getContentType()); group.setImage(byteArray); gmgr.saveGroup(group); Factory.getSocialSite().flush(); } else { // group or profile not indicated properly errorCode = HttpServletResponse.SC_NOT_FOUND; } } } if (errorCode == -1) { resp.sendError(HttpServletResponse.SC_OK); return; } else { resp.sendError(errorCode); } } catch (SecurityException sx) { log.error("Permission denied", sx); resp.sendError(HttpServletResponse.SC_UNAUTHORIZED); } catch (FileUploadException fx) { log.error("ERROR uploading profile image", fx); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } catch (SocialSiteException ex) { log.error("ERROR saving profile image", ex); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } }
From source file:ee.ria.xroad.asyncsender.ProxyClientTest.java
/** * Test./*from w w w. ja v a 2 s . co m*/ * @throws Exception if an error occurs */ @Test public void sendMessageAndExpectFaultResponse() throws Exception { thrown.expectError(ErrorCodes.X_HTTP_ERROR); createMockServer(new AbstractHandler() { @Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { checkHeader(request); try { IOUtils.copy(getFaultMessage(ErrorCodes.X_HTTP_ERROR, "bar", "baz", ""), response.getOutputStream()); response.setContentType(MimeTypes.TEXT_XML); response.setStatus(HttpServletResponse.SC_OK); } catch (Exception e) { response.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage()); } finally { baseRequest.setHandled(true); } } }); client.send(MimeTypes.TEXT_XML, getSimpleMessage()); }
From source file:com.carolinarollergirls.scoreboard.jetty.XmlScoreBoardServlet.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { super.doGet(request, response); try {// w w w.j ava 2s . c o m if ("/get".equals(request.getPathInfo())) get(request, response); else if ("/debug".equals(request.getPathInfo())) setDebug(request, response); else if ("/config".equals(request.getPathInfo())) listenerConfig(request, response); else if (request.getPathInfo().endsWith(".xml")) getAll(request, response); else if (!response.isCommitted()) response.sendError(HttpServletResponse.SC_NOT_FOUND); } catch (JDOMException jE) { ScoreBoardManager.printMessage("XmlScoreBoardServlet ERROR: " + jE.getMessage()); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } }
From source file:org.magnum.mobilecloud.video.VideoSvc.java
@RequestMapping(value = VideoSvcApi.VIDEO_SVC_PATH + "/{id}/likedby", method = RequestMethod.GET) public @ResponseBody Collection<String> getUsersWhoLikedVideo(@PathVariable("id") long id, HttpServletResponse response) {/*from ww w .jav a 2s .co m*/ Video video = videos.findOne(id); Set<String> users = null; if (video != null) { users = video.getLikesUserNames(); response.setStatus(HttpServletResponse.SC_OK); } else { response.setStatus(HttpServletResponse.SC_NOT_FOUND); } return users; }