Java Code Examples for javax.servlet.ServletOutputStream#setWriteListener()

The following examples show how to use javax.servlet.ServletOutputStream#setWriteListener() . 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: AsyncServlet.java    From tutorials with MIT License 6 votes vote down vote up
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    ByteBuffer content = ByteBuffer.wrap(HEAVY_RESOURCE.getBytes(StandardCharsets.UTF_8));

    AsyncContext async = request.startAsync();
    ServletOutputStream out = response.getOutputStream();
    out.setWriteListener(new WriteListener() {
        @Override
        public void onWritePossible() throws IOException {
            while (out.isReady()) {
                if (!content.hasRemaining()) {
                    response.setStatus(200);
                    async.complete();
                    return;
                }
                out.write(content.get());
            }
        }

        @Override
        public void onError(Throwable t) {
            getServletContext().log("Async Error", t);
            async.complete();
        }
    });
}
 
Example 2
Source File: AccessLogFilter.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@Override
public ServletOutputStream getOutputStream() throws IOException {

  final ServletOutputStream outputStream = d.getOutputStream();
  return new ServletOutputStream() {

    @Override
    public void write(int b) throws IOException {
      respBody.write(b);
      outputStream.write(b);
    }

    @Override
    public void setWriteListener(WriteListener writeListener) {
      outputStream.setWriteListener(writeListener);
    }

    @Override
    public boolean isReady() {
      return outputStream.isReady();
    }
  };
}
 
Example 3
Source File: TestIoTimeouts.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    // Need to be in async mode to use non-blocking I/O
    AsyncContext ac = req.startAsync();
    ac.setTimeout(10000);

    ServletInputStream sis = null;
    ServletOutputStream sos = null;

    try {
        sis = req.getInputStream();
        sos = resp.getOutputStream();
    } catch (IOException ioe) {
        throw new ServletException(ioe);
    }

    EchoListener listener = new EchoListener(ac, sis, sos);
    sis.setReadListener(listener);
    sos.setWriteListener(listener);
}
 
Example 4
Source File: TestUpgrade.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Override
public void init(WebConnection connection) {
    ServletInputStream sis;
    ServletOutputStream sos;

    try {
        sis = connection.getInputStream();
        sos = connection.getOutputStream();
    } catch (IOException ioe) {
        throw new IllegalStateException(ioe);
    }

    EchoListener echoListener = new EchoListener(sis, sos);
    sis.setReadListener(echoListener);
    sos.setWriteListener(echoListener);
}
 
Example 5
Source File: TestUpgrade.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
public void init(WebConnection connection) {
    ServletOutputStream sos;
    try {
        sos = connection.getOutputStream();
    } catch (IOException ioe) {
        throw new IllegalStateException(ioe);
    }
    sos.setWriteListener(null);
}
 
Example 6
Source File: JSON.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * The JSON serialization is performed on the request processing thread and
 * the response is sent back asynchronously.
 */
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
		IOException {
	final AsyncContext async = req.startAsync();
	final ServletOutputStream out = resp.getOutputStream();
	LOGGER.debug("JSON sync start");
	resp.setContentType(Helper.MEDIATYPE_APPLICATION_JSON);
	byte[] content = mapper.writeValueAsBytes(new HelloMessage());
	out.setWriteListener(new WriteListener() {
		@Override
		public void onWritePossible() throws IOException {
			byte[] buffer = new byte[32];
			ByteArrayInputStream is = new ByteArrayInputStream(content);

			while (out.isReady()) {
				int len = is.read(buffer);

				if (len < 0) {
					async.complete();
					LOGGER.debug("JSON async end");
					return;
				}
				out.write(buffer, 0, len);
			}
		}

		@Override
		public void onError(Throwable t) {
			LOGGER.error("JSON async error", t);
			async.complete();
		}
	});
}
 
Example 7
Source File: Plaintext.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
		IOException {
	final AsyncContext async = req.startAsync();
	final ServletOutputStream out = resp.getOutputStream();
	LOGGER.debug("plaintext async start");
	resp.setContentType(Helper.MEDIATYPE_TEXT_PLAIN);

	out.setWriteListener(new WriteListener() {
		@Override
		public void onWritePossible() throws IOException {
			byte[] buffer = new byte[32];
			ByteArrayInputStream is = new ByteArrayInputStream(Helper.CONTENT);

			while (out.isReady()) {
				int len = is.read(buffer);

				if (len < 0) {
					async.complete();
					LOGGER.debug("plaintext async end");
					return;
				}
				out.write(buffer, 0, len);
			}
		}

		@Override
		public void onError(Throwable t) {
			LOGGER.error("plaintext async error", t);
			async.complete();
		}
	});
}
 
