Java Code Examples for org.xnio.channels.StreamSinkChannel

The following examples show how to use org.xnio.channels.StreamSinkChannel. These examples are extracted from open source projects. 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 Project: spring-analysis-note   Author: Vip-Augus   File: UndertowServerHttpResponse.java    License: MIT License 6 votes vote down vote up
@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 Project: spring-analysis-note   Author: Vip-Augus   File: UndertowServerHttpResponse.java    License: MIT License 6 votes vote down vote up
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 #3
Source Project: lams   Author: lamsfoundation   File: HttpReadListener.java    License: GNU General Public License v2.0 6 votes vote down vote up
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 #4
Source Project: lams   Author: lamsfoundation   File: HttpContinueReadHandler.java    License: GNU General Public License v2.0 6 votes vote down vote up
@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 #5
Source Project: lams   Author: lamsfoundation   File: ServerSentEventConnection.java    License: GNU General Public License v2.0 6 votes vote down vote up
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 #6
Source Project: lams   Author: lamsfoundation   File: HttpServerExchange.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 #7
Source Project: lams   Author: lamsfoundation   File: FixedLengthStreamSourceConduit.java    License: GNU General Public License v2.0 6 votes vote down vote up
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 #8
Source Project: lams   Author: lamsfoundation   File: WebSocketChannel.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 #9
Source Project: lams   Author: lamsfoundation   File: StringWriteChannelListener.java    License: GNU General Public License v2.0 6 votes vote down vote up
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 #10
Source Project: lams   Author: lamsfoundation   File: StringWriteChannelListener.java    License: GNU General Public License v2.0 6 votes vote down vote up
@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 #11
Source Project: lams   Author: lamsfoundation   File: StringWriteChannelListener.java    License: GNU General Public License v2.0 6 votes vote down vote up
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 #12
Source Project: lams   Author: lamsfoundation   File: AsyncSenderImpl.java    License: GNU General Public License v2.0 6 votes vote down vote up
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 #13
Source Project: rpc-benchmark   Author: hank-whu   File: AsyncHttpHandler.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 #14
Source Project: spring-analysis-note   Author: Vip-Augus   File: UndertowServerHttpResponse.java    License: MIT License 5 votes vote down vote up
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 #15
Source Project: spring-analysis-note   Author: Vip-Augus   File: UndertowServerHttpResponse.java    License: MIT License 5 votes vote down vote up
@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 Project: spring-analysis-note   Author: Vip-Augus   File: UndertowServerHttpResponse.java    License: MIT License 5 votes vote down vote up
@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 Project: java-technology-stack   Author: codeEngraver   File: UndertowServerHttpResponse.java    License: MIT License 5 votes vote down vote up
@Override
public Mono<Void> writeWith(Path file, long position, long count) {
	return doCommit(() ->
			Mono.defer(() -> {
				try (FileChannel source = FileChannel.open(file, StandardOpenOption.READ)) {
					StreamSinkChannel destination = this.exchange.getResponseChannel();
					Channels.transferBlocking(destination, source, position, count);
					return Mono.empty();
				}
				catch (IOException ex) {
					return Mono.error(ex);
				}
			}));
}
 
Example #18
Source Project: java-technology-stack   Author: codeEngraver   File: UndertowServerHttpResponse.java    License: MIT License 5 votes vote down vote up
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 Project: java-technology-stack   Author: codeEngraver   File: UndertowServerHttpResponse.java    License: MIT License 5 votes vote down vote up
@Override
protected void flush() throws IOException {
	StreamSinkChannel channel = UndertowServerHttpResponse.this.responseChannel;
	if (channel != null) {
		if (rsWriteFlushLogger.isTraceEnabled()) {
			rsWriteFlushLogger.trace(getLogPrefix() + "flush");
		}
		channel.flush();
	}
}
 
Example #20
Source Project: java-technology-stack   Author: codeEngraver   File: UndertowServerHttpResponse.java    License: MIT License 5 votes vote down vote up
@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 #21
Source Project: lams   Author: lamsfoundation   File: UpgradeServletOutputStream.java    License: GNU General Public License v2.0 5 votes vote down vote up
private void handleError(final StreamSinkChannel channel, final IOException e) {
    try {
        listener.onError(e);
    } finally {
        IoUtils.safeClose(channel);
    }
}
 
Example #22
Source Project: lams   Author: lamsfoundation   File: Http2Channel.java    License: GNU General Public License v2.0 5 votes vote down vote up
private void flushChannelIgnoreFailure(StreamSinkChannel stream) {
    try {
        flushChannel(stream);
    } catch (IOException e) {
        UndertowLogger.REQUEST_IO_LOGGER.ioException(e);
    } catch (Throwable t) {
        UndertowLogger.REQUEST_IO_LOGGER.handleUnexpectedFailure(t);
    }
}
 
Example #23
Source Project: lams   Author: lamsfoundation   File: Http2Channel.java    License: GNU General Public License v2.0 5 votes vote down vote up
private void flushChannel(StreamSinkChannel stream) throws IOException {
    stream.shutdownWrites();
    if (!stream.flush()) {
        stream.getWriteSetter().set(ChannelListeners.flushingChannelListener(null, writeExceptionHandler()));
        stream.resumeWrites();
    }
}
 
Example #24
Source Project: lams   Author: lamsfoundation   File: SslConduit.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public long transferTo(long count, ByteBuffer throughBuffer, StreamSinkChannel target) throws IOException {
    if(anyAreSet(state, FLAG_READ_SHUTDOWN)) {
        return -1;
    }
    return IoUtils.transfer(new ConduitReadableByteChannel(this), count, throughBuffer, target);
}
 
Example #25
Source Project: lams   Author: lamsfoundation   File: AjpClientConnection.java    License: GNU General Public License v2.0 5 votes vote down vote up
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 #26
Source Project: lams   Author: lamsfoundation   File: AjpClientExchange.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public StreamSinkChannel getRequestChannel() {
    return new DetachableStreamSinkChannel(requestChannel) {
        @Override
        protected boolean isFinished() {
            return anyAreSet(state, REQUEST_TERMINATED);
        }
    };
}
 
Example #27
Source Project: lams   Author: lamsfoundation   File: HttpClientExchange.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public StreamSinkChannel getRequestChannel() {
    return new DetachableStreamSinkChannel(clientConnection.getConnection().getSinkChannel()) {
        @Override
        protected boolean isFinished() {
            return anyAreSet(state, REQUEST_TERMINATED);
        }
    };
}
 
Example #28
Source Project: lams   Author: lamsfoundation   File: AjpServerRequestConduit.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public long transferTo(long count, ByteBuffer throughBuffer, StreamSinkChannel target) throws IOException {
    try {
        return IoUtils.transfer(new ConduitReadableByteChannel(this), count, throughBuffer, target);
    } catch (IOException | RuntimeException e) {
        IoUtils.safeClose(exchange.getConnection());
        throw e;
    }
}
 
Example #29
Source Project: lams   Author: lamsfoundation   File: ServerSentEventConnection.java    License: GNU General Public License v2.0 5 votes vote down vote up
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 #30
Source Project: lams   Author: lamsfoundation   File: HttpServerExchange.java    License: GNU General Public License v2.0 5 votes vote down vote up
@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;
    }
}