org.xnio.channels.StreamSinkChannel Java Examples
The following examples show how to use
org.xnio.channels.StreamSinkChannel.
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: UndertowServerHttpResponse.java From spring-analysis-note with MIT License | 6 votes |
@Override public Mono<Void> writeWith(Path file, long position, long count) { return doCommit(() -> Mono.create(sink -> { try { FileChannel source = FileChannel.open(file, StandardOpenOption.READ); TransferBodyListener listener = new TransferBodyListener(source, position, count, sink); sink.onDispose(listener::closeSource); StreamSinkChannel destination = this.exchange.getResponseChannel(); destination.getWriteSetter().set(listener::transfer); listener.transfer(destination); } catch (IOException ex) { sink.error(ex); } })); }
Example #2
Source File: ServerSentEventConnection.java From lams with GNU General Public License v2.0 | 6 votes |
public ServerSentEventConnection(HttpServerExchange exchange, StreamSinkChannel sink) { this.exchange = exchange; this.sink = sink; this.sink.getCloseSetter().set(new ChannelListener<StreamSinkChannel>() { @Override public void handleEvent(StreamSinkChannel channel) { if(timerKey != null) { timerKey.remove(); } for (ChannelListener<ServerSentEventConnection> listener : closeTasks) { ChannelListeners.invokeChannelListener(ServerSentEventConnection.this, listener); } IoUtils.safeClose(ServerSentEventConnection.this); } }); this.sink.getWriteSetter().set(writeListener); }
Example #3
Source File: HttpContinueReadHandler.java From lams with GNU General Public License v2.0 | 6 votes |
@Override public long transferTo(final long count, final ByteBuffer throughBuffer, final StreamSinkChannel target) throws IOException { if (exchange.getStatusCode() == StatusCodes.EXPECTATION_FAILED) { //rejected return -1; } if (!sent) { sent = true; response = HttpContinue.createResponseSender(exchange); } if (response != null) { if (!response.send()) { return 0; } response = null; } return super.transferTo(count, throughBuffer, target); }
Example #4
Source File: HttpServerExchange.java From lams with GNU General Public License v2.0 | 6 votes |
/** * Get the response channel. The channel must be closed and fully flushed before the next response can be started. * In order to close the channel you must first call {@link org.xnio.channels.StreamSinkChannel#shutdownWrites()}, * and then call {@link org.xnio.channels.StreamSinkChannel#flush()} until it returns true. Alternatively you can * call {@link #endExchange()}, which will close the channel as part of its cleanup. * <p> * Closing a fixed-length response before the corresponding number of bytes has been written will cause the connection * to be reset and subsequent requests to fail; thus it is important to ensure that the proper content length is * delivered when one is specified. The response channel may not be writable until after the response headers have * been sent. * <p> * If this method is not called then an empty or default response body will be used, depending on the response code set. * <p> * The returned channel will begin to write out headers when the first write request is initiated, or when * {@link org.xnio.channels.StreamSinkChannel#shutdownWrites()} is called on the channel with no content being written. * Once the channel is acquired, however, the response code and headers may not be modified. * <p> * * @return the response channel, or {@code null} if another party already acquired the channel */ public StreamSinkChannel getResponseChannel() { if (responseChannel != null) { return null; } final ConduitWrapper<StreamSinkConduit>[] wrappers = responseWrappers; this.responseWrappers = null; final ConduitStreamSinkChannel sinkChannel = connection.getSinkChannel(); if (sinkChannel == null) { return null; } if(wrappers != null) { final WrapperStreamSinkConduitFactory factory = new WrapperStreamSinkConduitFactory(wrappers, responseWrapperCount, this, sinkChannel.getConduit()); sinkChannel.setConduit(factory.create()); } else { sinkChannel.setConduit(connection.getSinkConduit(this, sinkChannel.getConduit())); } this.responseChannel = new WriteDispatchChannel(sinkChannel); this.startResponse(); return responseChannel; }
Example #5
Source File: HttpReadListener.java From lams with GNU General Public License v2.0 | 6 votes |
private void sendBadRequestAndClose(final StreamConnection connection, final Throwable exception) { UndertowLogger.REQUEST_IO_LOGGER.failedToParseRequest(exception); connection.getSourceChannel().suspendReads(); new StringWriteChannelListener(BAD_REQUEST) { @Override protected void writeDone(final StreamSinkChannel c) { super.writeDone(c); c.suspendWrites(); IoUtils.safeClose(connection); } @Override protected void handleError(StreamSinkChannel channel, IOException e) { IoUtils.safeClose(connection); } }.setup(connection.getSinkChannel()); }
Example #6
Source File: FixedLengthStreamSourceConduit.java From lams with GNU General Public License v2.0 | 6 votes |
public long transferTo(final long count, final ByteBuffer throughBuffer, final StreamSinkChannel target) throws IOException { if (count == 0L) { return 0L; } long val = state; checkMaxSize(val); if (anyAreSet(val, FLAG_CLOSED | FLAG_FINISHED) || allAreClear(val, MASK_COUNT)) { if (allAreClear(val, FLAG_FINISHED)) { invokeFinishListener(); } return -1; } long res = 0L; try { return res = next.transferTo(min(count, val & MASK_COUNT), throughBuffer, target); } catch (IOException | RuntimeException | Error e) { IoUtils.safeClose(exchange.getConnection()); throw e; } finally { exitRead(res + throughBuffer.remaining()); } }
Example #7
Source File: WebSocketChannel.java From lams with GNU General Public License v2.0 | 6 votes |
/** * Send a Close frame without a payload */ public void sendClose() throws IOException { closeReason = ""; closeCode = CloseMessage.NORMAL_CLOSURE; StreamSinkFrameChannel closeChannel = send(WebSocketFrameType.CLOSE); closeChannel.shutdownWrites(); if (!closeChannel.flush()) { closeChannel.getWriteSetter().set(ChannelListeners.flushingChannelListener( null, new ChannelExceptionHandler<StreamSinkChannel>() { @Override public void handleException(final StreamSinkChannel channel, final IOException exception) { IoUtils.safeClose(WebSocketChannel.this); } } )); closeChannel.resumeWrites(); } }
Example #8
Source File: StringWriteChannelListener.java From lams with GNU General Public License v2.0 | 6 votes |
public void setup(final StreamSinkChannel channel) { try { int c; do { c = channel.write(buffer); } while (buffer.hasRemaining() && c > 0); if (buffer.hasRemaining()) { channel.getWriteSetter().set(this); channel.resumeWrites(); } else { writeDone(channel); } } catch (IOException e) { handleError(channel, e); } }
Example #9
Source File: StringWriteChannelListener.java From lams with GNU General Public License v2.0 | 6 votes |
@Override public void handleEvent(final StreamSinkChannel channel) { try { int c; do { c = channel.write(buffer); } while (buffer.hasRemaining() && c > 0); if (buffer.hasRemaining()) { channel.resumeWrites(); return; } else { writeDone(channel); } } catch (IOException e) { handleError(channel, e); } }
Example #10
Source File: StringWriteChannelListener.java From lams with GNU General Public License v2.0 | 6 votes |
protected void writeDone(final StreamSinkChannel channel) { try { channel.shutdownWrites(); if (!channel.flush()) { channel.getWriteSetter().set(ChannelListeners.flushingChannelListener(new ChannelListener<StreamSinkChannel>() { @Override public void handleEvent(StreamSinkChannel o) { IoUtils.safeClose(channel); } }, ChannelListeners.closingChannelExceptionHandler())); channel.resumeWrites(); } } catch (IOException e) { handleError(channel, e); } }
Example #11
Source File: AsyncSenderImpl.java From lams with GNU General Public License v2.0 | 6 votes |
private void initWriteListener() { writeListener = new ChannelListener<StreamSinkChannel>() { @Override public void handleEvent(final StreamSinkChannel streamSinkChannel) { try { long toWrite = Buffers.remaining(buffer); long written = 0; while (written < toWrite) { long res = streamSinkChannel.write(buffer, 0, buffer.length); written += res; if (res == 0) { return; } } streamSinkChannel.suspendWrites(); invokeOnComplete(); } catch (IOException e) { streamSinkChannel.suspendWrites(); invokeOnException(callback, e); } } }; }
Example #12
Source File: AsyncHttpHandler.java From rpc-benchmark with Apache License 2.0 | 6 votes |
/** * response * * @param exchange * @param statusCode * @param output * auto release */ protected final void send(HttpServerExchange exchange, int statusCode, PooledByteBufferOutputStream output) { try { output.flip(); StreamSinkChannel channel = getResponseChannel(exchange); Sender sender = exchange.getResponseSender(); setStatusCode(exchange, statusCode); setResponseChannel(sender, channel); setPooledBuffers(sender, output.getPooledByteBuffers()); sender.send(output.getByteBuffers()); } catch (Throwable t) { UndertowLogger.REQUEST_IO_LOGGER.handleUnexpectedFailure(t); } }
Example #13
Source File: UndertowServerHttpResponse.java From spring-analysis-note with MIT License | 6 votes |
public void transfer(StreamSinkChannel destination) { try { while (this.count > 0) { long len = destination.transferFrom(this.source, this.position, this.count); if (len != 0) { this.position += len; this.count -= len; } else { destination.resumeWrites(); return; } } this.sink.success(); } catch (IOException ex) { this.sink.error(ex); } }
Example #14
Source File: FinishableStreamSourceConduit.java From lams with GNU General Public License v2.0 | 5 votes |
public long transferTo(final long count, final ByteBuffer throughBuffer, final StreamSinkChannel target) throws IOException { long res = 0; try { return res = next.transferTo(count, throughBuffer, target); } finally { exitRead(res); } }
Example #15
Source File: UndertowServerHttpResponse.java From java-technology-stack with MIT License | 5 votes |
@Override protected void flush() throws IOException { StreamSinkChannel channel = UndertowServerHttpResponse.this.responseChannel; if (channel != null) { if (rsWriteFlushLogger.isTraceEnabled()) { rsWriteFlushLogger.trace(getLogPrefix() + "flush"); } channel.flush(); } }
Example #16
Source File: UndertowServerHttpResponse.java From java-technology-stack with MIT License | 5 votes |
@Override protected boolean isWritePossible() { StreamSinkChannel channel = UndertowServerHttpResponse.this.responseChannel; if (channel != null) { // We can always call flush, just ensure writes are on.. channel.resumeWrites(); return true; } return false; }
Example #17
Source File: AjpClientConnection.java From lams with GNU General Public License v2.0 | 5 votes |
private void handleFailedFlush(AjpClientRequestClientStreamSinkChannel sinkChannel) { sinkChannel.getWriteSetter().set(ChannelListeners.flushingChannelListener(null, new ChannelExceptionHandler<StreamSinkChannel>() { @Override public void handleException(StreamSinkChannel channel, IOException exception) { handleError(exception); } })); sinkChannel.resumeWrites(); }
Example #18
Source File: UndertowServerHttpResponse.java From spring-analysis-note with MIT License | 5 votes |
public ResponseBodyProcessor(StreamSinkChannel channel) { super(request.getLogPrefix()); Assert.notNull(channel, "StreamSinkChannel must not be null"); this.channel = channel; this.channel.getWriteSetter().set(c -> { this.writePossible = true; onWritePossible(); }); this.channel.suspendWrites(); }
Example #19
Source File: AsyncHttpHandler.java From rpc-benchmark with Apache License 2.0 | 5 votes |
/** * force set response channel * * @param sender * @param channel */ private void setResponseChannel(Sender sender, StreamSinkChannel channel) { if (!(sender instanceof AsyncSenderImpl)) { throw new RuntimeException("only support AsyncSenderImpl"); } unsafe().getAndSetObject(sender, asyncSenderImplChannelFieldOffset, channel); }
Example #20
Source File: ServerSentEventConnection.java From lams with GNU General Public License v2.0 | 5 votes |
private synchronized void close(IOException e) throws IOException { if (openUpdater.compareAndSet(this, 1, 0)) { if (pooled != null) { pooled.close(); pooled = null; } List<SSEData> cb = new ArrayList<>(buffered.size() + queue.size() + flushingMessages.size()); cb.addAll(buffered); cb.addAll(queue); cb.addAll(flushingMessages); queue.clear(); buffered.clear(); flushingMessages.clear(); for (SSEData i : cb) { if (i.callback != null) { try { i.callback.failed(this, i.data, i.event, i.id, e); } catch (Exception ex) { UndertowLogger.REQUEST_LOGGER.failedToInvokeFailedCallback(i.callback, ex); } } } sink.shutdownWrites(); if(!sink.flush()) { sink.getWriteSetter().set(ChannelListeners.flushingChannelListener(null, new ChannelExceptionHandler<StreamSinkChannel>() { @Override public void handleException(StreamSinkChannel channel, IOException exception) { IoUtils.safeClose(sink); } })); sink.resumeWrites(); } } }
Example #21
Source File: AsyncHttpHandler.java From rpc-benchmark with Apache License 2.0 | 5 votes |
/** * force get response channel * * @param exchange * @return */ private StreamSinkChannel getResponseChannel(HttpServerExchange exchange) { StreamSinkChannel channel = (StreamSinkChannel) unsafe().getObject(exchange, exchangeResponseChannelFieldOffset); if (channel == null) { channel = exchange.getResponseChannel(); } return channel; }
Example #22
Source File: HttpServerExchange.java From lams with GNU General Public License v2.0 | 5 votes |
@Override public long transferTo(long count, ByteBuffer throughBuffer, StreamSinkChannel target) throws IOException { PooledByteBuffer[] buffered = getAttachment(BUFFERED_REQUEST_DATA); if (buffered == null) { return super.transferTo(count, throughBuffer, target); } //make sure there is no garbage in throughBuffer throughBuffer.position(0); throughBuffer.limit(0); long copied = 0; for (int i = 0; i < buffered.length; ++i) { PooledByteBuffer pooled = buffered[i]; if (pooled != null) { final ByteBuffer buf = pooled.getBuffer(); if (buf.hasRemaining()) { int res = target.write(buf); if (!buf.hasRemaining()) { pooled.close(); buffered[i] = null; } if (res == 0) { return copied; } else { copied += res; } } else { pooled.close(); buffered[i] = null; } } } removeAttachment(BUFFERED_REQUEST_DATA); if (copied == 0) { return super.transferTo(count, throughBuffer, target); } else { return copied; } }
Example #23
Source File: DetachableStreamSinkChannel.java From lams with GNU General Public License v2.0 | 5 votes |
@Override public ChannelListener.Setter<? extends StreamSinkChannel> getWriteSetter() { if (writeSetter == null) { writeSetter = new ChannelListener.SimpleSetter<>(); if (!isFinished()) { if(delegate instanceof ConduitStreamSinkChannel) { ((ConduitStreamSinkChannel) delegate).setWriteListener(new SetterDelegatingListener((ChannelListener.SimpleSetter)writeSetter, this)); } else { delegate.getWriteSetter().set(new SetterDelegatingListener((ChannelListener.SimpleSetter)writeSetter, this)); } } } return writeSetter; }
Example #24
Source File: ChunkedStreamSourceConduit.java From lams with GNU General Public License v2.0 | 5 votes |
@Override public long transferTo(final long count, final ByteBuffer throughBuffer, final StreamSinkChannel target) throws IOException { try { return IoUtils.transfer(new ConduitReadableByteChannel(this), count, throughBuffer, target); } catch (IOException | RuntimeException | Error e) { IoUtils.safeClose(closeable); throw e; } }
Example #25
Source File: IdleTimeoutConduit.java From lams with GNU General Public License v2.0 | 5 votes |
@Override public long transferTo(long count, ByteBuffer throughBuffer, StreamSinkChannel target) throws IOException { handleIdleTimeout(); long w = source.transferTo(count, throughBuffer, target); if(sink.isWriteShutdown() && w == -1) { if(handle != null) { handle.remove(); handle = null; } } return w; }
Example #26
Source File: InflatingStreamSourceConduit.java From lams with GNU General Public License v2.0 | 5 votes |
@Override public long transferTo(final long count, final ByteBuffer throughBuffer, final StreamSinkChannel target) throws IOException { try { return IoUtils.transfer(new ConduitReadableByteChannel(this), count, throughBuffer, target); } catch (IOException | RuntimeException | Error e) { IoUtils.safeClose(exchange.getConnection()); throw e; } }
Example #27
Source File: AsyncSenderImpl.java From lams with GNU General Public License v2.0 | 5 votes |
public boolean run(boolean complete) { try { FileChannel source = fileChannel; long pos = source.position(); long size = source.size(); StreamSinkChannel dest = channel; if (dest == null) { if (callback == IoCallback.END_EXCHANGE) { if (exchange.getResponseContentLength() == -1 && !exchange.getResponseHeaders().contains(Headers.TRANSFER_ENCODING)) { exchange.setResponseContentLength(size); } } channel = dest = exchange.getResponseChannel(); if (dest == null) { throw UndertowMessages.MESSAGES.responseChannelAlreadyProvided(); } } while (size - pos > 0) { long ret = dest.transferFrom(source, pos, size - pos); pos += ret; if (ret == 0) { source.position(pos); dest.getWriteSetter().set(this); dest.resumeWrites(); return false; } } if (complete) { invokeOnComplete(); } } catch (IOException e) { invokeOnException(callback, e); } return true; }
Example #28
Source File: DetachableStreamSinkChannel.java From lams with GNU General Public License v2.0 | 5 votes |
public void handleEvent(final StreamSinkChannel channel) { ChannelListener<? super StreamSinkChannel> channelListener = setter.get(); if(channelListener != null) { ChannelListeners.invokeChannelListener(this.channel, channelListener); } else { UndertowLogger.REQUEST_LOGGER.debugf("suspending writes on %s to prevent listener runaway", channel); channel.suspendWrites(); } }
Example #29
Source File: DetachableStreamSinkChannel.java From lams with GNU General Public License v2.0 | 5 votes |
@Override public ChannelListener.Setter<? extends StreamSinkChannel> getCloseSetter() { if (closeSetter == null) { closeSetter = new ChannelListener.SimpleSetter<>(); if (!isFinished()) { delegate.getCloseSetter().set(ChannelListeners.delegatingChannelListener(this, closeSetter)); } } return closeSetter; }
Example #30
Source File: Transfer.java From lams with GNU General Public License v2.0 | 5 votes |
private static <I extends StreamSourceChannel, O extends StreamSinkChannel> void done(I source, O sink, ChannelListener<? super I> sourceListener, ChannelListener<? super O> sinkListener) { Channels.setReadListener(source, sourceListener); if (sourceListener == null) { source.suspendReads(); } else { source.wakeupReads(); } Channels.setWriteListener(sink, sinkListener); if (sinkListener == null) { sink.suspendWrites(); } else { sink.wakeupWrites(); } }