org.xnio.channels.StreamSourceChannel Java Examples

The following examples show how to use org.xnio.channels.StreamSourceChannel. 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: jweb-cms   Author: chifei   File: RequestBodyParser.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
public void read(StreamSourceChannel channel) {
    WritableByteChannel out = Channels.newChannel(body);
    try (PooledByteBuffer poolItem = exchange.getConnection().getByteBufferPool().allocate()) {
        ByteBuffer buffer = poolItem.getBuffer();
        int bytesRead;
        while (true) {
            buffer.clear();
            bytesRead = channel.read(buffer);
            if (bytesRead <= 0) break;
            buffer.flip();
            out.write(buffer);
        }
        if (bytesRead == -1) {
            complete = true;
            exchange.putAttachment(REQUEST_BODY, new RequestBody(body.toByteArray(), null));
        }
    } catch (IOException e) {
        IoUtils.safeClose(channel);
        complete = true;
        exchange.putAttachment(REQUEST_BODY, new RequestBody(null, e));
    }
}
 
Example #2
Source Project: jweb-cms   Author: chifei   File: UndertowIOHandler.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    if (exchange.isInIoThread()) {
        exchange.dispatch(this);
        return;
    }
    try {
        if (hasBody(exchange)) {
            RequestBodyParser reader = new RequestBodyParser(exchange, next);
            StreamSourceChannel channel = exchange.getRequestChannel();
            reader.read(channel);
            if (!reader.complete()) {
                channel.getReadSetter().set(reader);
                channel.resumeReads();
                return;
            }
        }
        exchange.dispatch(next);
    } catch (Throwable e) {
        if (exchange.isResponseChannelAvailable()) {
            exchange.setStatusCode(500);
            exchange.getResponseHeaders().add(new HttpString("Content-Type"), "text/plain");
            exchange.getResponseSender().send(Exceptions.stackTrace(e));
        }
    }
}
 
Example #3
Source Project: lams   Author: lamsfoundation   File: MultiPartParserDefinition.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public void parse(final HttpHandler handler) throws Exception {
    if (exchange.getAttachment(FORM_DATA) != null) {
        handler.handleRequest(exchange);
        return;
    }
    this.handler = handler;
    //we need to delegate to a thread pool
    //as we parse with blocking operations

    StreamSourceChannel requestChannel = exchange.getRequestChannel();
    if (requestChannel == null) {
        throw new IOException(UndertowMessages.MESSAGES.requestChannelAlreadyProvided());
    }
    if (executor == null) {
        exchange.dispatch(new NonBlockingParseTask(exchange.getConnection().getWorker(), requestChannel));
    } else {
        exchange.dispatch(executor, new NonBlockingParseTask(executor, requestChannel));
    }
}
 
Example #4
Source Project: lams   Author: lamsfoundation   File: FormEncodedDataDefinition.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public void parse(HttpHandler handler) throws Exception {
    if (exchange.getAttachment(FORM_DATA) != null) {
        handler.handleRequest(exchange);
        return;
    }
    this.handler = handler;
    StreamSourceChannel channel = exchange.getRequestChannel();
    if (channel == null) {
        throw new IOException(UndertowMessages.MESSAGES.requestChannelAlreadyProvided());
    } else {
        doParse(channel);
        if (state != 4) {
            channel.getReadSetter().set(this);
            channel.resumeReads();
        } else {
            exchange.dispatch(SameThreadExecutor.INSTANCE, handler);
        }
    }
}
 
