List of usage examples for javax.servlet.http HttpServletResponseWrapper HttpServletResponseWrapper
public HttpServletResponseWrapper(HttpServletResponse response)
From source file:org.craftercms.commons.web.CORSFilter.java
@Override protected void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response, final FilterChain filterChain) throws ServletException, IOException { final HttpServletResponseWrapper responseWrapper = new HttpServletResponseWrapper(response); responseWrapper.addHeader(ALLOW_ORIGIN, allowOrigins); responseWrapper.addHeader(ALLOW_METHODS, allowMethods); responseWrapper.addHeader(MAX_AGE, maxAge); responseWrapper.addHeader(ALLOW_HEADERS, allowHeaders); responseWrapper.addHeader(ALLOW_CREDENTIALS, allowCredentials); filterChain.doFilter(request, responseWrapper); }
From source file:de.micromata.genome.gwiki.page.search.SearchFoundHighlighterFilter.java
public Void filter(GWikiFilterChain<Void, GWikiServeElementFilterEvent, GWikiServeElementFilter> chain, GWikiServeElementFilterEvent event) { String words = event.getWikiContext().getRequestParameter("_gwhiwords"); if (StringUtils.isEmpty(words) == true) { return chain.nextFilter(event); }/*www.j av a 2 s .c o m*/ GWikiElement el = event.getElement(); if (el == null || (el instanceof GWikiWikiPage) == false) { return chain.nextFilter(event); } // el.getElementInfo().get HttpServletResponse resp = event.getWikiContext().getResponse(); final StringWriter sout = new StringWriter(); final PrintWriter pout = new PrintWriter(sout); final Holder<Boolean> skip = new Holder<Boolean>(Boolean.FALSE); HttpServletResponseWrapper wrapper = new HttpServletResponseWrapper(resp) { @Override public void sendRedirect(String location) throws IOException { skip.set(Boolean.TRUE); super.sendRedirect(location); } @Override public ServletOutputStream getOutputStream() throws IOException { skip.set(Boolean.TRUE); return super.getOutputStream(); } @Override public PrintWriter getWriter() throws IOException { return pout; } @Override public void resetBuffer() { sout.getBuffer().setLength(0); } }; event.getWikiContext().setResponse(wrapper); chain.nextFilter(event); if (skip.get() == Boolean.TRUE) { return null; } try { PrintWriter pr = resp.getWriter(); String orgString = sout.getBuffer().toString(); if (StringUtils.containsIgnoreCase(orgString, "<html") == false) { pr.print(orgString); return null; } StringWriter filteredContent = new StringWriter(); SearchHilightHtmlFilter filter = new SearchHilightHtmlFilter(filteredContent, Converter.parseStringTokens(words, ", ", false)); filter.doFilter(orgString); // System.out.println("\n\nOrig:\n" + sout.getBuffer().toString() + "\n\nFiltered:\n" + filteredContent.getBuffer().toString()); // pr // .println("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">"); pr.print(filteredContent.getBuffer().toString()); } catch (IOException ex) { throw new RuntimeIOException(ex); } return null; }
From source file:com.marklogic.samplestack.web.security.SamplestackAuthenticationSuccessHandler.java
@Override /**/*from w w w. ja v a2 s . c o m*/ * Override handler that sends 200 OK to client along with JSON * for the logged-in user. */ public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException { SavedRequest savedRequest = requestCache.getRequest(request, response); String targetUrlParam = getTargetUrlParameter(); if (savedRequest != null && isAlwaysUseDefaultTargetUrl() || (targetUrlParam != null && StringUtils.hasText(request.getParameter(targetUrlParam)))) { requestCache.removeRequest(request, response); } clearAuthenticationAttributes(request); HttpServletResponseWrapper responseWrapper = new HttpServletResponseWrapper(response); Writer writer = responseWrapper.getWriter(); String userName = ClientRole.securityContextUserName(); ObjectNode userNode; Contributor contributor = contributorService.getByUserName(userName); if (contributor != null) { userNode = mapper.convertValue(contributor, ObjectNode.class); } else { userNode = mapper.createObjectNode(); userNode.put("userName", userName); } ArrayNode roleNode = userNode.putArray("role"); roleNode.add(ClientRole.securityContextRole().toString()); mapper.writeValue(writer, userNode); writer.close(); }
From source file:com.tremolosecurity.embedd.EmbPostProc.java
@Override public void postProcess(HttpFilterRequest req, HttpFilterResponse resp, UrlHolder holder, HttpFilterChain curSChain) throws Exception { ProxyRequest pr = (ProxyRequest) req.getServletRequest(); HashMap<String, Attribute> reqHeaders = this.setHeadersCookiesEmb(req); EmbRequest embReq = new EmbRequest(req, pr.getSession(true), reqHeaders); /*Enumeration enumer = embReq.getParameterNames(); while (enumer.hasMoreElements()) {//from w w w . j ava 2 s .co m String name = (String) enumer.nextElement(); logger.info("Parameter : '" + name + "'='" + embReq.getParameter(name) + "'"); }*/ HttpServletRequestWrapper reqWrapper = new HttpServletRequestWrapper(embReq); /*enumer = reqWrapper.getHeaderNames(); while (enumer.hasMoreElements()) { String name = (String) enumer.nextElement(); Enumeration enumer1 = reqWrapper.getHeaders(name); while (enumer1.hasMoreElements()) { String val = (String) enumer1.nextElement(); logger.info("wrapper header : '" + name + "'='" + val + "'"); } }*/ HttpServletResponseWrapper respWrapper = new HttpServletResponseWrapper(resp.getServletResponse()); chain.doFilter(reqWrapper, respWrapper); /*logger.info(resp); logger.info(resp.getServletResponse()); logger.info(resp.getServletResponse().getContentType());*/ /*if (resp.getServletResponse().getContentType() != null && resp.getServletResponse().getContentType().startsWith("text")) { req.setAttribute(ProxySys.AUTOIDM_STREAM_WRITER, true); } else { req.setAttribute(ProxySys.AUTOIDM_STREAM_WRITER, false); }*/ //TODO: support content manipulation }
From source file:com.boundlessgeo.geoserver.AppAuthFilter.java
@Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) servletRequest; HttpServletResponse res = (HttpServletResponse) servletResponse; String path = req.getPathInfo(); if (req.getServletPath().startsWith("/app") && path.startsWith("/api")) { if ("POST".equalsIgnoreCase(req.getMethod()) && LOGIN_RE.matcher(path).matches()) { // hack: we have to jump through a few hoops to piggy back on the geoserver web auth: // 1. we fake the request path to fool the security filter // 2. we ignore redirects boolean success = runSecurityFilters(new HttpServletRequestWrapper(req) { @Override/*w w w.ja v a 2 s. com*/ public String getServletPath() { return ""; } @Override public String getPathInfo() { return "/j_spring_security_check"; } }, new HttpServletResponseWrapper(res) { @Override public void sendRedirect(String location) throws IOException { } }, WEB_LOGIN_CHAIN_NAME); if (success) { filterChain.doFilter(servletRequest, servletResponse); } else { res.setStatus(401); } } else if (LOGOUT_RE.matcher(path).matches()) { // invalidate the session if it exists HttpSession session = req.getSession(false); if (session != null) { session.invalidate(); } } else { // two modes of authentication, basic vs form. String chainName = req.getHeader("Authorization") != null ? DEFAULT_CHAIN_NAME : WEB_CHAIN_NAME; if (runSecurityFilters(req, res, chainName)) { filterChain.doFilter(servletRequest, servletResponse); } else { res.setStatus(401); } } } else { filterChain.doFilter(servletRequest, servletResponse); } }
From source file:com.codename1.corsproxy.CORSProxy.java
@Override protected void copyResponseHeaders(final HttpResponse proxyResponse, final HttpServletRequest servletRequest, final HttpServletResponse servletResponse) { HttpServletResponseWrapper responseWrapper = new HttpServletResponseWrapper(servletResponse) { @Override//from w w w . j a va 2 s . c o m public void addHeader(String name, String value) { if ("Location".equalsIgnoreCase(name)) { super.addHeader("X-CN1-" + name, value); } else if ("Content-Security-Policy".equalsIgnoreCase(name)) { } else { super.addHeader(name, value); } } }; super.copyResponseHeaders(proxyResponse, servletRequest, responseWrapper); //To change body of generated methods, choose Tools | Templates. servletResponse.setHeader("Access-Control-Expose-Headers", "Set-Cookie, Set-Cookie2"); Collection<String> cookies = servletResponse.getHeaders("Set-Cookie"); if (cookies != null) { for (String cookie : cookies) { servletResponse.addHeader("X-CN1-Set-Cookie", cookie); } } //servletResponse.setHeader("Access-Control-Allow-Origin", "*"); }
From source file:info.magnolia.cms.filters.RangeSupportFilter.java
private HttpServletResponse wrapResponse(final HttpServletRequest request, final HttpServletResponse response) { return new HttpServletResponseWrapper(response) { /** default length is max. We hope that the underlying code will set proper content length as a header before we proceed serving some bytes. */ private int length = Integer.MAX_VALUE; private final Map<String, Object> headers = new HashMap<String, Object>(); private String eTag; private List<RangeInfo> ranges; private RangeInfo full; private ServletOutputStream stream; private PrintWriter writer; @Override//www. java 2 s . com public void addDateHeader(String name, long date) { super.addDateHeader(name, date); this.headers.put(name, date); if ("Last-Modified".equalsIgnoreCase(name)) { lastModTime = date; } } @Override public void setDateHeader(String name, long date) { super.setDateHeader(name, date); this.headers.put(name, date); if ("Last-Modified".equalsIgnoreCase(name)) { lastModTime = date; } } @Override public void addHeader(String name, String value) { if ("Content-Disposition".equalsIgnoreCase(name) && log.isDebugEnabled()) { log.warn("content disposition enforced by underlying filter/servlet"); } super.addHeader(name, value); this.headers.put(name, value); } @Override public void setHeader(String name, String value) { if ("Content-Disposition".equalsIgnoreCase(name) && log.isDebugEnabled()) { log.warn("content disposition enforced by underlying filter/servlet"); } super.setHeader(name, value); this.headers.put(name, value); } @Override public void addIntHeader(String name, int value) { super.addIntHeader(name, value); this.headers.put(name, value); } @Override public void setIntHeader(String name, int value) { super.setIntHeader(name, value); this.headers.put(name, value); } @Override public void setContentLength(int len) { this.length = len; // do not propagate length up. We might not be able to change it once it is set. We will set it ourselves once we are ready to serve bytes. } @Override public ServletOutputStream getOutputStream() throws IOException { // make sure we set stream only once. Multiple calls to this method are allowed. if (this.stream == null) { ServletOutputStream stream = super.getOutputStream(); // wrap the response to filter out everything except desired range this.stream = addRangeSupportWrapper(request, response, stream); if (!isServeContent || this.stream == null) { // swallow output on head requests this.stream = new ServletOutputStream() { @Override public void write(int b) throws IOException { // do nothing, we do not write any output now } }; } } return stream; } private ServletOutputStream addRangeSupportWrapper(final HttpServletRequest request, final HttpServletResponse response, ServletOutputStream stream) throws IOException { if (!processContent(request, response)) { // we might have to return null stream instead as the previous method already called res.sendError(); return null; } if (headers.containsKey("Content-Range")) { // doesn't work for tomcat as it accesses underlying stream under our hands!!! log.debug("Range request was handled by underlying filter/servlet."); return stream; } if (ranges == null || ranges.isEmpty()) { // no op, serve all as usual log.debug("Didn't find any range to speak of. Serving all content as usual."); if (length != Integer.MAX_VALUE) { // set real length when we know it response.setContentLength(length); } } else if (ranges.size() == 1) { RangeInfo range = ranges.get(0); log.debug("Serving range [{}].", range); // setting 206 header is essential for some clients. The would abort if response is set to 200 response.setStatus(SC_PARTIAL_CONTENT); stream = new RangedOutputStream(stream, range); } else { log.error("Requested multiple ranges [{}].", ranges.size()); // TODO: add support for multiple ranges (sent as multipart request), for now just send error back response.setHeader("Content-Range", "bytes */" + length); response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); // again we might have to return null stream after calling sendError() as the original stream might no longer be valid } return stream; } @Override public PrintWriter getWriter() throws IOException { if (!wrapWriter) { return super.getWriter(); } if (this.writer == null) { this.writer = new PrintWriter(new OutputStreamWriter(getOutputStream())); } return writer; } private boolean processContent(HttpServletRequest request, HttpServletResponse response) throws IOException { log.debug("Serving binary on uri {} was last modified at {}", new Object[] { request.getRequestURI(), lastModTime }); if (!isRequestValid(request, response)) { log.debug("Skipping request {} since it doesn't require body", new Object[] { request.getRequestURI() }); return false; } if (!processRange(request)) { log.debug("Could not process range of request {}", new Object[] { request.getRequestURI() }); return false; } return true; } private boolean processRange(HttpServletRequest request) throws IOException { full = new RangeInfo(0, length - 1, length); ranges = new ArrayList<RangeInfo>(); String range = request.getHeader("Range"); // Valid range header format is "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); response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return false; } // If-Range header must match ETag or be greater then LastModified. If not, then return full file. String ifRange = request.getHeader("If-Range"); if (ifRange != null && !ifRange.equals(eTag)) { try { long ifRangeTime = request.getDateHeader("If-Range"); if (ifRangeTime != -1 && ifRangeTime + 1000 < lastModTime) { ranges.add(full); } } catch (IllegalArgumentException ignore) { // happens when if-range contains something else then date ranges.add(full); } } // in case there were no invalid If-Range headers, then look at requested byte ranges. if (ranges.isEmpty()) { for (String part : range.substring(6).split(",")) { int start = intSubstring(StringUtils.substringBefore(part, "-")); int end = intSubstring(StringUtils.substringAfter(part, "-")); if (start == -1) { start = length - end; end = length - 1; } else if (end == -1 || end > length - 1) { end = length - 1; } // Is range valid? if (start > end) { response.setHeader("Content-Range", "bytes */" + length); // Required in 416. response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return false; } // Add range. ranges.add(new RangeInfo(start, end, length)); } } response.setHeader("ETag", eTag); if (ranges.size() == 1) { RangeInfo r = ranges.get(0); response.setHeader("Accept-Ranges", "bytes"); response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.totalLengthOfServedBinary); length = r.lengthOfRange; } return true; } private int intSubstring(String value) { return value.length() > 0 ? Integer.parseInt(value) : -1; } @Override public void flushBuffer() throws IOException { if (writer != null) { writer.flush(); } if (stream != null) { stream.flush(); } super.flushBuffer(); } private boolean isRequestValid(HttpServletRequest request, HttpServletResponse response) throws IOException { String fileName = StringUtils.substringAfterLast(request.getRequestURI(), "/"); eTag = fileName + "_" + length + "_" + lastModTime; // If-None-Match header should contain "*" or ETag. String ifNoneMatch = request.getHeader("If-None-Match"); if (ifNoneMatch != null && matches(ifNoneMatch, eTag)) { response.setHeader("ETag", eTag); // Required in 304. log.debug("Returning {} on header If-None-Match", HttpServletResponse.SC_NOT_MODIFIED); response.sendError(HttpServletResponse.SC_NOT_MODIFIED); return false; } // If-Modified-Since header must be greater than LastModified. ignore if If-None-Match header exists long ifModifiedSince = request.getDateHeader("If-Modified-Since"); if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > lastModTime) { response.setHeader("ETag", eTag); // Required in 304. // 304 response should contain Date header unless running on timeless server (see 304 response docu) response.addDateHeader("Date", lastModTime); log.debug("Returning {} on header If-Modified-Since", HttpServletResponse.SC_NOT_MODIFIED); response.sendError(HttpServletResponse.SC_NOT_MODIFIED); return false; } // If-Match header should contain "*" or ETag. String ifMatch = request.getHeader("If-Match"); if (ifMatch != null && !matches(ifMatch, eTag)) { log.debug("Returning {} on header If-Match", HttpServletResponse.SC_PRECONDITION_FAILED); response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return false; } // If-Unmodified-Since header must be greater than LastModified. long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since"); if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= lastModTime) { log.debug("Returning {} on header If-Unmodified-Since", HttpServletResponse.SC_PRECONDITION_FAILED); response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return false; } log.debug("Passed all precondition checkes for request {}", request.getRequestURI()); return true; } }; }
From source file:de.terrestris.shogun.security.ShogunAuthProcessingFilter.java
/** * On successful authentication by an Authentication Manager of Spring Security * we intercept with this method and change the respone to include the ROLES of * the logged in user./*ww w .j a v a 2s .co m*/ * This way we can react on the ROLES and redirect accordingly within the requesting login form (here login.js) * * @see WebContent/client/login.js */ @Override protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, Authentication authResult) throws IOException, ServletException { SecurityContextHolder.getContext().setAuthentication(authResult); SavedRequestAwareAuthenticationSuccessHandler srh = new SavedRequestAwareAuthenticationSuccessHandler(); this.setAuthenticationSuccessHandler(srh); srh.setRedirectStrategy(new RedirectStrategy() { @Override public void sendRedirect(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, String s) throws IOException { //do nothing, no redirect } }); super.successfulAuthentication(request, response, authResult); // build a comma separated string of the ROLES String authorityText = StringUtils.join(authResult.getAuthorities(), ","); // write the servlet return object HttpServletResponseWrapper responseWrapper = new HttpServletResponseWrapper(response); Writer out = responseWrapper.getWriter(); JsonFactory jsonFactory = new JsonFactory(); JsonGenerator jsonGenerator = jsonFactory.createJsonGenerator(out); jsonGenerator.writeStartObject(); jsonGenerator.writeBooleanField("success", true); jsonGenerator.writeStringField("name", authResult.getName()); jsonGenerator.writeStringField("role", authorityText); jsonGenerator.writeEndObject(); jsonGenerator.close(); }
From source file:com.meltmedia.cadmium.servlets.ErrorPageFilter.java
/** * <p>Traps calls to sendError and catches all throwables from the chain. Error pages from the content * service are rendered in these situations if:</p> * <ul>/* w ww . jav a 2s.co m*/ * <li>The status code is a 400 or 500.</li> * <li>The response has not been committed.</li> * </ul> * <p>Any thrown Throwable is treated like a 500 error.</p> * * @param req the servlet request being handled. * @param res the servlet response being written to. * @param chain the filter chain to execute inside this filter. * @throws IOException if there is a problem rendering the error page. * @throws ServletException never. */ @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { try { final HttpServletRequest httpReq = (HttpServletRequest) req; final HttpServletResponse httpRes = (HttpServletResponse) res; if (ignorePath != null) { String contextPath = httpReq.getContextPath(); String uri = httpReq.getRequestURI(); if (contextPath != null && contextPath.trim().length() > 0 && uri.startsWith(contextPath)) { uri = uri.substring(contextPath.length()); } if (uri.startsWith(ignorePath)) { log.trace("Not handling errors for request server:{}, uri:{}", httpReq.getServerName(), uri); chain.doFilter(req, res); return; } } HttpServletResponse wrappedRes = new HttpServletResponseWrapper(httpRes) { @Override public void sendError(int sc) throws IOException { ErrorPageFilter.this.sendError(sc, null, httpReq, httpRes); } @Override public void sendError(int sc, String msg) throws IOException { ErrorPageFilter.this.sendError(sc, msg, httpReq, httpRes); } }; try { chain.doFilter(httpReq, wrappedRes); } catch (Throwable e) { log.trace("Handling thrown Exception", e); sendError(500, null, httpReq, httpRes); } } catch (IOException ioe) { log.trace("Failed in error filter.", ioe); throw ioe; } catch (ServletException se) { log.trace("Failed in error filter.", se); throw se; } catch (Throwable t) { log.trace("Failed in error filter.", t); throw new ServletException(t); } }
From source file:com.scooterframework.web.controller.ScooterRequestFilter.java
/** * Time the processing that is performed by all subsequent filters in the * current filter stack, including the ultimately invoked servlet. * * @param request The servlet request we are processing * @param chain The filter chain we are processing * * @exception IOException if an input/output error occurs * @exception ServletException if a servlet error occurs */// www . j av a 2 s. co m public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { boolean staticContent = isStaticContentRequest((HttpServletRequest) request); if (encoding != null) { request.setCharacterEncoding(encoding); if (!staticContent) { response.setCharacterEncoding(encoding); } } // boolean skip = skippedRequestPath((HttpServletRequest)request); boolean skip = staticContent; long before = System.currentTimeMillis(); if (!skip) { initializeActionContext((HttpServletRequest) request, (HttpServletResponse) response); } else { request.setAttribute(Constants.SKIP_PATH, "Y"); } if (isAjaxRequest((HttpServletRequest) request)) { request.setAttribute(Constants.SITEMESH_FILTERAPPLIED, Boolean.TRUE); } String requestPathKeyWithQueryString = requestInfo(skip, (HttpServletRequest) request); log.debug("============>>\"" + requestPathKeyWithQueryString + "\""); try { chain.doFilter(request, response); } catch (Throwable ex) { log.error("Error from chain.doFilter: " + ex.getMessage(), ex); } long after = System.currentTimeMillis(); if (EnvConfig.getInstance().allowRecordBenchmark()) { log.info("\"" + requestPathKeyWithQueryString + "\" takes: " + (after - before) + " ms"); if (EnvConfig.getInstance().allowRecordBenchmarkInHeader()) { HttpServletResponseWrapper resw = new HttpServletResponseWrapper((HttpServletResponse) response); resw.addHeader("Exec-Time", (after - before) + " ms"); } } clearCachedRequestData(); }