List of usage examples for javax.servlet ServletResponse getWriter
public PrintWriter getWriter() throws IOException;
PrintWriter
object that can send character text to the client. From source file:com.pagecrumb.proxy.ProxyFilter.java
/** * TODO Add hander for null baseURL /* w w w . j a va 2s .c om*/ * @param ServletRequest servletrequest - request from client * @param ervletResponse servletresponse - response from server */ @Override public void doFilter(ServletRequest servletrequest, final ServletResponse servletresponse, FilterChain chain) throws IOException, ServletException { log.info("Before invoking chain"); try { String baseURL = ((HttpServletRequest) servletrequest).getQueryString(); if (baseURL != null) { log.info(this.getClass().toString() + " " + "Requested URL: " + baseURL); // TODO Must not pass request to .css or .ico etc. to the GenericResponseWrapper // Must use regex here, every thing that ends with ".*" must not be passed except //if (baseURL.matches(".*?\\.css.*")) { // GenericResponseWrapper responseWrapper // = new GenericResponseWrapper((HttpServletResponse) servletresponse, baseURL, "css"); // chain.doFilter(servletrequest, responseWrapper); //} if (baseURL.matches(".*?\\.png.*") || baseURL.matches(".*?\\.ico.*") || baseURL.matches(".*?\\.gif.*") || baseURL.matches(".*?\\.jpeg.*") || baseURL.matches(".*?\\.jpg.*") || baseURL.matches(".*?\\.js.*")) { // Do not process Javascript for now // Pass the wrapper on to the next filter or servlet log.info("Bypassing Parser - Just do Filter"); chain.doFilter(servletrequest, servletresponse); } else { String gwtModuleBase = (String) servletrequest.getAttribute("X-GWT-Module-Base"); log.info("Module-Base: " + gwtModuleBase); GenericResponseWrapper responseWrapper = new GenericResponseWrapper( (HttpServletResponse) servletresponse, baseURL); chain.doFilter(servletrequest, responseWrapper); log.info("Content type was " + responseWrapper.getContentType()); } } else { PrintWriter pw = servletresponse.getWriter(); pw.println("<html><body><p>Oops, query URL is missing.</p></body></html>"); } } catch (ServletException e) { log.error("Caught Servlet Exception"); Throwable rootCause = e.getRootCause(); log.error("Root cause is " + rootCause.toString()); if (rootCause instanceof RuntimeException) { // This is true for any FacesException. log.error("Rethrowing exception as RuntimeException" + rootCause.toString()); throw (RuntimeException) rootCause; // Throw wrapped RuntimeException instead of ServletException. } else { throw e; } } log.info("After invoking chain"); }
From source file:org.apache.nifi.web.security.x509.X509AuthenticationFilter.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { final HttpServletResponse httpResponse = (HttpServletResponse) response; // determine if this request is attempting to create a new account if (isNewAccountRequest((HttpServletRequest) request)) { // determine if this nifi supports new account requests if (properties.getSupportNewAccountRequests()) { // ensure there is a certificate in the request X509Certificate certificate = certificateExtractor .extractClientCertificate((HttpServletRequest) request); if (certificate != null) { // extract the principal from the certificate Object certificatePrincipal = principalExtractor.extractPrincipal(certificate); String principal = certificatePrincipal.toString(); // log the new user account request logger.info("Requesting new user account for " + principal); try { // get the justification String justification = request.getParameter("justification"); if (justification == null) { justification = StringUtils.EMPTY; }// www . j a v a2s . c o m // create the pending user account userService.createPendingUserAccount(principal, justification); // generate a response httpResponse.setStatus(HttpServletResponse.SC_CREATED); httpResponse.setContentType("text/plain"); // write the response message PrintWriter out = response.getWriter(); out.println("Not authorized. User account created. Authorization pending."); } catch (IllegalArgumentException iae) { handleUserServiceError((HttpServletRequest) request, httpResponse, HttpServletResponse.SC_BAD_REQUEST, iae.getMessage()); } catch (AdministrationException ae) { handleUserServiceError((HttpServletRequest) request, httpResponse, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ae.getMessage()); } } else { // can this really happen? handleMissingCertificate((HttpServletRequest) request, httpResponse); } } else { handleUserServiceError((HttpServletRequest) request, httpResponse, HttpServletResponse.SC_NOT_FOUND, "This NiFi does not support new account requests."); } } else { try { // this not a request to create a user account - try to authorize super.doFilter(request, response, chain); } catch (AuthenticationException ae) { // continue the filter chain since anonymous access should be supported if (!properties.getNeedClientAuth()) { chain.doFilter(request, response); } else { // create an appropriate response for the given exception handleUnsuccessfulAuthentication((HttpServletRequest) request, httpResponse, ae); } } } }
From source file:org.apache.wiki.ui.WikiJSPFilter.java
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException { WatchDog w = m_engine.getCurrentWatchDog(); try {/*from w w w .j a v a 2s . c o m*/ NDC.push(m_engine.getApplicationName() + ":" + ((HttpServletRequest) request).getRequestURI()); w.enterState("Filtering for URL " + ((HttpServletRequest) request).getRequestURI(), 90); HttpServletResponseWrapper responseWrapper; if (m_useOutputStream) { log.debug("Using ByteArrayResponseWrapper"); responseWrapper = new ByteArrayResponseWrapper((HttpServletResponse) response, m_wiki_encoding); } else { log.debug("Using MyServletResponseWrapper"); responseWrapper = new MyServletResponseWrapper((HttpServletResponse) response, m_wiki_encoding); } // fire PAGE_REQUESTED event String pagename = DefaultURLConstructor.parsePageFromURL((HttpServletRequest) request, response.getCharacterEncoding()); fireEvent(WikiPageEvent.PAGE_REQUESTED, pagename); super.doFilter(request, responseWrapper, chain); // The response is now complete. Lets replace the markers now. // WikiContext is only available after doFilter! (That is after // interpreting the jsp) try { w.enterState("Delivering response", 30); WikiContext wikiContext = getWikiContext(request); String r = filter(wikiContext, responseWrapper); if (m_useOutputStream) { OutputStreamWriter out = new OutputStreamWriter(response.getOutputStream(), response.getCharacterEncoding()); out.write(r); out.flush(); out.close(); } else { response.getWriter().write(r); } // Clean up the UI messages and loggers if (wikiContext != null) { wikiContext.getWikiSession().clearMessages(); } // fire PAGE_DELIVERED event fireEvent(WikiPageEvent.PAGE_DELIVERED, pagename); } finally { w.exitState(); } } finally { w.exitState(); NDC.pop(); NDC.remove(); } }
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//from w w w. j av a2s .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:com.flexive.war.servlet.CeFileUpload.java
@Override public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException { String renderContent = null;/*w w w .j av a 2 s.co m*/ try { final HttpServletRequest request = (HttpServletRequest) servletRequest; final BeContentEditorBean ceb = null; // = ContentEditorBean.getSingleton().getInstance(request); if (ceb == null) { renderContent = "No Content Editor Bean is active"; } else { // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request List /* FileItem */ items = upload.parseRequest(request); BinaryDescriptor binary = null; String xpath = null; for (Object item1 : items) { FileItem item = (FileItem) item1; if (item.isFormField()) { if (item.getFieldName().equalsIgnoreCase("result")) { renderContent = item.getString().replaceAll("\\\\n", "\\\n"); } else if (item.getFieldName().equalsIgnoreCase("xpath")) { xpath = item.getString(); } } else { InputStream uploadedStream = null; try { uploadedStream = item.getInputStream(); String name = item.getName(); if (name.indexOf('\\') > 0) name = name.substring(name.lastIndexOf('\\') + 1); binary = new BinaryDescriptor(name, item.getSize(), uploadedStream); } finally { if (uploadedStream != null) uploadedStream.close(); } } // System.out.println("Item: " + item.getName()); } //FxContent co = ceb.getContent(); FxBinary binProperty = new FxBinary(binary); //co.setValue(xpath, binProperty); //ceb.getContentEngine().prepareSave(co); } } catch (Throwable t) { System.err.println(t.getMessage()); t.printStackTrace(); renderContent = t.getMessage(); } // Render the result PrintWriter w = servletResponse.getWriter(); if (renderContent == null) { renderContent = "No content"; } w.print(renderContent); w.close(); servletResponse.setContentType("text/html"); servletResponse.setContentLength(renderContent.length()); ((HttpServletResponse) servletResponse).setStatus(HttpServletResponse.SC_OK); }
From source file:io.fabric8.apiman.rest.BearerTokenFilter.java
/** * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, * javax.servlet.ServletResponse, javax.servlet.FilterChain) *///from w ww. j ava2 s. c o m @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; String authHeader = req.getHeader("Authorization"); AuthToken.set(null); if (authHeader != null && authHeader.toUpperCase().startsWith("BEARER")) { //validate token with issuer try { String authToken = authHeader.substring(7); UserInfo userInfo = bearerTokenCache.get(authToken); AuthToken.set(authToken); AuthPrincipal principal = new AuthPrincipal(userInfo.username); principal.addRole("apiuser"); if (userInfo.isClusterAdmin) { principal.addRole("apiadmin"); } request = wrapTheRequest(request, principal); chain.doFilter(request, response); } catch (Exception e) { e.printStackTrace(); String errMsg = e.getMessage(); if (e.getMessage().contains("Server returned HTTP response code")) { errMsg = "Invalid BearerToken"; } else { errMsg = "Cannot validate BearerToken"; log.error(errMsg, e); } sendInvalidTokenResponse((HttpServletResponse) response, errMsg); } } else if (("/".equals(req.getPathInfo())) || ("/swagger.json".equals(req.getPathInfo())) || ("/config.js".equals(req.getPathInfo())) || ("/swagger.yaml".equals(req.getPathInfo())) || (req.getPathInfo().startsWith("/downloads/"))) { //allow anonymous requests to the root or swagger document log.debug("Allowing anonymous access to " + req.getPathInfo()); chain.doFilter(request, response); } else { //no bearer token present String loginForm = "<html>\n" + "<title>Login into APIMAN with authToken</title>\n" + "<head>\n" + "</head>\n" + "<body>\n" + "<h1>Provide valid authToken and a link into the Apiman console</h1>\n" + "<form action=\"/apimanui/link\" method=\"post\">\n" + " AuthToken: <input type=\"text\" name=\"access_token\" size=\"100\" value=\"oc whoami -t\" /></br>\n" + " Redirect URL: <input type=\"text\" name=\"redirect\" size=\"100\" value=\"/apimanui/api-manager/\" /></br>\n" + " <input type=\"submit\" value=\"Login\" /> \n" + "</form>\n" + "</body>\n" + "</html>"; response.setCharacterEncoding("UTF-8"); response.getWriter().append(loginForm); //sendInvalidTokenResponse((HttpServletResponse)response, "No BearerToken"); } }
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 {/* www .j a va 2 s. co m*/ 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:com.esoft.yeepay.user.service.impl.YeePayCorpAccountOperation.java
@Override @Transactional(rollbackFor = Exception.class) public void receiveOperationS2SCallback(ServletRequest request, ServletResponse response) { try {//from ww w. j av a 2 s . com request.setCharacterEncoding("UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } // ?? xml? String notifyxml = request.getParameter("notify"); // ?? String sign = request.getParameter("sign"); boolean flag = CFCASignUtil.isVerifySign(notifyxml, sign); if (flag) { // ?? @SuppressWarnings("unchecked") Map<String, String> resultMap = Dom4jUtil.xmltoMap(notifyxml); String code = resultMap.get("code"); String message = resultMap.get("message"); String platformUserNo = resultMap.get("platformUserNo"); TrusteeshipOperation to = trusteeshipOperationBO.get(YeePayConstants.OperationType.ENTERPRISE_REGISTER, platformUserNo, platformUserNo, "yeepay"); ht.evict(to); to = ht.get(TrusteeshipOperation.class, to.getId(), LockMode.UPGRADE); to.setResponseTime(new Date()); to.setResponseData(notifyxml); User user = ht.get(User.class, platformUserNo); log.info("code:" + code); if ("1".equals(code)) { if (user != null) { TrusteeshipAccount ta = ht.get(TrusteeshipAccount.class, user.getId()); if (ta == null) { ta = new TrusteeshipAccount(); ta.setId(user.getId()); ta.setUser(user); } ta.setAccountId(user.getId()); ta.setCreateTime(new Date()); ta.setStatus(TrusteeshipConstants.Status.PASSED); ta.setTrusteeship("yeepay"); ht.saveOrUpdate(ta); userBO.removeRole(user, new Role("WAIT_CONFIRM")); userBO.addRole(user, new Role("LOANER")); // ?? springSecurityService.refreshLoginUserAuthorities(user.getId()); to.setStatus(TrusteeshipConstants.Status.PASSED); ht.merge(to); } } else if ("0".equals(code) || "104".equals(code)) { to.setStatus(TrusteeshipConstants.Status.REFUSED); ht.merge(to); userBO.removeRole(user, new Role("WAIT_CONFIRM")); // ?? springSecurityService.refreshLoginUserAuthorities(user.getId()); } else { // throw new RuntimeException(new TrusteeshipReturnException(code + ":" + message)); } } try { response.getWriter().write("SUCCESS"); } catch (IOException e) { throw new RuntimeException(e.getMessage()); } }
From source file:org.hi.framework.acgei.AuthenticationProcessingFilterEntryPoint.java
public void commence(ServletRequest request, ServletResponse response, AuthenticationException authException) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; String scheme = request.getScheme(); String serverName = request.getServerName(); int serverPort = portResolver.getServerPort(request); String contextPath = req.getContextPath(); boolean inHttp = "http".equals(scheme.toLowerCase()); boolean inHttps = "https".equals(scheme.toLowerCase()); boolean includePort = true; String redirectUrl = null;/* w w w . ja v a 2 s. c o m*/ boolean doForceHttps = false; Integer httpsPort = null; if (inHttp && (serverPort == 80)) { includePort = false; } else if (inHttps && (serverPort == 443)) { includePort = false; } if (forceHttps && inHttp) { httpsPort = (Integer) portMapper.lookupHttpsPort(new Integer(serverPort)); if (httpsPort != null) { doForceHttps = true; if (httpsPort.intValue() == 443) { includePort = false; } else { includePort = true; } } } if (serverSideRedirect) { if (doForceHttps) { // before doing server side redirect, we need to do client redirect to https. String servletPath = req.getServletPath(); String pathInfo = req.getPathInfo(); String query = req.getQueryString(); redirectUrl = "https://" + serverName + ((includePort) ? (":" + httpsPort) : "") + contextPath + servletPath + (pathInfo == null ? "" : pathInfo) + (query == null ? "" : "?" + query); } else { if (logger.isDebugEnabled()) { logger.debug("Server side forward to: " + loginFormUrl); } RequestDispatcher dispatcher = req.getRequestDispatcher(loginFormUrl); dispatcher.forward(request, response); return; } } else { if (doForceHttps) { redirectUrl = "https://" + serverName + ((includePort) ? (":" + httpsPort) : "") + contextPath + loginFormUrl; } else { redirectUrl = scheme + "://" + serverName + ((includePort) ? (":" + serverPort) : "") + contextPath + loginFormUrl; } } if (logger.isDebugEnabled()) { logger.debug("Redirecting to: " + redirectUrl); } //------------- for DWZ ------------------// if ("XMLHttpRequest".equalsIgnoreCase(((HttpServletRequest) request).getHeader("X-Requested-With")) || request.getParameter("ajax") != null) { PrintWriter out = response.getWriter(); out.println("{\"statusCode\":\"301\",\"message\":\"Session Timeout! Please re-sign in!\"}"); throw new BusinessException("Session Timeout"); // throw new BusinessException("{\"statusCode\":\"301\",\"message\":\"Session Timeout! Please re-sign in!\"}"); } else { ((HttpServletResponse) response) .sendRedirect(((HttpServletResponse) response).encodeRedirectURL(redirectUrl)); } }
From source file:org.eclipse.equinox.http.servlet.tests.ServletTest.java
public void test_ServletContextHelper13() throws Exception { BundleContext bundleContext = getBundleContext(); Bundle bundle = bundleContext.getBundle(); // test that the helper handlesecurity is called before the filter by setting an attribute on the request ServletContextHelper servletContextHelper = new ServletContextHelper(bundle) { @Override//from ww w . ja va2s . com public boolean handleSecurity(HttpServletRequest request, HttpServletResponse response) throws IOException { request.setAttribute(getName(), Boolean.TRUE); return super.handleSecurity(request, response); } }; Filter f1 = new Filter() { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (request.getAttribute(getName()) == Boolean.TRUE) { request.setAttribute(getName() + ".fromFilter", Boolean.TRUE); } chain.doFilter(request, response); } @Override public void destroy() { } }; Servlet s1 = new HttpServlet() { private static final long serialVersionUID = 1L; @Override public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { res.getWriter().print(req.getAttribute(getName() + ".fromFilter")); } }; Collection<ServiceRegistration<?>> registrations = new ArrayList<ServiceRegistration<?>>(); try { Dictionary<String, String> contextProps = new Hashtable<String, String>(); contextProps.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_NAME, "a"); contextProps.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_PATH, "/"); registrations.add( bundleContext.registerService(ServletContextHelper.class, servletContextHelper, contextProps)); Dictionary<String, String> filterProps = new Hashtable<String, String>(); filterProps.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_FILTER_PATTERN, "/*"); filterProps.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_SELECT, "(" + HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_NAME + "=a)"); registrations.add(bundleContext.registerService(Filter.class, f1, filterProps)); Dictionary<String, String> servletProps = new Hashtable<String, String>(); servletProps.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_NAME, "S1"); servletProps.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_PATTERN, "/s1"); servletProps.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_SELECT, "(" + HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_NAME + "=a)"); registrations.add(bundleContext.registerService(Servlet.class, s1, servletProps)); String actual = requestAdvisor.request("s1"); Assert.assertEquals(Boolean.TRUE.toString(), actual); } finally { for (ServiceRegistration<?> registration : registrations) { registration.unregister(); } } }