org.xnio.IoUtils Java Examples

The following examples show how to use org.xnio.IoUtils. 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: 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 #2
Source Project: lams   Author: lamsfoundation   File: Hybi13Handshake.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
protected void handshakeInternal(final WebSocketHttpExchange exchange) {
    String origin = exchange.getRequestHeader(Headers.ORIGIN_STRING);
    if (origin != null) {
        exchange.setResponseHeader(Headers.ORIGIN_STRING, origin);
    }
    selectSubprotocol(exchange);
    selectExtensions(exchange);
    exchange.setResponseHeader(Headers.SEC_WEB_SOCKET_LOCATION_STRING, getWebSocketLocation(exchange));

    final String key = exchange.getRequestHeader(Headers.SEC_WEB_SOCKET_KEY_STRING);
    try {
        final String solution = solve(key);
        exchange.setResponseHeader(Headers.SEC_WEB_SOCKET_ACCEPT_STRING, solution);
        performUpgrade(exchange);
    } catch (NoSuchAlgorithmException e) {
        IoUtils.safeClose(exchange);
        exchange.endExchange();
        return;
    }
}
 
Example #3
Source Project: lams   Author: lamsfoundation   File: WebSockets.java    License: GNU General Public License v2.0 6 votes vote down vote up
private static void sendBlockingInternal(final PooledByteBuffer pooledData, WebSocketFrameType type, final WebSocketChannel wsChannel) throws IOException {
    boolean closePooledData = true;
    try {
        StreamSinkFrameChannel channel = wsChannel.send(type);
        // TODO chunk data into some MTU-like thing to control packet size
        closePooledData = false; // channel.send takes ownership of pooledData so it no longer needs to be closed
        if(!channel.send(pooledData)) {
            throw WebSocketMessages.MESSAGES.unableToSendOnNewChannel();
        }
        channel.shutdownWrites();
        while (!channel.flush()) {
            channel.awaitWritable();
        }
        if (type == WebSocketFrameType.CLOSE && wsChannel.isCloseFrameReceived()) {
            IoUtils.safeClose(wsChannel);
        }
    } finally {
        if (closePooledData) {
            pooledData.close();
        }
    }
}
 
Example #4
Source Project: lams   Author: lamsfoundation   File: Http2StreamSourceChannel.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
protected void handleHeaderData(FrameHeaderData headerData) {
    Http2FrameHeaderParser data = (Http2FrameHeaderParser) headerData;
    Http2PushBackParser parser = data.getParser();
    if(parser instanceof Http2DataFrameParser) {
        remainingPadding = ((Http2DataFrameParser) parser).getPadding();
        if(remainingPadding > 0) {
            try {
                updateFlowControlWindow(remainingPadding + 1);
            } catch (IOException e) {
                IoUtils.safeClose(getFramedChannel());
                throw new RuntimeException(e);
            }
        }
    } else if(parser instanceof Http2HeadersParser) {
        if(trailersHandler != null) {
            trailersHandler.handleTrailers(((Http2HeadersParser) parser).getHeaderMap());
        }
    }
    handleFinalFrame(data);
}
 
Example #5
Source Project: lams   Author: lamsfoundation   File: UndertowXnioSsl.java    License: GNU General Public License v2.0 6 votes vote down vote up
public void handleEvent(final StreamConnection connection) {
    try {

        SSLEngine sslEngine = JsseSslUtils.createSSLEngine(sslContext, optionMap, destination);
        SSLParameters params = sslEngine.getSSLParameters();
        params.setServerNames(Collections.singletonList(new SNIHostName(destination.getHostString())));
        sslEngine.setSSLParameters(params);

        final SslConnection wrappedConnection = new UndertowSslConnection(connection, sslEngine, bufferPool);
        if (!futureResult.setResult(wrappedConnection)) {
            IoUtils.safeClose(connection);
        } else {
            ChannelListeners.invokeChannelListener(wrappedConnection, openListener);
        }
    } catch (Throwable e) {
        futureResult.setException(new IOException(e));
    }
}
 