Example #5
Source Project: lams   Author: lamsfoundation   File: FormEncodedDataDefinition.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public FormData parseBlocking() throws IOException {
    final FormData existing = exchange.getAttachment(FORM_DATA);
    if (existing != null) {
        return existing;
    }

    StreamSourceChannel channel = exchange.getRequestChannel();
    if (channel == null) {
        throw new IOException(UndertowMessages.MESSAGES.requestChannelAlreadyProvided());
    } else {
        while (state != 4) {
            doParse(channel);
            if (state != 4) {
                channel.awaitReadable();
            }
        }
    }
    return data;
}
 
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 inbound request.  If there is no request body, calling this method
 * may cause the next request to immediately be processed.  The {@link StreamSourceChannel#close()} or {@link StreamSourceChannel#shutdownReads()}
 * method must be called at some point after the request is processed to prevent resource leakage and to allow
 * the next request to proceed.  Any unread content will be discarded.
 *
 * @return the channel for the inbound request, or {@code null} if another party already acquired the channel
 */
public StreamSourceChannel getRequestChannel() {
    if (requestChannel != null) {
        if(anyAreSet(state, FLAG_REQUEST_RESET)) {
            state &= ~FLAG_REQUEST_RESET;
            return requestChannel;
        }
        return null;
    }
    if (anyAreSet(state, FLAG_REQUEST_TERMINATED)) {
        return requestChannel = new ReadDispatchChannel(new ConduitStreamSourceChannel(Configurable.EMPTY, new EmptyStreamSourceConduit(getIoThread())));
    }
    final ConduitWrapper<StreamSourceConduit>[] wrappers = this.requestWrappers;
    final ConduitStreamSourceChannel sourceChannel = connection.getSourceChannel();
    if (wrappers != null) {
        this.requestWrappers = null;
        final WrapperConduitFactory<StreamSourceConduit> factory = new WrapperConduitFactory<>(wrappers, requestWrapperCount, sourceChannel.getConduit(), this);
        sourceChannel.setConduit(factory.create());
    }
    return requestChannel = new ReadDispatchChannel(sourceChannel);
}
 
Example #7
Source Project: lams   Author: lamsfoundation   File: AbstractFixedLengthStreamSinkConduit.java    License: GNU General Public License v2.0 6 votes vote down vote up
public long transferFrom(final StreamSourceChannel source, final long count, final ByteBuffer throughBuffer) throws IOException {
    if (count == 0L) return 0L;
    long val = state;
    if (allAreSet(val, FLAG_CLOSE_REQUESTED)) {
        throw new ClosedChannelException();
    }
    if (allAreClear(val, MASK_COUNT)) {
        throw new FixedLengthOverflowException();
    }
    long res = 0L;
    try {
        return res = next.transferFrom(source, min(count, (val & MASK_COUNT)), throughBuffer);
    } catch (IOException | RuntimeException | Error e) {
        broken = true;
        throw e;
    } finally {
        exitWrite(val, res);
    }
}
 
Example #8
Source Project: lams   Author: lamsfoundation   File: StringReadChannelListener.java    License: GNU General Public License v2.0 6 votes vote down vote up
public void setup(final StreamSourceChannel channel) {
    PooledByteBuffer resource = bufferPool.allocate();
    ByteBuffer buffer = resource.getBuffer();
    try {
        int r = 0;
        do {
            r = channel.read(buffer);
            if (r == 0) {
                channel.getReadSetter().set(this);
                channel.resumeReads();
            } else if (r == -1) {
                stringDone(string.extract());
                IoUtils.safeClose(channel);
            } else {
                buffer.flip();
                string.write(buffer);
            }
        } while (r > 0);
    } catch (IOException e) {
        error(e);
    } finally {
        resource.close();
    }
}
 
Example #9
Source Project: lams   Author: lamsfoundation   File: StringReadChannelListener.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public void handleEvent(final StreamSourceChannel channel) {
    PooledByteBuffer resource = bufferPool.allocate();
    ByteBuffer buffer = resource.getBuffer();
    try {
        int r = 0;
        do {
            r = channel.read(buffer);
            if (r == 0) {
                return;
            } else if (r == -1) {
                stringDone(string.extract());
                IoUtils.safeClose(channel);
            } else {
                buffer.flip();
                string.write(buffer);
            }
        } while (r > 0);
    } catch (IOException e) {
        error(e);
    } finally {
        resource.close();
    }
}
 
Example #10
Source Project: jweb-cms   Author: chifei   File: RequestBodyParser.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void handleEvent(StreamSourceChannel channel) {
    read(channel);
    if (complete) {
        exchange.dispatch(handler);
    }
}
 
Example #11
Source Project: lams   Author: lamsfoundation   File: SslConduit.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public long transferFrom(StreamSourceChannel source, long count, ByteBuffer throughBuffer) throws IOException {
    if(anyAreSet(state, FLAG_WRITE_SHUTDOWN)) {
        throw new ClosedChannelException();
    }
    return IoUtils.transfer(source, count, throughBuffer, new ConduitWritableByteChannel(this));
}
 
Example #12
Source Project: lams   Author: lamsfoundation   File: AjpClientExchange.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public StreamSourceChannel getResponseChannel() {
    return new DetachableStreamSourceChannel(responseChannel) {
        @Override
        protected boolean isFinished() {
            return anyAreSet(state, RESPONSE_TERMINATED);
        }
    };
}
 
Example #13
Source Project: lams   Author: lamsfoundation   File: HttpClientExchange.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public StreamSourceChannel getResponseChannel() {
    return new DetachableStreamSourceChannel(clientConnection.getConnection().getSourceChannel()) {
        @Override
        protected boolean isFinished() {
            return anyAreSet(state, RESPONSE_TERMINATED);
        }
    };
}
 
Example #14
Source Project: lams   Author: lamsfoundation   File: HttpResponseConduit.java    License: GNU General Public License v2.0 5 votes vote down vote up
public long transferFrom(final StreamSourceChannel source, final long count, final ByteBuffer throughBuffer) throws IOException {
    try {
        if (state != 0) {
            return IoUtils.transfer(source, count, throughBuffer, new ConduitWritableByteChannel(this));
        } else {
            return next.transferFrom(source, count, throughBuffer);
        }
    } catch (IOException| RuntimeException | Error e) {
        IoUtils.safeClose(connection);
        throw e;
    }
}
 
Example #15
Source Project: lams   Author: lamsfoundation   File: HttpReadListener.java    License: GNU General Public License v2.0 5 votes vote down vote up
private void handleHttp2PriorKnowledge(final StreamConnection connection, final HttpServerConnection serverConnection, PooledByteBuffer readData) throws IOException {

        final ConduitStreamSourceChannel request = connection.getSourceChannel();

        byte[] data = new byte[PRI_EXPECTED.length];
        final ByteBuffer buffer = ByteBuffer.wrap(data);
        if(readData.getBuffer().hasRemaining()) {
            while (readData.getBuffer().hasRemaining() && buffer.hasRemaining()) {
                buffer.put(readData.getBuffer().get());
            }
        }
        final PooledByteBuffer extraData;
        if(readData.getBuffer().hasRemaining()) {
            extraData = readData;
        } else {
            readData.close();
            extraData = null;
        }
        if(!doHttp2PriRead(connection, buffer, serverConnection, extraData)) {
            request.getReadSetter().set(new ChannelListener<StreamSourceChannel>() {
                @Override
                public void handleEvent(StreamSourceChannel channel) {
                    try {
                        doHttp2PriRead(connection, buffer, serverConnection, extraData);
                    } catch (IOException e) {
                        UndertowLogger.REQUEST_IO_LOGGER.ioException(e);
                        IoUtils.safeClose(connection);
                    } catch (Throwable t) {
                        UndertowLogger.REQUEST_IO_LOGGER.handleUnexpectedFailure(t);
                        IoUtils.safeClose(connection);
                    }
                }
            });
            request.resumeReads();
        }
    }
 
Example #16
Source Project: lams   Author: lamsfoundation   File: AbstractFramedChannel.java    License: GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings({"unchecked", "rawtypes"})
@Override
public void handleEvent(final StreamSourceChannel channel) {
    //clear the task queue before reading
    while (!taskRunQueue.isEmpty()) {
        taskRunQueue.poll().run();
    }

    final R receiver = AbstractFramedChannel.this.receiver;
    if ((readChannelDone || receivesSuspended) && receiver == null) {
        channel.suspendReads();
        return;
    } else {
        ChannelListener listener = receiveSetter.get();
        if(listener == null) {
            listener = DRAIN_LISTENER;
        }
        UndertowLogger.REQUEST_IO_LOGGER.tracef("Invoking receive listener", receiver);
        ChannelListeners.invokeChannelListener(AbstractFramedChannel.this, listener);
    }
    if (readData != null  && !readData.isFreed() && channel.isOpen()) {
        try {
            runInIoThread(new Runnable() {
                @Override
                public void run() {
                    ChannelListeners.invokeChannelListener(channel, FrameReadListener.this);
                }
            });
        } catch (RejectedExecutionException e) {
            IoUtils.safeClose(AbstractFramedChannel.this);
        }
    }
}
 
Example #17
Source Project: lams   Author: lamsfoundation   File: FormEncodedDataDefinition.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public void handleEvent(final StreamSourceChannel channel) {
    try {
        doParse(channel);
        if (state == 4) {
            exchange.dispatch(SameThreadExecutor.INSTANCE, handler);
        }
    } catch (IOException e) {
        IoUtils.safeClose(channel);
        UndertowLogger.REQUEST_IO_LOGGER.ioExceptionReadingFromChannel(e);
        exchange.endExchange();

    }
}
 
Example #18
Source Project: lams   Author: lamsfoundation   File: HttpServerExchange.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public long transferFrom(StreamSourceChannel source, long count, ByteBuffer throughBuffer) throws IOException {
    long l = super.transferFrom(source, count, throughBuffer);
    if(l > 0) {
        responseBytesSent += l;
    }
    return l;
}
 
Example #19
Source Project: lams   Author: lamsfoundation   File: RateLimitingStreamSinkConduit.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public long transferFrom(StreamSourceChannel source, long count, ByteBuffer throughBuffer) throws IOException {
    if (!canSend()) {
        return 0;
    }
    int bytes = this.bytes - this.byteCount;
    long written = super.transferFrom(source, Math.min(count, bytes), throughBuffer);
    handleWritten(written);
    return written;
}
 
Example #20
Source Project: lams   Author: lamsfoundation   File: ChunkedStreamSinkConduit.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public long transferFrom(final StreamSourceChannel source, final long count, final ByteBuffer throughBuffer) throws IOException {
    if (anyAreSet(state, FLAG_WRITES_SHUTDOWN)) {
        throw new ClosedChannelException();
    }
    return IoUtils.transfer(source, count, throughBuffer, new ConduitWritableByteChannel(this));
}
 
Example #21
Source Project: lams   Author: lamsfoundation   File: HeadStreamSinkConduit.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public long transferFrom(final StreamSourceChannel source, final long count, final ByteBuffer throughBuffer) throws IOException {
    if (anyAreSet(state, FLAG_CLOSE_COMPLETE)) {
        throw new ClosedChannelException();
    }
    return IoUtils.transfer(source, count, throughBuffer, new ConduitWritableByteChannel(this));
}
 
Example #22
Source Project: lams   Author: lamsfoundation   File: DeflatingStreamSinkConduit.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public long transferFrom(final StreamSourceChannel source, final long count, final ByteBuffer throughBuffer) throws IOException {
    if (anyAreSet(state, SHUTDOWN | CLOSED)) {
        throw new ClosedChannelException();
    }
    if (!performFlushIfRequired()) {
        return 0;
    }
    return IoUtils.transfer(source, count, throughBuffer, new ConduitWritableByteChannel(this));
}
 
Example #23
Source Project: lams   Author: lamsfoundation   File: PreChunkedStreamSinkConduit.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public long transferFrom(final StreamSourceChannel source, final long count, final ByteBuffer throughBuffer) throws IOException {
    if (anyAreSet(state, FLAG_WRITES_SHUTDOWN)) {
        throw new ClosedChannelException();
    }
    return IoUtils.transfer(source, count, throughBuffer, new ConduitWritableByteChannel(this));
}
 
Example #24
Source Project: lams   Author: lamsfoundation   File: Transfer.java    License: GNU General Public License v2.0 5 votes vote down vote up
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();
    }
}
 
