javax.servlet.WriteListener Java Examples

The following examples show how to use javax.servlet.WriteListener. 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: ConnectionTerminationServlet.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    req.startAsync();

    resp.getOutputStream().print("hi");
    resp.getOutputStream().setWriteListener(new WriteListener() {
        @Override
        public void onWritePossible() throws IOException {

        }

        @Override
        public void onError(Throwable t) {

        }
    });
    HttpServerExchange exchange = ServletRequestContext.current().getExchange();
    try {
        exchange.close();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
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: LocalResponseTest.java    From logbook with MIT License 6 votes vote down vote up
@BeforeEach
void setUp() throws IOException {
    mock = mock(HttpServletResponse.class);
    when(mock.getOutputStream()).thenReturn(new ServletOutputStream() {
        @Override
        public boolean isReady() {
            return false;
        }

        @Override
        public void setWriteListener(final WriteListener listener) {
            // nothing to do here
        }

        @Override
        public void write(final int b) {
            // serves as a null or no-op output stream
        }
    });
    unit = new LocalResponse(mock, "1");
}
 
Example #4
Source File: UpgradeServletOutputStream.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Override
public final void setWriteListener(WriteListener listener) {
    if (listener == null) {
        throw new IllegalArgumentException(
                sm.getString("upgrade.sos.writeListener.null"));
    }
    if (this.listener != null) {
        throw new IllegalArgumentException(
                sm.getString("upgrade.sos.writeListener.set"));
    }
    if (closed) {
        throw new IllegalStateException(sm.getString("upgrade.sos.write.closed"));
    }
    this.listener = listener;
    // Container is responsible for first call to onWritePossible().
    synchronized (registeredLock) {
        registered = true;
        // Container is responsible for first call to onDataAvailable().
        if (ContainerThreadMarker.isContainerThread()) {
            processor.addDispatch(DispatchType.NON_BLOCKING_WRITE);
        } else {
            socketWrapper.registerWriteInterest();
        }
    }

}
 
Example #5
Source File: CharResponseWrapper.java    From TeaStore with Apache License 2.0 6 votes vote down vote up
/**
 * Getter for output stream.
 * 
 * @return ServletOutputStream
 */
@Override
public ServletOutputStream getOutputStream() throws IOException {
  // This is the magic to prevent closing stream, create a "virtual" stream that
  // does nothing..
  return new ServletOutputStream() {
    @Override
    public void write(int b) throws IOException {
      output.write(b);
    }

    @Override
    public void setWriteListener(WriteListener writeListener) {
    }

    @Override
    public boolean isReady() {
      return true;
    }
  };
}
 
Example #6
Source File: ResponseWrapper.java    From wisp with Apache License 2.0 6 votes vote down vote up
@Override
public ServletOutputStream getOutputStream() throws IOException {
    return new ServletOutputStream() {
        @Override
        public boolean isReady() {
            return false;
        }

        @Override
        public void setWriteListener(WriteListener writeListener) {

        }

        private TeeOutputStream tee = new TeeOutputStream(ResponseWrapper.super.getOutputStream(), bos);

        @Override
        public void write(int b) throws IOException {
            tee.write(b);
        }
    };
}
 
Example #7
Source File: TestNonBlockingAPI.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
void emit() throws IOException {
    ctx.getResponse().getOutputStream().setWriteListener(new WriteListener() {
        private boolean written = false;

        @Override
        public void onWritePossible() throws IOException {
            ServletOutputStream out = ctx.getResponse().getOutputStream();
            if (out.isReady() && !written) {
                out.println("OK");
                written = true;
            }
            if (out.isReady() && written) {
                out.flush();
                if (out.isReady()) {
                    ctx.complete();
                }
            }
        }

        @Override
        public void onError(Throwable t) {
            t.printStackTrace();
        }

    });
}
 
Example #8
Source File: ProxyExchange.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Override
public ServletOutputStream getOutputStream() throws IOException {
	return new ServletOutputStream() {

		@Override
		public void write(int b) throws IOException {
			builder.append(new Character((char) b));
		}

		@Override
		public void setWriteListener(WriteListener listener) {
		}

		@Override
		public boolean isReady() {
			return true;
		}
	};
}
 
Example #9
Source File: ResponseWrapper.java    From app-engine with Apache License 2.0 6 votes vote down vote up
@Override
public ServletOutputStream getOutputStream() throws IOException {
    return new ServletOutputStream() {
        private TeeOutputStream tee = new TeeOutputStream(ResponseWrapper.super.getOutputStream(), bos);

        @Override
        public boolean isReady() {
            return true;
        }

        @Override
        public void setWriteListener(WriteListener writeListener) {
        }

        @Override
        public void write(int b) throws IOException {
            tee.write(b);
        }
    };
}
 
Example #10
Source File: UpgradeServletOutputStream.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void setWriteListener(final WriteListener writeListener) {
    if (writeListener == null) {
        throw UndertowServletMessages.MESSAGES.paramCannotBeNull("writeListener");
    }
    if (listener != null) {
        throw UndertowServletMessages.MESSAGES.listenerAlreadySet();
    }
    listener = writeListener;
    channel.getWriteSetter().set(new WriteChannelListener());
    state |= FLAG_READY;
    ioExecutor.execute(new Runnable() {
        @Override
        public void run() {
            channel.resumeWrites();
        }
    });
}
 
Example #11
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 #12
Source File: WebConnectionImpl.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Override
public void setWriteListener(WriteListener w) {
    writeListener = w;
    try {
        w.onWritePossible();
    } catch (IOException e) {
        writeListener.onError(e);
    }
}
 
Example #13
Source File: ServletOutputStreamImpl.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Override
public void setWriteListener(WriteListener writeListener) {
    if (writeListener == null) {
        throw UndertowServletMessages.MESSAGES.listenerCannotBeNull();
    }
    if (listener != null) {
        throw UndertowServletMessages.MESSAGES.listenerAlreadySet();
    }
    final ServletRequest servletRequest = servletRequestContext.getOriginalRequest();
    if (!servletRequest.isAsyncStarted()) {
        throw UndertowServletMessages.MESSAGES.asyncNotStarted();
    }
    listener = writeListener;
    listenerCallback = new ListenerCallback();
    servletRequestContext.getOriginalRequest().getAsyncContext().addAsyncTask(new Runnable() {
        @Override
        public void run() {
            //TODO: hack to make sure the invocation happens in the callback loop, to prevent recursive callbacks
            exchange.getIoThread().execute(new Runnable() {
                @Override
                public void run() {
                    listenerCallback.onComplete(null, null);
                }
            });
        }
    });
}
 
Example #14
Source File: ServletContextImpl.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
void invokeOnWritePossible(HttpServerExchange exchange, WriteListener listener) {
    try {
        this.onWritePossibleTask.call(exchange, listener);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #15
Source File: TestHttpResponseWrapper.java    From HttpSessionReplacer with MIT License 5 votes vote down vote up
@Before
public void setupWrapper() throws IOException {
  requestWrapper = mock(HttpRequestWrapper.class);
  response = mock(HttpServletResponse.class);
  manager = mock(SessionManager.class);
  configuration = new SessionConfiguration();
  when(manager.getConfiguration()).thenReturn(configuration);
  when(requestWrapper.getManager()).thenReturn(manager );
  responseWrapper = new HttpResponseWrapper31(requestWrapper, response);
  outputStream = new ByteArrayOutputStream();
  outputWriter = new StringWriter();
  when(response.getOutputStream()).thenReturn(new ServletOutputStream() {
    @Override
    public void write(int b) throws IOException {
      outputStream.write(b);
    }

    @Override
    public void setWriteListener(WriteListener writeListener) {
    }

    @Override
    public boolean isReady() {
      return false;
    }
  });
  when(response.getWriter()).thenReturn(new PrintWriter(outputWriter));
}
 
Example #16
Source File: ServletOutputStreamImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void setWriteListener(final WriteListener writeListener) {
    if (writeListener == null) {
        throw UndertowServletMessages.MESSAGES.listenerCannotBeNull();
    }
    if (listener != null) {
        throw UndertowServletMessages.MESSAGES.listenerAlreadySet();
    }
    final ServletRequest servletRequest = servletRequestContext.getOriginalRequest();
    if (!servletRequest.isAsyncStarted()) {
        throw UndertowServletMessages.MESSAGES.asyncNotStarted();
    }
    asyncContext = (AsyncContextImpl) servletRequest.getAsyncContext();
    listener = writeListener;
    //we register the write listener on the underlying connection
    //so we don't have to force the creation of the response channel
    //under normal circumstances this will break write listener delegation
    this.internalListener = new WriteChannelListener();
    if (this.channel != null) {
        this.channel.getWriteSetter().set(internalListener);
    }
    //we resume from an async task, after the request has been dispatched
    asyncContext.addAsyncTask(new Runnable() {
        @Override
        public void run() {
            if (channel == null) {
                servletRequestContext.getExchange().getIoThread().execute(new Runnable() {
                    @Override
                    public void run() {
                        internalListener.handleEvent(null);
                    }
                });
            } else {
                channel.resumeWrites();
            }
        }
    });
}
 
Example #17
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 #18
Source File: ServletContextImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
void invokeOnWritePossible(HttpServerExchange exchange, WriteListener listener) {
    try {
        this.onWritePossibleTask.call(exchange, listener);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #19
Source File: TestStandardHttpServletResponseEx.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void flushBuffer() throws IOException {
  Buffer buffer = Buffer.buffer();
  ServletOutputStream output = new ServletOutputStream() {
    @Override
    public boolean isReady() {
      return true;
    }

    @Override
    public void setWriteListener(WriteListener writeListener) {

    }

    @Override
    public void write(int b) throws IOException {
      buffer.appendByte((byte) b);
    }
  };
  response = new MockUp<HttpServletResponse>() {
    @Mock
    ServletOutputStream getOutputStream() {
      return output;
    }
  }.getMockInstance();
  responseEx = new StandardHttpServletResponseEx(response);

  // no body
  responseEx.flushBuffer();
  Assert.assertEquals(0, buffer.length());

  Buffer body = Buffer.buffer().appendString("body");
  responseEx.setBodyBuffer(body);
  responseEx.flushBuffer();
  Assert.assertEquals("body", buffer.toString());
}
 
Example #20
Source File: CachingHttpServletResponse.java    From juneau with Apache License 2.0 5 votes vote down vote up
@Override
public ServletOutputStream getOutputStream() throws IOException {
	return new ServletOutputStream() {

		@Override
		public boolean isReady() {
			return os.isReady();
		}

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

		@Override
		public void write(int b) throws IOException {
			baos.write(b);
			os.write(b);
		}

		@Override
		public void flush() throws IOException {
			os.flush();
		}

		@Override
		public void close() throws IOException {
			os.close();
		}
	};
}
 
Example #21
Source File: HttpResponseOutputStream.java    From spring-boot-starter-netty with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void setWriteListener(WriteListener writeListener) {
    checkNotNull(writeListener);
    if(this.writeListener != null){
        return; //只能设置一次
    }
    this.writeListener = writeListener;
    // TODO ISE when called more than once
    // TODO ISE when associated request is not async
}
 
Example #22
Source File: ServletOutputStreamImpl.java    From ByteTCC with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void setWriteListener(WriteListener listener) {
}
 
Example #23
Source File: FilterInvokingServletOutputStream.java    From vespa with Apache License 2.0 4 votes vote down vote up
@Override
public void setWriteListener(WriteListener writeListener) {
    delegate.setWriteListener(writeListener);
}
 
Example #24
Source File: IconServletTest.java    From openhab-core with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public void setWriteListener(WriteListener arg0) {
}
 
Example #25
Source File: LocalResponse.java    From logbook with MIT License 4 votes vote down vote up
@Override
public void setWriteListener(final WriteListener listener) {
    original.setWriteListener(listener);
}
 
Example #26
Source File: HttpResponseWrapper.java    From HttpSessionReplacer with MIT License 4 votes vote down vote up
@Override
public void setWriteListener(WriteListener writeListener) {
  // Only for Servlet 3.1
}
 
Example #27
Source File: InMemoryResponse.java    From component-runtime with Apache License 2.0 4 votes vote down vote up
@Override
public void setWriteListener(final WriteListener listener) {
    // no-op
}
 
Example #28
Source File: RedisFilter.java    From seed with Apache License 2.0 4 votes vote down vote up
@Override
public void setWriteListener(WriteListener listener) {
    throw new UnsupportedOperationException("UnsupportedMethod setWriteListener.");
}
 
Example #29
Source File: OpenFilter.java    From seed with Apache License 2.0 4 votes vote down vote up
@Override
public void setWriteListener(WriteListener listener) {
    throw new UnsupportedOperationException("UnsupportedMethod setWriteListener.");
}
 
Example #30
Source File: HttpResponseOutputStream.java    From Jinx with Apache License 2.0 4 votes vote down vote up
@Override
public void setWriteListener(WriteListener writeListener) {
    checkNotNull(writeListener);
    // TODO ISE when called more than once
    // TODO ISE when associated request is not async
}