Example #6
Source Project: lams   Author: lamsfoundation   File: SslConduit.java    License: GNU General Public License v2.0 6 votes vote down vote up
private void runReadListener(final boolean resumeInListener) {
    try {
        if(readListenerInvocationCount++ == MAX_READ_LISTENER_INVOCATIONS) {
            UndertowLogger.REQUEST_LOGGER.sslReadLoopDetected(this);
            IoUtils.safeClose(connection, delegate);
            close();
            return;
        }
        if(resumeInListener) {
            delegate.getIoThread().execute(runReadListenerAndResumeCommand);
        } else {
            delegate.getIoThread().execute(runReadListenerCommand);
        }
    } catch (Throwable e) {
        //will only happen on shutdown
        IoUtils.safeClose(connection, delegate);
        UndertowLogger.REQUEST_IO_LOGGER.debugf(e, "Failed to queue read listener invocation");
    }
}
 
Example #7
Source Project: lams   Author: lamsfoundation   File: WriteTimeoutStreamSinkConduit.java    License: GNU General Public License v2.0 6 votes vote down vote up
private void handleWriteTimeout(final long ret) throws IOException {
    if (!connection.isOpen()) {
        return;
    }
    if (ret == 0 && handle != null) {
        return;
    }
    Integer timeout = getTimeout();
    if (timeout == null || timeout <= 0) {
        return;
    }
    long currentTime = System.currentTimeMillis();
    long expireTimeVar = expireTime;
    if (expireTimeVar != -1 && currentTime > expireTimeVar) {
        IoUtils.safeClose(connection);
        throw new ClosedChannelException();
    }
    expireTime = currentTime + timeout;
}
 
Example #8
Source Project: bouncr   Author: kawasima   File: MultiAppProxyClient.java    License: Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void completed(final ClientConnection connection) {
    final ServerConnection serverConnection = exchange.getConnection();
    //we attach to the connection so it can be re-used
    if (connectionCache) {
        serverConnection.putAttachment(clientAttachmentKey, connection);
    }
    serverConnection.addCloseListener(serverConnection1 -> IoUtils.safeClose(connection));
    connection.getCloseSetter().set((ChannelListener<Channel>) channel -> serverConnection.removeAttachment(clientAttachmentKey));

    exchange.setRelativePath("/");
    Realm realm = realmCache.matches(exchange.getRequestPath());
    Application application = realmCache.getApplication(realm);
    String path = exchange.getRequestURI();
    if (path.startsWith(application.getVirtualPath())) {
        String passTo = calculatePathTo(path, application);
        exchange.setRequestPath(passTo);
        exchange.setRequestURI(passTo);
    }
    callback.completed(exchange, new ProxyConnection(connection, "/"));
}
 
Example #9
Source Project: lams   Author: lamsfoundation   File: Http2ReceiveListener.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public void handleEvent(Http2Channel channel) {

    try {
        final AbstractHttp2StreamSourceChannel frame = channel.receive();
        if (frame == null) {
            return;
        }
        if (frame instanceof Http2StreamSourceChannel) {

            handleRequests(channel, (Http2StreamSourceChannel) frame);

        }

    } catch (IOException e) {
        UndertowLogger.REQUEST_IO_LOGGER.ioException(e);
        IoUtils.safeClose(channel);
    } catch (Throwable t) {
        UndertowLogger.REQUEST_IO_LOGGER.handleUnexpectedFailure(t);
        IoUtils.safeClose(channel);
    }
}
 
Example #10
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 position, final long count, final FileChannel target) throws IOException {
    long val = state;
    checkMaxSize(val);
    if (anyAreSet(val, FLAG_CLOSED | FLAG_FINISHED) || allAreClear(val, MASK_COUNT)) {
        if (allAreClear(val, FLAG_FINISHED)) {
            invokeFinishListener();
        }
        return -1L;
    }
    long res = 0L;
    try {
        return res = next.transferTo(position, min(count, val & MASK_COUNT), target);
    } catch (IOException | RuntimeException | Error e) {
        IoUtils.safeClose(exchange.getConnection());
        throw e;
    } finally {
        exitRead(res);
    }
}
 
Example #11
Source Project: lams   Author: lamsfoundation   File: ProxyConnectionPool.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Should only be used for tests.
 *
 */
