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:es.logongas.ix3.web.util.ControllerHelper.java
public void exceptionToHttpResponse(Throwable throwable, HttpServletResponse httpServletResponse) { try {//from w w w .j a va 2s . c o m BusinessException businessException = ExceptionUtil.getBusinessExceptionFromThrowable(throwable); if (businessException != null) { if (businessException instanceof BusinessSecurityException) { BusinessSecurityException businessSecurityException = (BusinessSecurityException) businessException; Log log = LogFactory.getLog(ControllerHelper.class); log.info(businessSecurityException); httpServletResponse.setStatus(HttpServletResponse.SC_FORBIDDEN); httpServletResponse.setContentType("text/plain; charset=UTF-8"); if (businessSecurityException.getBusinessMessages().size() > 0) { httpServletResponse.getWriter() .println(businessSecurityException.getBusinessMessages().get(0).getMessage()); } } else if (businessException instanceof BusinessException) { httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); httpServletResponse.setContentType("application/json; charset=UTF-8"); httpServletResponse.getWriter() .println(jsonFactory.getJsonWriter().toJson(businessException.getBusinessMessages())); } else { Log log = LogFactory.getLog(ControllerHelper.class); log.error("Es un tipo de businessException desconocida:", businessException); httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); httpServletResponse.setContentType("text/plain"); businessException.printStackTrace(httpServletResponse.getWriter()); } } else { Log log = LogFactory.getLog(ControllerHelper.class); log.error("Fall la llamada al servidor:", throwable); httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); httpServletResponse.setContentType("text/plain"); throwable.printStackTrace(httpServletResponse.getWriter()); } } catch (IOException ioException) { Log log = LogFactory.getLog(ControllerHelper.class); log.error("Fall al devolver la excepcin por la HttpResponse:", ioException); log.error("Excepcion original:", throwable); httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } }
From source file:it.cnr.icar.eric.server.interfaces.rest.RestServlet.java
/** Handles the HTTP <code>GET</code> method. * @param request servlet request//w ww .j a v a2 s .c o m * @param response servlet response */ @SuppressWarnings("static-access") protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String interfase = request.getParameter("interface"); try { if ((interfase == null) || interfase.equals("")) { //First check if it is a user defined URL since that is less expensive to match UserDefinedURLHandler udefURLHandler = new UserDefinedURLHandler(request, response); try { udefURLHandler.processGetRequest(); response.setStatus(response.SC_OK); } catch (ObjectNotFoundException e) { FilePathURLHandler filePathURLHandler = new FilePathURLHandler(request, response); filePathURLHandler.processGetRequest(); response.setStatus(response.SC_OK); } } else if (interfase.equalsIgnoreCase("QueryManager")) { QueryManagerURLHandler qmURLHandler = new QueryManagerURLHandler(request, response); qmURLHandler.processGetRequest(); response.setStatus(response.SC_OK); } else if (interfase.equalsIgnoreCase("LifeCycleManager")) { LifeCycleManagerURLHandler lcmURLHandler = new LifeCycleManagerURLHandler(request, response); lcmURLHandler.processGetRequest(); response.setStatus(response.SC_OK); } else if (extendedInterfaces.containsKey(interfase)) { String className = extendedInterfaces.get(interfase).toString(); URLHandler handler = createURLHandlerInstance(className, request, response); if (handler != null) { handler.processGetRequest(); response.setStatus(response.SC_OK); } else { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid request. Unknown interface: " + interfase); } } else { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid request. Unknown interface: " + interfase); } } catch (ObjectNotFoundException e) { response.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage()); } catch (InvalidRequestException e) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage()); } catch (UnimplementedException e) { response.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, e.getMessage()); } catch (RegistryException e) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } }
From source file:com.streamsets.pipeline.stage.origin.ipctokafka.IpcToKafkaServlet.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String requestor = req.getRemoteAddr() + ":" + req.getRemotePort(); if (shuttingDown) { LOG.debug("Shutting down, discarding incoming request from '{}'", requestor); resp.setStatus(HttpServletResponse.SC_GONE); } else {/*from w w w . j av a2 s . c o m*/ String appId = req.getHeader(Constants.X_SDC_APPLICATION_ID_HEADER); String compression = req.getHeader(Constants.X_SDC_COMPRESSION_HEADER); String contentType = req.getContentType(); String json1Fragmentable = req.getHeader(Constants.X_SDC_JSON1_FRAGMENTABLE_HEADER); if (!Constants.APPLICATION_BINARY.equals(contentType)) { invalidRequestMeter.mark(); resp.sendError(HttpServletResponse.SC_BAD_REQUEST, Utils.format( "Wrong content-type '{}', expected '{}'", contentType, Constants.APPLICATION_BINARY)); } else if (!"true".equals(json1Fragmentable)) { invalidRequestMeter.mark(); resp.sendError(HttpServletResponse.SC_BAD_REQUEST, Utils.format( "RPC client is not using a fragmentable JSON1 encoding, client;s SDC must be upgraded")); } else if (!configs.appId.equals(appId)) { invalidRequestMeter.mark(); LOG.warn("IPC from '{}' invalid appId '{}', rejected", requestor, appId); resp.sendError(HttpServletResponse.SC_FORBIDDEN, "Invalid 'appId'"); } else { long start = System.currentTimeMillis(); LOG.debug("Request accepted from '{}'", requestor); try (InputStream in = req.getInputStream()) { InputStream is = in; boolean processRequest = true; if (compression != null) { switch (compression) { case Constants.SNAPPY_COMPRESSION: is = new SnappyFramedInputStream(is, true); break; default: invalidRequestMeter.mark(); LOG.warn("Invalid compression '{}' in request from '{}', returning error", compression, requestor); resp.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, "Unsupported compression: " + compression); processRequest = false; } } if (processRequest) { LOG.debug("Processing request from '{}'", requestor); List<byte[]> messages = SdcStreamFragmenter.fragment(is, maxMessageSize, maxRpcRequestSize); LOG.debug("Request from '{}' broken into '{}' messages", requestor, messages.size()); long kStart = System.currentTimeMillis(); SdcKafkaProducer producer = getKafkaProducer(); long kafkaTime = System.currentTimeMillis() - kStart; try { for (byte[] message : messages) { // we are using round robing partition strategy, partition key is ignored kStart = System.currentTimeMillis(); producer.enqueueMessage(kafkaConfigBean.kafkaConfig.topic, message, ""); kafkaTime += System.currentTimeMillis() - kStart; } kStart = System.currentTimeMillis(); producer.write(); kafkaTime += System.currentTimeMillis() - kStart; resp.setStatus(HttpServletResponse.SC_OK); requestMeter.mark(); } catch (StageException ex) { LOG.warn("Kakfa producer error: {}", ex.toString(), ex); errorQueue.offer(ex); errorRequestMeter.mark(); LOG.warn("Error while reading payload from '{}': {}", requestor, ex.toString(), ex); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.toString()); } finally { kStart = System.currentTimeMillis(); releaseKafkaProducer(producer); kafkaTime += System.currentTimeMillis() - kStart; } kafkaTimer.update(kafkaTime, TimeUnit.MILLISECONDS); kafkaMessagesMeter.mark(messages.size()); } } catch (Exception ex) { errorRequestMeter.mark(); LOG.warn("Error while reading payload from '{}': {}", requestor, ex.toString(), ex); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.toString()); } finally { requestTimer.update(System.currentTimeMillis() - start, TimeUnit.MILLISECONDS); } } } }
From source file:org.energyos.espi.datacustodian.web.api.UsagePointRESTController.java
@RequestMapping(value = Routes.ROOT_USAGE_POINT_MEMBER, method = RequestMethod.DELETE) @ResponseBody/* w ww .j a v a2 s .com*/ public void delete(HttpServletResponse response, @PathVariable Long usagePointId, @RequestParam Map<String, String> params) { try { resourceService.deleteById(usagePointId, UsagePoint.class); } catch (Exception e) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } }
From source file:com.iflytek.edu.cloud.frame.web.filter.CheckOpenServiceFilterTest.java
/** * ?version?//w ww . j av a 2s . c om */ @Test @Ignore public void testVersionNotExist() { MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); response.setCharacterEncoding("UTF-8"); try { request.setMethod("POST"); request.addParameter("method", "user.get"); request.addParameter("version", "1.0.1"); filter.doFilter(request, response, null); Assert.assertEquals(response.getStatus(), HttpServletResponse.SC_BAD_REQUEST); Assert.assertEquals(MainErrorType.UNSUPPORTED_VERSION.value(), ErrorMsgParser.getErrorCode(response)); } catch (IOException e) { e.printStackTrace(); } catch (ServletException e) { e.printStackTrace(); } }
From source file:com.github.jrialland.ajpclient.servlet.TestServletProxy.java
/** * Test that is fails with a request bigger that 8k *//*from w w w. j a va 2 s . com*/ @Test public void testTooBigRequest() throws Exception { final MockHttpServletRequest request = new MockHttpServletRequest(); request.setMethod("GET"); request.setRequestURI("/dizzy.mp4"); // generate a request with an enormous 'Cookie' header String cookie = ""; final int i = 0; while (cookie.length() < Constants.MAX_MESSAGE_SIZE) { cookie = cookie + "COOKIE" + i + "=foo;"; } request.addHeader("Cookie", cookie); final MockHttpServletResponse response = new MockHttpServletResponse(); AjpServletProxy.forHost("localhost", getPort()).forward(request, response); Assert.assertEquals(HttpServletResponse.SC_BAD_REQUEST, response.getStatus()); }
From source file:org.clothocad.phagebook.controllers.MiscControllers.java
@RequestMapping(value = "/resendVerification", method = RequestMethod.GET) protected void resendVerification(@RequestParam Map<String, String> params, HttpServletResponse response) throws ServletException, IOException { String userId = params.get("id"); boolean isValid = false; if (!userId.isEmpty()) { isValid = true;//from w ww .j a v a2 s. c o m } if (isValid) { ClothoConnection conn = new ClothoConnection(Args.clothoLocation); Clotho clothoObject = new Clotho(conn); Map loginMap = new HashMap(); String username = this.backendPhagebookUser; String password = this.backendPhagebookPassword; loginMap.put("username", username); loginMap.put("credentials", password); clothoObject.login(loginMap); //operating under the assumption that we will have the saved clotho ID of the user Person person1 = ClothoAdapter.getPerson(userId, clothoObject); if (person1 != null) { String link = Args.phagebookBaseURL + "/html/validateEmail.html?emailId=" + person1.getEmailId() + "&salt=" + person1.getSalt(); EmailHandler handly = EmailHandler.getEmailHandler(); handly.sendEmailVerification(person1, link); response.setStatus(HttpServletResponse.SC_OK); response.setContentType("application/json"); PrintWriter out = response.getWriter(); JSONObject responseJSON = new JSONObject(); responseJSON.put("message", "Email Sent!"); out.print(responseJSON.toString()); out.flush(); out.close(); } clothoObject.logout(); conn.closeConnection(); } else { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.setContentType("application/json"); PrintWriter out = response.getWriter(); JSONObject responseJSON = new JSONObject(); responseJSON.put("message", "Cannot find the user. Try again later!"); out.print(responseJSON.toString()); out.flush(); out.close(); } }
From source file:edu.ucsd.library.dams.api.FileStoreServlet.java
/** * Process the actual request.// w w w . j ava 2s.c o 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. */ private void processRequest(HttpServletRequest request, HttpServletResponse response, boolean content) throws IOException { // Validate the requested file ------------------------------------- // Get requested file by path info. /* start ucsd changes */ // get object and file ids from path String objid = null; String cmpid = null; String fileid = null; try { // /bb1234567x/1.tif // /bb1234567x/1/2.tif String[] path = request.getPathInfo().split("/"); if (path.length == 3) { objid = path[1]; fileid = path[2]; } else if (path.length == 4) { objid = path[1]; cmpid = path[2]; fileid = path[3]; } } catch (Exception e) { String errorMessage = "Error parsing request pathInfo: " + request.getPathInfo(); log.error(errorMessage, e); response.setContentType("text/plain"); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, errorMessage); return; } // make sure required parameters are populated if (objid == null || objid.trim().length() == 0 || fileid == null || fileid.trim().length() == 0) { response.setContentType("text/plain"); response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Subject and file must be specified in the request URI"); return; } String fullFilename = objid + (StringUtils.isNotBlank(cmpid) ? "-" + cmpid : "") + "-" + fileid; // first load the FileStore (no point if this doesn't work) FileStore fs = null; long fsTime = 0; try { long start = System.currentTimeMillis(); fs = FileStoreUtil.getFileStore(props, fsDefault); fsTime = System.currentTimeMillis() - start; } catch (Exception ex) { response.setContentType("text/plain"); response.sendError(response.SC_INTERNAL_SERVER_ERROR, "Error initializing FileStore"); ex.printStackTrace(); return; } // check authorization attribute String restricted = null; String authorized = (String) request.getAttribute("edu.ucsd.library.dams.api.DAMSAPIServlet.authorized"); if (authorized == null || !authorized.equals("true")) { log.warn("Illegal Access from IP " + request.getRemoteAddr() + " for file " + fullFilename); response.setContentType("text/plain"); response.sendError(HttpServletResponse.SC_FORBIDDEN, "Access without authorization."); return; } else { log.info("DAMS Access authorized for IP " + request.getRemoteAddr() + " for file " + fullFilename); restricted = (String) request.getAttribute("pas.restricted"); //Disable browser caching for restricted objects. if (restricted != null && restricted.equals("1")) { String browser = request.getHeader("User-Agent"); if (browser != null && browser.indexOf("MSIE") != -1) { response.addHeader("Cache-Control", "post-check=0, pre-check=0"); } else { response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate"); } response.setHeader("Pragma", "no-cache"); response.setHeader("Expires", "0"); } } /* end ucsd changes */ // load file metadata Map<String, String> meta = null; long metaTime = 0; try { long start = System.currentTimeMillis(); meta = fs.meta(objid, cmpid, fileid); metaTime = System.currentTimeMillis() - start; } catch (Exception ex) { log.error("File " + fullFilename + " doesn't exist.", ex); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // Prepare some variables. The ETag is an unique identifier of the file String length = meta.get("Content-Length"); String lastModStr = meta.get("Last-Modified"); long lastModified = 0L; try { lastModified = df.parse(lastModStr).getTime(); } catch (Exception ex) { // error parsing lastmod date... set to now lastModified = System.currentTimeMillis(); } String eTag = meta.get("ETag"); if (eTag == null) { eTag = fullFilename + "_" + length + "_" + lastModified; } // Validate request headers for caching ----------------------------- // If-None-Match header should contain "*" or ETag. If so, 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; } // Prepare and initialize response ---------------------------------- // Get content type by file name and set default GZIP support and // content disposition. String contentType = getServletContext().getMimeType(fullFilename); 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 UCSD download boolean download = request.getParameter("download") != null; if (download) { disposition = "attachment"; contentType = "application/x-download"; } // Else 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 if (contentType.startsWith("text")) { //String acceptEncoding = request.getHeader("Accept-Encoding"); //acceptsGzip = acceptEncoding != null && accepts(acceptEncoding, "gzip"); contentType += ";charset=UTF-8"; } // 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. else if (!contentType.startsWith("image")) { String accept = request.getHeader("Accept"); disposition = accept != null && accepts(accept, contentType) ? "inline" : "attachment"; } String sFileName = request.getParameter("name"); if (sFileName == null || (sFileName = sFileName.trim()).length() == 0) sFileName = fullFilename; // Initialize response. response.reset(); response.setBufferSize(DEFAULT_BUFFER_SIZE); response.setHeader("Content-Disposition", disposition + ";filename=\"" + sFileName + "\""); response.setHeader("ETag", eTag); response.setDateHeader("Last-Modified", lastModified); /* begin ucsd changes */ if (restricted == null || !restricted.equals("1")) { response.setDateHeader("Expires", System.currentTimeMillis() + DEFAULT_EXPIRE_TIME); } /* end ucsd changes */ // Send requested file to client ------------------------------------ // Prepare streams. InputStream input = null; OutputStream output = null; long fileTime = 0; if (content) { try { long start = System.currentTimeMillis(); // Open streams. input = fs.getInputStream(objid, cmpid, fileid); output = response.getOutputStream(); response.setContentType(contentType); 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", length); } // Copy full range. /* begin ucsd changes */ FileStoreUtil.copy(input, output); fileTime = System.currentTimeMillis() - start; /* begin ucsd changes */ } catch (Exception ex) { log.error("Error reading " + fullFilename, ex); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } finally { /* begin ucsd changes */ log.info("Time in miliseconds to retrival file " + fullFilename + "(" + length + " bytes)" + ": Total " + (fsTime + metaTime + fileTime) + "[FileStore initiation: " + fsTime + "; Metadata query: " + metaTime + "; File download: " + fileTime + "]"); /* begin ucsd changes */ // Gently close streams. close(output); close(input); } } }