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 File: Http2ReceiveListener.java    From lams with 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 #2
Source File: ProxyConnectionPool.java    From lams with 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 #3
Source File: UndertowXnioSsl.java    From lams with 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 #4
Source File: HttpReadListener.java    From lams with 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 #5
Source File: SslConduit.java    From lams with 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 #6
Source File: Http2StreamSourceChannel.java    From lams with 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 #7
Source File: WebSockets.java    From lams with 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 #8
Source File: WriteTimeoutStreamSinkConduit.java    From lams with 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 #9
Source File: FixedLengthStreamSourceConduit.java    From lams with 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 #10
Source File: Hybi13Handshake.java    From lams with 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 #11
Source File: FixedLengthStreamSourceConduit.java    From lams with 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 #12
Source File: ProxyHandler.java    From lams with 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 #13
Source File: ServerSentEventConnection.java    From lams with 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 #14
Source File: MultiAppProxyClient.java    From bouncr with 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 #15
Source File: FormEncodedDataDefinition.java    From lams with 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 #16
Source File: AbstractFramedChannel.java    From lams with 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 File: AbstractFramedStreamSourceChannel.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected void lastFrame() {
    synchronized (lock) {
        state |= STATE_LAST_FRAME;
    }
    waitingForFrame = false;
    if(data == null && pendingFrameData.isEmpty() && frameDataRemaining == 0) {
        state |= STATE_DONE | STATE_CLOSED;
        getFramedChannel().notifyFrameReadComplete(this);
        IoUtils.safeClose(this);
    }
}
 
Example #18
Source File: ProxyHandler.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
static void handleFailure(HttpServerExchange exchange, ProxyClientHandler proxyClientHandler, Predicate idempotentRequestPredicate, IOException e) {
    UndertowLogger.PROXY_REQUEST_LOGGER.proxyRequestFailed(exchange.getRequestURI(), e);
    if(exchange.isResponseStarted()) {
        IoUtils.safeClose(exchange.getConnection());
    } else if(idempotentRequestPredicate.resolve(exchange) && proxyClientHandler != null) {
        proxyClientHandler.failed(exchange); //this will attempt a retry if configured to do so
    } else {
        exchange.setStatusCode(StatusCodes.SERVICE_UNAVAILABLE);
        exchange.endExchange();
    }
}
 
Example #19
Source File: ProxyHandler.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void couldNotResolveBackend(HttpServerExchange exchange) {
    if (exchange.isResponseStarted()) {
        IoUtils.safeClose(exchange.getConnection());
    } else {
        exchange.setStatusCode(StatusCodes.SERVICE_UNAVAILABLE);
        exchange.endExchange();
    }
}
 
Example #20
Source File: NodePingUtil.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void failed(IOException e) {
    taskFailed();
    if (exchange != null) {
        IoUtils.safeClose(exchange.getConnection());
    }
}
 
Example #21
Source File: InflatingStreamSourceConduit.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public long transferTo(final long position, final long count, final FileChannel target) throws IOException {
    try {
        return target.transferFrom(new ConduitReadableByteChannel(this), position, count);
    } catch (IOException | RuntimeException | Error e) {
        IoUtils.safeClose(exchange.getConnection());
        throw e;
    }
}
 
Example #22
Source File: AjpServerRequestConduit.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public long transferTo(long position, long count, FileChannel target) throws IOException {
    try {
        return target.transferFrom(new ConduitReadableByteChannel(this), position, count);
    } catch (IOException | RuntimeException e) {
        IoUtils.safeClose(exchange.getConnection());
        throw e;
    }
}
 
Example #23
Source File: HttpResponseConduit.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public long writeFinal(ByteBuffer[] srcs, int offset, int length) throws IOException {
    try {
        return Conduits.writeFinalBasic(this, srcs, offset, length);
    } catch (IOException | RuntimeException | Error e) {
        IoUtils.safeClose(connection);
        throw e;
    }
}
 
Example #24
Source File: HttpResponseConduit.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public int writeFinal(ByteBuffer src) throws IOException {
    try {
        return Conduits.writeFinalBasic(this, src);
    } catch (IOException | RuntimeException | Error e) {
        IoUtils.safeClose(connection);
        throw e;
    }
}
 
Example #25
Source File: HttpResponseConduit.java    From lams with 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 #26
Source File: PooledByteBufferOutputStream.java    From rpc-benchmark with Apache License 2.0 5 votes vote down vote up
public void release() {
	for (int i = 0; i < pooledList.size(); i++) {
		PooledByteBuffer pooled = pooledList.get(i);
		IoUtils.safeClose(pooled);
	}

	pooledList.clear();
}
 
Example #27
Source File: AjpServerRequestConduit.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void awaitReadable(long time, TimeUnit timeUnit) throws IOException {
    try {
        if (anyAreSet(state, STATE_READING)) {
            next.awaitReadable(time, timeUnit);
        }
    } catch (IOException | RuntimeException e) {
        IoUtils.safeClose(exchange.getConnection());
        throw e;
    }
}
 
Example #28
Source File: AjpServerRequestConduit.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void awaitReadable() throws IOException {
    try {
        if (anyAreSet(state, STATE_READING)) {
            next.awaitReadable();
        }
    } catch (IOException | RuntimeException e) {
        IoUtils.safeClose(exchange.getConnection());
        throw e;
    }
}
 
Example #29
Source File: ServerSentEventConnection.java    From lams with 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 File: AjpServerRequestConduit.java    From lams with 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;
    }
}