Example #25
Source Project: lams   Author: lamsfoundation   File: DetachableStreamSinkChannel.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public long transferFrom(final StreamSourceChannel source, final long count, final ByteBuffer throughBuffer) throws IOException {
    if (isFinished()) {
        throw UndertowMessages.MESSAGES.channelIsClosed();
    }
    return delegate.transferFrom(source, count, throughBuffer);
}
 
Example #26
Source Project: lams   Author: lamsfoundation   File: DetachableStreamSourceChannel.java    License: GNU General Public License v2.0 5 votes vote down vote up
public ChannelListener.Setter<? extends StreamSourceChannel> getReadSetter() {
    if (readSetter == null) {
        readSetter = new ChannelListener.SimpleSetter<>();
        if (!isFinished()) {
            if(delegate instanceof ConduitStreamSourceChannel) {
                ((ConduitStreamSourceChannel)delegate).setReadListener(new SetterDelegatingListener((ChannelListener.SimpleSetter)readSetter, this));
            } else {
                delegate.getReadSetter().set(new SetterDelegatingListener((ChannelListener.SimpleSetter)readSetter, this));
            }
        }
    }
    return readSetter;
}
 
Example #27
Source Project: lams   Author: lamsfoundation   File: DetachableStreamSourceChannel.java    License: GNU General Public License v2.0 5 votes vote down vote up
public ChannelListener.Setter<? extends StreamSourceChannel> getCloseSetter() {
    if (closeSetter == null) {
        closeSetter = new ChannelListener.SimpleSetter<>();
        if (!isFinished()) {
            if(delegate instanceof ConduitStreamSourceChannel) {
                ((ConduitStreamSourceChannel)delegate).setCloseListener(ChannelListeners.delegatingChannelListener(this, closeSetter));
            } else {
                delegate.getCloseSetter().set(ChannelListeners.delegatingChannelListener(this, closeSetter));
            }
        }
    }
    return closeSetter;
}
 
