Java Code Examples for javax.servlet.ServletResponse#getOutputStream()

The following examples show how to use javax.servlet.ServletResponse#getOutputStream() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: IndexServlet.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@Override
public void service(ServletRequest servletRequest, ServletResponse response) throws ServletException, IOException {
  Template tmp = templateCfg.getTemplate("/index.html");
  final ServerData data = dataProvider.get();

  final String dataAsJSON = mapper.writeValueAsString(data);

  response.setContentType("text/html; charset=utf-8");
  OutputStreamWriter outputWriter = new OutputStreamWriter(response.getOutputStream());
  try {
    tmp.process(ImmutableMap.of("dremio", dataAsJSON), outputWriter);
    outputWriter.flush();
    outputWriter.close();
  } catch (TemplateException e) {
    throw new IOException("Error rendering index.html template", e);
  }
}
 
Example 2
Source File: HttpUtils.java    From utils with Apache License 2.0 6 votes vote down vote up
/**
 * 向响应对象中输出字符串
 *
 * @param response 响应对象
 * @param content  内容
 * @throws IOException 异常
 */
public static void write(ServletResponse response, String content) throws IOException {
    response.setContentLength(-1);
    PrintWriter writer = null;
    ServletOutputStream sos = null;
    try {
        writer = response.getWriter();
        writer.println(content);
    } catch (Exception e) {
        sos = response.getOutputStream();
        sos.println(content);
    } finally {
        if (null != writer) {
            writer.flush();
            writer.close();
        }
        if (null != sos) {
            sos.flush();
            sos.close();
        }
    }
}
 
Example 3
Source File: HttpUtils.java    From utils with Apache License 2.0 6 votes vote down vote up
/**
 * 向响应对象中输出字符串
 *
 * @param response 响应对象
 * @param data     数据
 * @throws IOException 异常
 */
public static void write(ServletResponse response, Object data) throws IOException {
    response.setContentLength(-1);
    response.setContentType("application/json;charset=utf-8");
    response.setCharacterEncoding("utf-8");
    String json = JSON.toJSONString(data);
    PrintWriter writer = null;
    ServletOutputStream sos = null;
    try {
        writer = response.getWriter();
        writer.println(json);
    } catch (Exception e) {
        sos = response.getOutputStream();
        sos.println(json);
    } finally {
        if (null != writer) {
            writer.flush();
            writer.close();
        }
        if (null != sos) {
            sos.flush();
            sos.close();
        }
    }
}
 
Example 4
Source File: CaptchaFilter.java    From java-platform with Apache License 2.0 5 votes vote down vote up
protected void writeObject(ServletRequest request, ServletResponse response, Object result) throws IOException {
	String characterEncoding = ((HttpServletRequest) request).getCharacterEncoding();
	Charset charset = Strings.isNullOrEmpty(characterEncoding) ? DEFAULT_CHARSET
			: Charset.forName(characterEncoding);
	OutputStreamWriter out = new OutputStreamWriter(response.getOutputStream(), charset);
	SerializeWriter writer = new SerializeWriter(out);
	JSONSerializer serializer = new JSONSerializer(writer, this.serializeConfig);
	serializer.config(SerializerFeature.DisableCircularReferenceDetect, true);
	serializer.write(result);
	writer.flush();
	out.close();
}
 
Example 5
Source File: FederationSignOutCleanupFilter.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
    throws IOException, ServletException {

    String wa = request.getParameter(FederationConstants.PARAM_ACTION);
    if (FederationConstants.ACTION_SIGNOUT_CLEANUP.equals(wa)) {
        if (request instanceof HttpServletRequest) {
            ((HttpServletRequest)request).getSession().invalidate();
        }

        final ServletOutputStream responseOutputStream = response.getOutputStream();
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("logout.jpg");
        if (inputStream == null) {
            LOG.warn("Could not write logout.jpg");
            return;
        }
        int read = 0;
        byte[] buf = new byte[1024];
        while ((read = inputStream.read(buf)) != -1) {
            responseOutputStream.write(buf, 0, read);
        }
        inputStream.close();
        responseOutputStream.flush();
    } else {
        chain.doFilter(request, response);
    }
}
 
Example 6
Source File: XSSWebAppSRSOSDelay.java    From spiracle with Apache License 2.0 5 votes vote down vote up
@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
    try {
        Thread.sleep(10000);
    } catch (Exception e) {
        e.printStackTrace();
    }
    res.setContentType("text/html");
    ServletOutputStream out = res.getOutputStream();
    ReadHTML.readHTML(out, req.getParameter("taintedtext"), req);
}
 
