List of usage examples for io.netty.channel ChannelFuture isSuccess
boolean isSuccess();
From source file:io.scalecube.socketio.pipeline.WebSocketHandler.java
License:Apache License
private boolean handshake(final ChannelHandlerContext ctx, final FullHttpRequest req, final String requestPath) { WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(getWebSocketLocation(req), null, false, maxWebSocketFrameSize); WebSocketServerHandshaker handshaker = wsFactory.newHandshaker(req); if (handshaker != null) { handshaker.handshake(ctx.channel(), req).addListener(new ChannelFutureListener() { @Override/*from ww w. jav a 2s. c o m*/ public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { final String sessionId = PipelineUtils.getSessionId(requestPath); connect(ctx, req, sessionId); } } }); return true; } else { WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel()); } return false; }
From source file:io.soliton.protobuf.AbstractRpcServer.java
License:Apache License
/** * Starts this server.//from w w w. ja v a 2s. co m * <p/> * <p>This is a synchronous operation.</p> */ public void startUp() throws Exception { logger.info(String.format("Starting RPC server on port %d", port)); ServerBootstrap bootstrap = new ServerBootstrap(); ChannelFuture futureChannel = bootstrap.group(parentGroup, childGroup).channel(channelClass) .childHandler(channelInitializer()).bind(port).awaitUninterruptibly(); if (futureChannel.isSuccess()) { this.channel = futureChannel.channel(); logger.info("RPC server started successfully."); } else { logger.info("Failed to start RPC server."); throw new Exception(futureChannel.cause()); } }
From source file:io.soliton.protobuf.json.HttpJsonRpcClient.java
License:Apache License
@Override public <O extends Message> ListenableFuture<O> encodeMethodCall(final ClientMethod<O> method, Message input) { clientLogger.logMethodCall(method);//from w ww. j a va 2 s. co m final JsonResponseFuture<O> responseFuture = handler.newProvisionalResponse(method); JsonObject request = new JsonRpcRequest(method.serviceName(), method.name(), new JsonPrimitive(responseFuture.requestId()), Messages.toJson(input)).toJson(); ByteBuf requestBuffer = Unpooled.buffer(); JsonWriter writer = new JsonWriter( new OutputStreamWriter(new ByteBufOutputStream(requestBuffer), Charsets.UTF_8)); GSON.toJson(request, writer); try { writer.flush(); } catch (IOException ioe) { // Deliberately ignored, as this doesn't involve any I/O } String host = ((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress(); QueryStringEncoder encoder = new QueryStringEncoder(rpcPath); encoder.addParam("pp", "0"); HttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, encoder.toString(), requestBuffer); httpRequest.headers().set(HttpHeaders.Names.HOST, host); httpRequest.headers().set(HttpHeaders.Names.CONTENT_TYPE, JsonRpcProtocol.CONTENT_TYPE); httpRequest.headers().set(HttpHeaders.Names.CONTENT_LENGTH, requestBuffer.readableBytes()); channel.writeAndFlush(httpRequest).addListener(new GenericFutureListener<ChannelFuture>() { public void operationComplete(ChannelFuture future) { if (!future.isSuccess()) { clientLogger.logLinkError(method, future.cause()); handler.finish(responseFuture.requestId()); responseFuture.setException(future.cause()); } } }); return responseFuture; }
From source file:io.soliton.protobuf.json.HttpJsonRpcClientTest.java
License:Apache License
@Test public void testEncodeMethodCallSuccess() throws InvalidProtocolBufferException { Channel channel = Mockito.mock(Channel.class); Mockito.when(channel.remoteAddress()) .thenReturn(new InetSocketAddress(InetAddress.getLoopbackAddress(), 10000)); ArgumentCaptor<Object> captor = ArgumentCaptor.forClass(Object.class); ChannelFuture success = Mockito.mock(ChannelFuture.class); Mockito.when(success.isDone()).thenReturn(true); Mockito.when(success.isSuccess()).thenReturn(true); Mockito.when(channel.writeAndFlush(captor.capture())).thenReturn(success); JsonRpcClientHandler handler = new JsonRpcClientHandler(); HttpJsonRpcClient client = new HttpJsonRpcClient(channel, handler, "/rpc", new NullClientLogger()); ClientMethod<TimeResponse> method = Mockito.mock(ClientMethod.class); Mockito.when(method.serviceName()).thenReturn("TimeService"); Mockito.when(method.name()).thenReturn("GetTime"); Mockito.when(method.outputBuilder()).thenReturn(TimeResponse.newBuilder()); client.encodeMethodCall(method, TimeRequest.newBuilder().setTimezone("UTC").build()); Assert.assertEquals(1, handler.inFlightRequests().size()); Object captured = captor.getValue(); Assert.assertTrue(captured instanceof FullHttpRequest); FullHttpRequest request = (FullHttpRequest) captured; Assert.assertEquals("/rpc?pp=0", request.getUri()); }
From source file:io.soliton.protobuf.quartz.QuartzClient.java
License:Apache License
/** * {@inheritDoc}/*from w w w .j a v a 2s .c o m*/ */ @Override public <O extends Message> ListenableFuture<O> encodeMethodCall(final ClientMethod<O> method, Message input) { // Channel was manually closed earlier if (refuseNewRequests.get()) { return Futures.immediateFailedFuture(new RuntimeException("Client is closed")); } // Channel was closed by the server - we make an attempt to reopen. if (shouldCreateNewChannel.get()) { try { reopenChannel(); channel.closeFuture().addListener(new ChannelCloser()); } catch (IOException ioe) { return Futures.immediateFailedFuture(ioe); } } // Normal operation mode clientLogger.logMethodCall(method); final EnvelopeFuture<O> output = handler.newProvisionalResponse(method); Envelope request = Envelope.newBuilder().setRequestId(output.requestId()).setService(method.serviceName()) .setMethod(method.name()).setPayload(input.toByteString()).build(); HttpRequest httpRequest = handler.convertRequest(request); channel.writeAndFlush(httpRequest).addListener(new GenericFutureListener<ChannelFuture>() { public void operationComplete(ChannelFuture future) { if (!future.isSuccess()) { clientLogger.logLinkError(method, future.cause()); handler.finish(output.requestId()); output.setException(future.cause()); } } }); return output; }
From source file:io.soliton.protobuf.socket.RpcClient.java
License:Apache License
/** * {@inheritDoc}/*from ww w . j a v a 2 s.com*/ */ @Override public <O extends Message> ListenableFuture<O> encodeMethodCall(final ClientMethod<O> method, Message input) { clientLogger.logMethodCall(method); final EnvelopeFuture<O> output = handler.newProvisionalResponse(method); Envelope request = Envelope.newBuilder().setRequestId(output.requestId()).setService(method.serviceName()) .setMethod(method.name()).setPayload(input.toByteString()).build(); // TODO(julien): might be nice to couple the future returned from writeAndFlush // into the one returned to the user, so that calling cancel on the userland // future may also cancel the outgoing request if it isn't done yet. channel.writeAndFlush(request).addListener(new GenericFutureListener<ChannelFuture>() { public void operationComplete(ChannelFuture future) { if (!future.isSuccess()) { clientLogger.logLinkError(method, future.cause()); handler.finish(output.requestId()); output.setException(future.cause()); } } }); return output; }
From source file:io.soliton.protobuf.socket.RpcClientTest.java
License:Apache License
@Test public void testEncodeMethodCallSuccess() throws InvalidProtocolBufferException { Channel channel = Mockito.mock(Channel.class); ArgumentCaptor<Object> captor = ArgumentCaptor.forClass(Object.class); ChannelFuture success = Mockito.mock(ChannelFuture.class); Mockito.when(success.isDone()).thenReturn(true); Mockito.when(success.isSuccess()).thenReturn(true); Mockito.when(channel.writeAndFlush(captor.capture())).thenReturn(success); RpcClientHandler handler = new RpcClientHandler(); RpcClient client = new RpcClient(channel, handler, new NullClientLogger()); ClientMethod<TimeResponse> method = Mockito.mock(ClientMethod.class); Mockito.when(method.serviceName()).thenReturn("TimeService"); Mockito.when(method.name()).thenReturn("GetTime"); Mockito.when(method.outputParser()).thenReturn(TimeResponse.PARSER); client.encodeMethodCall(method, TimeRequest.newBuilder().setTimezone("UTC").build()); Assert.assertEquals(1, handler.inFlightRequests().size()); Object captured = captor.getValue(); Assert.assertTrue(captured instanceof Envelope); Envelope request = (Envelope) captured; Assert.assertTrue(request.hasPayload()); TimeRequest timeRequest = TimeRequest.parseFrom(request.getPayload()); Assert.assertEquals("UTC", timeRequest.getTimezone()); }
From source file:io.undertow.websockets.utils.WebSocketTestClient.java
License:Open Source License
/** * Send the WebSocketFrame and call the FrameListener once a frame was received as response or * when an Exception was caught.//w ww . j av a 2s . co m */ public WebSocketTestClient send(WebSocketFrame frame, final FrameListener listener) { ch.pipeline().addLast("responseHandler" + count.incrementAndGet(), new SimpleChannelInboundHandler<Object>() { @Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof CloseWebSocketFrame) { closed = true; } listener.onFrame((WebSocketFrame) msg); ctx.pipeline().remove(this); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); listener.onError(cause); ctx.pipeline().remove(this); } }); ChannelFuture cf = ch.writeAndFlush(frame).syncUninterruptibly(); if (!cf.isSuccess()) { listener.onError(cf.cause()); } return this; }
From source file:io.urmia.proxy.DirectWriteBackHttpProxyBackendHandler.java
License:Open Source License
@Override public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception { inboundChannel.writeAndFlush(msg).addListener(new ChannelFutureListener() { @Override/*ww w . j a v a2s. c o m*/ public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { //log.info("success on write back to inbound"); ctx.channel().read(); } else { log.warn("fail on write to back to inbound: {}", future.cause()); future.channel().close(); } } }); }
From source file:io.urmia.proxy.HttpProxyFrontendHandler.java
License:Open Source License
private Channel openOutboundChannel(final ChannelHandlerContext ctx, String remoteHost, int remotePort, final int index) { log.info("proxy opening outbound channel to({}): {}:{}", index, remoteHost, remotePort); Bootstrap b = new Bootstrap(); b.group(new NioEventLoopGroup()).channel(NioSocketChannel.class) .handler(new HttpProxyBackendInitializer(ctx, index, directWriteBack)) .option(ChannelOption.AUTO_READ, false); ChannelFuture f = b.connect(remoteHost, remotePort); Channel outboundChannel = f.channel(); f.addListener(new GenericFutureListener<ChannelFuture>() { @Override/*from w w w. j ava 2 s . co m*/ public void operationComplete(ChannelFuture futureC) throws Exception { if (futureC.isSuccess()) { futureC.channel().writeAndFlush(initHttpRequest) .addListener(new GenericFutureListener<ChannelFuture>() { @Override public void operationComplete(ChannelFuture futureW) throws Exception { if (futureW.isSuccess()) onSuccessfulWrite(ctx, index); else { log.info("unable to write http request: {}", futureW.cause()); ctx.fireUserEventTriggered(new ProxyUserEvent(OUTBOUND_ERROR, index)); } } }); } else { ctx.fireUserEventTriggered(new ProxyUserEvent(OUTBOUND_ERROR, index)); } } }); return outboundChannel; }