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:org.callistasoftware.netcare.web.mobile.controller.BankIdController.java
@RequestMapping(value = "/authenticate", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody/*from w w w .jav a 2 s . co m*/ public String authenticate(@RequestParam(value = "crn", required = true) String crn, HttpServletResponse response) throws IOException { log.info("Authenticating user {}", crn); final PatientEntity ent = repo.findByCivicRegistrationNumber(crn.trim()); if (ent != null) { try { return service.authenticate(new CivicRegistrationNumber(crn)); } catch (final Exception e) { log.error("Error in bank id service. Message: {}", e.getMessage()); response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage()); return null; } } log.info("User {} does not have an account in the system", crn); response.sendError(HttpServletResponse.SC_NOT_FOUND, "The user does not have an account..."); return null; }
From source file:net.siegmar.japtproxy.fetcher.FetcherHttp.java
/** * {@inheritDoc}/* w ww . ja v a 2 s. c om*/ */ @Override public FetchedResourceHttp fetch(final URL targetResource, final long lastModified, final String originalUserAgent) throws IOException, ResourceUnavailableException { final HttpGet httpGet = new HttpGet(targetResource.toExternalForm()); httpGet.addHeader(HttpHeaderConstants.USER_AGENT, StringUtils.trim(StringUtils.defaultString(originalUserAgent) + " " + Util.USER_AGENT)); if (lastModified != 0) { final String lastModifiedSince = Util.getRfc822DateFromTimestamp(lastModified); LOG.debug("Setting If-Modified-Since: {}", lastModifiedSince); httpGet.setHeader(HttpHeaderConstants.IF_MODIFIED_SINCE, lastModifiedSince); } CloseableHttpResponse httpResponse = null; try { httpResponse = httpClient.execute(httpGet); if (LOG.isDebugEnabled()) { logResponseHeader(httpResponse.getAllHeaders()); } final int retCode = httpResponse.getStatusLine().getStatusCode(); if (retCode == HttpServletResponse.SC_NOT_FOUND) { httpGet.releaseConnection(); throw new ResourceUnavailableException("Resource '" + targetResource + " not found"); } if (retCode != HttpServletResponse.SC_OK && retCode != HttpServletResponse.SC_NOT_MODIFIED) { throw new IOException("Invalid status code returned: " + httpResponse.getStatusLine()); } final FetchedResourceHttp fetchedResourceHttp = new FetchedResourceHttp(httpResponse); fetchedResourceHttp.setModified(lastModified == 0 || retCode != HttpServletResponse.SC_NOT_MODIFIED); if (LOG.isDebugEnabled()) { final long fetchedTimestamp = fetchedResourceHttp.getLastModified(); if (fetchedTimestamp != 0) { LOG.debug("Response status code: {}, Last modified: {}", retCode, Util.getSimpleDateFromTimestamp(fetchedTimestamp)); } else { LOG.debug("Response status code: {}", retCode); } } return fetchedResourceHttp; } catch (final IOException e) { // Closing only in case of an exception - otherwise closed by FetchedResourceHttp if (httpResponse != null) { httpResponse.close(); } throw e; } }
From source file:org.dspace.app.webui.cris.controller.jdyna.ResearcherTabImageController.java
@Override public ModelAndView handleRequest(HttpServletRequest req, HttpServletResponse response) throws Exception { String idString = req.getPathInfo(); String[] pathInfo = idString.split("/", 3); String tabId = pathInfo[2];//from w w w .j a v a 2 s .co m String contentType = ""; String ext = ""; Tab tab = applicationService.get(Tab.class, Integer.parseInt(tabId)); ext = tab.getExt(); contentType = tab.getMime(); if (ext != null && !ext.isEmpty() && contentType != null && !contentType.isEmpty()) { File image = new File( tab.getFileSystemPath() + File.separatorChar + AFormTabController.DIRECTORY_TAB_ICON + File.separatorChar + AFormTabController.PREFIX_TAB_ICON + tabId + "." + ext); InputStream is = null; try { is = new FileInputStream(image); response.setContentType(contentType); // Response length response.setHeader("Content-Length", String.valueOf(image.length())); Utils.bufferedCopy(is, response.getOutputStream()); is.close(); response.getOutputStream().flush(); } catch (FileNotFoundException not) { log.error(not.getMessage()); response.sendError(HttpServletResponse.SC_NOT_FOUND); } finally { if (is != null) { is.close(); } } } return null; }
From source file:com.thinkberg.webdav.DeleteHandler.java
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException { FileObject object = VFSBackend.resolveFile(request.getPathInfo()); try {//from w w w.ja va 2 s . c o m String fragment = new URI(request.getRequestURI()).getFragment(); if (fragment != null) { response.sendError(HttpServletResponse.SC_FORBIDDEN); return; } } catch (URISyntaxException e) { throw new IOException(e.getMessage()); } 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()) { int deletedObjects = object.delete(ALL_FILES_SELECTOR); LOG.debug("deleted " + deletedObjects + " objects"); if (deletedObjects > 0) { response.setStatus(HttpServletResponse.SC_OK); } else { response.sendError(HttpServletResponse.SC_FORBIDDEN); } } else { response.sendError(HttpServletResponse.SC_NOT_FOUND); } }
From source file:gov.nih.nci.caarray.web.helper.DownloadHelper.java
/** * Zips the selected files and writes the result to the servlet output stream. Also sets content type and * disposition appropriately.// w w w .j a v a 2s . c o m * * @param files the files to zip and send * @param baseFilename the filename w/o the suffix to use for the archive file. This filename will be set as the * Content-disposition header * @throws IOException if there is an error writing to the stream */ public static void downloadFiles(Collection<CaArrayFile> files, String baseFilename) throws IOException { final HttpServletResponse response = ServletActionContext.getResponse(); try { final PackagingInfo info = getPreferedPackageInfo(files, baseFilename); response.setContentType(info.getMethod().getMimeType()); response.addHeader("Content-disposition", "filename=\"" + info.getName() + "\""); final List<CaArrayFile> sortedFiles = new ArrayList<CaArrayFile>(files); Collections.sort(sortedFiles, CAARRAYFILE_NAME_COMPARATOR_INSTANCE); final OutputStream sos = response.getOutputStream(); final OutputStream closeShield = new CloseShieldOutputStream(sos); final ArchiveOutputStream arOut = info.getMethod().createArchiveOutputStream(closeShield); try { for (final CaArrayFile f : sortedFiles) { fileAccessUtils.addFileToArchive(f, arOut); } } finally { // note that the caller's stream is shielded from the close(), // but this is the only way to finish and flush the (gzip) stream. try { arOut.close(); } catch (final Exception e) { LOG.error(e); } } } catch (final Exception e) { LOG.error("Error streaming download of files " + files, e); response.sendError(HttpServletResponse.SC_NOT_FOUND); } }
From source file:com.alvexcore.repo.web.scripts.workflow.getModelWork.java
@Override protected Map<String, Object> buildModel(WorkflowModelBuilder modelBuilder, WebScriptRequest req, Status status, Cache cache) {/*from ww w . j a v a 2 s . c o m*/ Map<String, String> params = req.getServiceMatch().getTemplateVars(); // getting workflow instance id from request parameters String workflowInstanceId = params.get("workflow_instance_id"); boolean includeTasks = getIncludeTasks(req); WorkflowInstance workflowInstance = workflowService.getWorkflowById(workflowInstanceId); // task was not found -> return 404 if (workflowInstance == null) { throw new WebScriptException(HttpServletResponse.SC_NOT_FOUND, "Unable to find workflow instance with id: " + workflowInstanceId); } // TODO: think more carefully - if it is ok to return all tasks here. // We know only that workflowInstance is not null. // Is it enough to conclude that user have some rights for workflow? RunAsWork<Map<String, Object>> work = new getModelWork(modelBuilder, workflowInstance, includeTasks); Map<String, Object> model = AuthenticationUtil.runAsSystem(work); return model; }
From source file:com.harrywu.springweb.common.StreamingViewRenderer.java
@Override public void renderMergedOutputModel(Map<String, Object> objectMap, HttpServletRequest request, HttpServletResponse response) throws Exception { InputStream dataStream = (InputStream) objectMap.get(INPUT_STREAM); if (dataStream == null) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return;/* ww w.j av a2 s .co m*/ } long length = (Long) objectMap.get(CONTENT_LENGTH); String fileName = (String) objectMap.get(FILENAME); Date lastModifiedObj = (Date) objectMap.get(LAST_MODIFIED); if (StringUtils.isEmpty(fileName) || lastModifiedObj == null) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } long lastModified = lastModifiedObj.getTime(); String contentType = (String) objectMap.get(CONTENT_TYPE); // 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, fileName)) { response.setHeader("ETag", fileName); // 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", fileName); // 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, fileName)) { 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; } String ifRange = request.getHeader("If-Range"); if (ifRange != null && !ifRange.equals(fileName)) { try { long ifRangeTime = request.getDateHeader("If-Range"); // Throws // IAE // if // invalid. if (ifRangeTime != -1) { 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 content disposition. 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"; } else if (!contentType.startsWith("image")) { // 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. 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", fileName); response.setDateHeader("Last-Modified", lastModified); response.setDateHeader("Expires", System.currentTimeMillis() + DEFAULT_EXPIRE_TIME); // Send requested file (part(s)) to client // ------------------------------------------------ // Prepare streams. InputStream input = null; OutputStream output = null; try { // Open streams. input = new BufferedInputStream(dataStream); 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); response.setHeader("Content-Length", String.valueOf(r.length)); copy(input, output, length, 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. // Copy single part range. copy(input, output, length, r.start, r.length); } else { // Return multiple parts of file. response.setContentType("multipart/byteranges; boundary=" + MULTIPART_BOUNDARY); response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206. // 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, length, r.start, r.length); } // End with multipart boundary. sos.println(); sos.println("--" + MULTIPART_BOUNDARY + "--"); } } finally { // Gently close streams. close(output); close(input); close(dataStream); } }
From source file:com.imaginary.home.cloud.api.call.DeviceCall.java
@Override public void get(@Nonnull String requestId, @Nullable String userId, @Nonnull String[] path, @Nonnull HttpServletRequest req, @Nonnull HttpServletResponse resp, @Nonnull Map<String, Object> headers, @Nonnull Map<String, Object> parameters) throws RestException, IOException { if (logger.isDebugEnabled()) { logger.debug("GET " + req.getRequestURI()); }// www . j av a 2 s. c om try { String deviceId = (path.length > 1 ? path[1] : null); if (logger.isDebugEnabled()) { logger.debug("deviceId=" + deviceId); } if (deviceId != null) { Device device = Device.getDevice(deviceId); if (device == null) { throw new RestException(HttpServletResponse.SC_NOT_FOUND, RestException.NO_SUCH_OBJECT, "The device " + deviceId + " does not exist."); } resp.setStatus(HttpServletResponse.SC_OK); resp.getWriter().println((new JSONObject(toJSON(device))).toString()); resp.getWriter().flush(); } else { String locationId = req.getParameter("locationId"); String deviceType = req.getParameter("deviceType"); String tmp = req.getParameter("includeChildren"); boolean includeChildren = (tmp != null && tmp.equalsIgnoreCase("true")); if (logger.isDebugEnabled()) { logger.debug("Params=" + locationId + " / " + deviceType + " / " + includeChildren); } User user = (userId != null ? User.getUserByUserId(userId) : null); ControllerRelay relay = (user == null ? ControllerRelay.getRelay((String) headers.get(RestApi.API_KEY)) : null); Location location = (locationId == null ? null : Location.getLocation(locationId)); if (locationId != null && location == null) { throw new RestException(HttpServletResponse.SC_FORBIDDEN, RestException.INVALID_ACTION, "You do not have access to those resources"); } if (user == null && relay == null) { throw new RestException(HttpServletResponse.SC_FORBIDDEN, RestException.INVALID_ACTION, "Cannot request devices without a proper authentication context"); } if (relay != null && location != null) { if (!relay.getLocationId().equals(location.getLocationId())) { throw new RestException(HttpServletResponse.SC_FORBIDDEN, RestException.INVALID_ACTION, "You do not have access to those resources"); } } Collection<ControllerRelay> relays; if (relay != null) { relays = Collections.singletonList(relay); } else { if (location != null) { boolean allowed = location.getOwnerId().equals(user.getUserId()); if (!allowed) { for (String id : user.getLocationIds()) { if (id.equals(location.getLocationId())) { allowed = true; break; } } if (!allowed) { throw new RestException(HttpServletResponse.SC_FORBIDDEN, RestException.INVALID_ACTION, "You do not have access to those resources"); } } relays = ControllerRelay.findRelaysInLocation(location); } else { relays = new ArrayList<ControllerRelay>(); for (Location l : user.getLocations()) { relays.addAll(ControllerRelay.findRelaysInLocation(l)); } } } if (logger.isDebugEnabled()) { logger.debug("relays=" + relays); } ArrayList<Device> devices = new ArrayList<Device>(); for (ControllerRelay r : relays) { if (deviceType == null) { devices.addAll(Device.findDevicesForRelay(r)); } else if (deviceType.equals("powered")) { if (includeChildren) { PoweredDevice.findPoweredDevicesForRelayWithChildren(r, devices); } else { devices.addAll(PoweredDevice.findPoweredDevicesForRelay(r)); } } else if (deviceType.equals("light")) { devices.addAll(Light.findPoweredDevicesForRelay(r)); } else { throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_DEVICE_TYPE, "Invalid device type: " + deviceType); } } if (logger.isDebugEnabled()) { logger.debug("devices=" + devices); } ArrayList<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); for (Device d : devices) { list.add(toJSON(d)); } resp.setStatus(HttpServletResponse.SC_OK); resp.getWriter().println((new JSONArray(list)).toString()); resp.getWriter().flush(); } } catch (PersistenceException e) { throw new RestException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, RestException.INTERNAL_ERROR, e.getMessage()); } }
From source file:com.autentia.intra.servlet.DocServlet.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String uri = request.getRequestURI(); log.debug("doGet - uri='" + uri + "'"); int i = uri.indexOf(URL_PREFIX); if (i != -1) { String relPath = uri.substring(i + URL_PREFIX.length()); relPath = URLDecoder.decode(relPath, "UTF-8"); log.debug("doGet - relPath='" + relPath + "'"); File f = new File(ConfigurationUtil.getDefault().getUploadPath() + relPath); if (f.exists()) { response.setContentLength((int) f.length()); String mime = request.getParameter(ARG_MIME); if (mime != null && !mime.equals("")) { response.setContentType(mime); }/*from www . j a v a 2 s. co m*/ OutputStream out = response.getOutputStream(); InputStream in = new FileInputStream(f); byte[] buffer = new byte[8192]; int nr; while ((nr = in.read(buffer)) != -1) { out.write(buffer, 0, nr); } in.close(); } else { response.sendError(HttpServletResponse.SC_NOT_FOUND); } } else { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Bad URL prefix for servlet: check your web.xml file"); } }
From source file:com.bstek.dorado.web.resolver.ErrorPageResolver.java
private void doExcecute(HttpServletRequest request, HttpServletResponse response) throws Exception, IOException { response.setContentType(HttpConstants.CONTENT_TYPE_HTML); response.setCharacterEncoding(Constants.DEFAULT_CHARSET); Context velocityContext = new VelocityContext(); Exception e = (Exception) request.getAttribute(EXCEPTION_ATTRIBUTE); if (e != null) { logger.error(e, e);/* w w w .j av a 2 s. c om*/ if (e instanceof PageNotFoundException) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); } else if (e instanceof PageAccessDeniedException) { response.setStatus(HttpServletResponse.SC_FORBIDDEN); } Throwable throwable = e; while (throwable.getCause() != null) { throwable = throwable.getCause(); } String message = null; if (throwable != null) { message = throwable.getMessage(); } message = StringUtils.defaultString(message, throwable.getClass().getName()); velocityContext.put("message", message); velocityContext.put(EXCEPTION_ATTRIBUTE, throwable); } else { velocityContext.put("message", "Can not gain exception information!"); } velocityContext.put("esc", stringEscapeHelper); Template template = getVelocityEngine().getTemplate("com/bstek/dorado/web/resolver/ErrorPage.html"); PrintWriter writer = getWriter(request, response); try { template.merge(velocityContext, writer); } finally { writer.flush(); writer.close(); } }