Java Code Examples for org.xnio.ChannelListeners

The following examples show how to use org.xnio.ChannelListeners. 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: lams   Author: lamsfoundation   File: Http2Channel.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
protected void closeSubChannels() {

    for (Map.Entry<Integer, StreamHolder> e : currentStreams.entrySet()) {
        StreamHolder holder = e.getValue();
        AbstractHttp2StreamSourceChannel receiver = holder.sourceChannel;
        if(receiver != null) {
            receiver.markStreamBroken();
        }
        Http2StreamSinkChannel sink = holder.sinkChannel;
        if(sink != null) {
            if (sink.isWritesShutdown()) {
                ChannelListeners.invokeChannelListener(sink.getIoThread(), sink, ((ChannelListener.SimpleSetter) sink.getWriteSetter()).get());
            }
            IoUtils.safeClose(sink);
        }

    }
}
 
Example #2
Source Project: lams   Author: lamsfoundation   File: Http2Channel.java    License: GNU General Public License v2.0 6 votes vote down vote up
void sendPing(byte[] data, final ChannelExceptionHandler<AbstractHttp2StreamSinkChannel> exceptionHandler, boolean ack) {
    Http2PingStreamSinkChannel ping = new Http2PingStreamSinkChannel(this, data, ack);
    try {
        ping.shutdownWrites();
        if (!ping.flush()) {
            ping.getWriteSetter().set(ChannelListeners.flushingChannelListener(null, exceptionHandler));
            ping.resumeWrites();
        }
    } catch (IOException e) {
        if(exceptionHandler != null) {
            exceptionHandler.handleException(ping, e);
        } else {
            UndertowLogger.REQUEST_LOGGER.debug("Failed to send ping and no exception handler set", e);
        }
    } catch (Throwable t) {
        if(exceptionHandler != null) {
            exceptionHandler.handleException(ping, new IOException(t));
        } else {
            UndertowLogger.REQUEST_LOGGER.debug("Failed to send ping and no exception handler set", t);
        }
    }
}
 
Example #3
Source Project: lams   Author: lamsfoundation   File: UndertowAcceptingSslChannel.java    License: GNU General Public License v2.0 6 votes vote down vote up
UndertowAcceptingSslChannel(final UndertowXnioSsl ssl, final AcceptingChannel<? extends StreamConnection> tcpServer, final OptionMap optionMap, final ByteBufferPool applicationBufferPool, final boolean startTls) {
    this.tcpServer = tcpServer;
    this.ssl = ssl;
    this.applicationBufferPool = applicationBufferPool;
    this.startTls = startTls;
    clientAuthMode = optionMap.get(Options.SSL_CLIENT_AUTH_MODE);
    useClientMode = optionMap.get(Options.SSL_USE_CLIENT_MODE, false) ? 1 : 0;
    enableSessionCreation = optionMap.get(Options.SSL_ENABLE_SESSION_CREATION, true) ? 1 : 0;
    final Sequence<String> enabledCipherSuites = optionMap.get(Options.SSL_ENABLED_CIPHER_SUITES);
    cipherSuites = enabledCipherSuites != null ? enabledCipherSuites.toArray(new String[enabledCipherSuites.size()]) : null;
    final Sequence<String> enabledProtocols = optionMap.get(Options.SSL_ENABLED_PROTOCOLS);
    protocols = enabledProtocols != null ? enabledProtocols.toArray(new String[enabledProtocols.size()]) : null;
    //noinspection ThisEscapedInObjectConstruction
    closeSetter = ChannelListeners.<AcceptingChannel<SslConnection>>getDelegatingSetter(tcpServer.getCloseSetter(), this);
    //noinspection ThisEscapedInObjectConstruction
    acceptSetter = ChannelListeners.<AcceptingChannel<SslConnection>>getDelegatingSetter(tcpServer.getAcceptSetter(), this);
    useCipherSuitesOrder = optionMap.get(UndertowOptions.SSL_USER_CIPHER_SUITES_ORDER, false);
}
 
