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:com.linuxbox.enkive.web.search.MboxExportServlet.java
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException { String searchId = WebScriptUtils.cleanGetParameter(req, "searchid"); res.setContentType("text/plain"); try {//from ww w . j a v a 2 s . c o m SearchResult theResult = workspaceService.getSearchResult(searchId); if (theResult == null) { // null if searchId refers to a search query and it had no // search results throw new EnkiveServletException("search query " + searchId + " had no results"); } Collection<String> messageIds = theResult.getMessageIds(); Writer writer = res.getWriter(); String tmpLine; for (String messageId : messageIds) { try { Message message = archiveService.retrieve(messageId); writer.write("From " + message.getDateStr() + "\r\n"); BufferedReader reader = new BufferedReader(new StringReader(message.getReconstitutedEmail())); while ((tmpLine = reader.readLine()) != null) { if (tmpLine.startsWith("From ")) writer.write(">" + tmpLine); else writer.write(tmpLine); writer.write("\r\n"); } } catch (CannotRetrieveException e) { respondError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, res); LOGGER.error("Could not retrieve message with id" + messageId); } writer.write("\r\n"); auditService.addEvent(AuditService.SEARCH_EXPORTED, permService.getCurrentUsername(), "Search Exported to mbox - ID:" + searchId); } } catch (WorkspaceException e) { respondError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, res); throw new EnkiveServletException( "unable to access workspace or access search or result with id " + searchId); } catch (AuditServiceException e) { respondError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, res); throw new EnkiveServletException("Could not write to audit log"); } }
From source file:de.mpg.escidoc.services.fledgeddata.webservice.oaiServlet.java
/** * Peform the http GET action. Note that POST is shunted to here as well. * The verb widget is taken from the request and used to invoke an * OAIVerb object of the corresponding kind to do the actual work of the verb. * * @param request the servlet's request information * @param response the servlet's response information * @exception IOException an I/O error occurred *//*from w ww . j a v a 2s. c o m*/ public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { boolean serviceUnavailable = isServiceUnavailable(); HashMap serverVerbs = ServerVerb.getVerbs(); request.setCharacterEncoding("UTF-8"); if (serviceUnavailable) { LOGGER.info("[FDS] oai servcice set to 'unavailable' in properties file."); response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "[FDS] Sorry. This server is down for maintenance"); } else { try { String result = getResult(request, response, serverVerbs); Writer out = getWriter(request, response); out.write(result); out.close(); } catch (OAIInternalServerError e) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } catch (SocketException e) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } catch (Throwable e) { e.printStackTrace(); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } } }
From source file:com.thoughtworks.go.server.security.BasicAuthenticationFilter.java
private void generateResponse(HttpServletResponse httpResponse, String type, String msg) throws IOException { httpResponse.addHeader("WWW-Authenticate", "Basic realm=\"GoCD\""); httpResponse.setContentType(type);/*from www . ja v a2 s. c om*/ httpResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); httpResponse.getOutputStream().print(msg); }
From source file:com.amazon.speech.speechlet.servlet.SpeechletServlet.java
/** * Handles a POST request. Based on the request parameters, invokes the right method on the * {@code SpeechletV2}.//from w w w. j a v a 2 s . c o m * * @param request * the object that contains the request the client has made of the servlet * @param response * object that contains the response the servlet sends to the client * @throws IOException * if an input or output error is detected when the servlet handles the request */ @Override protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws IOException { byte[] serializedSpeechletRequest = IOUtils.toByteArray(request.getInputStream()); byte[] outputBytes = null; try { if (disableRequestSignatureCheck) { log.warn("Warning: Speechlet request signature verification has been disabled!"); } else { // Verify the authenticity of the request by checking the provided signature & // certificate. SpeechletRequestSignatureVerifier.checkRequestSignature(serializedSpeechletRequest, request.getHeader(Sdk.SIGNATURE_REQUEST_HEADER), request.getHeader(Sdk.SIGNATURE_CERTIFICATE_CHAIN_URL_REQUEST_HEADER)); } outputBytes = speechletRequestHandler.handleSpeechletCall(speechlet, serializedSpeechletRequest); } catch (SpeechletRequestHandlerException | SecurityException ex) { int statusCode = HttpServletResponse.SC_BAD_REQUEST; log.error("Exception occurred in doPost, returning status code {}", statusCode, ex); response.sendError(statusCode, ex.getMessage()); return; } catch (Exception ex) { int statusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; log.error("Exception occurred in doPost, returning status code {}", statusCode, ex); response.sendError(statusCode, ex.getMessage()); return; } // Generate JSON and send back the response response.setContentType("application/json"); response.setStatus(HttpServletResponse.SC_OK); try (final OutputStream out = response.getOutputStream()) { response.setContentLength(outputBytes.length); out.write(outputBytes); } }
From source file:eu.trentorise.smartcampus.mobility.controller.rest.CacheController.java
@SuppressWarnings("rawtypes") @RequestMapping(method = RequestMethod.POST, value = "/partialcachestatus") public @ResponseBody Map<String, CacheUpdateResponse> getPartialCacheStatus(HttpServletRequest request, HttpServletResponse response, HttpSession session, @RequestBody(required = false) Map<String, Map> versions) { try {//from www . j av a 2 s . c om // String address = otpURL + OTP + "getPartialCacheStatus"; // // ObjectMapper mapper = new ObjectMapper(); // String content = mapper.writeValueAsString(versions); // String res = HTTPConnector.doPost(address, content, MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON); // // Map<String, CacheUpdateResponse> result = mapper.readValue(res, Map.class); // // return result; return new HashMap<String, CacheUpdateResponse>(); } catch (Exception e) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return null; } }
From source file:org.activiti.rest.api.identity.LoginPost.java
/** * Authenticates username and password and prepares the response for the webscript template. * * @param req The webscripts request/*www. j a v a 2 s . co m*/ * @param status The webscripts status * @param cache The webscript cache * @param model The webscripts template model */ @Override protected void executeWebScript(WebScriptRequest req, Status status, Cache cache, Map<String, Object> model) { // Extract user and password from JSON POST Content c = req.getContent(); if (c == null) { throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Missing POST body."); } try { JSONObject json = new JSONObject(c.getContent()); String userId = json.getString("userId"); String password = json.getString("password"); if (userId == null || userId.length() == 0) { throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, "Username not specified"); } if (password == null) { throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, "Password not specified"); } String engineName = config.getEngine(); ProcessEngine pe = ProcessEngines.getProcessEngine(engineName); if (pe != null) { if (!pe.getIdentityService().checkPassword(userId, password)) { throw new WebScriptException(HttpServletResponse.SC_FORBIDDEN, "Username and password does not match."); } // Login successful ... } else { String message; ProcessEngineInfo pei = ProcessEngines.getProcessEngineInfo(engineName); if (pei != null) { message = pei.getException(); } else { message = "Can't find process engine named '" + engineName + "' which is needed to authenticate username and password."; List<ProcessEngineInfo> processEngineInfos = ProcessEngines.getProcessEngineInfos(); if (processEngineInfos.size() > 0) { message += "\nHowever " + processEngineInfos.size() + " other process engine(s) was found: "; } for (ProcessEngineInfo processEngineInfo : processEngineInfos) { message += "Process engine '" + processEngineInfo.getName() + "' (" + processEngineInfo.getResourceUrl() + "):"; if (processEngineInfo.getException() != null) { message += processEngineInfo.getException(); } else { message += "OK"; } } } throw new WebScriptException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); } } catch (JSONException e) { throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Unable to parse JSON POST body: " + e.getMessage()); } catch (IOException e) { throw new WebScriptException(Status.STATUS_INTERNAL_SERVER_ERROR, "Unable to retrieve POST body: " + e.getMessage()); } }
From source file:com.epam.wilma.webapp.config.servlet.stub.upload.MultiPartFormUploadServletTest.java
@Test public void testDoGetShouldSendErrorResponseWhenRequestParsingFailedByTheServletFileUpload() throws ServletException, IOException, FileUploadException { //GIVEN//from w w w.j a v a 2 s . c o m given(request.getMethod()).willReturn("POST"); given(fileUpload.parseRequest(request)).willThrow(new FileUploadException()); //WHEN underTest.doGet(request, response); //THEN verify(response).setContentType("text/html"); verify(response).setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); verify(writer).write(Matchers.anyString()); }
From source file:com.github.fge.jsonschema.servlets.SyntaxValidateServlet.java
@Override public void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { final Set<String> params = Sets.newHashSet(); /*/*from w ww .java2 s. c om*/ * First, check our parameters */ /* * Why, in 2013, doesn't servlet-api provide an Iterator<String>? * * Well, at least, Jetty's implementation has a generified Enumeration. * Still, that sucks. */ final Enumeration<String> enumeration = req.getParameterNames(); // FIXME: no duplicates, it seems, but I cannot find the spec which // guarantees that while (enumeration.hasMoreElements()) params.add(enumeration.nextElement()); // We have required parameters if (!params.containsAll(Request.required())) { log.warn("Missing parameters! Someone using me as a web service?"); resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing parameters"); return; } // We don't want extraneous parameters params.removeAll(Request.valid()); if (!params.isEmpty()) { log.warn("Invalid parameters! Someone using me as a web service?"); resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid parameters"); return; } final String rawSchema = req.getParameter(Request.SCHEMA); // Set correct content type resp.setContentType(MediaType.JSON_UTF_8.toString()); final JsonNode ret; try { ret = buildResult(rawSchema); } catch (ProcessingException e) { // Should not happen! log.error("Uh, syntax validation failed!", e); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } final OutputStream out = resp.getOutputStream(); try { out.write(ret.toString().getBytes(Charset.forName("UTF-8"))); out.flush(); } finally { Closeables.closeQuietly(out); } }
From source file:com.vmware.identity.openidconnect.server.AuthorizationController.java
@RequestMapping(value = "/oidc/authorize/{tenant:.*}", method = { RequestMethod.GET, RequestMethod.POST }) public ModelAndView authorize(Model model, Locale locale, HttpServletRequest request, HttpServletResponse response, @PathVariable("tenant") String tenant) throws IOException { ModelAndView page = null;// ww w. j a va 2s .c om IDiagnosticsContextScope context = null; try { HttpRequest httpRequest = HttpRequest.create(request); context = DiagnosticsContextFactory.createContext(CorrelationID.get(httpRequest).getValue(), tenant); AuthenticationRequestProcessor p = new AuthenticationRequestProcessor(this.idmClient, this.authzCodeManager, this.sessionManager, this.messageSource, model, locale, httpRequest, tenant); Pair<ModelAndView, HttpResponse> result = p.process(); page = result.getLeft(); HttpResponse httpResponse = result.getRight(); if (httpResponse != null) { httpResponse.applyTo(response); } } catch (Exception e) { logger.error("unhandled exception", e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "unhandled exception: " + e.getClass().getName()); } finally { if (context != null) { context.close(); } } return page; }
From source file:com.pymegest.applicationserver.api.PuestoController.java
@RequestMapping(value = { "/Puesto/{idsPuestos}" }, method = RequestMethod.DELETE) public void delete(HttpServletRequest request, HttpServletResponse response, @PathVariable("idsPuestos") String idsPuestosStr) { try {/*w w w. j av a2 s .c om*/ String[] idsPuestosArr = idsPuestosStr.split(","); for (int i = 0; i < idsPuestosArr.length; i++) { puestoDAO.delete(Integer.parseInt(idsPuestosArr[i])); } response.setStatus(HttpServletResponse.SC_NO_CONTENT); } catch (Exception ex) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.setContentType("text/plain; charset=UTF-8"); try { ex.printStackTrace(response.getWriter()); } catch (IOException ex1) { } } }