List of usage examples for javax.servlet.http HttpServletResponse getContentType
public String getContentType();
From source file:com.google.ratel.util.RatelUtils.java
public static void writeContent(HttpServletResponse response, String content, String contentType) { try {/* w ww.j a va 2 s .c o m*/ RatelHttpServletResponse ratelResponse = null; if (response instanceof RatelHttpServletResponse) { ratelResponse = (RatelHttpServletResponse) response; } if (response.getContentType() == null) { response.setContentType(contentType); } if (content == null) { if (ratelResponse != null && ratelResponse.isStatusSettable()) { response.setStatus(HttpServletResponse.SC_NO_CONTENT); } return; } PrintWriter writer = response.getWriter(); IOUtils.write(content, writer); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:com.adobe.acs.commons.http.injectors.AbstractHtmlRequestInjector.java
@Override public final void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse, final FilterChain filterChain) throws IOException, ServletException { if (!this.accepts(servletRequest, servletResponse)) { filterChain.doFilter(servletRequest, servletResponse); return;//from w w w. ja va2s . com } // We know these are HTTP Servlet Requests since accepts passed final HttpServletRequest request = (HttpServletRequest) servletRequest; final HttpServletResponse response = (HttpServletResponse) servletResponse; // Prepare to capture the original response final BufferingResponse originalResponse = new BufferingResponse(response); // Process and capture the original response filterChain.doFilter(request, originalResponse); // Get contents final String originalContents = originalResponse.getContents(); if (originalContents != null && StringUtils.contains(response.getContentType(), "html")) { final int injectionIndex = getInjectIndex(originalContents); if (injectionIndex != -1) { final PrintWriter printWriter = response.getWriter(); // Write all content up to the injection index printWriter.write(originalContents.substring(0, injectionIndex)); // Inject the contents; Pass the request/response - consumer can use as needed inject(request, response, printWriter); // Write all content after the injection index printWriter.write(originalContents.substring(injectionIndex)); return; } } if (originalContents != null) { response.getWriter().write(originalContents); } }
From source file:net.community.chest.gitcloud.facade.backend.git.GitBackendServlet.java
@Override protected void service(HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException { if (logger.isDebugEnabled()) { logger.debug(/*w ww . j a v a 2s . c o m*/ "service(" + req.getMethod() + ")[" + req.getRequestURI() + "][" + req.getQueryString() + "]"); } if (logger.isTraceEnabled()) { logHeaders(req, ServletUtils.getRequestHeaders(req), "REQ"); } super.service(req, rsp); if (logger.isDebugEnabled()) { logger.debug("service(" + req.getMethod() + ")[" + req.getRequestURI() + "][" + req.getQueryString() + "]" + " Content-Type: " + rsp.getContentType() + ", status=" + rsp.getStatus()); } if (logger.isTraceEnabled()) { logHeaders(req, ServletUtils.getResponseHeaders(rsp), "RSP"); } }
From source file:eionet.webq.web.controller.FileDownloadController.java
/** * Writes specified content to http response. * * @param response http response/*from w ww .ja v a 2 s. c om*/ * @param data content to be written to response */ private void writeToResponse(HttpServletResponse response, byte[] data) { ServletOutputStream output = null; try { response.setContentLength(data.length); boolean noCache = true; if (response.getContentType() != null && response.getContentType().startsWith("image")) { noCache = false; } if (noCache) { response.addHeader("Cache-control", "no-cache"); } output = response.getOutputStream(); IOUtils.write(data, output); output.flush(); } catch (IOException e) { throw new RuntimeException("Unable to write response", e); } finally { IOUtils.closeQuietly(output); } }
From source file:$.ResourceServlet.java
private OutputStream selectOutputStream(HttpServletRequest request, HttpServletResponse response) throws IOException { if (gzipEnabled) { String mimeType = response.getContentType(); if (matchesCompressedMimeTypes(mimeType)) { String acceptEncoding = request.getHeader("Accept-Encoding"); if (acceptEncoding != null && acceptEncoding.indexOf("gzip") != -1) { if (LOG.isDebugEnabled()) { LOG.debug("Enabling GZIP compression for the current response."); }// w w w . j av a 2 s.c om return new GZIPResponseStream(response); } } } return response.getOutputStream(); }
From source file:jp.xet.uncommons.web.HtmlCompressionFilter.java
@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { OutputStreamResponseWrapper wrappedResponse = new OutputStreamResponseWrapper(response); filterChain.doFilter(request, wrappedResponse); ByteArrayOutputStream baos = wrappedResponse.getRealOutputStream(); if (enabled && Strings.nullToEmpty(response.getContentType()).startsWith("text/html")) { HtmlCompressor compressor = new HtmlCompressor(); compressor.setEnabled(enabled);/*from w w w . j av a2s .c om*/ compressor.setRemoveComments(removeComments); compressor.setRemoveMultiSpaces(removeMultiSpaces); compressor.setRemoveIntertagSpaces(removeIntertagSpaces); compressor.setRemoveQuotes(removeQuotes); compressor.setCompressJavaScript(compressJavaScript); compressor.setCompressCss(compressCss); compressor.setYuiJsNoMunge(yuiJsNoMunge); compressor.setYuiJsPreserveAllSemiColons(yuiJsPreserveAllSemiColons); compressor.setYuiJsDisableOptimizations(yuiJsDisableOptimizations); compressor.setYuiJsLineBreak(yuiJsLineBreak); compressor.setYuiCssLineBreak(yuiCssLineBreak); PrintWriter writer = null; try { String compressed = compressor.compress(baos.toString()); response.setContentLength(compressed.length()); writer = response.getWriter(); writer.write(compressed); } finally { if (writer != null) { writer.close(); } } } else if (baos != null) { ServletOutputStream outputStream = null; try { outputStream = response.getOutputStream(); outputStream.write(baos.toByteArray()); } finally { if (outputStream != null) { outputStream.close(); } } } }
From source file:com.evon.injectTemplate.InjectTemplateFilter.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; StringWriter writer = new StringWriter(); BufferedResponseWrapper wrapper = new BufferedResponseWrapper((HttpServletResponse) response, writer); chain.doFilter(request, wrapper);// www . j a v a 2 s .c o m String contentType = null; String uri = httpRequest.getRequestURI(); contentType = httpResponse.getContentType(); if (contentTypes.containsKey(uri)) { contentType = contentTypes.get(uri); } else if (contentType != null) { contentTypes.put(uri, contentType); } contentType = (contentType == null) ? "none" : contentType; String out = writer.getBuffer().toString(); boolean requestedURIIsTheTemplate = false; requestedURIIsTheTemplate = InjectUtils.isTemplate(uri); boolean contentTypeIsText = !wrapper.isBinary() && contentType != null && !contentType.equals("none"); if (requestedURIIsTheTemplate || !contentTypeIsText) { if (contentTypeIsText) { response.getWriter().print(out); } return; } if (!templateLodaded && !templateLodadedStarted) { loadTemplates(httpRequest); } TemplateBean template = getTemplatePathByURI(uri); if (template == null) { response.getWriter().print(out); return; } String key = null; if (template.cache.equals("SESSION")) { String cookiesNames = getCookieHashs(httpRequest); key = template.path + cookiesNames; } else if (template.cache.equals("ON")) { key = template.path; } if (!templates.containsKey("/" + template.path)) { throw new ServletException("Template [" + template.path + "] not founded"); } boolean needRefresh = template.refreshInSeconds > 0 && ((System.currentTimeMillis() - template.lastUpdate) / 1000) > template.refreshInSeconds; boolean replaceTemplate = template.cache.equals("OFF") || !htmlContents.containsKey(key) || needRefresh; /* pra investigar erro de nulo, boolean notExist = key==null || !htmlContents.containsKey(key); * if(!notExist) { notExist=!notExist; //throw new ServletException("content not exist"); } */ if (replaceTemplate) { if (needRefresh) { template.lastUpdate = System.currentTimeMillis(); } try { loadContentTemplate(template, request.getServerName(), request.getServerPort(), request.getProtocol().contains("HTTPS"), httpRequest); } catch (Exception e) { throw new ServletException(e.getMessage(), e); } } HTMLInfoBean templateHTML = templates.get("/" + template.path); String contentTemplate = htmlContents.get(key).getContent(); IDocument docOut = HTMLParser.parse(out); for (String selector : templateHTML.getSelectors()) { IElements elements = docOut.select(selector); if (elements.size() == 0) { System.out.println("WARNING: Selector [" + selector + "] in template [" + templateHTML.getUri() + "] not founded in [" + httpRequest.getRequestURI() + "]"); continue; } if (elements.size() != 1) { System.out.println( "WARNING: Selector get many elements. Choosed the first to URI: " + templateHTML.getUri()); } IElement element = elements.get(0); String innerHTML = element.html(); contentTemplate = contentTemplate.replace("<INJECT selector='" + selector + "'/>", innerHTML); } response.getWriter().print(contentTemplate); }
From source file:com.atlassian.jira.web.dispatcher.JiraWebworkActionDispatcher.java
/** * Wrap servlet request with the appropriate request. It will check to see if request is a multipart request and * wrap in appropriately.//from w ww. j a v a 2 s. com * * @param httpServletRequest HttpServletRequest * @return wrapped request or original request */ private Pair<HttpServletRequest, HttpServletResponse> wrap(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) { // don't wrap more than once if (httpServletRequest instanceof MultiPartRequestWrapper) { return Pair.of(httpServletRequest, httpServletResponse); } // // SiteMesh turns itself on when it sees a content type of text/html which an earlier filter sets BUT // which SiteMesh misses because it runs later. So we do a numpty set here. // This allows SiteMesh to kick in because until setContentType is called then SiteMesh wont play ball // httpServletResponse.setContentType(httpServletResponse.getContentType()); final String disableMultipartGetString = multipartDisableGetString(); boolean disableMultipartGet = Boolean.valueOf(disableMultipartGetString); if (needsMultipartWrapper(httpServletRequest, disableMultipartGet)) { try { httpServletRequest = new MultiPartRequestWrapper(httpServletRequest, saveDir, getMaxSize()); } catch (IOException e) { httpServletRequest.setAttribute("webwork.action.ResultException", new ResultException(Action.ERROR, e.getLocalizedMessage())); } } return Pair.of(httpServletRequest, httpServletResponse); }
From source file:de.mpg.escidoc.pubman.viewItem.bean.FileBean.java
/** * Prepares the file the user wants to download * /*from w w w. j a va 2 s . c om*/ */ public String downloadFile() { try { LoginHelper loginHelper = (LoginHelper) FacesContext.getCurrentInstance().getApplication() .getVariableResolver().resolveVariable(FacesContext.getCurrentInstance(), "LoginHelper"); String fileLocation = ServiceLocator.getFrameworkUrl() + this.file.getContent(); String filename = this.file.getName(); // Filename suggested in browser Save As dialog filename = filename.replace(" ", "_"); // replace empty spaces because they cannot be procesed by the http-response (filename will be cutted after the first empty space) String contentType = this.file.getMimeType(); // For dialog, try System.out.println("MIME: " + contentType); // application/x-download FacesContext facesContext = FacesContext.getCurrentInstance(); HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse(); response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8")); if (this.file.getDefaultMetadata() != null) { response.setContentLength(this.file.getDefaultMetadata().getSize()); } response.setContentType(contentType); System.out.println("MIME: " + response.getContentType()); byte[] buffer = null; if (this.file.getDefaultMetadata() != null) { try { GetMethod method = new GetMethod(fileLocation); method.setFollowRedirects(false); if (loginHelper.getESciDocUserHandle() != null) { // downloading by account user addHandleToMethod(method, loginHelper.getESciDocUserHandle()); } // Execute the method with HttpClient. HttpClient client = new HttpClient(); ProxyHelper.setProxy(client, fileLocation); //???? client.executeMethod(method); OutputStream out = response.getOutputStream(); InputStream input = method.getResponseBodyAsStream(); try { if (this.file.getDefaultMetadata() != null) { buffer = new byte[this.file.getDefaultMetadata().getSize()]; int numRead; long numWritten = 0; while ((numRead = input.read(buffer)) != -1) { out.write(buffer, 0, numRead); out.flush(); numWritten += numRead; } facesContext.responseComplete(); } } catch (IOException e1) { logger.debug("Download IO Error: " + e1.toString()); } input.close(); out.close(); } catch (FileNotFoundException e) { logger.debug("File not found: " + e.toString()); } } } catch (Exception e) { logger.debug("File Download Error: " + e.toString()); System.out.println(e.toString()); } return null; }