Example 7
Source File: RequestCacheFilterImplTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void testDoFilterCompressesOutput() throws Exception {

      // Init
      final FilterConfig filterConfig = mockFilterConfig();
      requestCacheFilter.init(filterConfig);


      // Prepare
      final ServletOutputStream servletOutputStream = mock(ServletOutputStream.class);
      final HttpServletResponse httpServletResponse = mock(HttpServletResponse.class);
      when(httpServletResponse.getOutputStream()).thenReturn(servletOutputStream);

      //
      final HttpServletRequest httpServletRequest = mockRequest();
      when(httpServletRequest.getHeader(HEADER_ACCEPT_ENCODING)).thenReturn("gzip");

      final FilterChain filterChain = new FilterChain() {

         public void doFilter(final ServletRequest servletRequest,
                 final ServletResponse servletResponse) throws IOException {

            // Set content type
            servletResponse.setContentType("text/html");

            // Output
            final ServletOutputStream outputStream = servletResponse.getOutputStream();
            outputStream.write(new byte[]{0,1,2,3,4,5,6,7,8,9});
         }
      };

      // Do filter pass # 1
      requestCacheFilter.doFilter(httpServletRequest, httpServletResponse, filterChain);

      // Do filter pass # 2
      requestCacheFilter.doFilter(httpServletRequest, httpServletResponse, filterChain);

      //
      verify(httpServletResponse).setHeader(HEADER_ENCODING, GZIP);
   }
 
Example 8
Source File: BarcodeServlet.java    From feilong-taglib with Apache License 2.0 5 votes vote down vote up
/**
 * Encode.
 *
 * @param barcodeContentsAndConfig
 *            the barcode contents and config
 * @param response
 *            the response
 */
private static void render(BarcodeContentsAndConfig barcodeContentsAndConfig,ServletResponse response){
    try{
        ServletOutputStream outputStream = response.getOutputStream();
        BarcodeEncodeUtil.encode(barcodeContentsAndConfig.getContents(), outputStream, barcodeContentsAndConfig.getBarcodeConfig());
    }catch (IOException e){
        throw new UncheckedIOException(Slf4jUtil.format("barcodeContentsAndConfig:{}", JsonUtil.format(barcodeContentsAndConfig)), e);
    }
}
 
Example 9
Source File: ResponseHandlerBase.java    From development with Apache License 2.0 5 votes vote down vote up
/**
 * Writes the entire stream from the method to the response stream.
 * 
 * @param response
 *            Response to send data to
 * @throws IOException
 *             An IOException is thrown when we are having problems with
 *             reading the streams
 */
protected void sendStreamToClient(ServletResponse response)
        throws IOException {
    InputStream streamFromServer = method.getResponseBodyAsStream();
    OutputStream responseStream = null;

    if (streamFromServer != null) {
        byte[] buffer = new byte[1024];
        int read = streamFromServer.read(buffer);
        while (read > 0) {
            if (responseStream == null) {
                responseStream = response.getOutputStream();
            }
            responseStream.write(buffer, 0, read);
            read = streamFromServer.read(buffer);
        }
        streamFromServer.close();
    }
    // pock: if we dont't have any content set the length to 0 (corrects the
    // 302 Moved Temporarily processing)
    if (responseStream == null) {
        response.setContentLength(0);
    } else {
        responseStream.flush();
        responseStream.close();
    }
}
 
Example 10
Source File: ServletResponseMethodArgumentResolver.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private Object resolveArgument(Class<?> paramType, ServletResponse response) throws IOException {
	if (OutputStream.class.isAssignableFrom(paramType)) {
		return response.getOutputStream();
	}
	else if (Writer.class.isAssignableFrom(paramType)) {
		return response.getWriter();
	}

	// Should never happen...
	throw new UnsupportedOperationException("Unknown parameter type: " + paramType);
}
 
Example 11
Source File: AjaxAuthenticationFilter.java    From java-platform with Apache License 2.0 5 votes vote down vote up
protected void writeObject(ServletRequest request, ServletResponse response, Object result) throws IOException {
	String characterEncoding = ((HttpServletRequest) request).getCharacterEncoding();
	Charset charset = Strings.isNullOrEmpty(characterEncoding) ? DEFAULT_CHARSET : Charset.forName(characterEncoding);
	OutputStreamWriter out = new OutputStreamWriter(response.getOutputStream(), charset);
	SerializeWriter writer = new SerializeWriter(out);
	JSONSerializer serializer = new JSONSerializer(writer, SpringContext.getBean(SerializeConfig.class));
	serializer.config(SerializerFeature.DisableCircularReferenceDetect, true);
	serializer.write(result);
	writer.flush();
	out.close();
}
 
