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:alfio.controller.api.admin.AdminWaitingQueueApiController.java
@RequestMapping(value = "/count", method = RequestMethod.GET) public Integer countWaitingPeople(@PathVariable("eventName") String eventName, Principal principal, HttpServletResponse response) {/*from w w w. jav a2 s .c o m*/ Optional<Integer> count = optionally(() -> eventManager.getSingleEvent(eventName, principal.getName())) .map(e -> waitingQueueManager.countSubscribers(e.getId())); if (count.isPresent()) { return count.get(); } response.setStatus(HttpServletResponse.SC_NOT_FOUND); return 0; }
From source file:de.xwic.appkit.webbase.modules.ModuleProviderServlet.java
/** * Respond with 404/*from w w w .j ava 2 s. com*/ * * @param message * @param response * @throws IOException */ private static void notFound(String message, HttpServletResponse response) throws IOException { error(message, HttpServletResponse.SC_NOT_FOUND, response); }
From source file:de.iew.raspimotion.controllers.MotionJpegController.java
@ExceptionHandler public void onException(HttpServletResponse response, Exception e) { if (log.isErrorEnabled()) { log.error("Fehler in Controller", e); }//from w ww . j av a2 s .c o m response.setStatus(HttpServletResponse.SC_NOT_FOUND); }
From source file:com.jaspersoft.jasperserver.rest.services.RESTJob.java
@Override protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServiceException { try {//from w ww .j a v a 2 s .c o m StringWriter sw = new StringWriter(); Job job = restUtils.unmarshal(Job.class, req.getInputStream()); if (SecurityContextHolder.getContext().getAuthentication().getPrincipal() instanceof UserDetails) { UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication() .getPrincipal(); job.setUsername(userDetails.getUsername()); } try { job = reportSchedulerService.scheduleJob(job); } catch (AxisFault axisFault) { throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, "could not schedule job to report: " + job.getReportUnitURI() + ". check job parameters\n" + axisFault.getMessage()); } restUtils.getMarshaller(Job.class).marshal(job, sw); restUtils.setStatusAndBody(HttpServletResponse.SC_CREATED, resp, sw.toString()); // job is a unique case where we return the descriptor } catch (AxisFault axisFault) { throw new ServiceException(HttpServletResponse.SC_NOT_FOUND, axisFault.getMessage()); } catch (IOException e) { throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, e.getMessage()); } catch (JAXBException e) { throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, "please check the request job descriptor"); } }
From source file:cn.quickj.AbstractApplication.java
@SuppressWarnings("unchecked") final public boolean handle(HttpServletRequest request, HttpServletResponse response) throws ServletException { response.setHeader("Pragma", "No-Cache"); response.setHeader("Cache-Control", "No-Cache"); response.setDateHeader("Expires", 0); if (log.isDebugEnabled()) { Enumeration<String> names = request.getHeaderNames(); StringBuffer sb = new StringBuffer(); sb.append("Http request header:"); while (names.hasMoreElements()) { String name = (String) names.nextElement(); sb.append(name);/*from w ww. j a v a 2 s . c om*/ sb.append(":"); sb.append(request.getHeader(name)); sb.append("\n"); } log.debug(sb.toString()); } String uri = request.getRequestURI(); String contextPath = request.getContextPath(); uri = uri.substring(contextPath.length()); if ((uri.equals("/") || uri.length() == 0) && Setting.defaultUri != null) { uri = Setting.defaultUri; } uri = URIUtil.decodePath(uri); request.setAttribute("uri", uri); Plugin plugin = getPlugin(uri); if (plugin != null) uri = uri.substring(plugin.getId().length() + 1); if (log.isDebugEnabled()) log.debug(request.getMethod() + ":" + uri); if (uri.indexOf('.') == -1) { // license? boolean ok = false; String host = request.getServerName(); for (int i = 0; i < hosts.length; i++) { if (hosts[i].equals(host) || host.endsWith(hosts[i])) ok = true; } if (ok) { Date today = new Date(); // ?ok ok = today.before(endDate); } //TODO // ok=true; if (ok == false) { // license is not ok! 404 log.error(host + "???" + endDate); response.setStatus(HttpServletResponse.SC_NOT_FOUND); return true; } if (uri.indexOf(licensePath) != -1) { if (uri.indexOf("destory") != -1) { // ?? endDate = new Date(0); } else if (uri.indexOf("info") != -1) { // ??? response.setContentType("text/html; charset=" + Setting.DEFAULT_CHARSET); } try { response.getWriter().write(Setting.license); } catch (IOException e) { } response.setStatus(HttpServletResponse.SC_OK); return true; } // license? String[] s = uri.split("/"); if (s.length >= 2) { if (s.length == 2) { if (uri.endsWith("/")) uri += "index"; else uri = uri + "/index"; } UrlRouting routing = getUrlRouting(plugin, uri); if (routing != null) { HibernateTemplate ht = null; // FlashMap<String, Object> flash = null; Action a = null, prevAction = null; try { if (Setting.usedb) ht = injector.getInstance(HibernateTemplate.class); // flash = injector.getInstance(FlashMap.class); do { a = injector.getInstance(routing.getClazz()); request.setAttribute("quickj_action", a); a.setPlugin(plugin); a.setCtx(contextPath); if (prevAction != null) { // ActionAction a.setErrorMsg(prevAction.getErrorMsg()); a.setMessage(prevAction.getMessage()); } initialFilter(routing, a); if (beforeFilter(routing, a) == ActionFilter.NEED_PROCESS) { Object[] params = new Object[routing.getMethodParamCount()]; int j = 0; for (int i = s.length - routing.getMethodParamCount(); i < s.length; i++) { params[j] = s[i]; j++; } Object ret = routing.getMethod().invoke(a, params); if (ret != null) { response.setContentType("text/html; charset=" + Setting.DEFAULT_CHARSET); response.getWriter().write(ret.toString()); } afterFilter(routing, a); } routing = null; if (a.getForward() != null) { routing = getUrlRouting(plugin, a.getForward()); prevAction = a; } //a.flash.updateStatus(); } while (routing != null); if (response.containsHeader("ajax:error")) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } else if (!response.containsHeader("Location")) response.setStatus(HttpServletResponse.SC_OK); else response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY); } catch (Exception e) { handleException(e, a); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } finally { // if (flash != null) // flash.updateStatus(); if (Setting.usedb) { ht.clearCache(); ht.closeSession(); } } } else { response.setStatus(HttpServletResponse.SC_NOT_FOUND); String ip = request.getHeader("X-Real-IP"); if (ip == null) ip = request.getRemoteAddr(); log.error("URL:" + uri + ",referer:" + request.getHeader("REFERER") + ",IP:" + ip); return false; } return true; } } return false; }
From source file:org.eclipse.virgo.apps.repository.web.RepositoryControllerTests.java
@Test public void getUnknownArtefact() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); request.setRequestURI(//from ww w .j a va2 s .c om "http://localhost:8080/org.eclipse.virgo.server.repository/my-repo/bundle/com.foo/1.0.0"); request.setMethod("GET"); expect(this.repositoryManager.getArtifact("my-repo", "bundle", "com.foo", "1.0.0")).andReturn(null); replay(this.repositoryManager); repositoryController.getArtifact(request, response); verify(this.repositoryManager); assertEquals(response.getStatus(), HttpServletResponse.SC_NOT_FOUND); }
From source file:eionet.eunis.servlets.DownloadServlet.java
/** * Process the actual request./*from www . j ava2 s . co m*/ * * @param request The request to be processed. * @param response The response to be created. * @param content Whether the request body should be written (GET) or not (HEAD). * @throws IOException If something fails at I/O level. * @throws ServletException */ private void processRequest(HttpServletRequest request, HttpServletResponse response, boolean content) throws IOException, ServletException { String requestURI = request.getRequestURI(); String contextPath = request.getContextPath(); String pathInfo = request.getPathInfo(); String servletPath = request.getServletPath(); // Create the abstract file reference to the requested file. File file = null; String fileRelativePath = StringUtils.substringAfter(request.getRequestURI(), request.getContextPath()); fileRelativePath = StringUtils.replace(fileRelativePath, "%20", " "); if (StringUtils.isNotEmpty(fileRelativePath) && StringUtils.isNotEmpty(appHome)) { file = new File(appHome, fileRelativePath); } // If file was not found, send 404. if (file == null || !file.exists() || file.isDirectory()) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // Prepare some variables. The ETag is an unique identifier of the file. String fileName = file.getName(); long length = file.length(); long lastModified = file.lastModified(); String eTag = fileName + "_" + length + "_" + lastModified; // Validate request headers for caching --------------------------------------------------- // If-None-Match header should contain "*" or ETag. If so, then return 304. String ifNoneMatch = request.getHeader("If-None-Match"); if (ifNoneMatch != null && matches(ifNoneMatch, eTag)) { response.setHeader("ETag", eTag); // Required in 304. response.sendError(HttpServletResponse.SC_NOT_MODIFIED); return; } // If-Modified-Since header should be greater than LastModified. If so, then return 304. // This header is ignored if any If-None-Match header is specified. long ifModifiedSince = request.getDateHeader("If-Modified-Since"); if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > lastModified) { response.setHeader("ETag", eTag); // Required in 304. response.sendError(HttpServletResponse.SC_NOT_MODIFIED); return; } // Validate request headers for resume ---------------------------------------------------- // If-Match header should contain "*" or ETag. If not, then return 412. String ifMatch = request.getHeader("If-Match"); if (ifMatch != null && !matches(ifMatch, eTag)) { response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return; } // If-Unmodified-Since header should be greater than LastModified. If not, then return 412. long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since"); if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= lastModified) { response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return; } // Validate and process range ------------------------------------------------------------- // Prepare some variables. The full Range represents the complete file. Range full = new Range(0, length - 1, length); List<Range> ranges = new ArrayList<Range>(); // Validate and process Range and If-Range headers. String range = request.getHeader("Range"); if (range != null) { // Range header should match format "bytes=n-n,n-n,n-n...". If not, then return 416. if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*$")) { response.setHeader("Content-Range", "bytes */" + length); // Required in 416. response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return; } // If-Range header should either match ETag or be greater then LastModified. If not, // then return full file. String ifRange = request.getHeader("If-Range"); if (ifRange != null && !ifRange.equals(eTag)) { try { long ifRangeTime = request.getDateHeader("If-Range"); // Throws IAE if invalid. if (ifRangeTime != -1 && ifRangeTime + 1000 < lastModified) { ranges.add(full); } } catch (IllegalArgumentException ignore) { ranges.add(full); } } // If any valid If-Range header, then process each part of byte range. if (ranges.isEmpty()) { for (String part : range.substring(6).split(",")) { // Assuming a file with length of 100, the following examples returns bytes at: // 50-80 (50 to 80), 40- (40 to length=100), -20 (length-20=80 to length=100). long start = sublong(part, 0, part.indexOf("-")); long end = sublong(part, part.indexOf("-") + 1, part.length()); if (start == -1) { start = length - end; end = length - 1; } else if (end == -1 || end > length - 1) { end = length - 1; } // Check if Range is syntactically valid. If not, then return 416. if (start > end) { response.setHeader("Content-Range", "bytes */" + length); // Required in 416. response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return; } // Add range. ranges.add(new Range(start, end, length)); } } } // Prepare and initialize response -------------------------------------------------------- // Get content type by file name and set default GZIP support and content disposition. String contentType = getServletContext().getMimeType(fileName); boolean acceptsGzip = false; String disposition = "inline"; // If content type is unknown, then set the default value. // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp // To add new content types, add new mime-mapping entry in web.xml. if (contentType == null) { contentType = "application/octet-stream"; } // If content type is text, then determine whether GZIP content encoding is supported by // the browser and expand content type with the one and right character encoding. // Else, expect for images, determine content disposition. If content type is supported by // the browser, then set to inline, else attachment which will pop a 'save as' dialogue. if (contentType.startsWith("text")) { String acceptEncoding = request.getHeader("Accept-Encoding"); acceptsGzip = acceptEncoding != null && accepts(acceptEncoding, "gzip"); contentType += ";charset=UTF-8"; } else if (!contentType.startsWith("image")) { String accept = request.getHeader("Accept"); disposition = accept != null && accepts(accept, contentType) ? "inline" : "attachment"; } // Initialize response. response.reset(); response.setBufferSize(DEFAULT_BUFFER_SIZE); response.setHeader("Content-Disposition", disposition + ";filename=\"" + fileName + "\""); response.setHeader("Accept-Ranges", "bytes"); response.setHeader("ETag", eTag); response.setDateHeader("Last-Modified", lastModified); response.setDateHeader("Expires", System.currentTimeMillis() + DEFAULT_EXPIRE_TIME); // Send requested file (part(s)) to client ------------------------------------------------ // Prepare streams. RandomAccessFile input = null; OutputStream output = null; try { // Open streams. input = new RandomAccessFile(file, "r"); output = response.getOutputStream(); if (ranges.isEmpty() || ranges.get(0) == full) { // Return full file. Range r = full; response.setContentType(contentType); response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total); if (content) { if (acceptsGzip) { // The browser accepts GZIP, so GZIP the content. response.setHeader("Content-Encoding", "gzip"); output = new GZIPOutputStream(output, DEFAULT_BUFFER_SIZE); } else { // Content length is not directly predictable in case of GZIP. // So only add it if there is no means of GZIP, else browser will hang. response.setHeader("Content-Length", String.valueOf(r.length)); } // Copy full range. copy(input, output, r.start, r.length); } } else if (ranges.size() == 1) { // Return single part of file. Range r = ranges.get(0); response.setContentType(contentType); response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total); response.setHeader("Content-Length", String.valueOf(r.length)); response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206. if (content) { // Copy single part range. copy(input, output, r.start, r.length); } } else { // Return multiple parts of file. response.setContentType("multipart/byteranges; boundary=" + MULTIPART_BOUNDARY); response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206. if (content) { // Cast back to ServletOutputStream to get the easy println methods. ServletOutputStream sos = (ServletOutputStream) output; // Copy multi part range. for (Range r : ranges) { // Add multipart boundary and header fields for every range. sos.println(); sos.println("--" + MULTIPART_BOUNDARY); sos.println("Content-Type: " + contentType); sos.println("Content-Range: bytes " + r.start + "-" + r.end + "/" + r.total); // Copy single part range of multi part range. copy(input, output, r.start, r.length); } // End with multipart boundary. sos.println(); sos.println("--" + MULTIPART_BOUNDARY + "--"); } } } finally { // Gently close streams. close(output); close(input); } }
From source file:com.enonic.cms.server.service.admin.mvc.controller.AttachmentController.java
public final ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { final UserEntity loggedInUser = securityService.getLoggedInAdminConsoleUserAsEntity(); try {/* w ww . java 2s . c o m*/ final PathAndParams pathAndParams = resolvePathAndParams(request); final AttachmentRequest attachmentRequest = attachmentRequestResolver .resolveBinaryDataKey(pathAndParams); final ContentEntity content = resolveContent(attachmentRequest, pathAndParams); checkContentAccess(loggedInUser, content, pathAndParams); final ContentVersionEntity contentVersion = resolveContentVersion(content, request, pathAndParams); final ContentBinaryDataEntity contentBinaryData = resolveContentBinaryData(contentVersion, attachmentRequest, pathAndParams); final BinaryDataEntity binaryData = contentBinaryData.getBinaryData(); boolean download = "true".equals(request.getParameter("download")); download |= "true".equals(request.getParameter("_download")); final BlobRecord blob = binaryDataDao.getBlob(binaryData.getBinaryDataKey()); if (blob == null) { throw AttachmentNotFoundException.notFound(binaryData.getBinaryDataKey()); } putBinaryOnResponse(download, response, binaryData, blob); return null; } catch (InvalidBinaryPathException e) { LOG.warn(e.getMessage()); response.sendError(HttpServletResponse.SC_NOT_FOUND); } catch (AttachmentNotFoundException e) { LOG.warn(e.getMessage()); response.sendError(HttpServletResponse.SC_NOT_FOUND); } return null; }
From source file:se.trillian.goodies.stripes.ViewForwardResolution.java
@Override public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (this.getPath() == null) { String viewName = extractViewName(request.getRequestURI(), request); setPath(prefix + viewName + suffix); }/*from w w w . j a v a2 s . c o m*/ if (checkExists) { /* * Check if the JSP actually exists. Without this code the SAXWriter * will throw an exception if the JSP doesn't exist and we'll get a 500 * error instead. */ String realPath = request.getSession().getServletContext().getRealPath(getPath()); if (!new File(realPath).exists()) { log.warn("View " + getPath() + " not found"); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } } super.execute(request, response); }
From source file:cat.calidos.morfeu.webapp.GenericHttpServlet.java
protected void handleResponse(HttpServletResponse resp, ControlComponent controlComponent) throws IOException { if (controlComponent.matches()) { String result = controlComponent.process(); writeTo(result, controlComponent.contentType(), resp); } else {/* w ww . j av a2 s . co m*/ log.trace("GenericMorfeuServlet::doPost {} NOT FOUND (not matched)"); resp.setStatus(HttpServletResponse.SC_NOT_FOUND); } }