Example #4
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 #5
Source Project: lams   Author: lamsfoundation   File: HttpClientConnection.java    License: GNU General Public License v2.0 6 votes vote down vote up
protected void doHttp2Upgrade() {
    try {
        StreamConnection connectedStreamChannel = this.performUpgrade();
        Http2Channel http2Channel = new Http2Channel(connectedStreamChannel, null, bufferPool, null, true, true, options);
        Http2ClientConnection http2ClientConnection = new Http2ClientConnection(http2Channel, currentRequest.getResponseCallback(), currentRequest.getRequest(), currentRequest.getRequest().getRequestHeaders().getFirst(Headers.HOST), clientStatistics, false);
        http2ClientConnection.getCloseSetter().set(new ChannelListener<ClientConnection>() {
            @Override
            public void handleEvent(ClientConnection channel) {
                ChannelListeners.invokeChannelListener(HttpClientConnection.this, HttpClientConnection.this.closeSetter.get());
            }
        });
        http2Delegate = http2ClientConnection;
        connectedStreamChannel.getSourceChannel().wakeupReads(); //make sure the read listener is immediately invoked, as it may not happen if data is pushed back
        currentRequest = null;
        pendingResponse = null;
    } catch (IOException e) {
        UndertowLogger.REQUEST_IO_LOGGER.ioException(e);
        safeClose(this);
    }
}
 
Example #6
Source Project: lams   Author: lamsfoundation   File: AbstractServerConnection.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public void handleEvent(StreamConnection channel) {
    try {
        for (CloseListener l : closeListeners) {
            try {
                l.closed(AbstractServerConnection.this);
            } catch (Throwable e) {
                UndertowLogger.REQUEST_LOGGER.exceptionInvokingCloseListener(l, e);
            }
        }
        if (current != null) {
            current.endExchange();
        }
        ChannelListeners.invokeChannelListener(AbstractServerConnection.this, listener);
    } finally {
        if(extraBytes != null) {
            extraBytes.close();
            extraBytes = null;
        }
    }
}
 
Example #7
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 #8
Source Project: lams   Author: lamsfoundation   File: WriteTimeoutStreamSinkConduit.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public void run() {
    handle = null;
    if (expireTime == -1) {
        return;
    }
    long current = System.currentTimeMillis();
    if (current  < expireTime) {
        //timeout has been bumped, re-schedule
        handle = WorkerUtils.executeAfter(getWriteThread(),timeoutCommand, (expireTime - current) + FUZZ_FACTOR, TimeUnit.MILLISECONDS);
        return;
    }
    UndertowLogger.REQUEST_LOGGER.tracef("Timing out channel %s due to inactivity", connection.getSinkChannel());
    IoUtils.safeClose(connection);
    if (connection.getSourceChannel().isReadResumed()) {
        ChannelListeners.invokeChannelListener(connection.getSourceChannel(), connection.getSourceChannel().getReadListener());
    }
    if (connection.getSinkChannel().isWriteResumed()) {
        ChannelListeners.invokeChannelListener(connection.getSinkChannel(), connection.getSinkChannel().getWriteListener());
    }
}
 
Example #9
Source Project: lams   Author: lamsfoundation   File: ReadTimeoutStreamSourceConduit.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public void run() {
    handle = null;
    if (expireTime == -1) {
        return;
    }
    long current = System.currentTimeMillis();
    if (current  < expireTime) {
        //timeout has been bumped, re-schedule
        handle = WorkerUtils.executeAfter(connection.getIoThread(),timeoutCommand, (expireTime - current) + FUZZ_FACTOR, TimeUnit.MILLISECONDS);
        return;
    }
    UndertowLogger.REQUEST_LOGGER.tracef("Timing out channel %s due to inactivity", connection.getSourceChannel());
    IoUtils.safeClose(connection);
    if (connection.getSourceChannel().isReadResumed()) {
        ChannelListeners.invokeChannelListener(connection.getSourceChannel(), connection.getSourceChannel().getReadListener());
    }
    if (connection.getSinkChannel().isWriteResumed()) {
        ChannelListeners.invokeChannelListener(connection.getSinkChannel(), connection.getSinkChannel().getWriteListener());
    }
}
 
