List of usage examples for javax.servlet.http HttpServletResponse SC_INTERNAL_SERVER_ERROR
int SC_INTERNAL_SERVER_ERROR
To view the source code for javax.servlet.http HttpServletResponse SC_INTERNAL_SERVER_ERROR.
Click Source Link
From source file:controller.TemasNivel3RestController.java
/** * * @param request//from w w w .j a va 2 s . c o m * @param response * @return XML */ @RequestMapping(method = RequestMethod.GET, produces = "application/xml") public String getXML(HttpServletRequest request, HttpServletResponse response) { TemasNivel3DAO tabla = new TemasNivel3DAO(); XStream XML; List<TemasNivel3> lista; try { lista = tabla.selectAll(); if (lista.isEmpty()) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); Error e = new Error(); e.setTypeAndDescription("Warning", "No existen elementos"); XML = new XStream(); XML.alias("message", Error.class); return XML.toXML(e); } } catch (HibernateException ex) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); Error e = new Error(); e.setTypeAndDescription("errorServerError", ex.getMessage()); XML = new XStream(); XML.alias("message", Error.class); return XML.toXML(e); } Datos<TemasNivel3> datos = new Datos<>(); datos.setDatos(lista); XML = new XStream(); XML.alias("tema-nivel-3", TemasNivel3.class); response.setStatus(HttpServletResponse.SC_OK); return XML.toXML(lista); }
From source file:org.shept.services.jcaptcha.ImageCaptchaServlet.java
@SuppressWarnings("unchecked") protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException { BufferedImage challenge = null; try {/* ww w. ja v a 2 s . com*/ // get the session id that will identify the generated captcha. // the same id must be used to validate the response, the session id // is a good candidate! String captchaId = httpServletRequest.getSession().getId(); // If we have an explicit configuration for an ImageService we use this // else we use the predefined default ImageCaptchaService captchaService = CaptchaServiceSingleton.getInstance(); Map services = ctx.getBeansOfType(ImageCaptchaService.class); // there must be exactly on service configured if (services.size() == 1) { for (Iterator iterator = services.values().iterator(); iterator.hasNext();) { captchaService = (ImageCaptchaService) iterator.next(); } } // call the ImageCaptchaService getChallenge method challenge = captchaService.getImageChallengeForID(captchaId, httpServletRequest.getLocale()); } catch (IllegalArgumentException e) { httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND); return; } catch (CaptchaServiceException e) { httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } // flush it in the response httpServletResponse.setHeader("Cache-Control", "no-store"); httpServletResponse.setHeader("Pragma", "no-cache"); httpServletResponse.setDateHeader("Expires", 0); httpServletResponse.setContentType("image/jpeg"); ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream(); ImageIO.write(challenge, "jpeg", responseOutputStream); responseOutputStream.flush(); responseOutputStream.close(); }
From source file:com.app.inventario.controlador.Controlador.java
@RequestMapping(value = "/agregar-usuario", method = RequestMethod.POST) public @ResponseBody Map agregarUsuario(@ModelAttribute("usuario") Usuario usuario, HttpServletRequest request, HttpServletResponse response) {// ww w .j ava 2 s .c o m Map map = new HashMap(); try { this.usuarioServicio.guardar(usuario); response.setStatus(HttpServletResponse.SC_OK); map.put("Status", "OK"); map.put("Message", "Agregado Correctamente"); } catch (Exception ex) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); map.put("Status", "FAIL"); map.put("Message", ex.getCause().getCause().getCause().getMessage()); } return map; }
From source file:se.acrend.christopher.server.web.control.BillingController.java
@RequestMapping(value = "/billing/billingCompleted") public void billingCompleted(@RequestParam final String productId, final HttpServletResponse response) throws IOException { try {//from ww w. j ava 2s . com SubscriptionInfo result = billingService.billingCompleted(productId); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); Gson gson = ParserFactory.createParser(); gson.toJson(result, response.getWriter()); } catch (Exception e) { log.error("Kunde inte hmta prenumeration.", e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } }
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;/*w w w. j av a 2 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:org.mypackage.spring.controllers.EmailsSpringController.java
@RequestMapping(value = "/contacts/{id}/modify/new_email_submitted", method = RequestMethod.POST) public ModelAndView postCreateNewEmail(@PathVariable String id, @RequestParam("address") String address, @RequestParam("category") String categoryValue, @RequestParam("contactId") String contactId) { ModelAndView modelAndView = new ModelAndView(); try {//from w ww. j a v a 2 s . co m int newEmailId = newEmailController.addNewEmail(address, categoryValue, id); modelAndView.addObject("emailId", newEmailId); modelAndView = contactsSpringController.getAContact(id); modelAndView.setViewName("redirect:/contacts/" + id + "/modify"); } catch (DalException ex) { logger.error("An error occured while trying to add a new email for contact with ID = " + id + "Email object parameters: " + "/nAddress: " + address + "/nCategory value (enum): " + categoryValue + "/nfContactId: " + contactId, ex); modelAndView.addObject("errorCode", HttpServletResponse.SC_INTERNAL_SERVER_ERROR); modelAndView.addObject("errorMessage", "An internal database error occured. Please try again."); modelAndView.setViewName("/errorPage.jsp"); } catch (MalformedIdentifierException ex) { modelAndView.addObject("errorCode", HttpServletResponse.SC_BAD_REQUEST); modelAndView.addObject("errorMessage", "An error occured because of a malformed id." + id + " Please use only numeric values."); modelAndView.setViewName("/errorPage.jsp"); } catch (MalformedCategoryException ex) { modelAndView.addObject("errorCode", HttpServletResponse.SC_CONFLICT); modelAndView.addObject("errorMessage", "An internal conflict concerning the category of the email occured. Please try again."); modelAndView.setViewName("/errorPage.jsp"); } catch (DuplicateEmailException ex) { modelAndView = getCreateNewEmail(id); modelAndView.addObject("errorMessage", "This address already exists. Please enter a new one."); } return modelAndView; }
From source file:org.openmrs.module.openhmis.inventory.web.controller.JasperReportController.java
private String renderStockTakeReport(int reportId, WebRequest request, HttpServletResponse response) throws IOException { int stockroomId; String temp = request.getParameter("stockroomId"); if (!StringUtils.isEmpty(temp) && StringUtils.isNumeric(temp)) { stockroomId = Integer.parseInt(temp); } else {//from w ww . j a v a 2 s . c o m response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "The stockroom id ('" + temp + "') must be " + "defined and be numeric."); return null; } HashMap<String, Object> params = new HashMap<String, Object>(); params.put("stockroomId", stockroomId); return renderReport(reportId, params, null, response); }
From source file:edu.umich.ctools.sectionsUtilityTool.FriendServlet.java
private void friendRestApiCall(HttpServletRequest request, HttpServletResponse response) throws IOException { request.setCharacterEncoding("UTF-8"); M_log.debug("friendRestApiCall(): called"); Friend myFriend = new Friend(); PrintWriter out = response.getWriter(); response.setContentType("application/json"); Properties appExtSecureProperties = Friend.appExtSecureProperties; if (appExtSecureProperties == null) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); out = response.getWriter();/*from ww w .j av a 2 s . c o m*/ out.print(appExtProperties.getProperty("property.file.load.error")); out.flush(); M_log.error("Failed to load system properties(sectionsToolProps.properties) for SectionsTool"); return; } friendApiConnectionLogic(request, response, myFriend); }
From source file:dtu.ds.warnme.ws.rest.json.AbstractRestWS.java
@ExceptionHandler(Exception.class) @ResponseBody/* w w w. jav a 2 s.c o m*/ String handleOtherExceptions(Exception ex, HttpServletRequest request, HttpServletResponse response) { log.error("Internal server error!", ex); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); String responseBody = getMessage(ex, "exceptions.internalServerError", request.getLocale()); RestUtils.decorateResponseHeaderWithMD5(response, responseBody); RestUtils.decorateResponseHeaderForJsonContentType(response); return responseBody; }
From source file:eu.trentorise.smartcampus.permissionprovider.controller.BasicProfileController.java
@RequestMapping(method = RequestMethod.GET, value = "/basicprofile/all") public @ResponseBody BasicProfiles searchUsers(HttpServletResponse response, @RequestParam(value = "filter", required = false) String fullNameFilter) throws IOException { try {/* w ww . j a v a2 s . co m*/ List<BasicProfile> list; if (fullNameFilter != null && !fullNameFilter.isEmpty()) { list = profileManager.getUsers(fullNameFilter); } else { list = profileManager.getUsers(); } BasicProfiles profiles = new BasicProfiles(); profiles.setProfiles(list); return profiles; } catch (Exception e) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return null; } }