List of usage examples for javax.servlet.http HttpServletResponse setStatus
public void setStatus(int sc);
From source file:com.jaspersoft.jasperserver.rest.RESTUtils.java
/** * Set the status of the response to the errorCode and send the message to the client * * @param errorCode the errorCode (see HttpServletResponse for common HTTP status codes) * @param response the HttpServletResponse * @param body if null, an empty string is sent. */// www.j a va2 s.co m public static void setStatusAndBody(int errorCode, HttpServletResponse response, String body) { response.setStatus(errorCode); // we can put an error in the output too (so avoid the webserver to display unwanted pages...) try { PrintWriter pw = response.getWriter(); pw.print((body == null) ? "" : body); } catch (Exception ioEx) { // do nothing. If we have an I/O error, we just avoid to specify unuseful errors here. log.error("Error sending output a file", ioEx); } }
From source file:ee.ria.xroad.common.request.DummyCentralServiceHandler.java
private static void sendErrorResponse(HttpServletResponse response, String faultCode, String faultString, String faultActor, String faultDetail) throws IOException { String soapMessageXml = SoapFault.createFaultXml(faultCode, faultString, faultActor, faultDetail); String encoding = StandardCharsets.UTF_8.name(); byte[] messageBytes = soapMessageXml.getBytes(encoding); response.setStatus(HttpServletResponse.SC_OK); response.setContentType(MimeTypes.TEXT_XML); response.setContentLength(messageBytes.length); response.setHeader("SOAPAction", ""); response.setCharacterEncoding(encoding); response.getOutputStream().write(messageBytes); }
From source file:com.amazonaws.services.dynamodbv2.replication.server.ReplicationGroupHandler.java
private static void sendError(HttpServletResponse response, int sc, String msg) { try {//from w w w . j a va2 s . co m response.sendError(sc, msg); } catch (IOException e) { LOGGER.error("Error writing error response", e); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } }
From source file:com.googlecode.jsonplugin.JSONUtil.java
public static void writeJSONToResponse(SerializationParams serializationParams) throws IOException { StringBuilder stringBuilder = new StringBuilder(); if (TextUtils.stringSet(serializationParams.getSerializedJSON())) stringBuilder.append(serializationParams.getSerializedJSON()); if (TextUtils.stringSet(serializationParams.getWrapPrefix())) stringBuilder.insert(0, serializationParams.getWrapPrefix()); else if (serializationParams.isWrapWithComments()) { stringBuilder.insert(0, "/* "); stringBuilder.append(" */"); } else if (serializationParams.isPrefix()) stringBuilder.insert(0, "{}&& "); if (TextUtils.stringSet(serializationParams.getWrapSuffix())) stringBuilder.append(serializationParams.getWrapSuffix()); String json = stringBuilder.toString(); if (log.isDebugEnabled()) { log.debug("[JSON]" + json); }/*from w ww. j a v a 2 s . c o m*/ HttpServletResponse response = serializationParams.getResponse(); //status or error code if (serializationParams.getStatusCode() > 0) response.setStatus(serializationParams.getStatusCode()); else if (serializationParams.getErrorCode() > 0) response.sendError(serializationParams.getErrorCode()); //content type if (serializationParams.isSmd()) response.setContentType("application/json-rpc;charset=" + serializationParams.getEncoding()); else response.setContentType( serializationParams.getContentType() + ";charset=" + serializationParams.getEncoding()); if (serializationParams.isNoCache()) { response.setHeader("Cache-Control", "no-cache"); response.setHeader("Expires", "0"); response.setHeader("Pragma", "No-cache"); } if (serializationParams.isGzip()) { response.addHeader("Content-Encoding", "gzip"); GZIPOutputStream out = null; InputStream in = null; try { out = new GZIPOutputStream(response.getOutputStream()); in = new ByteArrayInputStream(json.getBytes()); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } } finally { if (in != null) in.close(); if (out != null) { out.finish(); out.close(); } } } else { response.setContentLength(json.getBytes(serializationParams.getEncoding()).length); PrintWriter out = response.getWriter(); out.print(json); } }
From source file:org.artifactory.util.HttpUtils.java
public static void sendErrorResponse(HttpServletResponse response, int statusCode, String message) throws IOException { response.setContentType(MediaType.APPLICATION_JSON_VALUE); response.setStatus(statusCode); ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); ErrorResponse errorResponse = new ErrorResponse(statusCode, message); response.getWriter().write(mapper.writeValueAsString(errorResponse)); }
From source file:ie.wombat.rt.fireeagle.CookieConsumer.java
/** * Handle an exception that occurred while processing an HTTP request. * Depending on the exception, either send a response, redirect the client * or propagate an exception./*from ww w . jav a 2 s. co m*/ */ public static void handleException(Exception e, HttpServletRequest request, HttpServletResponse response, OAuthConsumer consumer) throws IOException, ServletException { if (e instanceof RedirectException) { RedirectException redirect = (RedirectException) e; String targetURL = redirect.getTargetURL(); if (targetURL != null) { response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY); response.setHeader("Location", targetURL); } } else if (e instanceof OAuthProblemException) { OAuthProblemException p = (OAuthProblemException) e; String problem = p.getProblem(); if (consumer != null && RECOVERABLE_PROBLEMS.contains(problem)) { try { CookieMap cookies = new CookieMap(request, response); OAuthAccessor accessor = newAccessor(consumer, cookies); getAccessToken(request, cookies, accessor); // getAccessToken(request, consumer, // new CookieMap(request, response)); } catch (Exception e2) { handleException(e2, request, response, null); } } else { try { StringWriter s = new StringWriter(); PrintWriter pw = new PrintWriter(s); e.printStackTrace(pw); pw.flush(); p.setParameter("stack trace", s.toString()); } catch (Exception rats) { } response.setStatus(p.getHttpStatusCode()); response.resetBuffer(); request.setAttribute("OAuthProblemException", p); request.getRequestDispatcher // ("/OAuthProblemException.jsp").forward(request, response); } } else if (e instanceof IOException) { throw (IOException) e; } else if (e instanceof ServletException) { throw (ServletException) e; } else if (e instanceof RuntimeException) { throw (RuntimeException) e; } else { throw new ServletException(e); } }
From source file:com.mnt.base.web.DigestAuthenticator.java
/** * WWW-Authenticate: Digest realm="testrealm@host.com", * qop="auth,auth-int", * nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093", * opaque="5ccc069c403ebaf9f0171e9517f40e41" * @param req //from w w w.j av a 2 s. c o m * * @param resp * @param authInfoMap */ private static void postAuthRequired(HttpServletRequest req, HttpServletResponse resp, Map<String, Object> authInfoMap) { resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED); StringBuilder sb = new StringBuilder(); String siteHost; siteHost = req.getHeader("Host"); if (siteHost == null) { siteHost = "www.mntplay.com"; } sb.append("Digest realm=\"" + siteHost + "\",algorithm=\"md5\","); sb.append("qop=\"auth,auth-int\","); String nonce = (String) authInfoMap.get("nonce"); if (nonce == null) { nonce = UUID.randomUUID().toString(); } String opaque = UUID.randomUUID().toString(); sb.append("nonce=\"" + nonce + "\","); sb.append("opaque=\"" + opaque + "\""); authInfoMap.put("nonce", nonce); resp.setHeader("WWW-Authenticate", sb.toString()); try { resp.flushBuffer(); } catch (IOException e) { e.printStackTrace(); } }
From source file:net.sourceforge.fenixedu.presentationTier.servlets.filters.JerseyOAuth2Filter.java
private static boolean sendError(final HttpServletResponse response, String error, String errorDescription) throws IOException, ServletException { OAuthResponse errorResponse;//from w w w .jav a2 s .c om try { errorResponse = new OAuthErrorResponseBuilder(401).setError(error).setErrorDescription(errorDescription) .buildJSONMessage(); response.setContentType("application/json; charset=UTF-8"); response.setStatus(errorResponse.getResponseStatus()); PrintWriter pw = response.getWriter(); pw.print(errorResponse.getBody()); return false; } catch (OAuthSystemException e) { throw new ServletException(e); } }
From source file:com.ccf.util.ModDateHeaderUtil.java
/** * Sets the HTTP response status to 304 (NOT MODIFIED) if the request contains an * If-Modified-Since header that specifies a time that is * at or after the time specified by the value of lastModifiedTimeMillis * <em>truncated to second granularity</em>. Returns true if * the response status was set, false if not. * * @param request/*from w ww .ja va2s. c o m*/ * @param response * @param lastModifiedTimeMillis * @return true if a response status was sent, false otherwise. */ public static boolean respondIfNotModified(HttpServletRequest request, HttpServletResponse response, long lastModifiedTimeMillis) { long sinceDate = request.getDateHeader("If-Modified-Since"); // truncate to seconds lastModifiedTimeMillis -= (lastModifiedTimeMillis % 1000); log.debug("since date = " + sinceDate); log.debug("last mod date (trucated to seconds) = " + lastModifiedTimeMillis); if (lastModifiedTimeMillis <= sinceDate) { log.debug("NOT MODIFIED " + request.getRequestURL()); response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return true; } else { return false; } }
From source file:edu.du.penrose.systems.fedoraProxy.web.bus.ProxyController.java
/** * Call the HttpMethod and write all results and status to the HTTP response * object./*from w ww .j a va2s . c o m*/ * * THIS IS THE REQUEST WE NEED TO DUPLICATE GET * /fedora/get/codu:72/ECTD_test_1_access.pdf HTTP/1.1 Host: localhost:8080 * Connection: keep-alive Accept: * application/xml,application/xhtml+xml,text/ * html;q=0.9,text/plain;q=0.8,image/png,*;q=0.5 User-Agent: Mozilla/5.0 * (X11; U; Linux x86_64; en-US) AppleWebKit/534.10 (KHTML, like Gecko) * Chrome/8.0.552.215 Safari/534.10 Accept-Encoding: gzip,deflate,sdch * Accept-Language: en-US,en;q=0.8 Accept-Charset: * ISO-8859-1,utf-8;q=0.7,*;q=0.3 Cookie: fez_list=YjowOw%3D%3D * * ACTUAL SENT GET /fedora/get/codu:72/ECTD_test_1_access.pdf HTTP/1.1 * Accept: * application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q * =0.8,image/png,*;q=0.5 Connection: keep-alive Accept-Encoding: * gzip,deflate,sdch Accept-Language: en-US,en;q=0.8 Accept-Charset: * ISO-8859-1,utf-8;q=0.7,*;q=0.3 : User-Agent: Jakarta * Commons-HttpClient/3.1 Host: localhost:8080 * * @param proxyCommand * @param response * @param authenicate true to set Preemptive authentication */ public static void executeMethod(String proxyCommand, HttpServletResponse response, boolean authenicate) { HttpClient theClient = new HttpClient(); HttpMethod method = new GetMethod(proxyCommand); setDefaultHeaders(method); setAdrCredentials(theClient, authenicate); try { theClient.executeMethod(method); response.setStatus(method.getStatusCode()); // Set the content type, as it comes from the server Header[] headers = method.getResponseHeaders(); for (Header header : headers) { if ("Content-Type".equalsIgnoreCase(header.getName())) { response.setContentType(header.getValue()); } /** * Copy all headers, except Transfer-Encoding which is getting set * set elsewhere. At this point response.containsHeader( * "Transfer-Encoding" ) is false, however it is getting set twice * according to wireshark, therefore we do not set it here. */ if (!header.getName().equalsIgnoreCase("Transfer-Encoding")) { response.setHeader(header.getName(), header.getValue()); } } // Write the body, flush and close InputStream is = method.getResponseBodyAsStream(); BufferedInputStream bis = new BufferedInputStream(is); StringBuffer sb = new StringBuffer(); byte[] bytes = new byte[8192]; // reading as chunk of 8192 bytes int count = bis.read(bytes); while (count != -1 && count <= 8192) { response.getOutputStream().write(bytes, 0, count); count = bis.read(bytes); } bis.close(); response.getOutputStream().flush(); response.getOutputStream().close(); } catch (Exception e) { logger.error(e.getMessage()); } finally { method.releaseConnection(); } }