Java Code Examples for org.xnio.IoUtils#safeClose()

The following examples show how to use org.xnio.IoUtils#safeClose() . 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: ProxyHandler.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void handleException(Channel channel, IOException exception) {
    IoUtils.safeClose(channel);
    IoUtils.safeClose(clientConnection);
    if (exchange.isResponseStarted()) {
        UndertowLogger.REQUEST_IO_LOGGER.debug("Exception reading from target server", exception);
        if (!exchange.isResponseStarted()) {
            exchange.setStatusCode(StatusCodes.INTERNAL_SERVER_ERROR);
            exchange.endExchange();
        } else {
            IoUtils.safeClose(exchange.getConnection());
        }
    } else {
        UndertowLogger.REQUEST_IO_LOGGER.ioException(exception);
        exchange.setStatusCode(StatusCodes.INTERNAL_SERVER_ERROR);
        exchange.endExchange();
    }
}
 
Example 2
Source File: StringReadChannelListener.java    From lams with 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 3
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 4
Source File: ReadTimeoutStreamSourceConduit.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private void handleReadTimeout(final long ret) throws IOException {
    if (!connection.isOpen()) {
        cleanup();
        return;
    }
    if(ret == -1) {
        cleanup();
        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 5
Source File: AjpServerRequestConduit.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public long read(ByteBuffer[] dsts, int offset, int length) throws IOException {
    try {
        long total = 0;
        for (int i = offset; i < length; ++i) {
            while (dsts[i].hasRemaining()) {
                int r = read(dsts[i]);
                if (r <= 0 && total > 0) {
                    return total;
                } else if (r <= 0) {
                    return r;
                } else {
                    total += r;
                }
            }
        }
        return total;
    } catch (IOException | RuntimeException e) {
        IoUtils.safeClose(exchange.getConnection());
        throw e;
    }
}
 
Example 6
Source File: WebConnectionImpl.java    From lams with 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 7
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 8
Source File: Http2Channel.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected void lastDataRead() {
    lastDataRead = true;
    if(!peerGoneAway) {
        //we just close the connection, as the peer has performed an unclean close
        IoUtils.safeClose(this);
    } else {
        peerGoneAway = true;
        if(!thisGoneAway) {
            //we send a goaway message, and then close
            sendGoAway(ERROR_CONNECT_ERROR);
        }
    }
}
 
Example 9
Source File: AsyncWebSocketHttpServerExchange.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void close() {
    try {
        exchange.endExchange();
    } finally {
        IoUtils.safeClose(exchange.getConnection());
    }
}
 
Example 10
Source File: AjpClientChannel.java    From lams with 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 11
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 12
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 13
Source File: ParseTimeoutUpdater.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates new instance of ParseTimeoutSourceConduit.
 *  @param channel             Channel which will be closed in case of timeout.
 * @param requestParseTimeout Timeout value. Negative value will indicate that this updated is disabled.
 * @param requestIdleTimeout
 */
public ParseTimeoutUpdater(ConnectedChannel channel, long requestParseTimeout, long requestIdleTimeout) {
    this(channel, requestParseTimeout, requestIdleTimeout, new Runnable() {
        @Override
        public void run() {
            IoUtils.safeClose(channel);
        }
    });
}
 
Example 14
Source File: UndertowXhrTransport.java    From java-technology-stack with 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 15
Source File: FixedLengthStreamSourceConduit.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public int read(final ByteBuffer dst) throws IOException {
    long val = state;
    checkMaxSize(val);
    if (allAreSet(val, FLAG_CLOSED) || allAreClear(val, MASK_COUNT)) {
        if (allAreClear(val, FLAG_FINISHED)) {
            invokeFinishListener();
        }
        return -1;
    }
    int res = 0;
    final long remaining = val & MASK_COUNT;
    try {
        final int lim = dst.limit();
        final int pos = dst.position();
        if (lim - pos > remaining) {
            dst.limit((int) (remaining + (long) pos));
            try {
                return res = next.read(dst);
            } finally {
                dst.limit(lim);
            }
        } else {
            return res = next.read(dst);
        }
    } catch (IOException | RuntimeException | Error e) {
        IoUtils.safeClose(exchange.getConnection());
        throw e;
    }  finally {
        exitRead(res);
    }
}
 
Example 16
Source File: HttpOpenListener.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void handleEvent(final StreamConnection channel, PooledByteBuffer buffer) {
    if (UndertowLogger.REQUEST_LOGGER.isTraceEnabled()) {
        UndertowLogger.REQUEST_LOGGER.tracef("Opened connection with %s", channel.getPeerAddress());
    }

    //set read and write timeouts
    try {
        Integer readTimeout = channel.getOption(Options.READ_TIMEOUT);
        Integer idle = undertowOptions.get(UndertowOptions.IDLE_TIMEOUT);
        if(idle != null) {
            IdleTimeoutConduit conduit = new IdleTimeoutConduit(channel);
            channel.getSourceChannel().setConduit(conduit);
            channel.getSinkChannel().setConduit(conduit);
        }
        if (readTimeout != null && readTimeout > 0) {
            channel.getSourceChannel().setConduit(new ReadTimeoutStreamSourceConduit(channel.getSourceChannel().getConduit(), channel, this));
        }
        Integer writeTimeout = channel.getOption(Options.WRITE_TIMEOUT);
        if (writeTimeout != null && writeTimeout > 0) {
            channel.getSinkChannel().setConduit(new WriteTimeoutStreamSinkConduit(channel.getSinkChannel().getConduit(), channel, this));
        }
    } catch (IOException e) {
        IoUtils.safeClose(channel);
        UndertowLogger.REQUEST_IO_LOGGER.ioException(e);
    } catch (Throwable t) {
        IoUtils.safeClose(channel);
        UndertowLogger.REQUEST_IO_LOGGER.handleUnexpectedFailure(t);
    }
    if(statisticsEnabled) {
        channel.getSinkChannel().setConduit(new BytesSentStreamSinkConduit(channel.getSinkChannel().getConduit(), connectorStatistics.sentAccumulator()));
        channel.getSourceChannel().setConduit(new BytesReceivedStreamSourceConduit(channel.getSourceChannel().getConduit(), connectorStatistics.receivedAccumulator()));
    }

    HttpServerConnection connection = new HttpServerConnection(channel, bufferPool, rootHandler, undertowOptions, bufferSize, statisticsEnabled ? connectorStatistics : null);
    HttpReadListener readListener = new HttpReadListener(connection, parser, statisticsEnabled ? connectorStatistics : null);


    if(buffer != null) {
        if(buffer.getBuffer().hasRemaining()) {
            connection.setExtraBytes(buffer);
        } else {
            buffer.close();
        }
    }
    if(connectorStatistics != null && statisticsEnabled) {
        connectorStatistics.incrementConnectionCount();
    }

    connection.setReadListener(readListener);
    readListener.newRequest();
    channel.getSourceChannel().setReadListener(readListener);
    readListener.handleEvent(channel.getSourceChannel());
}
 
Example 17
Source File: ServerSentEventConnection.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
private void handleException(IOException e) {
    IoUtils.safeClose(this, sink, exchange.getConnection());
}
 
Example 18
Source File: WebSocket07Channel.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
protected void closeSubChannels() {
    IoUtils.safeClose(fragmentedChannel);
}
 
Example 19
Source File: UndertowXhrTransport.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Override
public void handleEvent(StreamSourceChannel channel) {
	if (this.session.isDisconnected()) {
		if (logger.isDebugEnabled()) {
			logger.debug("SockJS sockJsSession closed, closing response.");
		}
		IoUtils.safeClose(this.connection);
		throw new SockJsException("Session closed.", this.session.getId(), null);
	}

	PooledByteBuffer pooled = bufferPool.allocate();
	try {
		int r;
		do {
			ByteBuffer buffer = pooled.getBuffer();
			buffer.clear();
			r = channel.read(buffer);
			buffer.flip();
			if (r == 0) {
				return;
			}
			else if (r == -1) {
				onSuccess();
			}
			else {
				while (buffer.hasRemaining()) {
					int b = buffer.get();
					if (b == '\n') {
						handleFrame();
					}
					else {
						this.outputStream.write(b);
					}
				}
			}
		}
		while (r > 0);
	}
	catch (IOException exc) {
		onFailure(exc);
	}
	finally {
		pooled.close();
	}
}
 
Example 20
Source File: ProxyProtocolReadListener.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
protected void notifyWriteClosed() {
    IoUtils.safeClose(delegate.getSinkChannel());
}