List of usage examples for javax.servlet ServletResponse getOutputStream
public ServletOutputStream getOutputStream() throws IOException;
From source file:org.opencms.search.solr.CmsSolrIndex.java
/** * Writes the Solr response.<p>// w w w . jav a2 s .c o m * * @param response the servlet response * @param queryRequest the Solr request * @param queryResponse the Solr response to write * * @throws IOException if sth. goes wrong * @throws UnsupportedEncodingException if sth. goes wrong */ private void writeResp(ServletResponse response, SolrQueryRequest queryRequest, SolrQueryResponse queryResponse) throws IOException, UnsupportedEncodingException { if (m_solr instanceof EmbeddedSolrServer) { SolrCore core = ((EmbeddedSolrServer) m_solr).getCoreContainer().getCore(getCoreName()); Writer out = null; try { QueryResponseWriter responseWriter = core.getQueryResponseWriter(queryRequest); final String ct = responseWriter.getContentType(queryRequest, queryResponse); if (null != ct) { response.setContentType(ct); } if (responseWriter instanceof BinaryQueryResponseWriter) { BinaryQueryResponseWriter binWriter = (BinaryQueryResponseWriter) responseWriter; binWriter.write(response.getOutputStream(), queryRequest, queryResponse); } else { String charset = ContentStreamBase.getCharsetFromContentType(ct); out = ((charset == null) || charset.equalsIgnoreCase(UTF8.toString())) ? new OutputStreamWriter(response.getOutputStream(), UTF8) : new OutputStreamWriter(response.getOutputStream(), charset); out = new FastWriter(out); responseWriter.write(out, queryRequest, queryResponse); out.flush(); } } finally { core.close(); if (out != null) { out.close(); } } } else { throw new UnsupportedOperationException(); } }
From source file:org.opendaylight.sloth.filter.SlothSecurityFilter.java
@Override public void doFilter(ServletRequest servletRequest, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (servletRequest instanceof HttpServletRequest) { long startTime = System.nanoTime(); HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest; HttpServletRequest multiReadHttpServletRequest = httpServletRequest.getContentType() != null && Objects.equals(httpServletRequest.getContentType(), JSON_CONTENT_TYPE) ? new MultiHttpServletRequest(httpServletRequest) : httpServletRequest; Principal principal = getPrincipal((ODLPrincipal) SecurityUtils.getSubject().getPrincipal()); final Future<RpcResult<CheckPermissionOutput>> rpcResultFuture = slothPermissionService .checkPermission(new CheckPermissionInputBuilder().setPrincipal(principal) .setRequest(getRequest(multiReadHttpServletRequest, null)).build()); try {//w w w . j a va 2 s . c om RpcResult<CheckPermissionOutput> rpcResult = rpcResultFuture.get(); if (rpcResult.isSuccessful()) { long endTime = System.nanoTime(); LOG.info("Permission Checking Time: " + (endTime - startTime) + " nano seconds"); LOG.info("SlothSecurityFilter, check permission successful"); if (rpcResult.getResult().getStatusCode() / 100 == 2) { if (multiReadHttpServletRequest.getMethod().equals("GET")) { LOG.info("response content type: " + multiReadHttpServletRequest.getContentType()); GenericResponseWrapper genericResponseWrapper = new GenericResponseWrapper( (HttpServletResponse) response); chain.doFilter(multiReadHttpServletRequest, genericResponseWrapper); final Future<RpcResult<CheckPermissionOutput>> resultFuture = slothPermissionService .checkPermission(new CheckPermissionInputBuilder().setPrincipal(principal) .setRequest(getRequest(multiReadHttpServletRequest, new String(genericResponseWrapper.getData()))) .build()); RpcResult<CheckPermissionOutput> result = resultFuture.get(); if (result.isSuccessful()) { if (result.getResult().getStatusCode() / 100 == 2) { response.getOutputStream().write(genericResponseWrapper.getData()); } else { response.getWriter().write(String.format("status code: %s, response: %s", result.getResult().getStatusCode(), result.getResult().getResponse())); } } else { LOG.warn( "SlothSecurityFilter, unknown exception during permission checking, GET check"); response.getWriter() .write("unknown exception during permission checking, GET check"); } } else { chain.doFilter(multiReadHttpServletRequest, response); } } else { response.getWriter().write(String.format("status code: %s, response: %s", rpcResult.getResult().getStatusCode(), rpcResult.getResult().getResponse())); } } else { LOG.warn("SlothSecurityFilter, unknown exception during permission checking"); response.getWriter().write("unknown exception during permission checking"); } } catch (InterruptedException | ExecutionException e) { LOG.error("SlothSecurityFilter, check permission exception: " + e.getMessage()); response.getWriter().write("exception during check permission: " + e.getMessage()); } } else { LOG.warn("not http servletRequest, no permission check"); chain.doFilter(servletRequest, response); } }
From source file:org.overlord.commons.ui.header.OverlordHeaderResources.java
/** * Serve the appropriate resource's binary content. * @param response//from w ww.j a v a 2 s. co m * @param resourceURL * @throws IOException */ private void serveResource(ServletResponse response, URL resourceURL) throws IOException { String extension = resourceURL.getPath().substring(resourceURL.getPath().lastIndexOf('.') + 1); String ct = FILE_TYPES.get(extension); response.setContentType(ct); InputStream in = null; OutputStream out = null; try { in = resourceURL.openStream(); out = response.getOutputStream(); IOUtils.copy(in, out); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } }
From source file:org.pentaho.platform.web.http.filters.PentahoWebContextFilter.java
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; String requestStr = httpRequest.getRequestURI(); if (requestStr != null && requestStr.endsWith(WEB_CONTEXT_JS) && httpRequest.getAttribute(FILTER_APPLIED) == null) { httpRequest.setAttribute(FILTER_APPLIED, Boolean.TRUE); // split out a fully qualified url, guaranteed to have a trailing slash IPentahoRequestContext requestContext = PentahoRequestContextHolder.getRequestContext(); String contextPath = requestContext.getContextPath(); try {/*w w w . ja va2s .c o m*/ response.setContentType("text/javascript"); //$NON-NLS-1$ OutputStream out = response.getOutputStream(); out.write(initialCommentBytes); byte[] contextPathBytes = THREAD_LOCAL_CONTEXT_PATH.get(); byte[] requireScriptBytes = THREAD_LOCAL_REQUIRE_SCRIPT.get(); if (contextPathBytes == null) { String webContext = "var CONTEXT_PATH = '" + contextPath + "';\n\n"; //$NON-NLS-1$ //$NON-NLS-2$ contextPathBytes = webContext.getBytes(); THREAD_LOCAL_CONTEXT_PATH.set(contextPathBytes); if (requireScriptBytes == null) { String requireJsLocation = "content/common-ui/resources/web/require.js"; String requireJsConfigLocation = "content/common-ui/resources/web/require-cfg.js"; String requireScript = "document.write(\"<script type='text/javascript' src='" + contextPath + requireJsLocation + "'></scr\"+\"ipt>\");\n" + "document.write(\"<script type=\'text/javascript\' src='" + contextPath + requireJsConfigLocation + "'></scr\"+\"ipt>\");\n"; requireScriptBytes = requireScript.getBytes(); THREAD_LOCAL_REQUIRE_SCRIPT.set(requireScriptBytes); } } String basicAuthFlag = (String) httpRequest.getSession().getAttribute("BasicAuth"); if (basicAuthFlag != null && basicAuthFlag.equals("true")) { out.write(("document.write(\"<script type='text/javascript' src='" + contextPath + "js/postAuth.js'></scr\"+\"ipt>\");\n").getBytes("UTF-8")); } out.write(contextPathBytes); out.write(fullyQualifiedUrl.getBytes()); out.write(serverProtocol.getBytes()); // Compute the effective locale and set it in the global scope. Also provide it as a module if the RequireJs // system is available. Locale effectiveLocale = LocaleHelper.getLocale(); if (!StringUtils.isEmpty(request.getParameter("locale"))) { effectiveLocale = new Locale(request.getParameter("locale")); } // setup the RequireJS config object for plugins to extend out.write(REQUIRE_JS_CFG_START); // Let all plugins contribute to the RequireJS config printResourcesForContext(REQUIRE_JS, out, httpRequest, false); out.write(requireScriptBytes); printSessionName(out); printLocale(effectiveLocale, out); printHomeFolder(out); printReservedChars(out); printReservedCharsDisplay(out); printReservedRegexPattern(out); boolean requireJsOnly = "true".equals(request.getParameter("requireJsOnly")); if (!requireJsOnly) { // print global resources defined in plugins printResourcesForContext(GLOBAL, out, httpRequest, false); // print out external-resources defined in plugins if a context has been passed in String contextName = request.getParameter(CONTEXT); boolean cssOnly = "true".equals(request.getParameter("cssOnly")); if (StringUtils.isNotEmpty(contextName)) { printResourcesForContext(contextName, out, httpRequest, cssOnly); } } // Any subclass can add more information to webcontext.js addCustomInfo(out); out.close(); return; } finally { httpRequest.removeAttribute(FILTER_APPLIED); } } else { chain.doFilter(httpRequest, httpResponse); return; } }
From source file:org.polymap.service.fs.webdav.WebDavServer.java
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException { Timer timer = new Timer(); HttpServletRequest req = (HttpServletRequest) servletRequest; HttpServletResponse resp = (HttpServletResponse) servletResponse; DefaultSessionContextProvider contextProvider = FsPlugin.getDefault().sessionContextProvider; try {/*from ww w. j av a 2 s . c o m*/ Request request = new com.bradmcevoy.http.ServletRequest(req); Response response = new com.bradmcevoy.http.ServletResponse(resp); threadRequest.set(request); threadResponse.set(response); Auth auth = request.getAuthorization(); log.debug("Auth: " + auth); // map/create session context final HttpSession session = req.getSession(true); if (auth != null) { contextProvider.mapContext(auth.getUser(), true); log.debug("SessionContext: " + SessionContext.current()); } httpManager.process(request, response); log.debug("Request: " + Request.Header.ACCEPT_ENCODING.code + ": " + request.getHeaders().get(Request.Header.ACCEPT_ENCODING.code) + " --> Response: " + Response.Header.CONTENT_ENCODING.code + ": " + response.getHeaders().get(Response.Header.CONTENT_ENCODING.code)); log.debug("Response: " + response.getStatus()); } finally { if (contextProvider.currentContext() != null) { contextProvider.unmapContext(); } threadRequest.set(null); threadResponse.set(null); servletResponse.getOutputStream().flush(); servletResponse.flushBuffer(); } log.info("WebDAV request: " + timer.elapsedTime() + "ms"); }
From source file:org.sakaiproject.nakamura.http.i18n.I18nFilter.java
/** * Filter <code>output</code> of any message keys by replacing them with the matching * message from the language bundle associated to the user. * * @param srequest/* w ww . java 2s . c o m*/ * @param response * @param output * @throws IOException */ private void writeFilteredResponse(SlingHttpServletRequest srequest, ServletResponse response, String output) throws IOException { StringBuilder sb = new StringBuilder(output); try { Session session = srequest.getResourceResolver().adaptTo(Session.class); Node bundlesNode = session.getNode(bundlesPath); // load the language bundle Locale locale = getLocale(srequest); Properties bndLang = getLangBundle(bundlesNode, locale.toString()); // load the default bundle Properties bndLangDefault = getLangBundle(bundlesNode, "default"); // check for message keys and replace them with the appropriate message Matcher m = messageKeyPattern.matcher(output); ArrayList<String> matchedKeys = new ArrayList<String>(); while (m.find()) { String msgKey = m.group(0); String key = m.group(1); if (!matchedKeys.contains(key)) { String message = ""; if (bndLang.containsKey(key)) { message = bndLang.getProperty(key); } else if (bndLangDefault.containsKey(key)) { message = bndLangDefault.getProperty(key); } else { String msg = "[MESSAGE KEY NOT FOUND '" + key + "']"; logger.warn(msg); if (showMissingKeys) { message = msg; } } // replace all instances of msgKey with the actual message int keyStart = sb.indexOf(msgKey); while (keyStart >= 0) { sb.replace(keyStart, keyStart + msgKey.length(), message); keyStart = sb.indexOf(msgKey, keyStart); } // track the group so we don't try to replace it again matchedKeys.add(key); } } } catch (RepositoryException e) { logger.error(e.getMessage(), e); } response.setContentLength(sb.length()); // send the output to the actual response try { response.getWriter().write(sb.toString()); } catch (IllegalStateException e) { response.getOutputStream().write(sb.toString().getBytes("UTF-8")); } }
From source file:org.sakaiproject.nakamura.http.i18n.I18nFilterTest.java
private void writeToResponse(final String key, final boolean useOutputStream) throws IOException, ServletException { doAnswer(new Answer<Object>() { public Object answer(InvocationOnMock invocation) { Object[] args = invocation.getArguments(); ServletResponse response = (ServletResponse) args[1]; try { if (!useOutputStream) { response.getWriter().write("<html><body>" + key + "</body></html>"); } else { response.getOutputStream() .write(("<html><body>" + key + "</body></html>").getBytes("UTF-8")); }/*from www . j av a2s .c o m*/ } catch (IOException e) { // doesn't matter } return null; } }).when(chain).doFilter(isA(ServletRequest.class), isA(ServletResponse.class)); }
From source file:org.toobsframework.servlet.filters.compression.CompressionFilter.java
/** * The filter intercepts the querystring for this request * and will reject the request if any of the filtered characters are found * * @param request The servlet request object * @param response The servlet response object * @param chain The servlet chain//from w w w . j av a 2 s .c om * * @throws ServletException */ @SuppressWarnings("unchecked") public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (log.isDebugEnabled()) { log.debug("Begin [doFilter]"); } request.setCharacterEncoding("UTF-8"); String query = ((HttpServletRequest) request).getQueryString(); boolean noFilter = (query != null && query.indexOf("DisableWhiteSpace") != -1); boolean compressible = false; //long startTime = 0L; if (!filterEnabled || noFilter) { // || ((HttpServletRequest)request).getRequestURI().endsWith("application.do") chain.doFilter(request, response); } else { if (filterCompress) { Enumeration<String> headers = ((HttpServletRequest) request).getHeaders("Accept-Encoding"); while (headers.hasMoreElements()) { String value = (String) headers.nextElement(); if (value.indexOf(compressionType) != -1) { compressible = true; break; } } } if (smartCompress) { for (int i = 0; i < excludedHosts.size(); i++) { if (("" + ((HttpServletRequest) request).getRemoteAddr()) .startsWith((String) excludedHosts.get(i))) { compressible = false; } } } FilterResponseWrapper wrapper = new FilterResponseWrapper((HttpServletResponse) response); chain.doFilter(request, wrapper); byte[] input = wrapper.getData(); byte[] output = null; OutputStream servletoutputstream = null; String content = wrapper.getContentType(); if (content != null && content.toUpperCase().indexOf("TEXT/") >= 0) { response.setContentType(content); if (filterCompress && compressible) { HttpServletResponse httpResponse = (HttpServletResponse) response; httpResponse.addHeader("Content-Encoding", compressionType); servletoutputstream = new GZIPOutputStream(response.getOutputStream(), bufferSize); } else { servletoutputstream = response.getOutputStream(); } if (filterWhitespace) { output = new byte[input.length]; int i = 0; int o = 0; boolean htComment = false; boolean inScript = false; while (i < input.length) { if (input[i] == 13 || input[i] == 9) { // 13=CR, 9=TAB // nothing } else if (input[i] == 10) { // 10=LF if (inScript) { output[o] = input[i]; o++; } } else if (input[i] == 32) { // 32=Space if (!htComment && !inScript && i + 1 < input.length && input[i + 1] == 32) { i++; while (i + 1 < input.length && input[i + 1] == 32) { i++; } } else if (!htComment) { output[o] = input[i]; o++; } } else if (input[i] == 60) { // 60=< if (!inScript && (i + 2 < input.length) && (input[i + 1] == 33) && (input[i + 2] == 45)) { i += 3; htComment = true; } else if (!htComment && i + 2 < input.length && (input[i + 1] == 83 || input[i + 1] == 115) && (input[i + 2] == 67 || input[i + 2] == 99)) { inScript = true; output[o] = input[i]; output[o + 1] = input[i + 1]; output[o + 2] = input[i + 2]; o += 3; i += 2; } else if (!htComment && i + 3 < input.length && (input[i + 1] == 47) && (input[i + 2] == 83 || input[i + 2] == 115) && (input[i + 3] == 67 || input[i + 3] == 99)) { inScript = false; output[o] = input[i]; output[o + 1] = input[i + 1]; output[o + 2] = input[i + 2]; output[o + 3] = input[i + 3]; o += 4; i += 3; } else if (!htComment) { output[o] = input[i]; o++; } } else if (input[i] == 62) { // 62 = > if (htComment && input[i - 1] == 45 && input[i - 2] == 45) { htComment = false; } else if (!htComment) { output[o] = input[i]; o++; } } else if (!htComment) { output[o] = input[i]; o++; } i++; } servletoutputstream.write(output, 0, o); } else { servletoutputstream.write(input); } } else { servletoutputstream = response.getOutputStream(); servletoutputstream.write(input); } if (servletoutputstream != null) { servletoutputstream.flush(); servletoutputstream.close(); } input = null; output = null; } if (log.isDebugEnabled()) { log.debug("End [doFilter]"); } }
From source file:org.wso2.adminui.AdminUIServletFilter.java
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { try {/* w w w . ja va2 s . com*/ HttpServletRequest httpServletRequest = (HttpServletRequest) request; if (contextRoot == null) { //Context root could be "" or some othervalue this.contextRoot = httpServletRequest.getContextPath(); } String requestURI = httpServletRequest.getRequestURI(); int indexOfDot = requestURI.lastIndexOf("."); boolean isFile = false; if (indexOfDot != -1) { isFile = requestURI.substring(indexOfDot).matches("\\.(.)*"); } if (!isFile && requestURI.lastIndexOf("/") != requestURI.length() - 1) { requestURI += "/"; } Map generatedPages = (Map) servletContext.getAttribute(AdminUIConstants.GENERATED_PAGES); if (requestURI.equals(contextRoot) || requestURI.equals(contextRoot + "/")) { response.setContentType("text/html"); boolean enableConsole = ((Boolean) servletContext.getAttribute(AdminUIConstants.ENABLE_CONSOLE)) .booleanValue(); if (!enableConsole) { ServletOutputStream out = response.getOutputStream(); out.write(("<b>Management Console has been disabled.</b> " + "Enable it in the server.xml and try again.").getBytes()); ((HttpServletResponse) response).setStatus(HttpServletResponse.SC_FORBIDDEN); out.flush(); out.close(); return; } String fileContents = (String) generatedPages.get("index.html"); if (fileContents != null) { ServletOutputStream op = response.getOutputStream(); response.setContentLength(fileContents.getBytes().length); op.write(fileContents.getBytes()); return; } } else { String urlKey; if (contextRoot.equals("/")) { urlKey = requestURI.substring(contextRoot.length(), requestURI.length()); } else { urlKey = requestURI.substring(1 + contextRoot.length(), requestURI.length()); } if (generatedPages != null) { String fileContents = (String) generatedPages.get(urlKey); if (fileContents != null) { ServletOutputStream op = response.getOutputStream(); response.setContentType("text/html"); response.setContentLength(fileContents.getBytes().length); op.write(fileContents.getBytes()); return; } } /* || has been used to support any client who wants to access the "global_params.js" regardless of where they want to access. */ if (urlKey.equals(GLOBAL_PARAMS_JS) || urlKey.indexOf(GLOBAL_PARAMS_JS) > -1) { initGlobalParams((HttpServletResponse) response); return; } } } catch (Exception e) { String msg = "Exception occurred while processing Request"; log.error(msg, e); throw new ServletException(msg, e); } filterChain.doFilter(request, response); }
From source file:org.xchain.framework.filter.UrlTranslationFilter.java
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // Perform Url Translation if enabled. if (this.enabled) { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; URL url = null;/* w ww. j a v a 2s . c om*/ URLConnection connection = null; InputStream in = null; OutputStream out = null; String path = httpRequest.getServletPath(); boolean matchFound = false; try { // Check the incoming path against the registered patterns. for (Pattern pattern : translationMap.keySet()) { Matcher match = pattern.matcher(path); if (match.matches()) { // Match found. Get the URI the pattern translates to. String uri = translationMap.get(pattern); // Perform group substitution. for (int group = 1; group <= match.groupCount(); group++) { uri = uri.replaceAll("\\$[{]" + group + "[}]", match.group(group)); } // Create a new URL from the translated uri. url = UrlFactory.getInstance().newUrl(uri); matchFound = true; break; } } if (!matchFound) { // No match found. Let the request go through. chain.doFilter(request, response); return; } if (log.isDebugEnabled()) { log.debug("doFilter: redirecting " + path + " to " + url); } // get a connection to the url. connection = url.openConnection(); // set the headers. httpResponse.setContentLength(connection.getContentLength()); // try to set the content type header defined in the container. String servletContentType = servletContext.getMimeType(path); if (servletContentType != null) { httpResponse.setContentType(servletContentType); } // get the streams. in = connection.getInputStream(); out = response.getOutputStream(); // create buffer and length for coping. byte[] buffer = new byte[1024]; int length = 0; // transfer the bytes. while ((length = in.read(buffer)) > 0) { out.write(buffer, 0, length); } } catch (MalformedURLException mue) { throw new ServletException(mue); } catch (UnknownServiceException use) { throw new ServletException("The protocol '" + url.getProtocol() + "' does not support input.", use); } finally { // close the streams. if (in != null) { try { in.close(); } catch (IOException ioe) { } } if (out != null) { try { out.close(); } catch (IOException ioe) { } } } } else chain.doFilter(request, response); }