Example #28
Source Project: lams   Author: lamsfoundation   File: DetachableStreamSourceChannel.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void handleEvent(final StreamSourceChannel channel) {
    ChannelListener<? super StreamSourceChannel> channelListener = setter.get();
    if(channelListener != null) {
        ChannelListeners.invokeChannelListener(this.channel, channelListener);
    } else {
        UndertowLogger.REQUEST_LOGGER.debugf("suspending reads on %s to prevent listener runaway", channel);
        channel.suspendReads();
    }
}
 
Example #29
Source Project: light-4j   Author: networknt   File: ByteBufferReadChannelListener.java    License: Apache License 2.0 5 votes vote down vote up
public void setup(StreamSourceChannel channel) {
    PooledByteBuffer resource = this.bufferPool.allocate();
    ByteBuffer buffer = resource.getBuffer();

    try {
        int r;
        do {
            r = channel.read(buffer);
            if (r == 0) {
                channel.getReadSetter().set(this);
                channel.resumeReads();
            } else if (r == -1) {
                this.bufferDone(this.result);
                IoUtils.safeClose(channel);
            } else {
                buffer.flip();
                ByteBuffer[] buffs = new ByteBuffer[]{buffer};
                for(int i = 0; i < buffs.length; ++i) {
                    ByteBuffer buf = buffs[i];
                    while(buf.hasRemaining()) {
                        result.add(buf.get());
                    }
                }
            }
        } while(r > 0);
    } catch (IOException var8) {
        this.error(var8);
    } finally {
        resource.close();
    }

}
 
Example #30
Source Project: light-4j   Author: networknt   File: ByteBufferReadChannelListener.java    License: Apache License 2.0 5 votes vote down vote up
public void handleEvent(StreamSourceChannel channel) {
    PooledByteBuffer resource = this.bufferPool.allocate();
    ByteBuffer buffer = resource.getBuffer();

    try {
        int r;
        do {
            r = channel.read(buffer);
            if (r == 0) {
                return;
            }
            if (r == -1) {
                this.bufferDone(this.result);
                IoUtils.safeClose(channel);
            } else {
                buffer.flip();
                ByteBuffer[] buffs = new ByteBuffer[]{buffer};;
                for(int i = 0; i < buffs.length; ++i) {
                    ByteBuffer buf = buffs[i];
                    while(buf.hasRemaining()) {
                        result.add(buf.get());
                    }
                }
            }
        } while(r > 0);
    } catch (IOException var8) {
        this.error(var8);
    } finally {
        resource.close();
    }

}