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.seajas.search.attender.controller.FeedController.java
/** * Handle the request./*from w ww . ja va 2s. co m*/ * * @param request * @param response * @param locale * @throws Exception */ @RequestMapping(method = RequestMethod.GET) public void handleRequest(final HttpServletRequest request, final HttpServletResponse response, final Locale locale) throws Exception { String path = request.getPathInfo(); Integer results = null; String feedType = null; // The number of results may be optionally provided if (!StringUtils.isEmpty(request.getParameter(PARAM_RESULTS))) try { results = Integer.valueOf(request.getParameter(PARAM_RESULTS)); } catch (NumberFormatException e) { throw new Exception("Invalid result number given"); } if (!StringUtils.isEmpty(request.getParameter(PARAM_TYPE))) feedType = request.getParameter(PARAM_TYPE); // Reconstruct the URL from the request String baseUrl = request.getRequestURL().toString(); if (!StringUtils.isEmpty(request.getQueryString())) baseUrl += "?" + request.getQueryString(); if (path != null && path.startsWith("/feed")) path = path.substring(5); if (path != null && path.startsWith("/")) path = path.substring(1); if (!StringUtils.isEmpty(path)) { String[] pathParts = path.split("/"); // The first part should always indicate the UUID String profileUUID = pathParts[0]; // The second part is optional and defines the notification type NotificationType notificationType = pathParts.length > 1 && pathParts[1].equalsIgnoreCase(NotificationType.Weekly.toString()) ? NotificationType.Weekly : NotificationType.Daily; // First retrieve the profile and create the actual feed Profile profile = attenderService.getProfileByUUID(profileUUID); if (profile == null) { response.sendError(HttpServletResponse.SC_NOT_FOUND, "Unknown feed '" + profileUUID + "'"); return; } // Must have at least one confirmed subscriber Boolean isConfirmedOnce = false; for (ProfileSubscriber subscriber : profile.getSubscribers()) if (subscriber.getIsConfirmed()) { isConfirmedOnce = true; break; } if (!isConfirmedOnce) { response.sendError(HttpServletResponse.SC_FORBIDDEN, "This feed has no confirmed subscribers"); return; } SyndFeed result = feedService.createFeed(profile, notificationType, results, baseUrl, locale); // Set the feed type, or revert to the default if (feedType != null && availableFeedTypes.contains(feedType)) result.setFeedType(feedType); else result.setFeedType("rss_2.0"); // Set the response type and write out the result response.setContentType("application/xml; charset=UTF-8"); SyndFeedOutput output = new SyndFeedOutput(); output.output(result, response.getWriter()); } else response.sendError(HttpServletResponse.SC_NOT_FOUND, "No feed given"); }
From source file:com.adobe.cq.wcm.core.components.internal.servlets.AdaptiveImageServlet.java
@Override protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { try {/*from ww w .j ava2 s. c om*/ String[] selectors = request.getRequestPathInfo().getSelectors(); if (selectors.length != 1 && selectors.length != 2) { LOGGER.error("Expected 1 or 2 selectors, instead got: {}.", Arrays.toString(selectors)); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } Resource imageResource = request.getResource(); Image image = new Image(imageResource); if (!image.hasContent()) { LOGGER.error("The image from {} does not have a valid file reference.", imageResource.getPath()); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } if ("image/gif".equals(getImageType(request.getRequestPathInfo().getExtension()))) { if (checkModifiedSince(request, response)) { return; } else { response.setContentType("image/gif"); try { String fileReference = image.getFileReference(); if (StringUtils.isNotEmpty(fileReference)) { String damOriginalRendition = fileReference + "/jcr:content/renditions/original"; response.getOutputStream().write(IOUtils.toByteArray(request.getResourceResolver() .getResource(damOriginalRendition).adaptTo(InputStream.class))); } else { response.getOutputStream() .write(IOUtils.toByteArray(image.getData().getBinary().getStream())); } return; } catch (Exception e) { LOGGER.error("Cannot write GIF image stream.", e); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } } } String widthSelector = selectors[selectors.length - 1]; if (!DEFAULT_SELECTOR.equals(widthSelector)) { try { Integer width = Integer.parseInt(widthSelector); boolean isRequestedWidthAllowed = false; for (Integer allowedWidth : getAllowedRenditionWidths(request)) { if (width.equals(allowedWidth)) { isRequestedWidthAllowed = true; break; } } if (isRequestedWidthAllowed) { LOGGER.debug("The image was requested with a {}px width. Resizing.", width); threadLocalWidthSelector.set(width); } else { LOGGER.error("The requested width ({}) is not allowed by the content policy.", width); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } } catch (NumberFormatException e) { LOGGER.error("The requested width ({}) is not a valid Integer.", widthSelector); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } } else { List<Integer> allowedRenditionWidths = getAllowedRenditionWidths(request); if (!allowedRenditionWidths.isEmpty()) { // resize to the first value of the allowedRenditionWidths int size = allowedRenditionWidths.get(0); LOGGER.debug( "The image request contains no width information, but the image's content policy defines at least one " + "allowed width. Will resize the image to the first allowed width - {}px.", size); threadLocalWidthSelector.set(size); } else { // resize to the default value LOGGER.debug( "The image request contains no width information and there's no information about the allowed widths in " + "the image's content policy. Will resize the image to {}px.", defaultResizeWidth); threadLocalWidthSelector.set(defaultResizeWidth); } } super.doGet(request, response); } finally { threadLocalWidthSelector.remove(); } }
From source file:ru.mystamps.web.controller.CountryController.java
/** * @author Aleksander Parkhomenko//from ww w .j a v a 2s . c o m */ @GetMapping(Url.INFO_COUNTRY_BY_ID_PAGE) public View showInfoById(@Country @PathVariable("slug") LinkEntityDto country, HttpServletResponse response) throws IOException { if (country == null) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return null; } RedirectView view = new RedirectView(); view.setStatusCode(HttpStatus.MOVED_PERMANENTLY); view.setUrl(Url.INFO_COUNTRY_PAGE); return view; }
From source file:org.magnum.dataup.VideoUpController.java
@RequestMapping(value = VideoSvcApi.VIDEO_DATA_PATH, method = RequestMethod.GET) public void getData(@PathVariable(VideoSvcApi.ID_PARAMETER) long id, HttpServletResponse resp) { if (videos.containsKey(id)) { try {// w w w.j a v a2 s .c o m serveVideo(videos.get(id), resp); resp.setStatus(HttpServletResponse.SC_OK); resp.setHeader("Content-Type", "video/mpeg"); } catch (IOException e) { resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } else { resp.setStatus(HttpServletResponse.SC_NOT_FOUND); } }
From source file:com.lushapp.common.web.servlet.RemoteContentServlet.java
/** * HttpClient?.//from ww w . j av a2s.com */ private void fetchContentByApacheHttpClient(HttpServletResponse response, String contentUrl) throws IOException { // ? HttpEntity entity = null; HttpGet httpGet = new HttpGet(contentUrl); try { HttpContext context = new BasicHttpContext(); HttpResponse remoteResponse = httpClient.execute(httpGet, context); entity = remoteResponse.getEntity(); } catch (Exception e) { logger.error("fetch remote content" + contentUrl + " error", e); httpGet.abort(); return; } // 404 if (entity == null) { response.sendError(HttpServletResponse.SC_NOT_FOUND, contentUrl + " is not found."); return; } // Header response.setContentType(entity.getContentType().getValue()); if (entity.getContentLength() > 0) { response.setContentLength((int) entity.getContentLength()); } // InputStream input = entity.getContent(); OutputStream output = response.getOutputStream(); try { // byte?InputStreamOutputStream, ?4k. IOUtils.copy(input, output); output.flush(); } finally { // ??InputStream. IOUtils.closeQuietly(input); } }
From source file:edu.lternet.pasta.datapackagemanager.dataserver.DataServerServlet.java
/** * Process a data download HEAD request using information that was generated * by the Data Package Manager service./*from ww w.j a v a 2s.c o m*/ */ protected void doHead(HttpServletRequest request, HttpServletResponse response) throws ServletException { String dataToken = request.getParameter("dataToken"); String size = request.getParameter("size"); String objectName = request.getParameter("objectName"); if (dataToken == null || dataToken.isEmpty() || size == null || size.isEmpty() || objectName == null || objectName.isEmpty()) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } else { /* * Find out which directory the temporary data files are being * placed in by the Data Package Manager */ PropertiesConfiguration options = ConfigurationListener.getOptions(); String tmpDir = options.getString("datapackagemanager.tmpDir"); if (tmpDir == null || tmpDir.equals("")) { throw new ServletException("datapackagemanager.tmpDir property value was not specified."); } try { // reads input file from an absolute path String filePath = String.format("%s/%s", tmpDir, dataToken); File downloadFile = new File(filePath); if (!downloadFile.exists()) { String message = String.format("File not found: %s", filePath); throw new FileNotFoundException(message); } ServletContext context = getServletContext(); // gets MIME type of the file String mimeType = context.getMimeType(filePath); if (mimeType == null) { // set to binary type if MIME mapping not found mimeType = "application/octet-stream"; } // modifies response response.setContentType(mimeType); long length = Long.parseLong(size); if (length <= Integer.MAX_VALUE) { response.setContentLength((int) length); } else { response.addHeader("Content-Length", Long.toString(length)); } // forces download String headerKey = "Content-Disposition"; String headerValue = String.format("attachment; filename=\"%s\"", objectName); response.setHeader(headerKey, headerValue); } catch (FileNotFoundException e) { logger.error(e.getMessage()); e.printStackTrace(); response.setStatus(HttpServletResponse.SC_NOT_FOUND); } } }
From source file:com.epam.wilma.extras.shortcircuit.ShortCircuitInterceptorCore.java
/** * Method that handles GET (all) and DELETE (all) methods on the actual Short Circuit Map. * * @param myMethod is expected as either GET or DELETE * @param httpServletResponse is the response object * @param path is the request path * @return with the response body (and with the updated httpServletResponse object *///from w w w . ja v a 2 s . co m String handleBasicCall(String myMethod, HttpServletResponse httpServletResponse, String path) { String response = null; if ("get".equalsIgnoreCase(myMethod)) { //list the map (circuits + get) response = getShortCircuitMap(httpServletResponse); } if ("delete".equalsIgnoreCase(myMethod)) { //first detect if we have basic path or we have a specified id in it int index = path.lastIndexOf("/"); String idStr = path.substring(index + 1); int id; try { id = Integer.parseInt(idStr); //remove a specific map entry String[] keySet = shortCircuitMap.keySet().toArray(new String[shortCircuitMap.size()]); if (keySet.length > id) { //we can delete it String entryKey = keySet[id]; shortCircuitMap.remove(entryKey); response = getShortCircuitMap(httpServletResponse); } else { //resource cannot be deleted response = "{ \"Cannot found specified entry in Short Circuit Cache\": \"" + id + "\" }"; httpServletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND); } } catch (NumberFormatException e) { //it is not a problem, we should delete all //invalidate map (remove all from map) (circuits + delete) shortCircuitMap.clear(); response = getShortCircuitMap(httpServletResponse); } } return response; }
From source file:eu.trentorise.smartcampus.permissionprovider.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 a2 s .c o m * @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"); return String.format("redirect:/eauth/facebook?target=%s&id=%s&email=%s&first_name=%s&last_name=%s", URLEncoder.encode((String) request.getSession().getAttribute("redirect"), "UTF8"), userInfo.getId(), userInfo.getEmail(), userInfo.getFirst_name(), userInfo.getLast_name()); } catch (IOException e) { logger.error("IOException .. Problem in reading user data.", e); response.setStatus(HttpServletResponse.SC_NOT_FOUND); } } return "redirect:/"; }
From source file:edu.wisc.my.redirect.TabSelectingUrlRedirectController.java
@Override protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { final String serverName = request.getServerName(); final PortalUrl portalUrl = this.portalUrlProvider.getPortalUrl(serverName); //If strict param matching only run if the request parameter keyset matches the mapped parameter keyset final Set<?> requestParameterKeys = request.getParameterMap().keySet(); if (this.strictParameterMatching && !requestParameterKeys.equals(this.parameterMappings.keySet())) { if (this.logger.isInfoEnabled()) { this.logger.info("Sending not found error, requested parameter key set " + requestParameterKeys + " does not match mapped parameter key set " + this.parameterMappings.keySet()); }/*from www .j a v a 2 s . c o m*/ response.sendError(HttpServletResponse.SC_NOT_FOUND); return null; } //Map static parameters for (final Map.Entry<String, List<String>> parameterMappingEntry : this.staticParameters.entrySet()) { final String name = parameterMappingEntry.getKey(); final List<String> values = parameterMappingEntry.getValue(); if (this.logger.isDebugEnabled()) { this.logger.debug("Adding static parameter '" + name + "' with values: " + values); } portalUrl.setParameter(name, values.toArray(new String[values.size()])); } //Map request parameters for (final Map.Entry<String, Set<String>> parameterMappingEntry : this.parameterMappings.entrySet()) { final String name = parameterMappingEntry.getKey(); final String[] values = request.getParameterValues(name); if (values != null) { for (final String mappedName : parameterMappingEntry.getValue()) { if (this.logger.isDebugEnabled()) { this.logger.debug("Mapping parameter '" + name + "' to portal parameter '" + mappedName + "' with values: " + Arrays.asList(values)); } portalUrl.setParameter(mappedName, values); } } else if (this.logger.isDebugEnabled()) { this.logger.debug( "Skipping mapped parameter '" + name + "' since it was not specified on the original URL"); } } //Set public based on if remoteUser is set final String remoteUser = request.getRemoteUser(); final boolean isAuthenticated = StringUtils.isNotBlank(remoteUser); portalUrl.setPublic(!isAuthenticated); if (isAuthenticated) { portalUrl.setTabIndex(this.privateTabIndex); } else { portalUrl.setTabIndex(this.publicTabIndex); } portalUrl.setType(RequestType.ACTION); final String redirectUrl = portalUrl.toString(); if (this.logger.isInfoEnabled()) { this.logger.info("Redirecting to: " + redirectUrl); } return new ModelAndView(new RedirectView(redirectUrl, false)); }
From source file:org.magnum.mobilecloud.video.VideoSvc.java
@RequestMapping(value = VideoSvcApi.VIDEO_SVC_PATH + "/{id}/like", method = RequestMethod.POST) public @ResponseBody void likeVideo(@PathVariable("id") long id, HttpServletRequest request, HttpServletResponse response) {/*from w w w . ja v a 2s. com*/ Video video = videos.findOne(id); if (video != null) { Set<String> users = video.getLikesUserNames(); String user = request.getRemoteUser(); System.out.println("User: " + user); if (users.contains(user)) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } else { users.add(user); video.setLikesUserNames(users); video.setLikes(users.size()); videos.save(video); response.setStatus(HttpServletResponse.SC_OK); } } else { response.setStatus(HttpServletResponse.SC_NOT_FOUND); } }