Example 8
Source File: HelloWorldServer.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
private void asyncGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
  String str = body.concat("<h3>async</h3>");
  ByteBuffer content = ByteBuffer.wrap(str.getBytes(StandardCharsets.UTF_8));

  AsyncContext async = request.startAsync();
  response.setContentType("text/html");
  try {
    Thread.sleep(100);
  } catch (Exception e) {
    logger.info("Error sleeping");
  }
  ServletOutputStream out = response.getOutputStream();
  out.setWriteListener(
      new WriteListener() {
        @Override
        public void onWritePossible() throws IOException {
          while (out.isReady()) {
            if (!content.hasRemaining()) {
              response.setStatus(200);
              async.complete();
              return;
            }
            out.write(content.get());
          }
        }

        @Override
        public void onError(Throwable t) {
          logger.info("Server onError callled");
          getServletContext().log("Async Error", t);
          async.complete();
        }
      });
}
 
Example 9
Source File: TestUpgrade.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
public void init(WebConnection connection) {
    ServletInputStream sis;
    ServletOutputStream sos;
    try {
        sis = connection.getInputStream();
        sos = connection.getOutputStream();
    } catch (IOException ioe) {
        throw new IllegalStateException(ioe);
    }
    sis.setReadListener(new NoOpReadListener());
    WriteListener wl = new NoOpWriteListener();
    sos.setWriteListener(wl);
    sos.setWriteListener(wl);
}
 
Example 10
Source File: TestUpgrade.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
public void init(WebConnection connection) {
    ServletInputStream sis;
    ServletOutputStream sos;
    try {
        sis = connection.getInputStream();
        sos = connection.getOutputStream();
    } catch (IOException ioe) {
        throw new IllegalStateException(ioe);
    }
    sos.setWriteListener(new NoOpWriteListener());
    ReadListener rl = new NoOpReadListener();
    sis.setReadListener(rl);
    sis.setReadListener(rl);
}
 
Example 11
Source File: ByteCounter.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
private CounterListener(AsyncContext ac, ServletInputStream sis,
        ServletOutputStream sos) {
    this.ac = ac;
    this.sis = sis;
    this.sos = sos;

    // In Tomcat, the order the listeners are set controls the order
    // that the first calls are made. In this case, the read listener
    // will be called before the write listener.
    sis.setReadListener(this);
    sos.setWriteListener(this);
}
 
Example 12
Source File: TestAsyncFlush.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response)
        throws IOException {

    final AsyncContext asyncContext = request.startAsync();

    response.setStatus(HttpServletResponse.SC_OK);
    response.setContentType("application/binary");

    final ServletOutputStream output = response.getOutputStream();
    output.setWriteListener(new WriteListener() {

        int blockCount;
        byte[] bytes = new byte[BLOCK_SIZE];


        @Override
        public void onWritePossible() throws IOException {
            while (output.isReady()) {
                blockCount++;
                output.write(bytes);
                if (blockCount % 5 == 0) {
                    response.flushBuffer();
                }
                if (blockCount == blockLimit) {
                    asyncContext.complete();
                    return;
                }
            }
        }


        @Override
        public void onError(Throwable t) {
            t.printStackTrace();
        }
    });
}
 
Example 13
Source File: TestAsyncContextImpl.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    if (useComplete) {
        // Write expected body here
        resp.setContentType("text/plain");
        resp.setCharacterEncoding("UTF-8");
        resp.getOutputStream().write("OK".getBytes(StandardCharsets.UTF_8));
    }
    AsyncContext ac = req.startAsync();
    ServletOutputStream sos = resp.getOutputStream();
    asyncIoEndWriteListener= new AsyncIoEndWriteListener(ac, useThread, useComplete);
    sos.setWriteListener(asyncIoEndWriteListener);
}
 
Example 14
Source File: NumberWriter.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
private NumberWriterListener(AsyncContext ac, ServletInputStream sis,
        ServletOutputStream sos) {
    this.ac = ac;
    this.sis = sis;
    this.sos = sos;

    // In Tomcat, the order the listeners are set controls the order
    // that the first calls are made. In this case, the read listener
    // will be called before the write listener.
    sis.setReadListener(this);
    sos.setWriteListener(this);
}
 
