List of usage examples for io.netty.channel ChannelFutureListener ChannelFutureListener
ChannelFutureListener
From source file:org.hongxi.whatsmars.remoting.netty.NettyRemotingAbstract.java
License:Apache License
public void invokeAsyncImpl(final Channel channel, final RemotingCommand request, final long timeoutMillis, final InvokeCallback invokeCallback) throws InterruptedException, RemotingTooMuchRequestException, RemotingTimeoutException, RemotingSendRequestException { long beginStartTime = System.currentTimeMillis(); final int opaque = request.getOpaque(); boolean acquired = this.semaphoreAsync.tryAcquire(timeoutMillis, TimeUnit.MILLISECONDS); if (acquired) { final SemaphoreReleaseOnlyOnce once = new SemaphoreReleaseOnlyOnce(this.semaphoreAsync); long costTime = System.currentTimeMillis() - beginStartTime; if (timeoutMillis < costTime) { once.release();// w w w . j ava 2 s .co m throw new RemotingTimeoutException("invokeAsyncImpl call timeout"); } final ResponseFuture responseFuture = new ResponseFuture(channel, opaque, timeoutMillis - costTime, invokeCallback, once); this.responseTable.put(opaque, responseFuture); try { channel.writeAndFlush(request).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture f) throws Exception { if (f.isSuccess()) { responseFuture.setSendRequestOK(true); return; } requestFail(opaque); log.warn("send a request command to channel <{}> failed.", RemotingHelper.parseChannelRemoteAddr(channel)); } }); } catch (Exception e) { responseFuture.release(); log.warn("send a request command to channel <" + RemotingHelper.parseChannelRemoteAddr(channel) + "> Exception", e); throw new RemotingSendRequestException(RemotingHelper.parseChannelRemoteAddr(channel), e); } } else { if (timeoutMillis <= 0) { throw new RemotingTooMuchRequestException("invokeAsyncImpl invoke too fast"); } else { String info = String.format( "invokeAsyncImpl tryAcquire semaphore timeout, %dms, waiting thread nums: %d semaphoreAsyncValue: %d", timeoutMillis, this.semaphoreAsync.getQueueLength(), this.semaphoreAsync.availablePermits()); log.warn(info); throw new RemotingTimeoutException(info); } } }
From source file:org.hongxi.whatsmars.remoting.netty.NettyRemotingAbstract.java
License:Apache License
public void invokeOnewayImpl(final Channel channel, final RemotingCommand request, final long timeoutMillis) throws InterruptedException, RemotingTooMuchRequestException, RemotingTimeoutException, RemotingSendRequestException {/*from w w w.j a v a 2s .com*/ request.markOnewayRPC(); boolean acquired = this.semaphoreOneway.tryAcquire(timeoutMillis, TimeUnit.MILLISECONDS); if (acquired) { final SemaphoreReleaseOnlyOnce once = new SemaphoreReleaseOnlyOnce(this.semaphoreOneway); try { channel.writeAndFlush(request).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture f) throws Exception { once.release(); if (!f.isSuccess()) { log.warn("send a request command to channel <" + channel.remoteAddress() + "> failed."); } } }); } catch (Exception e) { once.release(); log.warn("write send a request command to channel <" + channel.remoteAddress() + "> failed."); throw new RemotingSendRequestException(RemotingHelper.parseChannelRemoteAddr(channel), e); } } else { if (timeoutMillis <= 0) { throw new RemotingTooMuchRequestException("invokeOnewayImpl invoke too fast"); } else { String info = String.format( "invokeOnewayImpl tryAcquire semaphore timeout, %dms, waiting thread nums: %d semaphoreAsyncValue: %d", timeoutMillis, this.semaphoreOneway.getQueueLength(), this.semaphoreOneway.availablePermits()); log.warn(info); throw new RemotingTimeoutException(info); } } }
From source file:org.hornetq.core.protocol.stomp.WebSocketServerHandler.java
License:Apache License
private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception { // Allow only GET methods. if (req.getMethod() != GET) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN)); return;/*from ww w .j a v a 2s . com*/ } // Handshake WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory( this.getWebSocketLocation(req), "v10.stomp,v11.stomp", false); this.handshaker = wsFactory.newHandshaker(req); if (this.handshaker == null) { WebSocketServerHandshakerFactory.sendUnsupportedWebSocketVersionResponse(ctx.channel()); } else { ChannelFuture handshake = this.handshaker.handshake(ctx.channel(), req); handshake.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { // we need to insert an encoder that takes the underlying ChannelBuffer of a StompFrame.toHornetQBuffer and // wrap it in a binary web socket frame before letting the wsencoder send it on the wire future.channel().pipeline().addAfter("wsencoder", "binary-websocket-encoder", BINARY_WEBSOCKET_ENCODER); } else { // Handshake failed, fire an exceptionCaught event future.channel().pipeline().fireExceptionCaught(future.cause()); } } }); } }
From source file:org.iotivity.cloud.base.protocols.coap.websocket.WebSocketFrameHandler.java
License:Open Source License
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { Object newMsg = msg;/*from w w w . j a v a 2 s .c o m*/ if (msg instanceof DefaultFullHttpResponse) { ChannelFuture ch = ctx.writeAndFlush(newMsg); ch.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { Log.v(future.channel().id().asLongText().substring(26) + " WebSocket Handshake done, Address: " + future.channel().remoteAddress().toString()); // remove http encoder/decoder after handshake done. future.channel().pipeline().remove(HttpServerCodec.class); future.channel().pipeline().remove(HttpObjectAggregator.class); } }); return; } if (msg instanceof CoapMessage) { CoapMessage coapMessage = (CoapMessage) msg; // covert content format to json. if (coapMessage.getPayloadSize() != 0) { byte[] payload = coapMessage.getPayload(); coapMessage.setPayload(convertCborToJson(payload)); coapMessage.setContentFormat(ContentFormat.APPLICATION_JSON); } ByteBuf encodedBytes = Unpooled.buffer(); new CoapEncoder().encode((CoapMessage) msg, encodedBytes, true); WebSocketFrame frame = new BinaryWebSocketFrame(encodedBytes); newMsg = frame; } else { throw new InternalServerErrorException("invalid response message type"); } ctx.writeAndFlush(newMsg); }
From source file:org.iotivity.cloud.base.protocols.http.HCProxyHandler.java
License:Open Source License
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) { // Create HTTP response from the response HttpResponse httpResponse = null;// w w w . j ava 2s . c o m if (msg instanceof IResponse) { IResponse response = (IResponse) msg; HCProxyProcessor hcProxyProcessor = HCProxyHandler.hcProxyProcessorMap .get(ctx.channel().id().asLongText()); if (hcProxyProcessor != null) { /* * If HTTP request was sign-in and HTTP response is 200 OK, * then set HTTP Cookie in the response for the session. */ httpResponse = hcProxyProcessor.getHttpResponse(response); } if (httpResponse == null) { String errorStatusCode = "500 Internal Server Error: " + "HTTP response could not be generated."; Log.v("HTTP Error: " + errorStatusCode); httpResponse = hcProxyProcessor.getErrorResponse(errorStatusCode); } msg = httpResponse; } ChannelFuture future = ctx.writeAndFlush(msg); // Close the http connection after sending response future.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { future.channel().close(); } else { Log.v(ctx.channel().id().asLongText().substring(26) + " HTTP Disconnected (Unexpectedly), Address: " + ctx.channel().remoteAddress().toString()); } } }); }
From source file:org.it4y.integration.IT_TProxyListenerTest.java
License:Apache License
@Test public void testPerformanceMultibleClients() throws Exception { final Counter msgcnt = new Counter(); final Counter errcnt = new Counter(); LinkManager linkManager = null;/* w w w.jav a 2 s . c o m*/ TProxyListener proxy = null; try { linkManager = startLinkManager(); //get interface with default gateway. this will be our source IP final NetworkInterface defaultGW = linkManager.getDefaultGateway(); log.info("Default GW: {}", defaultGW); //Run a proxy to intercept port 80 . this requires setup-test.sh to setup iptables and routing proxy = startTProxyListener(new TProxyListener(InetAddress.getByName(bind), port, backlog) { public void newClient(TProxyInterceptedSocket client) throws IOException { //log.info("intercept client connection: {}", client); //check client connection parameters Assert.assertNotNull(client); //we should check local and remote address are unchanged (thats transparent proxy) Assert.assertEquals(0x08080404, client.getRemoteAddress()); Assert.assertEquals(80, client.getRemotePort()); Assert.assertTrue(client.getSocket().toString() .contains(defaultGW.getIpv4AddressAsInetAddress().toString())); msgcnt.inc(); } public void onIOError(IOException io) { errcnt.inc(); log.info("oeps some error: {}", io.getMessage(), io); } }); log.info("TProxy running..."); //we use NETTY to generated massive tcp connections EventLoopGroup workerGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors() * 40); Bootstrap b = new Bootstrap(); // (1) b.group(workerGroup); // (2) b.channel(NioSocketChannel.class); // (3) b.option(ChannelOption.SO_KEEPALIVE, true); // (4) Bootstrap handler = b.handler(new ChannelInitializer<NioSocketChannel>() { @Override protected void initChannel(NioSocketChannel ch) throws Exception { } }); // Start the client. int nrOfConnections = 1000; //going to high here will cause TO MANY FILES open, you should see man page ulimit ;-) log.info("Starting {} connections ....", nrOfConnections); long start = System.currentTimeMillis(); int retry = 0; for (int i = 0; i < nrOfConnections; i++) { final ChannelFuture f = b.connect("8.8.4.4", 80); f.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { //close when connected if (future.isSuccess()) { future.channel().disconnect(); } else { log.error("ooeps:", future.cause()); } } }); Thread.sleep(0, 2000); //sleep a small bit else we see issues in VM's } //log.info("Started: {} msec", System.currentTimeMillis() - start); //wait until all are closed while (msgcnt.getCount() < nrOfConnections & retry < nrOfConnections) { Thread.sleep(100); //on vm's this can be slow retry++; } long end = System.currentTimeMillis(); log.info("Done: {} msec", end - start); Assert.assertEquals(nrOfConnections, msgcnt.getCount()); Assert.assertEquals(0, errcnt.getCount()); } finally { if (linkManager != null) stopLinkManager(linkManager); if (proxy != null) stopTProxyListener(proxy); } }
From source file:org.jboss.aerogear.sync.DiffSyncHandler.java
License:Apache License
private void addCloseHandler(final ChannelHandlerContext ctx, final NettySubscriber subscriber, final String documentId) { ctx.channel().closeFuture().addListener(new ChannelFutureListener() { @Override/* www. ja va 2s .co m*/ public void operationComplete(final ChannelFuture future) throws Exception { syncEngine.removeSubscriber(subscriber, documentId); } }); }
From source file:org.jboss.errai.bus.server.io.websockets.WebSocketServerHandler.java
License:Apache License
private void handleWebSocketFrame(final ChannelHandlerContext ctx, final WebSocketFrame frame) { // Check for closing frame if (frame instanceof CloseWebSocketFrame) { activeChannels.remove(ctx.channel()); this.handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain()); return;//from ww w . ja v a 2s. com } if (frame instanceof PingWebSocketFrame) { ctx.channel().write(new PongWebSocketFrame(frame.content().retain())); return; } if (!(frame instanceof TextWebSocketFrame)) { throw new UnsupportedOperationException( String.format("%s frame types not supported", frame.getClass().getName())); } @SuppressWarnings("unchecked") final EJValue val = JSONDecoder.decode(((TextWebSocketFrame) frame).text()); final QueueSession session; // this is not an active channel. if (!activeChannels.containsKey(ctx.channel())) { if (val == null) { sendMessage(ctx, getFailedNegotiation("illegal handshake")); return; } final EJObject ejObject = val.isObject(); if (ejObject == null) { return; } final EJValue ejValue = ejObject.get(MessageParts.CommandType.name()); if (ejValue.isNull()) { sendMessage(ctx, getFailedNegotiation("illegal handshake")); } final String commandType = ejValue.isString().stringValue(); // this client apparently wants to connect. if (BusCommand.Associate.name().equals(commandType)) { final String sessionKey = ejObject.get(MessageParts.ConnectionSessionKey.name()).isString() .stringValue(); // has this client already attempted a connection, and is in a wait verify state if (sessionKey != null && (session = svc.getBus().getSessionBySessionId(sessionKey)) != null) { final LocalContext localContext = LocalContext.get(session); if (localContext.hasAttribute(SESSION_ATTR_WS_STATUS) && WEBSOCKET_ACTIVE .equals(localContext.getAttribute(String.class, SESSION_ATTR_WS_STATUS))) { final MessageQueue queueBySession = svc.getBus().getQueueBySession(sessionKey); queueBySession.setDeliveryHandler( DirectDeliveryHandler.createFor(new NettyQueueChannel(ctx.channel()))); // open the channel activeChannels.put(ctx.channel(), session); ctx.channel().closeFuture().addListener(new ChannelFutureListener() { @Override public void operationComplete(final ChannelFuture channelFuture) throws Exception { activeChannels.remove(ctx.channel()); queueBySession.setDeliveryHandlerToDefault(); } }); // set the session queue into direct channel mode. localContext.removeAttribute(SESSION_ATTR_WS_STATUS); // service.schedule(new Runnable() { // @Override // public void run() { // ctx.getChannel().close(); // } // }, 5, TimeUnit.SECONDS); return; } // check the activation key matches. final EJString activationKey = ejObject.get(MessageParts.WebSocketToken.name()).isString(); if (activationKey == null || !WebSocketTokenManager.verifyOneTimeToken(session, activationKey.stringValue())) { // nope. go away! sendMessage(ctx, getFailedNegotiation("bad negotiation key")); } else { // the key matches. now we send the reverse challenge to prove this client is actually // already talking to the bus over the COMET channel. final String reverseToken = WebSocketTokenManager.getNewOneTimeToken(session); localContext.setAttribute(MessageParts.WebSocketToken.name(), reverseToken); localContext.setAttribute(SESSION_ATTR_WS_STATUS, WEBSOCKET_AWAIT_ACTIVATION); // send the challenge. sendMessage(ctx, getReverseChallenge(reverseToken)); return; } sendMessage(ctx, getSuccessfulNegotiation()); } else { sendMessage(ctx, getFailedNegotiation("bad session id")); } } else { sendMessage(ctx, getFailedNegotiation("bad command")); } } else { // this is an active session. send the message. session = activeChannels.get(ctx.channel()); for (final Message msg : MessageFactory.createCommandMessage(session, val)) { msg.setResource(HttpServletRequest.class.getName(), new SyntheticHttpServletRequest()); svc.store(msg); } } }
From source file:org.jupiter.registry.DefaultRegistry.java
License:Apache License
/** * Notify to registry server unpublish corresponding service. *//*w w w . j a v a2 s . c om*/ public void doUnregister(final RegisterMeta meta) { registryService.registerMetaSet().remove(meta); Message msg = new Message(serializerType.value()); msg.messageCode(JProtocolHeader.PUBLISH_CANCEL_SERVICE); msg.data(meta); channel.writeAndFlush(msg).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { Channel ch = future.channel(); if (ch.isActive()) { ch.pipeline().fireExceptionCaught(future.cause()); } else { if (logger.isWarnEnabled()) { logger.warn("Unregister {} fail because of channel is inactive: {}.", meta, stackTrace(future.cause())); } } } } }); MessageNonAck msgNonAck = new MessageNonAck(msg, channel); messagesNonAck.put(msgNonAck.id, msgNonAck); }
From source file:org.jupiter.transport.netty.channel.NettyChannel.java
License:Apache License
@Override public JChannel close(final JFutureListener<JChannel> listener) { final JChannel jChannel = this; channel.close().addListener(new ChannelFutureListener() { @Override//from w w w. j a v a 2s . c o m public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { listener.operationSuccess(jChannel); } else { listener.operationFailure(jChannel, future.cause()); } } }); return jChannel; }