List of usage examples for io.netty.channel ChannelFutureListener ChannelFutureListener
ChannelFutureListener
From source file:org.opendaylight.protocol.pcep.impl.PCEPSessionNegotiator.java
License:Open Source License
@Override protected void startNegotiation() throws ExecutionException { final Object lock = this; LOG.debug("Bootstrap negotiation for channel {} started", this.channel); /*//from w w w. j av a 2 s. co m * We have a chance to see if there's a client session already * registered for this client. */ final byte[] clientAddress = ((InetSocketAddress) this.channel.remoteAddress()).getAddress().getAddress(); final PCEPPeerRegistry sessionReg = this.negFactory.getSessionRegistry(); synchronized (lock) { if (sessionReg.getSessionReference(clientAddress).isPresent()) { final byte[] serverAddress = ((InetSocketAddress) this.channel.localAddress()).getAddress() .getAddress(); if (COMPARATOR.compare(serverAddress, clientAddress) > 0) { final Optional<SessionReference> sessionRefMaybe = sessionReg .removeSessionReference(clientAddress); try { if (sessionRefMaybe.isPresent()) { sessionRefMaybe.get().close(); } } catch (final Exception e) { LOG.error("Unexpected failure to close old session", e); } } else { negotiationFailed(new IllegalStateException("A conflicting session for address " + ((InetSocketAddress) this.channel.remoteAddress()).getAddress() + " found.")); return; } } final Short sessionId = sessionReg.nextSession(clientAddress); final AbstractPCEPSessionNegotiator n = this.negFactory.createNegotiator(this.promise, this.factory.getSessionListener(), this.channel, sessionId, this.peerProposal); sessionReg.putSessionReference(clientAddress, new SessionReference() { @Override public void close() throws ExecutionException { try { sessionReg.releaseSession(clientAddress, sessionId); } finally { PCEPSessionNegotiator.this.channel.close(); } } @Override public Short getSessionId() { return sessionId; } }); this.channel.closeFuture().addListener(new ChannelFutureListener() { @Override public void operationComplete(final ChannelFuture future) { synchronized (lock) { sessionReg.removeSessionReference(clientAddress); } } }); LOG.info("Replacing bootstrap negotiator for channel {}", this.channel); this.channel.pipeline().replace(this, "negotiator", n); n.startNegotiation(); } }
From source file:org.opendaylight.sxp.core.SxpNode.java
License:Open Source License
/** * Start SxpNode//w w w .j a v a2 s .c om */ public synchronized SxpNode start() { channelInitializationWait("Error while starting"); if (isEnabled()) { return this; } this.sourceIp = InetAddresses.forString(Search.getAddress(getNodeIdentity().getSourceIp())); final SxpNode node = this; try { ConnectFacade.createServer(node, handlerFactoryServer).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture channelFuture) throws Exception { if (channelFuture.isSuccess()) { serverChannel = channelFuture.channel(); LOG.info(node + " Server created [" + getSourceIp().getHostAddress() + ":" + getServerPort() + "]"); node.setTimer(TimerType.RetryOpenTimer, node.getRetryOpenTime()); } else { LOG.error(node + " Server [" + node.getSourceIp().getHostAddress() + ":" + getServerPort() + "] Could not be created " + channelFuture.cause()); } serverChannelInit.set(false); } }).syncUninterruptibly(); } catch (Exception e) { LOG.debug("Failed to bind SxpNode {} to ip", this, e); } return this; }
From source file:org.opendaylight.sxp.core.SxpNode.java
License:Open Source License
/** * @param sxpNode Node where MD5 keys will be updated * @return ChannelFutureListener callback *//* w w w .j a va2s.c o m*/ private ChannelFutureListener createMD5updateListener(final SxpNode sxpNode) { channelInitializationWait("Error while Updating MD5"); if (serverChannel == null) { updateMD5counter.set(0); return new ChannelPromiseNotifier(); } LOG.info("{} Updating MD5 keys", this); return future -> ConnectFacade.createServer(sxpNode, handlerFactoryServer) .addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { serverChannel = future.channel(); serverChannelInit.set(false); if (updateMD5counter.decrementAndGet() > 0) { updateMD5counter.set(1); serverChannel.close().addListener(createMD5updateListener(sxpNode)) .syncUninterruptibly(); } } }); }
From source file:org.opendaylight.usc.plugin.UscConnectionManager.java
License:Open Source License
protected UscChannelImpl addConnection(final UscDevice device, final Channel channel, final boolean isCallHome, final UscChannel.ChannelType type) { // standard idiom for double-checked locking UscChannelImpl connection = connections.get(device); if (connection == null) { final UscChannelImpl newConnection = new UscChannelImpl(plugin, device, channel, isCallHome, type); connection = connections.putIfAbsent(device, newConnection); if (connection == null) { channel.closeFuture().addListener(new ChannelFutureListener() { @Override/*from w w w .j a v a 2s . co m*/ public void operationComplete(ChannelFuture future) throws Exception { removeConnection(newConnection); log.trace("agentChannel for device " + device + " closed"); } }); if (brokerService != null) { UscRemoteChannelIdentifier remoteChannel = new UscRemoteChannelIdentifier( newConnection.getDevice().getInetAddress(), newConnection.getType()); brokerService.broadcastMessage(new UscRemoteChannelEventMessage(remoteChannel, UscRemoteChannelEventMessage.ChannelEventType.CREATE)); } else { log.warn("Broker service is null, can't send broadcast for adding channel message(" + newConnection.getDevice().getInetAddress() + ")!"); } plugin.sendEvent(new UscChannelCreateEvent(newConnection)); connection = newConnection; } else { // previous entry exists; put failed; close the new channel channel.close(); } } return connection; }
From source file:org.opendaylight.usc.plugin.UscSessionManager.java
License:Open Source License
/** * Add a session (channel) to this session manager. * /*from w ww.ja v a2s .c o m*/ * @param port * @param channel * @return */ public UscSessionImpl addSession(int port, LocalChannel channel) { // generate unique session ID for this agent // valid session ID range is 1 to 65535 // always assign in sequential order for ease of testing for (int sessionId = 1; sessionId <= Character.MAX_VALUE; ++sessionId) { // standard idiom for double-checked locking if (!sessions.containsKey(sessionId)) { final UscSessionImpl session = createSession(sessionId, port, channel); if (sessions.putIfAbsent(sessionId, session) == null) { final int sId = sessionId; channel.closeFuture().addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { removeSession(sId); log.trace("serverChannel for session " + sId + " closed"); } }); plugin.sendEvent(new UscSessionCreateEvent(session)); return session; } } } throw new RuntimeException("out of available session IDs"); }
From source file:org.openremote.agent.protocol.AbstractNettyMessageProcessor.java
License:Open Source License
@Override public synchronized void connect() { if (connectionStatus != ConnectionStatus.DISCONNECTED && connectionStatus != ConnectionStatus.WAITING) { LOG.finest("Must be disconnected before calling connect"); return;//from w ww . j av a 2 s. c o m } LOG.fine("Connecting"); onConnectionStatusChanged(ConnectionStatus.CONNECTING); if (workerGroup == null) { // TODO: In Netty 5 you can pass in an executor service; can only pass in thread factory for now workerGroup = getWorkerGroup(); } bootstrap = new Bootstrap(); bootstrap.channel(getChannelClass()); configureChannel(); bootstrap.group(workerGroup); bootstrap.handler(new ChannelInitializer() { @Override public void initChannel(Channel channel) { AbstractNettyMessageProcessor.this.initChannel(channel); } }); // Start the client and store the channel socketAddress = getSocketAddress(); channelFuture = bootstrap.connect(socketAddress); channel = channelFuture.channel(); // Add channel callback - this gets called when the channel connects or when channel encounters an error channelFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) { synchronized (AbstractNettyMessageProcessor.this) { channelFuture.removeListener(this); if (connectionStatus == ConnectionStatus.DISCONNECTING) { return; } if (future.isSuccess()) { LOG.log(Level.INFO, "Connection initialising"); reconnectTask = null; reconnectDelayMilliseconds = INITIAL_RECONNECT_DELAY_MILLIS; } else if (future.cause() != null) { LOG.log(Level.INFO, "Connection error", future.cause()); // Failed to connect so schedule reconnection attempt scheduleReconnect(); } } } }); // Add closed callback channel.closeFuture().addListener(future -> { if (connectionStatus != ConnectionStatus.DISCONNECTING) { scheduleReconnect(); } }); }
From source file:org.ow2.petals.bc.gateway.commons.AbstractDomain.java
License:Open Source License
private void sendToChannel(final ChannelHandlerContext ctx, final TransportedForExchange m) { if (m instanceof TransportedMessage) { final TransportedMessage tm = (TransportedMessage) m; logBeforeSendingToChannel(tm);/* w w w. j ava 2 s .c om*/ m.senderExtStep = PetalsExecutionContext.getFlowAttributes(); } ctx.writeAndFlush(m).addListener(new ChannelFutureListener() { @Override public void operationComplete(final @Nullable ChannelFuture future) throws Exception { assert future != null; // TODO add tests for these use cases! if (!future.isSuccess()) { // TODO introduce some basic retrying before cancelling the send // Careful because if we reconnect, I guess the channel is not the same one?!?! final Throwable cause = future.cause(); // TODO is the channel notified of the error too? // see https://groups.google.com/d/msg/netty/yWMRRS6zaQ0/2MYNvRZQAQAJ if (m instanceof TransportedMessage && !((TransportedMessage) m).last) { final TransportedMessage tm = (TransportedMessage) m; tm.exchange.setError(new MessagingException(cause)); // TODO what about the other side waiting for this exchange?! it should be removed there... but // if there is a connection problem, then maybe it is simply that it was stopped? // we could take note of which exchangeId failed and send them on reconnect for cleaning? logger.log(Level.WARNING, "Can't send message over the channel, sending back the error over the NMR: " + m, cause); // TODO we have to wrap the modification in a transported message even though it hasn't been // so there may be extra useless operations... improve that! receiveFromChannel(ctx, TransportedMessage.lastMessage(tm, tm.exchange)); } else { logger.log(Level.WARNING, "Can't send message over the channel but nothing I can do now: " + m, cause); } } } }); }
From source file:org.ow2.petals.bc.gateway.inbound.TransportListener.java
License:Open Source License
/** * Start listening// w w w. j a va2 s.com */ public void bind() { bootstrap.localAddress(jtl.getPort()).bind().addListener(new ChannelFutureListener() { @Override public void operationComplete(final @Nullable ChannelFuture future) throws Exception { assert future != null; if (!future.isSuccess()) { logger.log(Level.SEVERE, "Cannot bind transport listener " + jtl.getId() + ": fix the problem and, either stop/start the component or use the JMX API to (re-)set the port", future.cause()); lastBindingError = future.cause().getMessage(); } else { channel = future.channel(); lastBindingError = ""; } } }); }
From source file:org.ow2.petals.bc.gateway.outbound.TransportClient.java
License:Open Source License
private void doConnect() { final String ip = pd.getJPD().getRemoteIp(); // it should have been checked already at deploy final int port = Integer.parseInt(pd.getJPD().getRemotePort()); logger.info("Connecting to " + pd.getJPD().getId() + " (" + ip + ":" + port + ")" + (retries > 0 ? ", retry " + retries + " of " + pd.getJPD().getRetryMax() : "")); // it will be set by the channel initializer during connect! authenticationFuture = null;// w ww .j av a 2 s . co m connectOrNext = bootstrap.remoteAddress(ip, port).connect().addListener(new ChannelFutureListener() { @Override public void operationComplete(final @Nullable ChannelFuture future) throws Exception { assert future != null; final Channel ch = future.channel(); assert ch != null; if (!future.isSuccess()) { // here the connect itself failed, the cause will most certainly be non-null setupReconnectIfNeeded(ch, future.cause(), false); } else { // here the connect succeeded, but maybe the authentication will fail assert authenticationFuture != null; authenticationFuture.addListener(new FutureListener<Channel>() { @Override public void operationComplete(final @Nullable Future<Channel> future) throws Exception { assert future != null; if (future.isSuccess()) { // we set it only once we are sure everything went well channel = ch; // now we can setup reconnect for close ch.closeFuture().addListener(new ChannelFutureListener() { @Override public void operationComplete(final @Nullable ChannelFuture future) throws Exception { assert future != null; // here the channel was closed, the cause will most certainly be null setupReconnectIfNeeded(ch, future.cause(), true); } }); } else { // in that case, authentication failed, the cause will most certainly be non-null setupReconnectIfNeeded(ch, future.cause(), false); } } }); } } }); }
From source file:org.proton.plug.test.minimalclient.AMQPClientSPI.java
License:Apache License
@Override public void onTransport(final ByteBuf bytes, final AMQPConnectionContext connection) { if (DebugInfo.debug) { ByteUtil.debugFrame("Bytes leaving client", bytes); }/* w w w .ja v a2s. c om*/ final int bufferSize = bytes.writerIndex(); latch.countUp(); channel.writeAndFlush(bytes).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { // // connection.outputDone(bufferSize); latch.countDown(); } }); if (connection.isSyncOnFlush()) { try { if (!latch.await(5, TimeUnit.SECONDS)) { // TODO logs System.err.println("Flush took longer than 5 seconds!!!"); } } catch (Throwable e) { e.printStackTrace(); } } connection.outputDone(bufferSize); }