List of usage examples for io.netty.channel ChannelFuture isSuccess
boolean isSuccess();
From source file:eu.stratosphere.runtime.io.network.netty.OutboundConnectionQueue.java
License:Apache License
@Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { writeAndFlushNextEnvelopeIfPossible(); } else if (future.cause() != null) { exceptionOccurred(future.cause()); } else {//from ww w . jav a 2 s . c o m exceptionOccurred(new Exception("Envelope send aborted.")); } }
From source file:freddo.dtalk2.client.netty.NettyClient.java
License:Apache License
public NettyClient(String name, URI uri) { mName = name;/*from w ww .ja v a 2s . co m*/ // connect... EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); String protocol = uri.getScheme(); if (!"ws".equals(protocol)) { throw new IllegalArgumentException("Unsupported protocol: " + protocol); } HttpHeaders customHeaders = new DefaultHttpHeaders(); // customHeaders.add("MyHeader", "MyValue"); // Connect with V13 (RFC 6455 aka HyBi-17). final NettyClientHandler handler = new NettyClientHandler(this, WebSocketClientHandshakerFactory .newHandshaker(uri, WebSocketVersion.V13, null, false, customHeaders)); b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast("http-codec", new HttpClientCodec()); pipeline.addLast("aggregator", new HttpObjectAggregator(8192)); pipeline.addLast("ws-handler", handler); } }); LOG.debug("WebSocket Client connecting..."); mChannel = b.connect(uri.getHost(), uri.getPort()) .addListener(new GenericFutureListener<ChannelFuture>() { @Override public void operationComplete(ChannelFuture f) throws Exception { if (!f.isSuccess()) { LOG.debug("Connection error", f.cause()); } } }).sync().channel(); LOG.debug("Handshake..."); handler.handshakeFuture().sync(); } catch (Exception e) { LOG.debug("Error: {}", e.getMessage()); // e.printStackTrace(); group.shutdownGracefully(); group = null; } }
From source file:gash.router.client.CommConnection.java
License:Apache License
/** * messages pass through this method (no queueing). We use a blackbox design * as much as possible to ensure we can replace the underlining * communication without affecting behavior. * <p>/*w w w.j a v a 2 s .co m*/ * NOTE: Package level access scope * * @param msg * @return */ public boolean write(CommandMessage msg) { if (msg == null) return false; else if (channel == null) throw new RuntimeException("missing channel"); // TODO a queue is needed to prevent overloading of the socket // connection. For the demonstration, we don't need it ChannelFuture cf = connect().writeAndFlush(msg); if (cf.isDone() && !cf.isSuccess()) { logger.error("failed to send message to server"); return false; } return true; }
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 w w w. ja va2 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 * //from w ww. j a v a 2 s. com * @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;/*w ww. jav a 2 s .co 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;/*from www . j a v a 2 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"); } }
From source file:gash.router.server.queue.WorkOutboundAppWorker.java
License:Apache License
@Override public void run() { Channel conn = sq.channel;/*from w w w .j av a2 s .com*/ if (conn == null || !conn.isOpen()) { PerChannelWorkQueue.logger.error("connection missing, no outboundWork communication"); return; } while (true) { if (!forever && sq.outbound.size() == 0) break; try { // block until a message is enqueued GeneratedMessage msg = sq.outbound.take(); if (conn.isWritable()) { boolean rtn = false; if (sq.channel != null && sq.channel.isOpen() && sq.channel.isWritable()) { ChannelFuture cf = sq.channel.writeAndFlush((Work.WorkRequest) msg); logger.info("Server--sending -- work-- response"); // blocks on write - use listener to be async cf.awaitUninterruptibly(); logger.debug("Written to channel"); rtn = cf.isSuccess(); if (!rtn) { logger.error("Sending failed " + rtn + "{Reason:" + cf.cause() + "}"); sq.outbound.putFirst(msg); } else logger.info("Message Sent"); } } else sq.outbound.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:http.HTTPResponseHandler.java
License:Open Source License
/** * Provide asynchronous response to HTTP2 request * * @param streamId StreamID//from w w w .ja v a 2 s. com * @return Response string */ public String getResponse(int streamId) { String message = streamIdResponseMap.get(streamId); if (message != null) { return message; } else { Entry<ChannelFuture, ChannelPromise> channelFutureChannelPromiseEntry = streamIdPromiseMap .get(streamId); if (channelFutureChannelPromiseEntry != null) { ChannelFuture writeFuture = channelFutureChannelPromiseEntry.getKey(); if (!writeFuture.awaitUninterruptibly(ServerUtil.HTTP2_RESPONSE_TIME_OUT, ServerUtil.HTTP2_RESPONSE_TIME_UNIT)) { streamIdPromiseMap.remove(streamId); throw new IllegalStateException("Timed out waiting to write for stream id " + streamId); } if (!writeFuture.isSuccess()) { streamIdPromiseMap.remove(streamId); throw new RuntimeException(writeFuture.cause()); } ChannelPromise promise = channelFutureChannelPromiseEntry.getValue(); if (!promise.awaitUninterruptibly(ServerUtil.HTTP2_RESPONSE_TIME_OUT, ServerUtil.HTTP2_RESPONSE_TIME_UNIT)) { streamIdPromiseMap.remove(streamId); throw new IllegalStateException("Timed out waiting for response on stream id " + streamId); } if (!promise.isSuccess()) { streamIdPromiseMap.remove(streamId); throw new RuntimeException(promise.cause()); } } } return streamIdResponseMap.get(streamId); }
From source file:http2.client.HttpResponseHandler.java
License:Apache License
/** * anticipated : ?//from ww w . j a v a 2 s.c o m * Wait (sequentially) for a time duration for each anticipated response * * @param timeout Value of time to wait for each response * @param unit Units associated with {@code timeout} * @see HttpResponseHandler#put(int, ChannelFuture, ChannelPromise) */ public void awaitResponses(long timeout, TimeUnit unit) { Iterator<Entry<Integer, Entry<ChannelFuture, ChannelPromise>>> itr = streamidPromiseMap.entrySet() .iterator(); while (itr.hasNext()) { Entry<Integer, Entry<ChannelFuture, ChannelPromise>> entry = itr.next(); ChannelFuture writeFuture = entry.getValue().getKey(); // if (!writeFuture.awaitUninterruptibly(timeout, unit)) { throw new IllegalStateException("Timed out waiting to write for stream id " + entry.getKey()); } // if (!writeFuture.isSuccess()) { throw new RuntimeException(writeFuture.cause()); } // ChannelPromise promise = entry.getValue().getValue(); if (!promise.awaitUninterruptibly(timeout, unit)) { throw new IllegalStateException("Timed out waiting for response on stream id " + entry.getKey()); } if (!promise.isSuccess()) { throw new RuntimeException(promise.cause()); } System.out.println("---Stream id: " + entry.getKey() + " received---"); itr.remove(); } }