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:net.siegmar.japtproxy.JaptProxyServlet.java
/** * Check the requested data and forward the request to internal sender. * * @param req the HttpServletRequest object * @param res the HttpServletResponse object * @throws ServletException {@inheritDoc} * @throws IOException {@inheritDoc} *//*from ww w . j ava2 s .com*/ @Override protected void doGet(final HttpServletRequest req, final HttpServletResponse res) throws ServletException, IOException { res.setBufferSize(Util.DEFAULT_BUFFER_SIZE); MDC.put("REQUEST_ID", DigestUtils.md5Hex(Long.toString(System.currentTimeMillis()))); LOG.debug("Incoming request from IP '{}', " + "User-Agent '{}'", req.getRemoteAddr(), req.getHeader(HttpHeaderConstants.USER_AGENT)); if (LOG.isDebugEnabled()) { logHeader(req); } try { japtProxy.handleRequest(req, res); } catch (final InvalidRequestException e) { LOG.warn(e.getMessage()); res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid request"); return; } catch (final UnknownBackendException e) { LOG.info(e.getMessage()); res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Unknown backend"); return; } catch (final ResourceUnavailableException e) { LOG.debug(e.getMessage(), e); res.sendError(HttpServletResponse.SC_NOT_FOUND); return; } catch (final HandlingException e) { LOG.error("HandlingException", e); res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } finally { MDC.clear(); } res.flushBuffer(); }
From source file:com.alfaariss.oa.util.saml2.binding.soap11.SOAP11Utils.java
/** * Construct and send a SOAP Fault.//from w ww. j a va 2 s .c om * * Constructs a SOAP Fault message and send it using the out transport of * the message context. * * The followinf SOAP codes are send: * <dl> * <dt>soap11:Client</dt> * <dd>In case of a {@link RequestorEvent#REQUEST_INVALID}</dd> * <dt>soap11:Server</dt> * <dd>In case of other {@link RequestorEvent}s</dd> * </dl> * * @param messageContext The message context. * @param event The requestor event. * @throws OAException If sending fails due to internal error. */ public static void sendSOAPFault( SAMLMessageContext<SignableSAMLObject, SignableSAMLObject, SAMLObject> messageContext, RequestorEvent event) throws OAException { //DD SOAP HTTP server MUST return a "500 Internal Server Error" response and include a SOAP fault [saml-bindings-2.0-os r372] try { /** XMLObjectBuilderFactory */ XMLObjectBuilderFactory builderFactory = Configuration.getBuilderFactory(); //Build SOAP Envelope and Body EnvelopeBuilder envBuilder = (EnvelopeBuilder) builderFactory.getBuilder(Envelope.DEFAULT_ELEMENT_NAME); Envelope envelope = envBuilder.buildObject(); BodyBuilder bodyBuilder = (BodyBuilder) builderFactory.getBuilder(Body.DEFAULT_ELEMENT_NAME); Body body = bodyBuilder.buildObject(); //Build fault FaultCodeBuilder faultCodeBuilder = (FaultCodeBuilder) builderFactory .getBuilder(FaultCode.DEFAULT_ELEMENT_NAME); FaultCode code = faultCodeBuilder.buildObject(FaultCode.DEFAULT_ELEMENT_NAME); FaultStringBuilder faultStringBuilder = (FaultStringBuilder) builderFactory .getBuilder(FaultString.DEFAULT_ELEMENT_NAME); FaultString faultString = faultStringBuilder.buildObject(FaultString.DEFAULT_ELEMENT_NAME); switch (event) { case REQUEST_INVALID: { code.setValue(new QName(SOAPConstants.SOAP11_NS, "Client", SOAPConstants.SOAP11_PREFIX)); faultString.setValue(event.name()); break; } default: { code.setValue(new QName(SOAPConstants.SOAP11_NS, "Server", SOAPConstants.SOAP11_PREFIX)); faultString.setValue(RequestorEvent.INTERNAL_ERROR.name()); break; } } FaultBuilder faultBuilder = (FaultBuilder) builderFactory.getBuilder(Fault.DEFAULT_ELEMENT_NAME); Fault fault = faultBuilder.buildObject(); fault.setCode(code); fault.setMessage(faultString); body.getUnknownXMLObjects().add(fault); envelope.setBody(body); //Marshall message messageContext.setOutboundMessage(envelope); Marshaller m = Configuration.getMarshallerFactory().getMarshaller(Envelope.DEFAULT_ELEMENT_NAME); m.marshall(envelope); //Send SOAP Fault HTTPOutTransport outTransport = (HTTPOutTransport) messageContext.getOutboundMessageTransport(); HTTPTransportUtils.addNoCacheHeaders(outTransport); HTTPTransportUtils.setUTF8Encoding(outTransport); HTTPTransportUtils.setContentType(outTransport, "text/xml"); outTransport.setHeader("SOAPAction", "http://www.oasis-open.org/committees/security"); outTransport.setStatusCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); Writer out = new OutputStreamWriter(outTransport.getOutgoingStream(), SAML2Constants.CHARSET); XMLHelper.writeNode(envelope.getDOM(), out); out.flush(); } catch (UnsupportedEncodingException e) { _logger.error(SAML2Constants.CHARSET + " encoding error", e); throw new OAException(SystemErrors.ERROR_INTERNAL); } catch (IOException e) { _logger.error("I/O error while sending SOAP Fault", e); throw new OAException(SystemErrors.ERROR_INTERNAL); } catch (MarshallingException e) { _logger.error("Marshalling error while sending SOAP Fault", e); throw new OAException(SystemErrors.ERROR_INTERNAL); } }
From source file:com.janrain.backplane2.server.Token.java
public static @NotNull Token fromRequest(DAOFactory daoFactory, HttpServletRequest request, String tokenString, String authorizationHeader) throws TokenException { Pair<String, EnumSet<TokenSource>> tokenAndSource = extractToken(request.getQueryString(), tokenString, authorizationHeader);//from w ww . j a v a 2s . c o m if (!Token.looksLikeOurToken(tokenAndSource.getLeft())) { throw new TokenException("invalid token", HttpServletResponse.SC_FORBIDDEN); } Token token; try { token = daoFactory.getTokenDao().get(tokenAndSource.getLeft()); } catch (BackplaneServerException e) { logger.error("Error looking up token: " + tokenAndSource.getLeft(), e); throw new TokenException(OAuth2.OAUTH2_TOKEN_SERVER_ERROR, "error loading token", HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } if (token == null) { logger.warn("token not found: " + tokenAndSource.getLeft()); throw new TokenException("invalid token", HttpServletResponse.SC_FORBIDDEN); } if (token.isExpired()) { throw new TokenException("expired token", HttpServletResponse.SC_FORBIDDEN); } token.checkAllowedSources(tokenAndSource.getRight()); return token; }
From source file:ee.pri.rl.blog.web.servlet.FileDownloadServlet.java
private void sendFile(String path, String calculatedTag, File directory, HttpServletResponse resp) { File file = new File(directory, path); String mimeType = getServletContext().getMimeType(path); if (mimeType == null) { mimeType = "application/octet-stream"; }/*from w w w. j a v a2s . c om*/ resp.setHeader("ETag", calculatedTag); resp.setDateHeader("Date", System.currentTimeMillis()); resp.setContentType(mimeType); resp.setContentLength((int) file.length()); long liveTime = 3600 * 24 * 30; resp.setDateHeader("Expires", System.currentTimeMillis() + liveTime * 1000); resp.setHeader("Cache-Control", "public, max-age=" + liveTime); try { DataInputStream input = new DataInputStream(new FileInputStream(file)); try { IOUtils.copy(input, resp.getOutputStream()); resp.getOutputStream().flush(); resp.getOutputStream().close(); } catch (IOException e) { log.warn("Sending " + file + " failed", e); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } if (input != null) { input.close(); } } catch (IOException e) { log.warn("Sending " + file + " failed", e); try { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } catch (IOException e1) { log.warn("Sending response for " + file + " failed"); } } }
From source file:eu.trentorise.smartcampus.mobility.controller.rest.CacheController.java
/** * @param request//from w w w. j av a 2s .c o m * @param response * @param session * @param versions */ @Deprecated @RequestMapping(method = RequestMethod.POST, value = "/getcachestatus") public @ResponseBody Map<String, Map<String, Object>> getCacheStatus(HttpServletRequest request, HttpServletResponse response, HttpSession session, @RequestBody(required = false) Map<String, String> versions) { try { Map<String, Map<String, Object>> result = new HashMap<String, Map<String, Object>>(); for (String agency : versions.keySet()) { Map<String, Object> map = new HashMap<String, Object>(); map.put("version", Long.parseLong(versions.get(agency))); map.put("added", Collections.emptyList()); map.put("removed", Collections.emptyList()); map.put("calendar", null); result.put(agency, map); } return result; } catch (Exception e) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return null; } }
From source file:org.springsource.ide.eclipse.boot.maven.analyzer.server.AetherialController.java
/** * Helper method to send a 'Future' as a response to the client. * If the future is 'done' actual content (or error) is sent. Otherwise * a 'try later' result is sent instead. *///from ww w .jav a2 s.com private void sendResponse(HttpServletResponse resp, Future<byte[]> result) throws IOException, UnsupportedEncodingException { if (!result.isDone()) { //Return something quickly to let client know we are working on their request but // it may be a while. resp.setStatus(HttpServletResponse.SC_ACCEPTED); resp.setContentType("text/plain"); resp.setCharacterEncoding("utf8"); resp.getWriter().println("I'm working on it... ask me again later"); } else { //Done: could be a actual result or an error try { byte[] resultData = result.get(); //this will throw in case of an error in processing. resp.setStatus(HttpServletResponse.SC_OK); //resp.setContentType(contentType); //resp.setCharacterEncoding("utf8"); resp.getOutputStream().write(resultData); } catch (Exception e) { resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); resp.setContentType("text/plain"); resp.setCharacterEncoding("utf8"); e.printStackTrace(new PrintStream(resp.getOutputStream(), true, "utf8")); } } }
From source file:edu.emory.cci.aiw.cvrg.eureka.servlet.JobSubmitServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Principal principal = request.getUserPrincipal(); if (principal == null) { throw new ServletException("Spreadsheet upload attempt: no user associated with the request"); }/*from w ww. j a v a 2s .co m*/ SubmitJobResponse jobResponse = new SubmitJobResponse(); String value; try { Long jobId = submitJob(request, principal); jobResponse.setJobId(jobId); } catch (ParseException ex) { jobResponse.setMessage("The date range you specified is invalid."); jobResponse.setStatusCode(HttpServletResponse.SC_BAD_REQUEST); jobResponse.setErrorThrown("Bad request"); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } catch (ClientException | FileUploadException | IOException ex) { String msg = "Upload failed due to an internal error"; jobResponse.setMessage(msg); jobResponse.setStatusCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); jobResponse.setErrorThrown("Internal server error"); log("Upload failed for user " + principal.getName(), ex); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } value = MAPPER.writeValueAsString(jobResponse); response.setContentLength(value.length()); response.setContentType("application/json"); PrintWriter out = response.getWriter(); out.println(value); }
From source file:contestWebsite.PublicResults.java
@Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { VelocityEngine ve = new VelocityEngine(); ve.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, "html/pages, html/snippets, html/templates"); ve.init();//w w w . ja v a 2 s .c o m VelocityContext context = new VelocityContext(); Pair<Entity, UserCookie> infoAndCookie = init(context, req); UserCookie userCookie = infoAndCookie.y; boolean loggedIn = (boolean) context.get("loggedIn"); Map<String, Integer> awardCriteria = Retrieve.awardCriteria(infoAndCookie.x); if (!loggedIn && req.getParameter("refresh") != null && req.getParameter("refresh").equals("1")) { resp.sendRedirect("/?refresh=1"); } Entity contestInfo = infoAndCookie.x; context.put("testsGradedNums", contestInfo.hasProperty("testsGradedNums") && contestInfo.getProperty("testsGradedNums") != null ? ((Text) contestInfo.getProperty("testsGradedNums")).getValue() : "{}"); if (contestInfo.hasProperty("testsGraded") && contestInfo.getProperty("testsGraded") != null) { context.put("testsGraded", contestInfo.getProperty("testsGraded")); } Object complete = contestInfo.getProperty("complete"); if (complete != null && (Boolean) complete || loggedIn && userCookie.isAdmin()) { context.put("complete", true); String type = req.getParameter("type"); context.put("type", type); if (type != null) { String[] types = type.split("_"); String levelString = req.getParameter("level"); Level level; try { level = Level.fromString(levelString); } catch (IllegalArgumentException e) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid level: " + levelString); return; } context.put("level", level.toString()); context.put("tests", Test.getTests(level)); context.put("Test", Test.class); if (type.startsWith("category_")) { context.put("test", Test.fromString(types[1])); context.put("trophy", awardCriteria.get("category_" + level + "_trophy")); context.put("medal", awardCriteria.get("category_" + level + "_medal")); context.put("winners", Retrieve.categoryWinners(types[1], level)); } else if (type.startsWith("qualifying_")) { context.put("School", School.class); Pair<School, List<Student>> schoolAndStudents = Retrieve.schoolStudents(types[1], level); context.put("school", schoolAndStudents.x); context.put("students", schoolAndStudents.y); } else if (type.startsWith("categorySweep")) { context.put("trophy", awardCriteria.get("categorySweep_" + level)); context.put("winners", Retrieve.categorySweepstakesWinners(level)); } else if (type.equals("sweep")) { context.put("trophy", awardCriteria.get("sweepstakes_" + level)); context.put("winners", Retrieve.sweepstakesWinners(level)); } else if (type.equals("visualizations")) { Map<Test, Statistics> statistics; try { statistics = Retrieve.visualizations(level); } catch (JSONException e) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString()); e.printStackTrace(); return; } context.put("statistics", statistics); } else { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid type: " + type); return; } } else { context.put("type", "avail"); } } else { context.put("complete", false); } Map<Level, List<String>> schools = new HashMap<Level, List<String>>(); for (Level level : Level.values()) { schools.put(level, Retrieve.schoolNames(level)); } context.put("schools", schools); context.put("qualifyingCriteria", Retrieve.qualifyingCriteria(infoAndCookie.x)); context.put("hideFullNames", contestInfo.getProperty("hideFullNames")); context.put("date", contestInfo.getProperty("updated")); context.put("subjects", Subject.values()); context.put("Level", Level.class); context.put("levels", Level.values()); context.put("esc", new EscapeTool()); close(context, ve.getTemplate("publicResults.html"), resp); }
From source file:gov.lanl.adore.djatoka.openurl.OpenURLJP2Ping.java
/** * Returns the OpenURLResponse of a JSON object defining image status. Status Codes: */// www . jav a 2 s. c o m @Override public OpenURLResponse resolve(final ServiceType serviceType, final ContextObject contextObject, final OpenURLRequest openURLRequest, final OpenURLRequestProcessor processor) { final String responseFormat = RESPONSE_TYPE; int status = HttpServletResponse.SC_NOT_FOUND; byte[] bytes = new byte[] {}; try { final String id = ((URI) contextObject.getReferent().getDescriptors()[0]).toASCIIString(); status = ReferentManager.getResolver().getStatus(id); if (status != HttpServletResponse.SC_NOT_FOUND) { final ObjectMapper mapper = new ObjectMapper(); final ObjectNode rootNode = mapper.createObjectNode(); String res_status = null; if (status == HttpServletResponse.SC_OK) { res_status = STATUS_OK; } else if (status == HttpServletResponse.SC_ACCEPTED) { res_status = STATUS_ACCEPTED; } rootNode.put("identifier", id); rootNode.put("status", res_status); bytes = mapper.writeValueAsBytes(rootNode); } } catch (final Exception e) { LOGGER.error(e.getMessage(), e); status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; } final HashMap<String, String> header_map = new HashMap<String, String>(); header_map.put("Content-Length", Integer.toString(bytes.length)); header_map.put("Date", HttpDate.getHttpDate()); return new OpenURLResponse(status, responseFormat, bytes, header_map); }
From source file:contestWebsite.MainPage.java
@Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { VelocityEngine ve = new VelocityEngine(); ve.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, "html/pages, html/snippets"); ve.init();/* ww w .j ava2s .c o m*/ VelocityContext context = new VelocityContext(); Pair<Entity, UserCookie> infoAndCookie = init(context, req); UserCookie userCookie = infoAndCookie.y; Entity user = userCookie != null ? userCookie.authenticateUser() : null; boolean loggedIn = (boolean) context.get("loggedIn"); if (!loggedIn && req.getParameter("refresh") != null && req.getParameter("refresh").equals("1")) { resp.sendRedirect("/?refresh=1"); } if (loggedIn) { if (!userCookie.isAdmin()) { String username = (String) user.getProperty("user-id"); String name = (String) user.getProperty("name"); DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); Query query = new Query("registration") .setFilter(new FilterPredicate("email", FilterOperator.EQUAL, username)); Entity reg = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(1)).get(0); ArrayList<String> regData = new ArrayList<String>(); Map<String, Object> props = reg.getProperties(); for (Entry<String, Object> prop : props.entrySet()) { String key = prop.getKey(); if (!key.equals("account") && !key.equals("cost") && PropNames.names.get(key) != null && !prop.getValue().equals("")) { regData.add("<dt>" + PropNames.names.get(key) + "</dt>\n<dd>" + prop.getValue() + "</dd>"); } } Entity contestInfo = infoAndCookie.x; String endDateStr = (String) contestInfo.getProperty("editEndDate"); String startDateStr = (String) contestInfo.getProperty("editStartDate"); Date endDate = new Date(); Date startDate = new Date(); try { SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy"); dateFormat.setTimeZone(TimeZone.getTimeZone("GMT+6")); endDate = dateFormat.parse(endDateStr); startDate = dateFormat.parse(startDateStr); } catch (ParseException e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Incorrect date format"); } if (new Date().after(endDate) || new Date().before(startDate)) { context.put("regEditClosed", true); } Collections.sort(regData); context.put("regData", regData); context.put("level", contestTabulation.Level.fromString(props.get("schoolLevel").toString())); context.put("studentData", unescapeHtml4(((Text) props.get("studentData")).getValue())); context.put("price", contestInfo.getProperty("price")); context.put("name", name); context.put("user", user.getProperty("user-id")); context.put("updated", req.getParameter("updated")); } else { context.put("error", req.getParameter("error")); context.put("user", user.getProperty("user-id")); context.put("name", "Contest Administrator"); context.put("admin", true); } context.put("complete", infoAndCookie.x.getProperty("complete")); context.put("testDownloadURL", infoAndCookie.x.getProperty("testDownloadURL")); } else { Yaml yaml = new Yaml(); ArrayList<ArrayList<String>> slideshow = (ArrayList<ArrayList<String>>) yaml .load(((Text) infoAndCookie.x.getProperty("slideshow")).getValue()); context.put("slideshow", slideshow); } context.put("esc", new EscapeTool()); context.put("aboutText", ((Text) infoAndCookie.x.getProperty("aboutText")).getValue()); context.put("siteVerification", infoAndCookie.x.getProperty("siteVerification")); close(context, ve.getTemplate("main.html"), resp); }