List of usage examples for io.netty.channel ChannelFuture awaitUninterruptibly
@Override ChannelFuture awaitUninterruptibly();
From source file:com.titilink.camel.rest.server.CamelServer.java
License:LGPL
public static void shutdown() { for (Channel ch : CHANNEL_LIST) { if (ch != null) { ChannelFuture cf = ch.close(); cf.awaitUninterruptibly(); ch = null;// w ww.j av a 2 s. c o m } } for (EventLoopGroup group : BOSS_GROUP_LIST) { if (group != null) { group.shutdownGracefully(); group = null; } } for (EventLoopGroup group : WORKER_GROUP_LIST) { if (group != null) { group.shutdownGracefully(); group = null; } } CHANNEL_LIST.clear(); BOSS_GROUP_LIST.clear(); WORKER_GROUP_LIST.clear(); }
From source file:com.twitter.http2.HttpHeaderCompressionTest.java
License:Apache License
private void testHeaderEcho(HttpHeaderBlockFrame frame) throws Throwable { final EchoHandler sh = new EchoHandler(); final TestHandler ch = new TestHandler(frame); ServerBootstrap sb = new ServerBootstrap().group(new LocalEventLoopGroup()) .channel(LocalServerChannel.class).childHandler(new ChannelInitializer<LocalChannel>() { @Override/*from w w w . ja v a2 s . c o m*/ public void initChannel(LocalChannel channel) throws Exception { channel.pipeline().addLast(new HttpConnectionHandler(true), sh); } }); Bootstrap cb = new Bootstrap().group(new LocalEventLoopGroup()).channel(LocalChannel.class) .handler(new ChannelInitializer<LocalChannel>() { @Override public void initChannel(LocalChannel channel) throws Exception { channel.pipeline().addLast(new HttpConnectionHandler(false), ch); } }); LocalAddress localAddress = new LocalAddress("HttpHeaderCompressionTest"); Channel sc = sb.bind(localAddress).sync().channel(); ChannelFuture ccf = cb.connect(localAddress); assertTrue(ccf.awaitUninterruptibly().isSuccess()); while (!ch.success) { if (sh.exception.get() != null) { break; } if (ch.exception.get() != null) { break; } try { Thread.sleep(1); } catch (InterruptedException e) { // Ignore. } } sc.close().awaitUninterruptibly(); cb.group().shutdownGracefully(); sb.group().shutdownGracefully(); if (sh.exception.get() != null && !(sh.exception.get() instanceof IOException)) { throw sh.exception.get(); } if (ch.exception.get() != null && !(ch.exception.get() instanceof IOException)) { throw ch.exception.get(); } if (sh.exception.get() != null) { throw sh.exception.get(); } if (ch.exception.get() != null) { throw ch.exception.get(); } }
From source file:com.ura.proxy.HexDumpProxy.java
License:Apache License
public void stop() { logger.info("Stoping proxying *:" + localPort + " to " + remoteHost + ':' + remotePort + " ..."); ChannelFuture closeChannelFuture = mainChannel.getCloseFuture(); ChannelFuture channelFuture = mainChannel.close(); channelFuture.awaitUninterruptibly(); closeChannelFuture.awaitUninterruptibly(); factory.releaseExternalResources();/*from ww w. ja v a 2 s.c om*/ }
From source file:com.ura.websocket.WebSocketServer.java
License:Apache License
public void stop() { final String funcName = "stop - "; logger.trace(funcName + "start"); ChannelFuture closeChannelFuture = mainChannel.getCloseFuture(); ChannelFuture channelFuture = mainChannel.close(); channelFuture.awaitUninterruptibly(); closeChannelFuture.awaitUninterruptibly(); factory.releaseExternalResources();/*from w w w .j a va 2s . co m*/ logger.trace(funcName + "end"); }
From source file:de.jackwhite20.japs.shared.nio.NioSocketClient.java
License:Open Source License
public boolean connect(String host, int port) { ChannelFuture channelFuture = new Bootstrap().group(PipelineUtils.newEventLoopGroup(1)) .channel(PipelineUtils.getChannel()).handler(new ClientChannelInitializer(this)) .option(ChannelOption.TCP_NODELAY, true) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONNECT_TIMEOUT).connect(host, port); channelFuture.awaitUninterruptibly(); channel = channelFuture.channel();/*from w w w.ja v a2 s .com*/ CountDownLatch countDownLatch = new CountDownLatch(1); channelFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture channelFuture) throws Exception { connected = channelFuture.isSuccess(); countDownLatch.countDown(); } }); try { countDownLatch.await(2, TimeUnit.SECONDS); } catch (InterruptedException e) { e.printStackTrace(); } return connected; }
From source file:de.ocarthon.core.network.HttpClient.java
License:Apache License
public synchronized String postRequest(String query, List<Map.Entry<String, String>> postParameters, String filePostName, String fileName, ByteBuf fileData, String mime) { if (bootstrap == null) { setupBootstrap();// w w w.ja va 2s . co m } if (channel == null || forceReconnect) { ChannelFuture cf = bootstrap.connect(host, port); forceReconnect = false; cf.awaitUninterruptibly(); channel = cf.channel(); channel.pipeline().addLast("handler", new SimpleChannelInboundHandler<HttpObject>() { @Override protected void messageReceived(ChannelHandlerContext ctx, HttpObject msg) throws Exception { if (msg instanceof HttpResponse) { HttpResponse response = ((HttpResponse) msg); String connection = (String) response.headers().get(HttpHeaderNames.CONNECTION); if (connection != null && connection.equalsIgnoreCase(HttpHeaderValues.CLOSE.toString())) forceReconnect = true; } if (msg instanceof HttpContent) { HttpContent chunk = (HttpContent) msg; String message = chunk.content().toString(CharsetUtil.UTF_8); if (!message.isEmpty()) { result[0] = message; synchronized (result) { result.notify(); } } } } }); } boolean isFileAttached = fileData != null && fileData.isReadable(); HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, scheme + "://" + host + ":" + port + "/" + query); HttpPostRequestEncoder bodyReqEncoder; try { bodyReqEncoder = new HttpPostRequestEncoder(httpDataFactory, request, isFileAttached); for (Map.Entry<String, String> entry : postParameters) { bodyReqEncoder.addBodyAttribute(entry.getKey(), entry.getValue()); } if (isFileAttached) { if (mime == null) mime = "application/octet-stream"; MixedFileUpload mfu = new MixedFileUpload(filePostName, fileName, mime, "binary", null, fileData.capacity(), DefaultHttpDataFactory.MINSIZE); mfu.addContent(fileData, true); bodyReqEncoder.addBodyHttpData(mfu); } HttpHeaders headers = request.headers(); headers.set(HttpHeaderNames.HOST, host); headers.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE); headers.set(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP); headers.set(HttpHeaderNames.USER_AGENT, "OcarthonCore HttpClient"); request = bodyReqEncoder.finalizeRequest(); } catch (Exception e) { throw new NullPointerException("key or value is empty or null"); } channel.write(request); if (bodyReqEncoder.isChunked()) { channel.write(bodyReqEncoder); } channel.flush(); synchronized (result) { try { result.wait(); } catch (InterruptedException e) { return null; } } return result[0]; }
From source file:gash.router.server.handler.CommandHandler.java
License:Apache License
/** * override this method to provide processing behavior. This implementation * mimics the routing we see in annotating classes to support a RESTful-like * behavior (e.g., jax-rs)./*from ww w.j ava2 s . c o m*/ * * @param msg */ public void handleMessage(CommandMessage msg, Channel channel) { if (msg == null) { // TODO add logging System.out.println("ERROR: Unexpected content - " + msg); return; } //PrintUtil.printCommand(msg); try { // TODO How can you implement this without if-else statements? if (msg.hasTask()) { /** * TODO Enqueue the command message and the channel into the server queue */ logger.info("Received task from " + msg.getHeader().getNodeId()); System.out.println("Queuing task"); System.out.flush(); QueueManager.getInstance().enqueueInboundCommmand(msg, channel); } else if (msg.hasPing()) { logger.info("ping from " + msg.getHeader().getNodeId()); } else if (msg.hasMessage()) { logger.info(msg.getMessage()); } } catch (Exception e) { // TODO add logging try { Failure.Builder eb = Failure.newBuilder(); eb.setId(conf.getNodeId()); eb.setRefId(msg.getHeader().getNodeId()); eb.setMessage(e.getMessage()); CommandMessage.Builder rb = CommandMessage.newBuilder(msg); rb.setErr(eb); ChannelFuture cf = channel.write(rb.build()); channel.flush(); cf.awaitUninterruptibly(); if (cf.isDone() && !cf.isSuccess()) { logger.info("Failed to write the message to the channel "); } } catch (Exception e2) { e.printStackTrace(); } } System.out.flush(); }
From source file:gash.router.server.handler.WorkHandler.java
License:Apache License
/** * override this method to provide processing behavior. T * /* ww w . j ava2 s . co m*/ * @param msg */ public void handleMessage(WorkMessage msg, Channel channel) { if (msg == null) { logger.error("ERROR: Unexpected content - " + msg); return; } if (debug) PrintUtil.printWork(msg); // TODO How can you implement this without if-else statements? try { if (msg.getStateOfLeader() == StateOfLeader.LEADERALIVE) { System.out.println("Leader is Alive "); exec.shutdownNow(); int currentTimeout = RandomTimeoutGenerator.randTimeout() * state.getConf().getNodeId(); exec = Executors.newSingleThreadScheduledExecutor(); exec.schedule(new ElectionTImer(), (long) currentTimeout, TimeUnit.MILLISECONDS); } else if (msg.hasLeader() && msg.getLeader().getAction() == LeaderQuery.WHOISTHELEADER) { WorkMessage buildNewNodeLeaderStatusResponseMessage = MessageBuilder .buildNewNodeLeaderStatusResponseMessage(NodeChannelManager.currentLeaderID, NodeChannelManager.currentLeaderAddress); ChannelFuture cf = channel.write(buildNewNodeLeaderStatusResponseMessage); channel.flush(); cf.awaitUninterruptibly(); if (cf.isDone() && !cf.isSuccess()) { logger.info("Failed to write the message to the channel "); } // Sent the newly discovered node all the data on this node. logger.info("Attempting to auto-replicate to node : " + channel.remoteAddress().toString()); DataReplicationManager.getInstance().replicateToNewNode(channel); } else if (msg.hasLeader() && msg.getLeader().getAction() == LeaderQuery.THELEADERIS) { NodeChannelManager.currentLeaderID = msg.getLeader().getLeaderId(); NodeChannelManager.currentLeaderAddress = msg.getLeader().getLeaderHost(); NodeChannelManager.amIPartOfNetwork = true; logger.info("The leader is " + NodeChannelManager.currentLeaderID); } if (msg.hasBeat() && msg.getStateOfLeader() != StateOfLeader.LEADERALIVE) { logger.info("heartbeat received from " + msg.getHeader().getNodeId()); } else if (msg.hasSteal()) { switch (msg.getSteal().getStealtype()) { case STEAL_RESPONSE: logger.info("------Stealing work from node:------ " + msg.getHeader().getNodeId()); QueueManager.getInstance().enqueueInboundWork(msg, channel); logger.info("------A task was stolen from another node------"); break; case STEAL_REQUEST: WorkMessageChannelCombo msgOnQueue = QueueManager.getInstance().getInboundWorkQ().peek(); if (msgOnQueue != null && msgOnQueue.getWorkMessage().getTask().getTaskType() == TaskType.READ) { logger.info("------Pending Read Request found in Queue, Sending to another node------"); WorkMessage wmProto = QueueManager.getInstance().dequeueInboundWork().getWorkMessage(); WorkMessage.Builder wm = WorkMessage.newBuilder(wmProto); WorkSteal.Builder stealMessage = WorkSteal.newBuilder(); stealMessage.setStealtype(StealType.STEAL_RESPONSE); wm.setSteal(stealMessage); QueueManager.getInstance().enqueueOutboundWork(wm.build(), channel); } break; default: break; } } else if (msg.hasTask()) { // Enqueue it to the inbound work queue logger.info("Received inbound work "); QueueManager.getInstance().enqueueInboundWork(msg, channel); } else if (msg.hasFlagRouting()) { logger.info("Routing information recieved " + msg.getHeader().getNodeId()); logger.info("Routing Entries: " + msg.getRoutingEntries()); logger.debug("Connected to new node"); SocketAddress remoteAddress = channel.remoteAddress(); InetSocketAddress addr = (InetSocketAddress) remoteAddress; state.getEmon().createOutboundIfNew(msg.getHeader().getNodeId(), addr.getHostName(), 5100); System.out.println(addr.getHostName()); } else if (msg.hasNewNode()) { logger.info("NEW NODE TRYING TO CONNECT " + msg.getHeader().getNodeId()); WorkMessage wm = state.getEmon().createRoutingMsg(); ChannelFuture cf = channel.write(wm); channel.flush(); cf.awaitUninterruptibly(); if (cf.isDone() && !cf.isSuccess()) { logger.info("Failed to write the message to the channel "); } // TODO New node has been detected. Push all your data to it // now. SocketAddress remoteAddress = channel.remoteAddress(); InetSocketAddress addr = (InetSocketAddress) remoteAddress; state.getEmon().createInboundIfNew(msg.getHeader().getNodeId(), addr.getHostName(), 5100); state.getEmon().getInboundEdges().getNode(msg.getHeader().getNodeId()).setChannel(channel); } else if (msg.hasPing()) { logger.info("ping from " + msg.getHeader().getNodeId()); boolean p = msg.getPing(); WorkMessage.Builder rb = WorkMessage.newBuilder(); rb.setPing(true); // channel.writeAndFlush(rb.build()); } else if (msg.getHeader().hasElection() && msg.getHeader().getElection()) { // call the election handler to handle this request System.out.println(" ---- Message for election has come ---- "); ElectionManagement.processElectionMessage(channel, msg); } else if (msg.hasErr()) { Failure err = msg.getErr(); logger.error("failure from " + msg.getHeader().getNodeId()); // PrintUtil.printFailure(err); } else if (msg.hasState()) { WorkState s = msg.getState(); } else { logger.info("Executing from work handler "); } } catch (NullPointerException e) { logger.error("Null pointer has occured" + e.getMessage()); } catch (Exception e) { // TODO add logging Failure.Builder eb = Failure.newBuilder(); eb.setId(state.getConf().getNodeId()); eb.setRefId(msg.getHeader().getNodeId()); eb.setMessage(e.getMessage()); WorkMessage.Builder rb = WorkMessage.newBuilder(msg); rb.setErr(eb); ChannelFuture cf = channel.write(rb.build()); channel.flush(); cf.awaitUninterruptibly(); if (cf.isDone() && !cf.isSuccess()) { logger.info("Failed to write the message to the channel "); } } System.out.flush(); }
From source file:gash.router.server.queue.CommandOutboundAppWorker.java
License:Apache License
@Override public void run() { Channel conn = sq.channel;/*from w w w.j a v a2 s. c o m*/ if (conn == null || !conn.isOpen()) { PerChannelCommandQueue.logger.error("connection missing, no outboundWork communication"); return; } while (true) { if (!forever && sq.outboundWork.size() == 0) break; try { // block until a message is enqueued GeneratedMessage msg = sq.outboundWork.take(); if (conn.isWritable()) { boolean rtn = false; if (sq.channel != null && sq.channel.isOpen() && sq.channel.isWritable()) { ChannelFuture cf = sq.channel.writeAndFlush(msg); logger.info("Server--sending -- command -- response"); // blocks on write - use listener to be async cf.awaitUninterruptibly(); logger.debug("Written to channel"); rtn = cf.isSuccess(); if (!rtn) { System.out.println("Sending failed " + rtn + "{Reason:" + cf.cause() + "}"); sq.outboundWork.putFirst(msg); } else logger.info("Message Sent"); } } else sq.outboundWork.putFirst(msg); } catch (InterruptedException ie) { break; } catch (Exception e) { logger.error("Unexpected communcation failure", e); break; } } if (!forever) { logger.debug("connection queue closing"); } }
From source file:gash.router.server.queue.GlobalCommandOutboundAppWorker.java
License:Apache License
@Override public void run() { Channel conn = sq.channel;/* w w w .jav a2 s .co m*/ if (conn == null || !conn.isOpen()) { PerChannelGlobalCommandQueue.logger.error("connection missing, no outboundWork communication"); return; } while (true) { if (!forever && sq.outboundWork.size() == 0) break; try { // block until a message is enqueued GeneratedMessage msg = sq.outboundWork.take(); if (conn.isWritable()) { boolean rtn = false; if (sq.channel != null && sq.channel.isOpen() && sq.channel.isWritable()) { ChannelFuture cf = sq.channel.writeAndFlush(msg); logger.info("Server--sending -- command -- response"); // blocks on write - use listener to be async cf.awaitUninterruptibly(); logger.debug("Written to channel"); rtn = cf.isSuccess(); if (!rtn) { System.out.println("Sending failed " + rtn + "{Reason:" + cf.cause() + "}"); sq.outboundWork.putFirst(msg); } else logger.info("Message Sent"); } } else sq.outboundWork.putFirst(msg); } catch (InterruptedException ie) { break; } catch (Exception e) { logger.error("Unexpected communcation failure", e); break; } } if (!forever) { logger.info("connection queue closing"); } }