Example 12
Source File: CommonAuthResponseWrapper.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
private void writeContent() throws IOException {
    byte[] content = getContent();
    ServletResponse response = getResponse();
    OutputStream os = response.getOutputStream();

    response.setContentLength(content.length);
    os.write(content);
    os.close();
}
 
Example 13
Source File: ServletBlockingHttpExchange.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public OutputStream getOutputStream() {
    ServletResponse response = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY).getServletResponse();
    try {
        return response.getOutputStream();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 14
Source File: ServletResponseMethodArgumentResolver.java    From java-technology-stack with MIT License 5 votes vote down vote up
private Object resolveArgument(Class<?> paramType, ServletResponse response) throws IOException {
	if (OutputStream.class.isAssignableFrom(paramType)) {
		return response.getOutputStream();
	}
	else if (Writer.class.isAssignableFrom(paramType)) {
		return response.getWriter();
	}

	// Should never happen...
	throw new UnsupportedOperationException("Unknown parameter type: " + paramType);
}
 
Example 15
Source File: ServletBlockingHttpExchange.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Override
public OutputStream getOutputStream() {
    ServletResponse response = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY).getServletResponse();
    try {
        try {
            return response.getOutputStream();
        } catch (IllegalStateException ex) {
            return new WriterOutputStream(exchange, response.getWriter(), response.getCharacterEncoding());
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 16
Source File: MCRURIResolverFilter.java    From mycore with GNU General Public License v3.0 4 votes vote down vote up
/**
 * adds debug information from MCRURIResolver to Servlet output.
 * 
 * The information includes all URIs resolved by MCRURIResolver by the
 * current request. The filter is triggered by the log4j statement of the
 * MCRURIResolver. To switch it on set the logger to DEBUG level.
 * 
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
 *      javax.servlet.ServletResponse, javax.servlet.FilterChain)
 */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException,
    ServletException {
    /*
     * isDebugEnabled() may return a different value when called a second
     * time. Since we initialize things in the first block, we need to make
     * sure to visit the second block only if we visited the first block,
     * too.
     */
    final boolean debugEnabled = LOGGER.isDebugEnabled();
    if (!debugEnabled) {
        //do not filter...
        filterChain.doFilter(request, response);
    } else {
        MyResponseWrapper wrapper = new MyResponseWrapper((HttpServletResponse) response);
        // process request
        filterChain.doFilter(request, wrapper);
        final String origOutput = wrapper.toString();
        final String characterEncoding = wrapper.getCharacterEncoding();
        if (!uriList.get().isEmpty() && origOutput.length() > 0
            && (response.getContentType().contains("text/html")
                || response.getContentType().contains("text/xml"))) {
            final String insertString = "\n<!-- \n" + uriList.get() + "\n-->";
            final byte[] insertBytes = insertString.getBytes(characterEncoding);
            response.setContentLength(origOutput.getBytes(characterEncoding).length + insertBytes.length);
            int pos = getInsertPosition(origOutput);
            try (ServletOutputStream out = response.getOutputStream()) {
                out.write(origOutput.substring(0, pos).getBytes(characterEncoding));
                out.write(insertBytes);
                out.write(origOutput.substring(pos).getBytes(characterEncoding));
                // delete debuglist
                uriList.remove();
                LOGGER.debug("end filter: {}", origOutput.substring(origOutput.length() - 10));
            }
        } else {
            LOGGER.debug("Sending original response");
            byte[] byteArray = wrapper.output.toByteArray();
            if (byteArray.length > 0) {
                try (ServletOutputStream out = response.getOutputStream()) {
                    out.write(byteArray);
                }
            }
        }
    }
}
 
Example 17
Source File: LocalResponse.java    From logbook with MIT License 4 votes vote down vote up
default ServletOutputStream getOutputStream(
        final ServletResponse response) throws IOException {

    return response.getOutputStream();
}
 
Example 18
Source File: LocalResponse.java    From logbook with MIT License 4 votes vote down vote up
@Override
public State buffer(final ServletResponse response) throws IOException {
    final Tee tee = new Tee(response.getOutputStream());
    return new Buffering(tee);
}
 
Example 19
Source File: ResponseRewriter.java    From jease with GNU General Public License v3.0 4 votes vote down vote up
public ResponseRewriter(ServletResponse response, Function<String, String> rewriter) throws IOException {
	super((HttpServletResponse) response);
	this.printWriter = new Rewriter(response.getOutputStream(), rewriter);
}
 
Example 20
Source File: XSSWebAppSRSOS.java    From spiracle with Apache License 2.0 4 votes vote down vote up
@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
    res.setContentType("text/html");
    ServletOutputStream out = res.getOutputStream();
    ReadHTML.readHTML(out, req.getParameter("taintedtext"), req);
}