Example 15
Source File: ByteCounter.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
private CounterListener(AsyncContext ac, ServletInputStream sis,
        ServletOutputStream sos) {
    this.ac = ac;
    this.sis = sis;
    this.sos = sos;

    // In Tomcat, the order the listeners are set controls the order
    // that the first calls are made. In this case, the read listener
    // will be called before the write listener.
    sis.setReadListener(this);
    sos.setWriteListener(this);
}
 
Example 16
Source File: NumberWriter.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
private NumberWriterListener(AsyncContext ac, ServletInputStream sis,
        ServletOutputStream sos) {
    this.ac = ac;
    this.sis = sis;
    this.sos = sos;

    // In Tomcat, the order the listeners are set controls the order
    // that the first calls are made. In this case, the read listener
    // will be called before the write listener.
    sis.setReadListener(this);
    sos.setWriteListener(this);
}
 
Example 17
Source File: AsyncOutputStreamServlet.java    From quarkus-http with Apache License 2.0 4 votes vote down vote up
@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
    final boolean flush = req.getParameter("flush") != null;
    final boolean close = req.getParameter("close") != null;
    final boolean preable = req.getParameter("preamble") != null;
    final boolean offIoThread = req.getParameter("offIoThread") != null;
    final int reps = Integer.parseInt(req.getParameter("reps"));

    final AtomicInteger count = new AtomicInteger();

    final AsyncContext context = req.startAsync();
    final ServletOutputStream outputStream = resp.getOutputStream();
    if(preable) {
        for(int i = 0; i < reps; ++i) {
            outputStream.write(ServletOutputStreamTestCase.message.getBytes());
        }
    }
    WriteListener listener = new WriteListener() {
        @Override
        public synchronized void onWritePossible() throws IOException {
            while (outputStream.isReady() && count.get() < reps) {
                count.incrementAndGet();
                outputStream.write(ServletOutputStreamTestCase.message.getBytes());
            }
            if (count.get() == reps) {
                if (flush) {
                    outputStream.flush();
                }
                if (close) {
                    outputStream.close();
                }
                context.complete();
            }
        }

        @Override
        public void onError(final Throwable t) {

        }
    };
    outputStream.setWriteListener(offIoThread ? new WriteListener() {
        @Override
        public void onWritePossible() throws IOException {
            context.start(new Runnable() {
                @Override
                public void run() {
                    try {
                        listener.onWritePossible();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
        }

        @Override
        public void onError(Throwable throwable) {

        }
    } : listener);
}
 
Example 18
Source File: TestAsync.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException {

    final AsyncContext asyncContext = request.startAsync();

    response.setStatus(HttpServletResponse.SC_OK);
    response.setContentType("application/binary");

    final ServletOutputStream output = response.getOutputStream();
    output.setWriteListener(new WriteListener() {

        // Intermittent CI errors were observed where the response body
        // was exactly one block too small. Use an AtomicInteger to be
        // sure blockCount is thread-safe.
        final AtomicInteger blockCount = new AtomicInteger(0);
        byte[] bytes = new byte[BLOCK_SIZE];


        @Override
        public void onWritePossible() throws IOException {
            if (useNonContainerThreadForWrite) {
                future = scheduler.schedule(new Runnable() {

                    @Override
                    public void run() {
                        try {
                            write();
                        } catch (IOException e) {
                            throw new IllegalStateException(e);
                        }
                    }
                }, 200, TimeUnit.MILLISECONDS);
            } else {
                write();
            }
        }


        private void write() throws IOException {
            while (output.isReady()) {
                blockCount.incrementAndGet();
                output.write(bytes);
                if (blockCount.get()  == blockLimit) {
                    asyncContext.complete();
                    scheduler.shutdown();
                    return;
                }
            }
        }

        @Override
        public void onError(Throwable t) {
            if (future != null) {
                future.cancel(false);
            }
            t.printStackTrace();
        }
    });
}
 
Example 19
Source File: PingServlet31Async.java    From sample.daytrader7 with Apache License 2.0 4 votes vote down vote up
public void onAllDataRead() throws IOException {
    ServletOutputStream output = res.getOutputStream();
    WriteListener writeListener = new WriteListenerImpl(output, queue, ac);
    output.setWriteListener(writeListener);
}