List of usage examples for javax.servlet.http HttpServletResponse SC_BAD_REQUEST
int SC_BAD_REQUEST
To view the source code for javax.servlet.http HttpServletResponse SC_BAD_REQUEST.
Click Source Link
From source file:org.openmhealth.reference.filter.ExceptionFilter.java
/** * <p>/* w ww .ja v a 2 s .c o m*/ * If the request throws an exception, specifically a OmhException, * attempt to respond with that message from the exception. * </p> * * <p> * For example, HTTP responses have their status codes changed to * {@link HttpServletResponse#SC_BAD_REQUEST} and the body of the response * is the error message. * </p> */ @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { // Get a handler for the correct exception type. Throwable exception = null; // Always let the request continue but setup to catch exceptions. try { chain.doFilter(request, response); } // The servlet container may wrap the exception, in which case we // must first unwrap it, then delegate it. catch (NestedServletException e) { // Get the underlying cause. Throwable cause = e.getCause(); // If the underlying exception is one of ours, then store the // underlying exception. if (cause instanceof OmhException) { exception = cause; } // Otherwise, store this exception. else { exception = e; } } // Otherwise, store the exception, catch (Exception e) { exception = e; } // If an exception was thrown, attempt to handle it. if (exception != null) { // Save the exception in the request. request.setAttribute(ATTRIBUTE_KEY_EXCEPTION, exception); // Handle the exception. if (exception instanceof NoSuchSchemaException) { LOGGER.log(Level.INFO, "An unknown schema was requested.", exception); // Respond to the user. sendResponse(response, HttpServletResponse.SC_NOT_FOUND, exception.getMessage()); } else if (exception instanceof InvalidAuthenticationException) { LOGGER.log(Level.INFO, "A user's authentication information was invalid.", exception); // Respond to the user. sendResponse(response, HttpServletResponse.SC_UNAUTHORIZED, exception.getMessage()); } else if (exception instanceof InvalidAuthorizationException) { LOGGER.log(Level.INFO, "A user's authorization information was invalid.", exception); // Respond to the user. sendResponse(response, HttpServletResponse.SC_UNAUTHORIZED, exception.getMessage()); } else if (exception instanceof OmhException) { LOGGER.log(Level.INFO, "An invalid request was made.", exception); // Respond to the user. sendResponse(response, HttpServletResponse.SC_BAD_REQUEST, exception.getMessage()); } // If the exception was not one of ours, the server must have // crashed. else { LOGGER.log(Level.SEVERE, "The server threw an unexpected exception.", exception); // Respond to the user. sendResponse(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null); } } }
From source file:edu.umd.cs.submitServer.servlets.UploadSubmission.java
@Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { long now = System.currentTimeMillis(); Timestamp submissionTimestamp = new Timestamp(now); // these are set by filters or previous servlets Project project = (Project) request.getAttribute(PROJECT); StudentRegistration studentRegistration = (StudentRegistration) request.getAttribute(STUDENT_REGISTRATION); MultipartRequest multipartRequest = (MultipartRequest) request.getAttribute(MULTIPART_REQUEST); boolean webBasedUpload = ((Boolean) request.getAttribute("webBasedUpload")).booleanValue(); String clientTool = multipartRequest.getCheckedParameter("submitClientTool"); String clientVersion = multipartRequest.getOptionalCheckedParameter("submitClientVersion"); String cvsTimestamp = multipartRequest.getOptionalCheckedParameter("cvstagTimestamp"); Collection<FileItem> files = multipartRequest.getFileItems(); Kind kind;//w w w . ja va 2s . c o m byte[] zipOutput = null; // zipped version of bytesForUpload boolean fixedZip = false; try { if (files.size() > 1) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ZipOutputStream zos = new ZipOutputStream(bos); for (FileItem item : files) { String name = item.getName(); if (name == null || name.length() == 0) continue; byte[] bytes = item.get(); ZipEntry zentry = new ZipEntry(name); zentry.setSize(bytes.length); zentry.setTime(now); zos.putNextEntry(zentry); zos.write(bytes); zos.closeEntry(); } zos.flush(); zos.close(); zipOutput = bos.toByteArray(); kind = Kind.MULTIFILE_UPLOAD; } else { FileItem fileItem = multipartRequest.getFileItem(); if (fileItem == null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "There was a problem processing your submission. " + "No files were found in your submission"); return; } // get size in bytes long sizeInBytes = fileItem.getSize(); if (sizeInBytes == 0 || sizeInBytes > Integer.MAX_VALUE) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Trying upload file of size " + sizeInBytes); return; } // copy the fileItem into a byte array byte[] bytesForUpload = fileItem.get(); String fileName = fileItem.getName(); boolean isSpecialSingleFile = OfficeFileName.matcher(fileName).matches(); FormatDescription desc = FormatIdentification.identify(bytesForUpload); if (!isSpecialSingleFile && desc != null && desc.getMimeType().equals("application/zip")) { fixedZip = FixZip.hasProblem(bytesForUpload); kind = Kind.ZIP_UPLOAD; if (fixedZip) { bytesForUpload = FixZip.fixProblem(bytesForUpload, studentRegistration.getStudentRegistrationPK()); kind = Kind.FIXED_ZIP_UPLOAD; } zipOutput = bytesForUpload; } else { // ========================================================================================== // [NAT] [Buffer to ZIP Part] // Check the type of the upload and convert to zip format if // possible // NOTE: I use both MagicMatch and FormatDescription (above) // because MagicMatch was having // some trouble identifying all zips String mime = URLConnection.getFileNameMap().getContentTypeFor(fileName); if (!isSpecialSingleFile && mime == null) try { MagicMatch match = Magic.getMagicMatch(bytesForUpload, true); if (match != null) mime = match.getMimeType(); } catch (Exception e) { // leave mime as null } if (!isSpecialSingleFile && "application/zip".equalsIgnoreCase(mime)) { zipOutput = bytesForUpload; kind = Kind.ZIP_UPLOAD2; } else { InputStream ins = new ByteArrayInputStream(bytesForUpload); if ("application/x-gzip".equalsIgnoreCase(mime)) { ins = new GZIPInputStream(ins); } ByteArrayOutputStream bos = new ByteArrayOutputStream(); ZipOutputStream zos = new ZipOutputStream(bos); if (!isSpecialSingleFile && ("application/x-gzip".equalsIgnoreCase(mime) || "application/x-tar".equalsIgnoreCase(mime))) { kind = Kind.TAR_UPLOAD; TarInputStream tins = new TarInputStream(ins); TarEntry tarEntry = null; while ((tarEntry = tins.getNextEntry()) != null) { zos.putNextEntry(new ZipEntry(tarEntry.getName())); tins.copyEntryContents(zos); zos.closeEntry(); } tins.close(); } else { // Non-archive file type if (isSpecialSingleFile) kind = Kind.SPECIAL_ZIP_FILE; else kind = Kind.SINGLE_FILE; // Write bytes to a zip file ZipEntry zentry = new ZipEntry(fileName); zos.putNextEntry(zentry); zos.write(bytesForUpload); zos.closeEntry(); } zos.flush(); zos.close(); zipOutput = bos.toByteArray(); } // [END Buffer to ZIP Part] // ========================================================================================== } } } catch (NullPointerException e) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "There was a problem processing your submission. " + "You should submit files that are either zipped or jarred"); return; } finally { for (FileItem fItem : files) fItem.delete(); } if (webBasedUpload) { clientTool = "web"; clientVersion = kind.toString(); } Submission submission = uploadSubmission(project, studentRegistration, zipOutput, request, submissionTimestamp, clientTool, clientVersion, cvsTimestamp, getDatabaseProps(), getSubmitServerServletLog()); request.setAttribute("submission", submission); if (!webBasedUpload) { response.setContentType("text/plain"); PrintWriter out = response.getWriter(); out.println("Successful submission #" + submission.getSubmissionNumber() + " received for project " + project.getProjectNumber()); out.flush(); out.close(); return; } boolean instructorUpload = ((Boolean) request.getAttribute("instructorViewOfStudent")).booleanValue(); // boolean // isCanonicalSubmission="true".equals(request.getParameter("isCanonicalSubmission")); // set the successful submission as a request attribute String redirectUrl; if (fixedZip) { redirectUrl = request.getContextPath() + "/view/fixedSubmissionUpload.jsp?submissionPK=" + submission.getSubmissionPK(); } if (project.getCanonicalStudentRegistrationPK() == studentRegistration.getStudentRegistrationPK()) { redirectUrl = request.getContextPath() + "/view/instructor/projectUtilities.jsp?projectPK=" + project.getProjectPK(); } else if (instructorUpload) { redirectUrl = request.getContextPath() + "/view/instructor/project.jsp?projectPK=" + project.getProjectPK(); } else { redirectUrl = request.getContextPath() + "/view/project.jsp?projectPK=" + project.getProjectPK(); } response.sendRedirect(redirectUrl); }
From source file:org.openinfinity.web.controller.ProductController.java
@Log @AuditTrail(argumentStrategy = ArgumentStrategy.ALL) @RequestMapping(method = RequestMethod.POST) public @ResponseBody Map<String, ? extends Object> create(@Valid @RequestBody ProductModel productModel, HttpServletResponse response) {//w w w. j a va 2s . c om Set<ConstraintViolation<ProductModel>> failures = validator.validate(productModel); if (failures.isEmpty()) { Product product = productService.create(productModel.getProduct()); return new ModelMap("id", product.getId()); } else { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return getValidationMessages(failures); } }
From source file:org.jetbrains.webdemo.sessions.MyHttpSession.java
private void sendDeleteProjectResult(HttpServletRequest request) { try {// ww w. ja v a 2 s .co m sessionInfo.setType(SessionInfo.TypeOfRequest.DELETE_PROJECT); MySqlConnector.getInstance().deleteProject(sessionInfo.getUserInfo(), request.getParameter("publicId")); writeResponse(HttpServletResponse.SC_OK); } catch (NullPointerException e) { writeResponse("Can't get parameters", HttpServletResponse.SC_BAD_REQUEST); } catch (DatabaseOperationException e) { writeResponse(e.getMessage(), HttpServletResponse.SC_FORBIDDEN); } }
From source file:ge.taxistgela.servlet.AdminServlet.java
private void toogleBan(SuperUserManager superUserManager, String sID, String password, HttpServletRequest request, HttpServletResponse response) { if (superUserManager == null) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } else {//from w w w .ja v a 2 s . co m Admin admin = (Admin) request.getSession().getAttribute(Admin.class.getName()); if (admin != null) { if (sID != null) { Integer id = null; try { id = Integer.parseInt(sID); } catch (Exception e) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } SuperDaoUser superUser = superUserManager.getByID(id); if (superUser != null) { superUser.setPassword(password); ErrorCode errorCode = superUserManager.update(superUser); if (errorCode.errorNotAccrued()) { response.setStatus(HttpServletResponse.SC_ACCEPTED); } else { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } else { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } } } else { response.setStatus(HttpServletResponse.SC_FORBIDDEN); } } }
From source file:org.energyos.espi.datacustodian.web.api.RetailCustomerRESTController.java
@RequestMapping(value = Routes.RETAIL_CUSTOMER_COLLECTION, method = RequestMethod.POST, consumes = "application/atom+xml", produces = "application/atom+xml") @ResponseBody/*from w w w. j ava2 s . c o m*/ public void create(HttpServletRequest request, HttpServletResponse response, @RequestParam Map<String, String> params, InputStream stream) throws IOException { Long subscriptionId = getSubscriptionId(request); response.setContentType(MediaType.APPLICATION_ATOM_XML_VALUE); try { RetailCustomer retailCustomer = this.retailCustomerService.importResource(stream); exportService.exportRetailCustomer(subscriptionId, retailCustomer.getId(), response.getOutputStream(), new ExportFilter(new HashMap<String, String>())); } catch (Exception e) { System.out.printf("***** Error Caused by RetailCustomer.x.IndentifiedObject need: %s", e.toString()); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } }
From source file:com.lp.webapp.cc.CCOrderResponseServlet.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException { ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory()); upload.setSizeMax(maxUploadSize);/* w ww. ja v a 2 s .c om*/ if (!ServletFileUpload.isMultipartContent(req)) { myLogger.info("Received request without form/multipart data. Aborting."); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } FileItem file = null; try { List<FileItem> files = upload.parseRequest(req); if (files.size() != 1) { response.setStatus(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE); return; } file = files.get(0); processOrder(req, response, file); } catch (FileUploadException e) { myLogger.error("Upload exception: ", e); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } catch (Exception e) { myLogger.error("Processing file exception: ", e); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); saveXmlFile(file); } }
From source file:info.raack.appliancelabeler.web.BaseController.java
@ExceptionHandler public ModelAndView handleUncaughtException(Exception ex, HttpServletRequest request, HttpServletResponse response) throws IOException { if (ex instanceof AccessDeniedException) { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); } else if (ex instanceof OAuthUnauthorizedException) { /*if(request.getSession() != null) { request.getSession().invalidate(); }//ww w .ja v a 2 s .co m SecurityContextHolder.getContext().setAuthentication(null);*/ try { response.sendRedirect("/t/logout.do"); logger.warn("Could not authorize oauth request", ex); } catch (IOException e1) { logger.error("Could not send redirect", e1); } return null; } else if (ex instanceof ClientAPIException) { if (ex.getCause() != null && ex.getCause() instanceof OAuthUnauthorizedException) { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); } else { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } response.getOutputStream().write(ex.getMessage().getBytes()); return null; } else { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); errorService.reportError("Error while processing user web page request", URGENCY.URGENT, ex); logger.error("An exception was caught while processing", ex); } return templateProvider.showPageInTemplate(1, "error/basic", new ModelMap()); }