void closeCurrentConnections() {
    final CountDownLatch latch = new CountDownLatch(hostThreadData.size());
    for(final Map.Entry<XnioIoThread, HostThreadData> data : hostThreadData.entrySet()) {
        data.getKey().execute(new Runnable() {
            @Override
            public void run() {
                ConnectionHolder d = data.getValue().availableConnections.poll();
                while (d != null) {
                    IoUtils.safeClose(d.clientConnection);
                    d = data.getValue().availableConnections.poll();
                }
                data.getValue().connections = 0;
                latch.countDown();
            }
        });
    }
    try {
        latch.await(10, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}
 
Example #12
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 #13
Source Project: lams   Author: lamsfoundation   File: ProxyHandler.java    License: GNU General Public License v2.0 6 votes vote down vote up
void cancel(final HttpServerExchange exchange) {
    final ProxyConnection connectionAttachment = exchange.getAttachment(CONNECTION);
    if (connectionAttachment != null) {
        ClientConnection clientConnection = connectionAttachment.getConnection();
        UndertowLogger.PROXY_REQUEST_LOGGER.timingOutRequest(clientConnection.getPeerAddress() + "" + exchange.getRequestURI());
        IoUtils.safeClose(clientConnection);
    } else {
        UndertowLogger.PROXY_REQUEST_LOGGER.timingOutRequest(exchange.getRequestURI());
    }
    if (exchange.isResponseStarted()) {
        IoUtils.safeClose(exchange.getConnection());
    } else {
        exchange.setStatusCode(StatusCodes.SERVICE_UNAVAILABLE);
        exchange.endExchange();
    }
}
 
Example #14
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 #15
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 #16
Source Project: spring-analysis-note   Author: Vip-Augus   File: UndertowXhrTransport.java    License: MIT License 5 votes vote down vote up
public void onSuccess() {
	if (this.outputStream.size() > 0) {
		handleFrame();
	}
	if (logger.isTraceEnabled()) {
		logger.trace("XHR receive request completed.");
	}
	IoUtils.safeClose(this.connection);
	executeReceiveRequest(this.request, this.url, this.headers, this.session, this.connectFuture);
}
 
Example #17
Source Project: spring-analysis-note   Author: Vip-Augus   File: UndertowXhrTransport.java    License: MIT License 5 votes vote down vote up
public void onFailure(Throwable failure) {
	IoUtils.safeClose(this.connection);
	if (this.connectFuture.setException(failure)) {
		return;
	}
	if (this.session.isDisconnected()) {
		this.session.afterTransportClosed(null);
	}
	else {
		this.session.handleTransportError(failure);
		this.session.afterTransportClosed(new CloseStatus(1006, failure.getMessage()));
	}
}
 
Example #18
Source Project: java-technology-stack   Author: codeEngraver   File: UndertowXhrTransport.java    License: MIT License 5 votes vote down vote up
public void onSuccess() {
	if (this.outputStream.size() > 0) {
		handleFrame();
	}
	if (logger.isTraceEnabled()) {
		logger.trace("XHR receive request completed.");
	}
	IoUtils.safeClose(this.connection);
	executeReceiveRequest(this.request, this.url, this.headers, this.session, this.connectFuture);
}
 
Example #19
Source Project: java-technology-stack   Author: codeEngraver   File: UndertowXhrTransport.java    License: MIT License 5 votes vote down vote up
public void onFailure(Throwable failure) {
	IoUtils.safeClose(this.connection);
	if (this.connectFuture.setException(failure)) {
		return;
	}
	if (this.session.isDisconnected()) {
		this.session.afterTransportClosed(null);
	}
	else {
		this.session.handleTransportError(failure);
		this.session.afterTransportClosed(new CloseStatus(1006, failure.getMessage()));
	}
}
 
Example #20
Source Project: lams   Author: lamsfoundation   File: WebConnectionImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public void close() throws Exception {
    try {
        outputStream.closeBlocking();
    } finally {
        IoUtils.safeClose(inputStream, channel);
    }
}
 
Example #21
Source Project: lams   Author: lamsfoundation   File: AjpClientChannel.java    License: GNU General Public License v2.0 5 votes vote down vote up
protected void lastDataRead() {
    if(!lastFrameSent) {
        markReadsBroken(new ClosedChannelException());
        markWritesBroken(new ClosedChannelException());
    }
    lastFrameReceived = true;
    lastFrameSent = true;
    IoUtils.safeClose(this);
}
 
Example #22
Source Project: lams   Author: lamsfoundation   File: Http2StreamSinkChannel.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
protected void handleFlushComplete(boolean channelClosed) {
    if (channelClosed) {
        getChannel().removeStreamSink(getStreamId());
    }
    if(reset) {
        IoUtils.safeClose(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: Http2Channel.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
protected void handleBrokenSinkChannel(Throwable e) {
    UndertowLogger.REQUEST_LOGGER.debugf(e, "Closing HTTP2 channel to %s due to broken write side", getPeerAddress());
    //the write side is broken, so we can't even send GO_AWAY
    //just tear down the TCP connection
    IoUtils.safeClose(this);
}
 
Example #25
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 #26
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 #27
Source Project: lams   Author: lamsfoundation   File: PerMessageDeflateFunction.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public synchronized PooledByteBuffer transformForRead(PooledByteBuffer pooledBuffer, StreamSourceFrameChannel channel, boolean lastFragmentOfMessage) throws IOException {
    if ((channel.getRsv() & 4) == 0) {
        //rsv bit not set, this message is not compressed
        return pooledBuffer;
    }
    PooledByteBuffer output = allocateBufferWithArray(channel.getWebSocketChannel(), 0); // first pass
    PooledByteBuffer inputBuffer = null;
    if (currentReadChannel != null && currentReadChannel != channel) {
        //new channel, we did not get a last fragment message which can happens sometimes

        decompress.setInput(TAIL);
        output = decompress(channel.getWebSocketChannel(), output);
    }
    ByteBuffer buffer = pooledBuffer.getBuffer();

    if (buffer.hasArray()) {
        decompress.setInput(buffer.array(), buffer.arrayOffset() + buffer.position(), buffer.remaining());
    } else {
        inputBuffer = toArrayBacked(buffer, channel.getWebSocketChannel().getBufferPool());
        decompress.setInput(inputBuffer.getBuffer().array(), inputBuffer.getBuffer().arrayOffset() + inputBuffer.getBuffer().position(), inputBuffer.getBuffer().remaining());
    }
    try {
        output = decompress(channel.getWebSocketChannel(), output);
    } finally {
        // Free the buffer AFTER decompression so it doesn't get re-used out from under us
        IoUtils.safeClose(inputBuffer, pooledBuffer);
    }

    if (lastFragmentOfMessage) {
        decompress.setInput(TAIL);
        output = decompress(channel.getWebSocketChannel(), output);
        currentReadChannel = null;
    } else {
        currentReadChannel = channel;
    }

    output.getBuffer().flip();
    return output;
}
 
Example #28
Source Project: lams   Author: lamsfoundation   File: SslConduit.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public void forceTermination() {
    try {
        if (delegateHandler != null) {
            delegateHandler.forceTermination();
        }
    } finally {
        IoUtils.safeClose(delegate);
    }
}
 
Example #29
Source Project: lams   Author: lamsfoundation   File: SslConduit.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public void writeReady() {
    if(anyAreSet(state, FLAG_READ_REQUIRES_WRITE)) {
        if(anyAreSet(state, FLAG_READS_RESUMED)) {
            readReadyHandler.readReady();
        } else {
            try {
                doHandshake();
            } catch (IOException e) {
                UndertowLogger.REQUEST_LOGGER.ioException(e);
                IoUtils.safeClose(delegate);
            } catch (Throwable t) {
                UndertowLogger.REQUEST_LOGGER.handleUnexpectedFailure(t);
                IoUtils.safeClose(delegate);
            }
        }
    }
    if (anyAreSet(state, FLAG_WRITES_RESUMED)) {
        if(delegateHandler == null) {
                final ChannelListener<? super ConduitStreamSinkChannel> writeListener = connection.getSinkChannel().getWriteListener();
                if (writeListener == null) {
                    suspendWrites();
                } else {
                    ChannelListeners.invokeChannelListener(connection.getSinkChannel(), writeListener);
                }
        } else {
            delegateHandler.writeReady();
        }
    }
    if(!anyAreSet(state, FLAG_WRITES_RESUMED | FLAG_READ_REQUIRES_WRITE)) {
        delegate.getSinkChannel().suspendWrites();
    }
}
 
Example #30
Source Project: lams   Author: lamsfoundation   File: Http2ClientConnection.java    License: GNU General Public License v2.0 5 votes vote down vote up
private void handleError(Throwable t) {
    IOException e = t instanceof IOException ? (IOException) t : new IOException(t);
    UndertowLogger.REQUEST_IO_LOGGER.ioException(e);
    IoUtils.safeClose(Http2ClientConnection.this);
    for (Map.Entry<Integer, Http2ClientExchange> entry : currentExchanges.entrySet()) {
        try {
            entry.getValue().failed(e);
        } catch (Exception ex) {
            UndertowLogger.REQUEST_IO_LOGGER.ioException(new IOException(ex));
        }
    }
}