List of usage examples for javax.servlet ServletResponse setContentType
public void setContentType(String type);
From source file:org.apache.myfaces.custom.ppr.PPRPhaseListener.java
/** * Respond to an AJAX request from a {@link PPRPanelGroup}. The * triggered components are determined by reading the * TRIGGERED_COMPONENTS_PARAMETER from either the RequestParameterMap or * the Request Map. Those componenets are encoded into an XML response. * The lifecycle is quit afterwards.// w w w . java2s . c o m * * @param context the current {@link FacesContext} * @param externalContext the current {@link ExternalContext} * @param requestMap Map containing the request attributes */ private void processPartialPageRequest(FacesContext context, final ExternalContext externalContext, Map requestMap) { ServletResponse response = (ServletResponse) externalContext.getResponse(); ServletRequest request = (ServletRequest) externalContext.getRequest(); UIViewRoot viewRoot = context.getViewRoot(); // Set Character encoding, contentType and locale for the response final String characterEncoding = request.getCharacterEncoding(); String contentType = getContentType("text/xml", characterEncoding); response.setContentType(contentType); response.setLocale(viewRoot.getLocale()); // Fetch the comma-separated list of triggered components String triggeredComponents = getTriggeredComponents(context); try { PrintWriter out = response.getWriter(); context.setResponseWriter(new HtmlResponseWriterImpl(out, contentType, characterEncoding)); out.print(XML_HEADER); out.print("<response>\n"); encodeTriggeredComponents(out, triggeredComponents, viewRoot, context); out.print("</response>"); out.flush(); } catch (IOException e) { throw new FacesException(e); } context.responseComplete(); }
From source file:de.thorstenberger.taskmodel.view.webapp.filter.ExportPDFFilter.java
/** * Render the given xhtml document as pdf and write it to the response outputstream. * * @param dom/*from w w w . j av a 2 s .c om*/ * xhtml document * @param request * @param response * @throws IOException * if the document could not get renderered */ private void renderPdf(final Document dom, final HttpServletRequest request, final ServletResponse response) throws IOException { final ITextRenderer renderer = new ITextRenderer(80 / 3f, 15); if (fontPath != null) { try { log.debug("Using unicode font at path " + fontPath); renderer.getFontResolver().addFont(fontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED); } catch (DocumentException e1) { e1.printStackTrace(); } } renderer.setDocument(dom, getLocalURL(request)); renderer.layout(); response.setContentType("application/pdf"); // set an appropriate filename ((HttpServletResponse) response).setHeader("Content-Disposition", "attachment; filename=" + request.getParameter(EXPORTFILENAME)); try { renderer.createPDF(response.getOutputStream()); } catch (final DocumentException e) { log.error("Could not render pdf.", e); // FIXME should we just return the original content? throw new IOException(e.getMessage()); } }
From source file:ar.com.zauber.commons.web.filter.JSONPRequestFilter.java
/** * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, * javax.servlet.ServletResponse, javax.servlet.FilterChain) *//* w w w. ja va2 s .c o m*/ public final void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (!(request instanceof HttpServletRequest)) { throw new ServletException("This filter can " + " only process HttpServletRequest requests"); } final HttpServletRequest httpRequest = (HttpServletRequest) request; final String callback = httpRequest.getParameter(callbackParameterName); if (StringUtils.isNotBlank(callback) && acceptsJSONP(httpRequest)) { ServletOutputStream out = response.getOutputStream(); out.print(callback + "("); chain.doFilter(request, response); out.print(");"); response.setContentType(responseContentType); } else { chain.doFilter(request, response); } }
From source file:org.apache.cxf.fediz.spring.web.FederationAuthenticationEntryPoint.java
@Override public void commence(ServletRequest request, ServletResponse response, AuthenticationException authException) throws IOException, ServletException { HttpServletRequest hrequest = (HttpServletRequest) request; HttpServletResponse hresponse = (HttpServletResponse) response; FedizContext fedContext = federationConfig.getFedizContext(); LOG.debug("Federation context: {}", fedContext); if (hrequest.getRequestURL().indexOf(FederationConstants.METADATA_PATH_URI) != -1 || hrequest.getRequestURL().indexOf(getMetadataURI(fedContext)) != -1) { if (LOG.isDebugEnabled()) { LOG.debug("Metadata document requested"); }/*from w w w. ja v a2s .c om*/ response.setContentType("text/xml"); PrintWriter out = response.getWriter(); FedizProcessor wfProc = FedizProcessorFactory.newFedizProcessor(fedContext.getProtocol()); try { Document metadata = wfProc.getMetaData(hrequest, fedContext); out.write(DOM2Writer.nodeToString(metadata)); return; } catch (Exception ex) { LOG.warn("Failed to get metadata document: " + ex.getMessage()); hresponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } } String redirectUrl = null; try { FedizProcessor wfProc = FedizProcessorFactory.newFedizProcessor(fedContext.getProtocol()); RedirectionResponse redirectionResponse = wfProc.createSignInRequest(hrequest, fedContext); redirectUrl = redirectionResponse.getRedirectionURL(); if (redirectUrl == null) { LOG.warn("Failed to create SignInRequest."); hresponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to create SignInRequest."); } Map<String, String> headers = redirectionResponse.getHeaders(); if (!headers.isEmpty()) { for (String headerName : headers.keySet()) { hresponse.addHeader(headerName, headers.get(headerName)); } } } catch (ProcessingException ex) { System.err.println("Failed to create SignInRequest: " + ex.getMessage()); LOG.warn("Failed to create SignInRequest: " + ex.getMessage()); hresponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to create SignInRequest."); } preCommence(hrequest, hresponse); if (LOG.isInfoEnabled()) { LOG.info("Redirecting to IDP: " + redirectUrl); } hresponse.sendRedirect(redirectUrl); }
From source file:org.ajax4jsf.context.AjaxContextImpl.java
/** * @param context//from w ww . j av a 2 s . c o m * @throws AbortProcessingException */ public void renderAjax(FacesContext context) throws FacesException { if (log.isDebugEnabled()) { log.debug(Messages.getMessage(Messages.RENDER_AJAX_REQUEST, getSubmittedRegionClientId())); } try { // Just in case... setSelfRender(true); setAjaxRequest(true); // create response writer. ExternalContext extContext = context.getExternalContext(); RenderKit renderKit = context.getRenderKit(); String encoding; // Depends if we talk about servlets, portlets, ... if (extContext.getRequest() instanceof ServletRequest) { ServletRequest request = (ServletRequest) extContext.getRequest(); ServletResponse response = (ServletResponse) extContext.getResponse(); // Setup encoding and content type String contentType = "text/xml"; // get the encoding - must be setup by faces context or filter. encoding = request.getCharacterEncoding(); if (encoding == null) { encoding = "UTF-8"; } response.setContentType(contentType + ";charset=" + encoding); } else encoding = "UTF-8"; PrintWriter servletWriter; servletWriter = getWriter(extContext); ResponseWriter writer = renderKit.createResponseWriter(servletWriter, null, encoding); context.setResponseWriter(writer); // make response writer.startDocument(); encodeAjaxBegin(context); context.getViewRoot().encodeAll(context); saveViewState(context); encodeAjaxEnd(context); writer.endDocument(); writer.flush(); writer.close(); servletWriter.close(); // Save tree state. } catch (IOException e) { throw new FacesException( Messages.getMessage(Messages.RENDERING_AJAX_REGION_ERROR, getSubmittedRegionClientId()), e); } finally { context.responseComplete(); // component.setRendererType(defaultRenderer); } }
From source file:org.artifactory.webapp.servlet.ArtifactoryFilter.java
@Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { // Redirect or forward if need for (RedirectionHandler redirectionHandler : redirectionHandlers) { if (redirectionHandler.shouldRedirect(request)) { redirectionHandler.redirect(request, response); return; }//from ww w . j av a 2 s. c om } if (filterConfig.getServletContext().getAttribute(DelayedInit.APPLICATION_CONTEXT_LOCK_KEY) != null) { String requestURI = ((HttpServletRequest) request).getRequestURI(); if (requestURI.endsWith("artifactory-splash.gif")) { ((HttpServletResponse) response).setStatus(200); ServletOutputStream out = response.getOutputStream(); ResourceUtils.copyResource("/artifactory-splash.gif", out, null, getClass()); return; } response.setContentType("text/html"); ((HttpServletResponse) response).setStatus(HttpStatus.SC_SERVICE_UNAVAILABLE); ServletOutputStream out = response.getOutputStream(); ResourceUtils.copyResource("/startup.html", out, null, getClass()); return; } try { ServletContext servletContext = filterConfig.getServletContext(); ArtifactoryContext context = RequestUtils.getArtifactoryContext(servletContext); if (context == null) { respondFailedToInitialize(response); return; } bind(context); if (response instanceof HttpServletResponse) { HttpServletResponse httpResponse = (HttpServletResponse) response; if (!httpResponse.containsHeader("Server")) { //Add the server header (curl -I http://localhost:8080/artifactory/) httpResponse.setHeader("Server", HttpUtils.getArtifactoryUserAgent()); } // set the Artifactory instance id header String hostId = ContextHelper.get().beanForType(AddonsManager.class) .addonByType(HaCommonAddon.class).getHostId(); httpResponse.setHeader(ArtifactoryResponse.ARTIFACTORY_ID, hostId); String serverId = ContextHelper.get().getServerId(); if (StringUtils.isNotBlank(serverId) && !HaCommonAddon.ARTIFACTORY_PRO.equals(serverId)) { httpResponse.setHeader(HaCommonAddon.ARTIFACTORY_NODE_ID, serverId); } } chain.doFilter(request, response); } finally { unbind(); } }
From source file:org.opencms.jsp.jsonpart.CmsJsonPartFilter.java
/** * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain) *//*from www. j a va2 s.co m*/ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (isJsonRequest(request)) { if (m_isNested.get() == null) { try { m_isNested.set(Boolean.TRUE); RequestWrapper reqWrapper = new RequestWrapper((HttpServletRequest) request); ResponseWrapper resWrapper = new ResponseWrapper((HttpServletResponse) response); chain.doFilter(reqWrapper, resWrapper); byte[] data = resWrapper.getBytes(); String content = new String(data, resWrapper.getCharacterEncoding()); String transformedContent = transformContent(content); byte[] transformedData = transformedContent.getBytes("UTF-8"); response.setContentType("application/json; charset=UTF-8"); response.setContentLength(transformedData.length); response.getOutputStream().write(transformedData); response.getOutputStream().flush(); } finally { m_isNested.set(null); } } } else { chain.doFilter(request, response); } }
From source file:ORG.oclc.os.ipUseThrottleFilter.ipUseThrottleFilter.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { String longAddr = null, shortAddr, s, transactionKey = null; int count;/*from w ww. j av a2s .co m*/ boolean ignorable = false; synchronized (simultaneousRequestsByShortIPAddr) { if (totalSimultaneousRequests >= maxTotalSimultaneousRequests) { log.error("This system has exceeded the maxTotalSimultaneousRequests limit of " + maxTotalSimultaneousRequests); log.error(simultaneousRequestsByShortIPAddr); for (String str : simultaneousRequests) log.error(str); ((HttpServletResponse) response).setStatus(HttpURLConnection.HTTP_UNAVAILABLE); response.setContentType("text/html"); PrintWriter writer = response.getWriter(); writer.println("<html><body><h1>Service Temporarily Unavailable</h1>"); writer.println( "The system is experiencing a severe load and is temporarily unable to accept new requests"); if (contactInfo != null) writer.println("<p>Contact " + contactInfo + " for more information</p>"); writer.println("</body></html>"); writer.close(); return; } if (addressInHeader != null) { @SuppressWarnings("unchecked") Enumeration<String> addrs = ((HttpServletRequest) request).getHeaders(addressInHeader); while (addrs.hasMoreElements()) { longAddr = addrs.nextElement(); if (longAddr == null) { if (++addressInHeaderErrorCount < 10) log.error("Expected a " + addressInHeader + " header but got null"); continue; } if (longAddr.lastIndexOf('.') >= 0) break; } } if (longAddr == null) longAddr = request.getRemoteAddr(); int i = longAddr.lastIndexOf('.'); if (i < 0) { log.error("bogus IP address: '" + longAddr + "'"); longAddr = "0.0.0.0"; } shortAddr = longAddr.substring(0, i); // trim off 4th number group // that lets us spot requests from clusters s = equivalentAddresses.get(shortAddr); // map one short addr to another? if (s != null) shortAddr = s; if (ignorableAddresses.contains(shortAddr)) { ignorable = true; } else { Integer icount = simultaneousRequestsByShortIPAddr.get(shortAddr); if (icount != null) count = icount; else count = 0; int maxSimultaneousRequests = (maxTotalSimultaneousRequests - totalSimultaneousRequests) / 4; if (maxSimultaneousRequests == 0) maxSimultaneousRequests = 1; if (count >= maxSimultaneousRequests) { log.error("IP addr " + shortAddr + ".* has exceeded " + maxSimultaneousRequests + " simultaneous requests!"); log.error("maxTotalSimultaneousRequests=" + maxTotalSimultaneousRequests); log.error("totalSimultaneousRequests=" + totalSimultaneousRequests); for (String str : simultaneousRequests) log.error(str); // ((HttpServletResponse)response).setStatus(HttpURLConnection.HTTP_TOO_MANY_REQUESTS); // someday ((HttpServletResponse) response).setStatus(429); // too many requests response.setContentType("text/html"); PrintWriter writer = response.getWriter(); writer.println( "<html><head><title>Too Many Requests</title></head><body><h1>Too Many Requests</h1>"); writer.println("You have exceeded the maximum simultaneous request value of " + maxSimultaneousRequests); writer.println("<p>This message and your IP address have been logged and reported</p>"); if (contactInfo != null) writer.println("<p>Contact " + contactInfo + " for more information</p>"); writer.println("</body></html>"); writer.close(); return; } simultaneousRequestsByShortIPAddr.put(shortAddr, count + 1); icount = totalRequests.get(shortAddr); if (icount != null) count = icount; else count = 0; totalRequests.put(shortAddr, count + 1); totalSimultaneousRequests++; transactionKey = new StringBuilder((new Date(System.currentTimeMillis())).toString()).append('|') .append(shortAddr).append('|').append(((HttpServletRequest) request).getQueryString()) .toString(); simultaneousRequests.add(transactionKey); } } try { HttpServletResponseWrapper wrapper = new HttpServletResponseWrapper((HttpServletResponse) response); chain.doFilter(request, wrapper); } finally { if (!ignorable) synchronized (simultaneousRequestsByShortIPAddr) { totalSimultaneousRequests--; simultaneousRequests.remove(transactionKey); count = simultaneousRequestsByShortIPAddr.get(shortAddr); if (count == 1) // prune them from the table simultaneousRequestsByShortIPAddr.remove(shortAddr); else simultaneousRequestsByShortIPAddr.put(shortAddr, count - 1); } } Calendar c = new GregorianCalendar(); int hour = c.get(Calendar.HOUR_OF_DAY); if (hour == 0 && nextReportingHour == 24) { // new day! // you could reset your daily limits table here nextReportingHour = 0; } if (hour >= nextReportingHour) { // generate the hourly report // you could reset your hourly limits table here nextReportingHour = hour + 1; if (log.isInfoEnabled()) { HashMap<String, Integer> map = new LinkedHashMap<String, Integer>(); List<String> yourMapKeys = new ArrayList<String>(totalRequests.keySet()); List<Integer> yourMapValues = new ArrayList<Integer>(totalRequests.values()); TreeSet<Integer> sortedSet = new TreeSet<Integer>(yourMapValues); Integer[] sortedArray = sortedSet.descendingSet().toArray(new Integer[0]); int size = sortedArray.length; for (int i = 0; i < size; i++) map.put(yourMapKeys.get(yourMapValues.indexOf(sortedArray[i])), sortedArray[i]); Iterator<String> it = map.keySet().iterator(); String key; StringBuilder sb = new StringBuilder("Top 10 users in the last hour"); for (int i = 0; i < 10 && it.hasNext(); i++) { key = it.next(); sb.append("\n ").append(key).append(" : ").append(map.get(key)); } log.info(sb); } totalRequests.clear(); } }
From source file:org.qifu.sys.GreenStepBaseFormAuthenticationFilter.java
protected void redirectToLogin(ServletRequest request, ServletResponse response) throws IOException { if (!Constants.getSystem().equals(Constants.getMainSystem()) && !isAjaxRequest((HttpServletRequest) request)) { // ? core-web try {/* w w w . j a va2s . c om*/ if (this.loginUseCurrentCookieForGeneralPackage(request, response)) { // no need to login-page String url = SimpleUtils.getHttpRequestUrl((HttpServletRequest) request); logger.warn("URL = " + url); WebUtils.issueRedirect(request, response, url); return; } } catch (Exception e) { e.printStackTrace(); } } if (isAjaxRequest((HttpServletRequest) request)) { response.setCharacterEncoding(Constants.BASE_ENCODING); response.setContentType("application/json"); response.getWriter().write(Constants.NO_LOGIN_JSON_DATA); return; } /* if (this.isIframeMode((HttpServletRequest)request)) { // iframe ??? login.action ? WebUtils.issueRedirect(request, response, "/pages/system/error_static.jsp"); return; } */ if (this.isTabPage((HttpServletRequest) request)) { // dojox.layout.ContentPane ??? login.action ?? WebUtils.issueRedirect(request, response, "/pages/system/login_again.jsp"); return; } WebUtils.issueRedirect(request, response, getLoginUrl()); }
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 {/*from ww w.j a v a 2 s. co 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; } }