List of usage examples for io.netty.channel ChannelFuture sync
@Override
ChannelFuture sync() throws InterruptedException;
From source file:org.ogcs.netty.impl.TcpProtocolClient.java
License:Apache License
@Override public void start() { if (bootstrap == null) { createBootstrap();/* w w w.j a v a 2s . c om*/ } try { ChannelFuture future = doConnect(); future.await(); client = future.channel(); future.sync(); } catch (Exception e) { e.printStackTrace(); } finally { // add shutdown hook Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override public void run() { stop(); } })); } }
From source file:org.onosproject.lisp.ctl.impl.LispControllerBootstrap.java
License:Apache License
/** * Stitches all channel handlers into server bootstrap. *///from ww w. j a v a 2 s.c o m private void run() { try { final Bootstrap bootstrap = createServerBootstrap(); configBootstrapOptions(bootstrap); lispPorts.forEach(p -> { InetSocketAddress sa = new InetSocketAddress(p); channelFutures.add(bootstrap.bind(sa)); log.info("Listening for LISP router connections on {}", sa); }); for (ChannelFuture f : channelFutures) { f.sync(); } } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.onosproject.lisp.ctl.LispControllerBootstrap.java
License:Apache License
/** * Stitches all channel handlers into server bootstrap. *//*from w ww.j ava2 s . c o m*/ public void run() { try { final Bootstrap bootstrap = createServerBootstrap(); configBootstrapOptions(bootstrap); List<ChannelFuture> channelFutures = Lists.newArrayList(); lispPorts.forEach(p -> { InetSocketAddress sa = new InetSocketAddress(p); channelFutures.add(bootstrap.bind(sa)); log.info("Listening for LISP router connections on {}", sa); }); for (ChannelFuture f : channelFutures) { f.sync(); } } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.opendaylight.protocol.bmp.impl.app.BmpMonitoringStationImpl.java
License:Open Source License
public static BmpMonitoringStation createBmpMonitorInstance(final RIBExtensionConsumerContext ribExtensions, final BmpDispatcher dispatcher, final DOMDataBroker domDataBroker, final MonitorId monitorId, final InetSocketAddress address, final Optional<KeyMapping> keys, final BindingCodecTreeFactory codecFactory, final SchemaContext schemaContext, final List<MonitoredRouter> mrs) throws InterruptedException { Preconditions.checkNotNull(ribExtensions); Preconditions.checkNotNull(dispatcher); Preconditions.checkNotNull(domDataBroker); Preconditions.checkNotNull(monitorId); Preconditions.checkNotNull(address); final YangInstanceIdentifier yangMonitorId = YangInstanceIdentifier.builder().node(BmpMonitor.QNAME) .node(Monitor.QNAME).nodeWithKey(Monitor.QNAME, MONITOR_ID_QNAME, monitorId.getValue()).build(); final BindingRuntimeContext runtimeContext = BindingRuntimeContext .create(ribExtensions.getClassLoadingStrategy(), schemaContext); final BindingCodecTree tree = codecFactory.create(runtimeContext); final RouterSessionManager sessionManager = new RouterSessionManager(yangMonitorId, domDataBroker, ribExtensions, tree);/* w ww .j a v a2 s .co m*/ final ChannelFuture channelFuture = dispatcher.createServer(address, sessionManager, keys); return new BmpMonitoringStationImpl(domDataBroker, yangMonitorId, channelFuture.sync().channel(), sessionManager, monitorId, dispatcher, mrs); }
From source file:org.opendaylight.protocol.bmp.mock.BmpMockDispatcherTest.java
License:Open Source License
@Test public void testCreateClient() throws InterruptedException { final BmpMockDispatcher dispatcher = new BmpMockDispatcher(this.registry, this.sessionFactory); final int port = InetSocketAddressUtil.getRandomPort(); final InetSocketAddress serverAddr = InetSocketAddressUtil.getRandomLoopbackInetSocketAddress(port); final BmpDispatcherImpl serverDispatcher = new BmpDispatcherImpl(new NioEventLoopGroup(), new NioEventLoopGroup(), this.registry, this.sessionFactory); final ChannelFuture futureServer = serverDispatcher.createServer(serverAddr, this.slf, Optional.<KeyMapping>absent()); waitFutureSuccess(futureServer);/*www.j a v a2 s. co m*/ final ChannelFuture channelFuture = dispatcher .createClient(InetSocketAddressUtil.getRandomLoopbackInetSocketAddress(0), serverAddr); waitFutureSuccess(channelFuture); final Channel channel = channelFuture.sync().channel(); Assert.assertTrue(channel.isActive()); channel.close(); serverDispatcher.close(); }
From source file:org.opendaylight.protocol.bmp.mock.BmpMockDispatcherTest.java
License:Open Source License
@Test public void testCreateServer() throws InterruptedException { final BmpMockDispatcher dispatcher = new BmpMockDispatcher(this.registry, this.sessionFactory); final int port = InetSocketAddressUtil.getRandomPort(); final BmpDispatcherImpl serverDispatcher = new BmpDispatcherImpl(new NioEventLoopGroup(), new NioEventLoopGroup(), this.registry, this.sessionFactory); final ChannelFuture futureServer = dispatcher .createServer(new InetSocketAddress(InetAddresses.forString("0.0.0.0"), port)); waitFutureSuccess(futureServer);/*from w w w. j av a 2s . c o m*/ final ChannelFuture channelFuture = serverDispatcher.createClient( InetSocketAddressUtil.getRandomLoopbackInetSocketAddress(port), this.slf, Optional.<KeyMapping>absent()); waitFutureSuccess(channelFuture); final Channel channel = channelFuture.sync().channel(); Assert.assertTrue(channel.isActive()); channel.close(); serverDispatcher.close(); }
From source file:org.opendaylight.usc.plugin.UscPlugin.java
License:Open Source License
public ChannelFuture connect(Bootstrap clientBootstrap, final InetSocketAddress address, boolean remote) throws InterruptedException, ExecutionException, Exception { LOG.trace("Attempt to connect to " + address + ",remote is " + remote); boolean remoteDevice = false; // Connect to USC Agent to the device if one's not already created UscChannelImpl connection = null;//w ww . j av a 2 s. c om Channel directChannel = null; UscDevice device = new UscDevice(address.getAddress(), address.getPort()); UscRouteBrokerService routeBroker = UscServiceUtils.getService(UscRouteBrokerService.class); Exception connectException = null; if (remote) { if (routeBroker != null) { if (routeBroker.existRemoteChannel( new UscRemoteChannelIdentifier(device.getInetAddress(), getChannelType()))) { remoteDevice = true; LOG.trace("Find remote channel for device " + device); } else { remote = false; LOG.warn("remote channel is not found for device " + device + ", try to connect from local."); } } else { LOG.error("Broker service is null, try to connect from local."); remote = false; } } if (!remote) { if (getChannelType() == ChannelType.DTLS || getChannelType() == ChannelType.UDP) { try { connection = connectionManager.getConnection( new UscDevice(address.getAddress(), address.getPort()), getChannelType()); } catch (Exception e) { LOG.error("Failed to get udp agent connection, try to directly connect.error is " + e.getMessage()); connectException = e; } LOG.trace("Returned connection is " + connection); Channel channel = connection.getChannel(); UscDemultiplexer handler = (UscDemultiplexer) channel.pipeline().get("UscDemultiplexer"); SocketAddress remoteAddress = channel.remoteAddress(); if (!handler.promiseMap.containsKey(remoteAddress)) { handler.promiseMap.putIfAbsent(remoteAddress, SettableFuture.<Throwable>create()); UscControl echoControl = new UscControl(address.getPort(), 1, UscControl.ControlCode.ECHO.getCode()); channel.writeAndFlush(echoControl); LOG.trace("Send a ECHO message to see if the usc agent port is reachable."); } Throwable e = null; e = handler.promiseMap.get(remoteAddress).get(5000, TimeUnit.MILLISECONDS); if (e != null) { LOG.trace("connect: handler.promise is " + e); if (e != null && e instanceof PortUnreachableException) { LOG.trace("connect: caught exception PortUnreachableException"); channel.close(); connectionManager.removeConnection(connection); connection = null; LOG.trace("connect: start connecting to " + address.getAddress() + (":") + address.getPort() + " directly."); try { directChannel = connectToDeviceDirectly( new UscDevice(address.getAddress(), address.getPort())); } catch (Exception ex) { LOG.error("Failed to get direct connection, try to remote connect.error is " + e.getMessage()); connectException = ex; } } } } else { try { connection = connectionManager.getConnection( new UscDevice(address.getAddress(), address.getPort()), getChannelType()); } catch (Exception e) { LOG.error("Failed to get agent connection, try to directly connect.error is " + e.getMessage()); try { directChannel = connectToDeviceDirectly( new UscDevice(address.getAddress(), address.getPort())); } catch (Exception ex) { LOG.error("Failed to get direct connection, try to remote connect.error is " + e.getMessage()); connectException = ex; } } } } if (connectException != null) { if (routeBroker != null) { if (routeBroker.existRemoteChannel( new UscRemoteChannelIdentifier(device.getInetAddress(), getChannelType()))) { remoteDevice = true; LOG.trace("Found remote channel for device " + device); } else { LOG.warn("Failed to find remote channel in device table!"); throw connectException; } } else { LOG.warn("Broker service is null, can't find exist remote channel, throw exception dirctly."); throw connectException; } } final ChannelFuture clientChannelFuture = clientBootstrap.connect(localServerAddr); clientChannelFuture.channel().pipeline().addLast(uscExceptionHandler); // sync to ensure that localAddress is not null final Channel clientChannel = clientChannelFuture.sync().channel(); SocketAddress localAddress = clientChannel.localAddress(); serverChannels.putIfAbsent(localAddress, SettableFuture.<LocalChannel>create()); // wait for the peer to populate LocalChannel serverChannel = serverChannels.get(localAddress).get(); LOG.trace("connect: serverChannel = " + serverChannel); assert serverChannel != null; // remove the entry from the map as its purpose is complete serverChannels.remove(localAddress); if (connection != null) { UscSessionImpl session = connection.addSession(address.getPort(), serverChannel); LOG.trace("clientChannel set session " + session); // these attributes are used by unit test cases clientChannel.attr(SESSION).setIfAbsent(SettableFuture.<UscSessionImpl>create()); clientChannel.attr(SESSION).get().set(session); // these attributes are used by UscMultiplexer serverChannel.attr(SESSION).get().set(session); // this attribute is used by UscDemultiplexer serverChannel.attr(CLIENT_CHANNEL).set(clientChannel); LOG.info("Connected with channel for " + session); } else if (directChannel != null) { clientChannel.attr(LOCAL_SERVER_CHANNEL).set(serverChannel); serverChannel.attr(DIRECT_CHANNEL).set(directChannel); serverChannel.attr(CLIENT_CHANNEL).set(clientChannel); directChannel.attr(LOCAL_SERVER_CHANNEL).set(serverChannel); LOG.info("Connected channel using direct way for " + device); } if (remoteDevice) { UscRemoteChannelIdentifier remoteChannel = new UscRemoteChannelIdentifier(device.getInetAddress(), getChannelType()); UscRouteIdentifier routeId = new UscRouteIdentifier(remoteChannel, serverChannel.hashCode(), address.getPort()); clientChannel.attr(ROUTE_IDENTIFIER).setIfAbsent(routeId); serverChannel.attr(ROUTE_IDENTIFIER).setIfAbsent(routeId); sendEvent(new UscChannelCreateEvent(remoteChannel.getIp(), true, remoteChannel.getRemoteChannelType())); // register local session for routing to remote device routeBroker.addLocalSession(routeId, serverChannel); if (directChannel != null) { // direct connection only has one session directChannel.attr(ROUTE_IDENTIFIER).set(routeId); } LOG.info("Initialized local remote channel for " + routeId); } return clientChannelFuture; }
From source file:org.opendaylight.usc.plugin.UscPluginUdp.java
License:Open Source License
/** * Constructs a new UscPluginUdp/*from w w w.jav a2s . c o m*/ */ public UscPluginUdp() { super(new LocalAddress("usc-local-server-udp")); UscRouteBrokerService routeBroker = UscServiceUtils.getService(UscRouteBrokerService.class); if (routeBroker != null) { routeBroker.setConnetionManager(ChannelType.UDP, super.getConnectionManager()); routeBroker.setConnetionManager(ChannelType.DTLS, super.getConnectionManager()); } else { log.error("UscRouteBrokerService is not found, failed to set connection manager for all UDP Channel!"); } configService = UscServiceUtils.getService(UscConfigurationService.class); secureService = UscServiceUtils.getService(UscSecureService.class); agentBootstrap.group(agentGroup); agentBootstrap.channel(NioDatagramChannel.class); agentBootstrap.handler(new ChannelInitializer<Channel>() { @Override public void initChannel(final Channel ch) throws Exception { if (secureService == null) { log.error("UscSecureService is not initialized!"); return; } ChannelPipeline p = ch.pipeline(); ChannelHandler dtlsHandler = secureService.getUdpClientHandler(ch); initAgentPipeline(p, dtlsHandler); } }); final Bootstrap callHomeServerUdpBootstrap = new Bootstrap(); callHomeServerUdpBootstrap.group(agentGroup); callHomeServerUdpBootstrap.channel(NioDatagramChannel.class); callHomeServerUdpBootstrap.handler(new ChannelInitializer<NioDatagramChannel>() { @Override public void initChannel(final NioDatagramChannel ch) throws Exception { if (secureService == null) { log.error("UscSecureService is not initialized!"); return; } ChannelPipeline p = ch.pipeline(); // no remoteAddress yet until data received, so need a // handler // to add the channel p.addLast("callHomeHandler", callHomeHandler); p.addLast(new LoggingHandler(LogLevel.TRACE)); ChannelHandler dtlsHandler = secureService.getUdpServerHandler(ch); initAgentPipeline(ch.pipeline(), dtlsHandler); } }); if (configService == null) { log.error("UscConfigurationService is not initialized!"); return; } int pluginPort = configService.getConfigIntValue(UscConfigurationService.USC_PLUGIN_PORT); final ChannelFuture callHomeChannelUdpFuture = callHomeServerUdpBootstrap.bind(pluginPort); log.debug("callHomeChannelUdpFuture : " + callHomeChannelUdpFuture); try { callHomeChannelUdpFuture.sync(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:org.restcomm.media.network.deprecated.netty.UdpNetworkManagerTest.java
License:Open Source License
@Test public void testBindChannel() throws InterruptedException { // given/*from w w w . ja v a2 s.co m*/ final String address = "127.0.0.1"; final int port = 60000; final ChannelHandler handler = mock(ChannelHandler.class); this.manager = new UdpNetworkManager(); // when - activate manager and bind channel manager.activate(); final ChannelFuture future = manager.bindDatagramChannel(address, port, handler); final DatagramChannel channel = (DatagramChannel) future.sync().channel(); // then assertTrue(manager.isActive()); assertTrue(future.isSuccess()); assertNotNull(channel); assertTrue(channel.isOpen()); assertTrue(channel.isActive()); assertFalse(channel.isConnected()); assertEquals(new InetSocketAddress(address, port), channel.localAddress()); // when - deactivate manager manager.deactivate(); Thread.sleep(UdpNetworkManager.SHUTDOWN_TIME * 1000); // then assertFalse(manager.isActive()); assertFalse(channel.isOpen()); assertFalse(channel.isActive()); }
From source file:org.restcomm.media.network.netty.filter.SbcNetworkGuardTest.java
License:Open Source License
@Test public void testSecureSourceWhileChannelInactive() throws Exception { // given//from ww w. j ava 2s . co m final InetSocketAddress remoteAddress = new InetSocketAddress("192.168.1.22", 2727); final Channel channel = Mockito.mock(Channel.class); final ChannelFuture connectFuture = Mockito.mock(ChannelFuture.class); final NetworkGuard guard = new SbcNetworkGuard(); // when Mockito.when(channel.isActive()).thenReturn(false); Mockito.when(channel.remoteAddress()).thenReturn(null); Mockito.when(channel.connect(remoteAddress)).thenReturn(connectFuture); Mockito.when(connectFuture.isSuccess()).thenReturn(true); Mockito.when(connectFuture.sync()).thenReturn(connectFuture); final boolean secure = guard.isSecure(channel, remoteAddress); // then Assert.assertTrue(secure); }