Example #10
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 #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: wildfly-core   Author: wildfly   File: ManagementHttpServer.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
public void start() {
    try {

        OptionMap.Builder serverOptionsBuilder = OptionMap.builder()
                .set(Options.TCP_NODELAY, true)
                .set(Options.REUSE_ADDRESSES, true);
        ChannelListener acceptListener = ChannelListeners.openListenerAdapter(openListener);
        if (httpAddress != null) {
            normalServer = worker.createStreamConnectionServer(httpAddress, acceptListener, serverOptionsBuilder.getMap());
            normalServer.resumeAccepts();
        }
        if (secureAddress != null) {
            if (sslClientAuthMode != null) {
                serverOptionsBuilder.set(SSL_CLIENT_AUTH_MODE, sslClientAuthMode);
            }
            OptionMap secureOptions = serverOptionsBuilder.getMap();
            XnioSsl xnioSsl = new UndertowXnioSsl(worker.getXnio(), secureOptions, sslContext);
            secureServer = xnioSsl.createSslConnectionServer(worker, secureAddress, acceptListener, secureOptions);
            secureServer.resumeAccepts();
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #13
Source Project: lams   Author: lamsfoundation   File: AjpClientChannel.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void sendPing(ClientConnection.PingListener pingListener, long timeout, TimeUnit timeUnit) {
    AjpClientCPingStreamSinkChannel pingChannel = new AjpClientCPingStreamSinkChannel(this);
    try {
        pingChannel.shutdownWrites();
        if (!pingChannel.flush()) {
            pingChannel.getWriteSetter().set(ChannelListeners.flushingChannelListener(null, new ChannelExceptionHandler<AbstractAjpClientStreamSinkChannel>() {
                @Override
                public void handleException(AbstractAjpClientStreamSinkChannel channel, IOException exception) {
                    pingListener.failed(exception);
                    synchronized (pingListeners) {
                        pingListeners.remove(pingListener);
                    }
                }
            }));
            pingChannel.resumeWrites();
        }
    } catch (IOException e) {
        pingListener.failed(e);
        return;
    }

    synchronized (pingListeners) {
        pingListeners.add(pingListener);
    }
    getIoThread().executeAfter(() -> {
        synchronized (pingListeners) {
            if(pingListeners.contains(pingListener)) {
                pingListeners.remove(pingListener);
                pingListener.failed(UndertowMessages.MESSAGES.pingTimeout());
            }
        }
    }, timeout, timeUnit);
}
 
Example #14
Source Project: lams   Author: lamsfoundation   File: Http2StreamSourceChannel.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
protected void complete() throws IOException {
    super.complete();
    if (completionListener != null) {
        ChannelListeners.invokeChannelListener(this, completionListener);
    }
}
 
Example #15
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 #16
Source Project: lams   Author: lamsfoundation   File: Http2Channel.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void sendGoAway(int status, final ChannelExceptionHandler<AbstractHttp2StreamSinkChannel> exceptionHandler) {
    if (thisGoneAway) {
        return;
    }
    thisGoneAway = true;
    if(UndertowLogger.REQUEST_IO_LOGGER.isTraceEnabled()) {
        UndertowLogger.REQUEST_IO_LOGGER.tracef(new ClosedChannelException(), "Sending goaway on channel %s", this);
    }
    Http2GoAwayStreamSinkChannel goAway = new Http2GoAwayStreamSinkChannel(this, status, lastGoodStreamId);
    try {
        goAway.shutdownWrites();
        if (!goAway.flush()) {
            goAway.getWriteSetter().set(ChannelListeners.flushingChannelListener(new ChannelListener<Channel>() {
                @Override
                public void handleEvent(Channel channel) {
                    IoUtils.safeClose(Http2Channel.this);
                }
            }, exceptionHandler));
            goAway.resumeWrites();
        } else {
            IoUtils.safeClose(this);
        }
    } catch (IOException e) {
        exceptionHandler.handleException(goAway, e);
    } catch (Throwable t) {
        exceptionHandler.handleException(goAway, new IOException(t));
    }
}
 
Example #17
Source Project: lams   Author: lamsfoundation   File: Http2DataStreamSinkChannel.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public boolean flush() throws IOException {
    if(completionListenerReady && completionListener != null) {
        ChannelListeners.invokeChannelListener(this, completionListener);
        completionListener = null;
    }
    return super.flush();
}
 
Example #18
Source Project: lams   Author: lamsfoundation   File: Http2DataStreamSinkChannel.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
protected void channelForciblyClosed() throws IOException {
    super.channelForciblyClosed();
    if (completionListener != null) {
        ChannelListeners.invokeChannelListener(this, completionListener);
        completionListener = null;
    }
}
 
Example #19
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 #20
Source Project: lams   Author: lamsfoundation   File: UndertowSslConnection.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public void run() {
    final ChannelListener<? super SslConnection> listener = handshakeSetter.get();
    if (listener == null) {
        return;
    }
    ChannelListeners.<SslConnection>invokeChannelListener(UndertowSslConnection.this, listener);
}
 
Example #21
Source Project: lams   Author: lamsfoundation   File: AjpClientConnection.java    License: GNU General Public License v2.0 5 votes vote down vote up
AjpClientConnection(final AjpClientChannel connection, final OptionMap options, final ByteBufferPool bufferPool, ClientStatistics clientStatistics) {
    this.clientStatistics = clientStatistics;
    this.options = options;
    this.connection = connection;
    this.bufferPool = bufferPool;

    connection.addCloseTask(new ChannelListener<AjpClientChannel>() {
        @Override
        public void handleEvent(AjpClientChannel channel) {
            log.debugf("connection to %s closed", getPeerAddress());
            AjpClientConnection.this.state |= CLOSED;
            ChannelListeners.invokeChannelListener(AjpClientConnection.this, closeSetter.get());
            for(ChannelListener<ClientConnection> listener : closeListeners) {
                listener.handleEvent(AjpClientConnection.this);
            }
            AjpClientExchange pending = pendingQueue.poll();
            while (pending != null) {
                pending.setFailed(new ClosedChannelException());
                pending = pendingQueue.poll();
            }
            if(currentRequest != null) {
                currentRequest.setFailed(new ClosedChannelException());
                currentRequest = null;
            }
        }
    });
    connection.getReceiveSetter().set(new ClientReceiveListener());
    connection.resumeReceives();
}
 
Example #22
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 #23
Source Project: lams   Author: lamsfoundation   File: Http2ClientConnection.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public void handleEvent(Http2Channel channel) {
    ChannelListeners.invokeChannelListener(Http2ClientConnection.this, closeSetter.get());
    for (ChannelListener<ClientConnection> listener : closeListeners) {
        listener.handleEvent(Http2ClientConnection.this);
    }
    for (Map.Entry<Integer, Http2ClientExchange> entry : currentExchanges.entrySet()) {
        entry.getValue().failed(new ClosedChannelException());
    }
    currentExchanges.clear();
}
 
Example #24
Source Project: lams   Author: lamsfoundation   File: AbstractFramedStreamSinkChannel.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public void close() throws IOException {
    if(fullyFlushed || anyAreSet(state, STATE_CLOSED)) {
        return;
    }
    try {
        synchronized (lock) {
            state |= STATE_CLOSED;
        }
        if(writeBuffer != null) {
            writeBuffer.close();
            writeBuffer = null;
        }
        if(body != null) {
            body.close();
            body = null;
        }
        if (header != null && header.getByteBuffer() != null) {
            header.getByteBuffer().close();
            header = null;
        }
        channelForciblyClosed();
        //we need to wake up/invoke the write listener
        if (isWriteResumed()) {
            ChannelListeners.invokeChannelListener(getIoThread(), this, (ChannelListener) getWriteListener());
        }
        wakeupWrites();
    } finally {
        wakeupWaiters();
    }
}
 
Example #25
Source Project: lams   Author: lamsfoundation   File: AbstractFramedStreamSinkChannel.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void markBroken() {
    this.broken = true;
    try {
        wakeupWrites();
        wakeupWaiters();
        if (isWriteResumed()) {
            ChannelListener<? super S> writeListener = this.writeSetter.get();
            if (writeListener != null) {
                ChannelListeners.invokeChannelListener(getIoThread(), (S) this, writeListener);
            }
        }
        ChannelListener<? super S> closeListener = this.closeSetter.get();
        if (closeListener != null) {
            ChannelListeners.invokeChannelListener(getIoThread(), (S) this, closeListener);
        }
    } finally {
        if(header != null) {
            if( header.getByteBuffer() != null) {
                header.getByteBuffer().close();
                header = null;
            }
        }
        if(body != null) {
            body.close();
            body = null;
        }
        if(writeBuffer != null) {
            writeBuffer.close();
            writeBuffer = null;
        }
    }
}
 
Example #26
Source Project: lams   Author: lamsfoundation   File: AbstractFramedChannel.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public void handleEvent(AbstractFramedChannel channel) {
    try {
        AbstractFramedStreamSourceChannel stream = channel.receive();
        if(stream != null) {
            UndertowLogger.REQUEST_IO_LOGGER.debugf("Draining channel %s as no receive listener has been set", stream);
            stream.getReadSetter().set(ChannelListeners.drainListener(Long.MAX_VALUE, null, null));
            stream.wakeupReads();
        }
    } catch (IOException | RuntimeException | Error e) {
        IoUtils.safeClose(channel);
    }
}
 
Example #27
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 #28
Source Project: lams   Author: lamsfoundation   File: AbstractFramedStreamSourceChannel.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * For this class there is no difference between a resume and a wakeup
 */
void resumeReadsInternal(boolean wakeup) {
    synchronized (lock) {
        boolean alreadyResumed = anyAreSet(state, STATE_READS_RESUMED);
        state |= STATE_READS_RESUMED;
        if (!alreadyResumed || wakeup) {
            if (!anyAreSet(state, STATE_IN_LISTENER_LOOP)) {
                state |= STATE_IN_LISTENER_LOOP;
                getFramedChannel().runInIoThread(new Runnable() {

                    @Override
                    public void run() {
                        try {
                            boolean moreData;
                            do {
                                ChannelListener<? super R> listener = getReadListener();
                                if (listener == null || !isReadResumed()) {
                                    return;
                                }
                                ChannelListeners.invokeChannelListener((R) AbstractFramedStreamSourceChannel.this, listener);
                                //if writes are shutdown or we become active then we stop looping
                                //we stop when writes are shutdown because we can't flush until we are active
                                //although we may be flushed as part of a batch
                                moreData = (frameDataRemaining > 0 && data != null) || !pendingFrameData.isEmpty() || anyAreSet(state, STATE_WAITNG_MINUS_ONE);
                            }
                            while (allAreSet(state, STATE_READS_RESUMED) && allAreClear(state, STATE_CLOSED | STATE_STREAM_BROKEN) && moreData);
                        } finally {
                            state &= ~STATE_IN_LISTENER_LOOP;
                        }
                    }
                });
            }
        }
    }
}
 
Example #29
Source Project: lams   Author: lamsfoundation   File: AbstractFramedStreamSourceChannel.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public void close() {
    if(anyAreSet(state, STATE_CLOSED)) {
        return;
    }
    synchronized (lock) {
        state |= STATE_CLOSED;
        if (allAreClear(state, STATE_DONE | STATE_LAST_FRAME)) {
            state |= STATE_STREAM_BROKEN;
            channelForciblyClosed();
        }
        if (data != null) {
            data.close();
            data = null;
        }
        while (!pendingFrameData.isEmpty()) {
            pendingFrameData.poll().frameData.close();
        }

        ChannelListeners.invokeChannelListener(this, (ChannelListener<? super AbstractFramedStreamSourceChannel<C, R, S>>) closeSetter.get());
        if (closeListeners != null) {
            for (int i = 0; i < closeListeners.length; ++i) {
                closeListeners[i].handleEvent(this);
            }
        }
    }
}
 
Example #30
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();
        }
    }
}