io.netty.channel.Channel Java Examples

The following examples show how to use io.netty.channel.Channel. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CustomModbusMasterResponseHandler.java    From easymodbus4j with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
protected void processResponseFrame(Channel channel, ModbusFrame respFrame) {
	super.processResponseFrame(channel, respFrame);
	int respTransactionIdentifier = respFrame.getHeader().getTransactionIdentifier();
	ModbusFrame reqFrame = ModebusFrameCacheFactory.getInstance().getRequestCache()
			.get(respTransactionIdentifier - this.getTransactionIdentifierOffset());
	boolean isErr = false;
	if (reqFrame != null) {
		if (reqFrame.getFunction() instanceof AbstractFunction) {
			AbstractFunction reqFunc = (AbstractFunction) reqFrame.getFunction();
			ModbusFunction respFunc = respFrame.getFunction();
			processResponseFrame(channel, reqFunc, respFunc);
		} else {
			isErr = true;
		}
	} else {
		isErr = true;
	}
	if (isErr) {
		logger.error(String.format("req is null:%s;%s", channel.remoteAddress(), respFrame));
	}
}
 
Example #2
Source File: NettyRequestExecutorTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void cancelExecuteFuture_channelAcquired_submitsRunnable() {
    EventLoop mockEventLoop = mock(EventLoop.class);
    Channel mockChannel = mock(Channel.class);
    when(mockChannel.eventLoop()).thenReturn(mockEventLoop);

    when(mockChannelPool.acquire(any(Promise.class))).thenAnswer((Answer<Promise>) invocationOnMock -> {
        Promise p = invocationOnMock.getArgumentAt(0, Promise.class);
        p.setSuccess(mockChannel);
        return p;
    });

    CompletableFuture<Void> executeFuture = nettyRequestExecutor.execute();

    executeFuture.cancel(true);

    verify(mockEventLoop).submit(any(Runnable.class));
}
 
Example #3
Source File: NioUdtMessageConnectorChannel.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
public NioUdtMessageConnectorChannel(final Channel parent, final SocketChannelUDT channelUDT) {
    super(parent, channelUDT, OP_READ);
    try {
        channelUDT.configureBlocking(false);
        switch (channelUDT.socketUDT().status()) {
        case INIT:
        case OPENED:
            config = new DefaultUdtChannelConfig(this, channelUDT, true);
            break;
        default:
            config = new DefaultUdtChannelConfig(this, channelUDT, false);
            break;
        }
    } catch (final Exception e) {
        try {
            channelUDT.close();
        } catch (final Exception e2) {
            if (logger.isWarnEnabled()) {
                logger.warn("Failed to close channel.", e2);
            }
        }
        throw new ChannelException("Failed to configure channel.", e);
    }
}
 
Example #4
Source File: ProducerManager.java    From reading-and-annotate-rocketmq-3.4.6 with GNU General Public License v3.0 6 votes vote down vote up
public HashMap<String, HashMap<Channel, ClientChannelInfo>> getGroupChannelTable() {
    HashMap<String /* group name */, HashMap<Channel, ClientChannelInfo>> newGroupChannelTable =
            new HashMap<String, HashMap<Channel, ClientChannelInfo>>();
    try {
        if (this.groupChannelLock.tryLock(LockTimeoutMillis, TimeUnit.MILLISECONDS)){
            try {
                newGroupChannelTable.putAll(groupChannelTable);
            } finally {
                groupChannelLock.unlock();
            }
        }
    } catch (InterruptedException e) {
       log.error("",e);
    }
    return newGroupChannelTable;
}
 
Example #5
Source File: ModelServerTest.java    From serve with Apache License 2.0 6 votes vote down vote up
@Test(
        alwaysRun = true,
        dependsOnMethods = {"testRegisterModelHttpError"})
public void testRegisterModelInvalidPath() throws InterruptedException {
    Channel channel = TestUtils.connect(true, configManager);
    Assert.assertNotNull(channel);

    HttpRequest req =
            new DefaultFullHttpRequest(
                    HttpVersion.HTTP_1_1,
                    HttpMethod.POST,
                    "/models?url=..%2Ffake.mar&synchronous=false");
    channel.writeAndFlush(req).sync();
    channel.closeFuture().sync();

    ErrorResponse resp = JsonUtils.GSON.fromJson(TestUtils.getResult(), ErrorResponse.class);

    Assert.assertEquals(resp.getCode(), HttpResponseStatus.NOT_FOUND.code());
    Assert.assertEquals(resp.getMessage(), "Relative path is not allowed in url: ../fake.mar");
}
 
Example #6
Source File: RedisMasterReplicationTrafficRateLimitTest.java    From x-pipe with Apache License 2.0 6 votes vote down vote up
@Override
public void masterDisconntected(Channel channel) {
    super.masterDisconntected(channel);

    redisKeeperServer.getKeeperMonitor().getReplicationStoreStats().refreshReplDownSince(System.currentTimeMillis());
    long interval = System.currentTimeMillis() - connectedTime;
    long scheduleTime = masterConnectRetryDelaySeconds * 1000 - interval;
    if (scheduleTime < 0) {
        scheduleTime = 0;
    }
    logger.info("[masterDisconntected][reconnect after {} ms]", scheduleTime);
    scheduled.schedule(new AbstractExceptionLogTask() {

        @Override
        public void doRun() {
            connectWithMaster();
        }
    }, scheduleTime, TimeUnit.MILLISECONDS);
}
 
Example #7
Source File: NettyHttpServletHandler.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

    LOG.log(Level.SEVERE, "UNEXPECTED_EXCEPCTION_IN_NETTY_SERVLET_HANDLER", cause);

    interceptOnRequestFailed(ctx, cause);

    Channel ch = ctx.channel();
    if (cause instanceof IllegalArgumentException) {

        ch.close();

    } else {

        if (cause instanceof TooLongFrameException) {
            sendError(ctx, HttpResponseStatus.BAD_REQUEST);
            return;
        }

        if (ch.isActive()) {
            sendError(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR);
        }

    }
    ctx.close();
}
 
Example #8
Source File: MixClient.java    From incubator-hivemall with Apache License 2.0 6 votes vote down vote up
@Override
public void sendCancelRequest(@Nonnull Object feature, @Nonnull MixedWeight mixed)
        throws Exception {
    assert (initialized);

    float weight = mixed.getWeight();
    float covar = mixed.getCovar();
    int deltaUpdates = mixed.getDeltaUpdates();

    MixMessage msg = new MixMessage(event, feature, weight, covar, deltaUpdates, true);
    assert (groupID != null);
    msg.setGroupID(groupID);

    // TODO REVIEWME consider mix server faults (what if mix server dead? Do not send cancel request?)
    NodeInfo server = router.selectNode(msg);
    Channel ch = channelMap.get(server);
    if (!ch.isActive()) {// reconnect
        SocketAddress remoteAddr = server.getSocketAddress();
        ch.connect(remoteAddr).sync();
    }

    ch.writeAndFlush(msg); // send asynchronously in the background
}
 
Example #9
Source File: ConnectorHandler.java    From Jupiter with Apache License 2.0 6 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    Channel ch = ctx.channel();

    if (msg instanceof JResponsePayload) {
        try {
            processor.handleResponse(NettyChannel.attachChannel(ch), (JResponsePayload) msg);
        } catch (Throwable t) {
            logger.error("An exception was caught: {}, on {} #channelRead().", StackTraceUtil.stackTrace(t), ch);
        }
    } else {
        logger.warn("Unexpected message type received: {}, channel: {}.", msg.getClass(), ch);

        ReferenceCountUtil.release(msg);
    }
}
 
Example #10
Source File: NettyChannelBuilder.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
NettyTransportFactory(ProtocolNegotiator protocolNegotiator,
    ChannelFactory<? extends Channel> channelFactory,
    Map<ChannelOption<?>, ?> channelOptions, ObjectPool<? extends EventLoopGroup> groupPool,
    boolean autoFlowControl, int flowControlWindow, int maxMessageSize, int maxHeaderListSize,
    long keepAliveTimeNanos, long keepAliveTimeoutNanos, boolean keepAliveWithoutCalls,
    TransportTracer.Factory transportTracerFactory, LocalSocketPicker localSocketPicker,
    boolean useGetForSafeMethods) {
  this.protocolNegotiator = checkNotNull(protocolNegotiator, "protocolNegotiator");
  this.channelFactory = channelFactory;
  this.channelOptions = new HashMap<ChannelOption<?>, Object>(channelOptions);
  this.groupPool = groupPool;
  this.group = groupPool.getObject();
  this.autoFlowControl = autoFlowControl;
  this.flowControlWindow = flowControlWindow;
  this.maxMessageSize = maxMessageSize;
  this.maxHeaderListSize = maxHeaderListSize;
  this.keepAliveTimeNanos = new AtomicBackoff("keepalive time nanos", keepAliveTimeNanos);
  this.keepAliveTimeoutNanos = keepAliveTimeoutNanos;
  this.keepAliveWithoutCalls = keepAliveWithoutCalls;
  this.transportTracerFactory = transportTracerFactory;
  this.localSocketPicker =
      localSocketPicker != null ? localSocketPicker : new LocalSocketPicker();
  this.useGetForSafeMethods = useGetForSafeMethods;
}
 
Example #11
Source File: ModelServerTest.java    From multi-model-server with Apache License 2.0 6 votes vote down vote up
private void testLoadingMemoryError() throws InterruptedException {
    Channel channel = connect(true);
    Assert.assertNotNull(channel);
    result = null;
    latch = new CountDownLatch(1);
    HttpRequest req =
            new DefaultFullHttpRequest(
                    HttpVersion.HTTP_1_1,
                    HttpMethod.POST,
                    "/models?url=loading-memory-error&model_name=memory_error&runtime=python&initial_workers=1&synchronous=true");
    channel.writeAndFlush(req);
    latch.await();

    Assert.assertEquals(httpStatus, HttpResponseStatus.INSUFFICIENT_STORAGE);
    channel.close();
}
 
Example #12
Source File: AbstractNettyEventListener.java    From reef with Apache License 2.0 5 votes vote down vote up
@Override
public void channelRead(final ChannelHandlerContext ctx, final Object msg) {
  final Channel channel = ctx.channel();
  final byte[] message = (byte[]) msg;

  if (LOG.isLoggable(Level.FINEST)) {
    LOG.log(Level.FINEST, "MessageEvent: local: {0} remote: {1} :: {2}", new Object[]{
        channel.localAddress(), channel.remoteAddress(), message});
  }

  if (message.length > 0) {
    // send to the dispatch stage
    this.stage.onNext(this.getTransportEvent(message, channel));
  }
}
 
Example #13
Source File: ProxyOutboundHandler.java    From JLilyPad with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void channelRead0(ChannelHandlerContext context, Packet packet) throws Exception {
	Channel channel = context.channel();
	if(this.proxySession == null || !this.proxySession.isInboundConnected()) {
		channel.close();
		return;
	}
	switch(this.state) {
	case LOGIN:
		if(packet.getOpcode() == LoginSuccessPacket.opcode) {
			this.state = ProxyState.INIT;
			this.proxySession.setRedirecting(true);
			context.channel().attr(StatefulPacketCodecProviderPair.attributeKey).get().setState(PlayStateCodecProvider.instance);
		} else if(packet.getOpcode() == LoginDisconnectPacket.opcode) {
			this.proxySession.disconnect(new PlayDisconnectPacket((((LoginDisconnectPacket) packet)).getJson()));
			channel.close();
		} else {
			this.proxySession.disconnectIfInitializing("Error: Protocol Mismatch");
			channel.close();
		}
		break;
	case INIT:
		if(packet.getOpcode() == 0x08) {
			this.state = ProxyState.CONNECTED;
			this.proxySession.setOutboundChannel(this.server, channel);
		}
	case CONNECTED:
		this.proxySession.outboundReceived(channel, packet);
		if(packet.getOpcode() == PlayDisconnectPacket.opcode) {
			this.state = ProxyState.DISCONNECTED;
		}
		break;
	default:
		break;
	}
}
 
Example #14
Source File: HttpRequestOperation.java    From styx with Apache License 2.0 5 votes vote down vote up
public void write() {
    Channel originChannel = this.nettyConnection.channel();
    if (originChannel.isActive()) {
        io.netty.handler.codec.http.HttpRequest httpRequest = makeRequest(request);

        originChannel.writeAndFlush(httpRequest)
            .addListener(subscribeToRequestBody());
    } else {
        responseFromOriginFlux.error(new TransportLostException(originChannel.remoteAddress(), nettyConnection.getOrigin()));
    }
}
 
Example #15
Source File: BungeeChannelInitializer.java    From ViaVersion with MIT License 5 votes vote down vote up
public BungeeChannelInitializer(ChannelInitializer<Channel> oldInit) {
    this.original = oldInit;
    try {
        this.method = ChannelInitializer.class.getDeclaredMethod("initChannel", Channel.class);
        this.method.setAccessible(true);
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    }
}
 
Example #16
Source File: PingInjector.java    From PingAPI with MIT License 5 votes vote down vote up
/**
 * Iterates through every open NetworkManager and adds my ChannelDuplexHandler subclass into the pipeline
 * This allows you to listen for outgoing packets and modify them before they are sent
 * 
 * The List of NetworkManager instances is converted to an array to avoid ConcurrentModificationExceptions
 * NullPointerExceptions, IllegalArgumentExceptions, and NoSuchElementException only occur if there is a massive amount of ping requests being sent to the server.
 * NullPointerExceptions are thrown when the pipeline has yet to be created. 
 * Since ping responses are handled on separate threads IllegalArgumentExceptions are thrown when this method is invoked at the same time on two different threads
 * This means the null check will be passed and this method will attempt to create a duplicate handler which throws this exception
 * NoSuchElementExceptions have a similar cause. They are caused when the "packet_handler" has yet to be added.
 * The best solution I could find is simply ignoring these exceptions
 */
public void injectOpenConnections() {
	try {
		Field field = ReflectUtils.getFirstFieldByType(NetworkManager.class, Channel.class);
		field.setAccessible(true);
		for(Object manager : networkManagers.toArray()) {
			Channel channel = (Channel) field.get(manager);
			if(channel.pipeline().context("pingapi_handler") == null && (channel.pipeline().context("packet_handler") != null)) {
				channel.pipeline().addBefore("packet_handler", "pingapi_handler", new DuplexHandler());
			}
		}
	} catch(IllegalAccessException e) {
		e.printStackTrace();
	} catch(NullPointerException | IllegalArgumentException | NoSuchElementException ignored) {}
}
 
Example #17
Source File: ReverseShadowSocksProxy.java    From panama with MIT License 5 votes vote down vote up
public ReverseShadowSocksProxy(Channel clientChannel,
                               Callback finish,
                               ShadowSocksConfiguration shadowSocksConfiguration,
                               NioEventLoopGroup eventLoopGroup,
                               ShadowsocksRequestResolver requestResolver) {
    super(clientChannel, finish, shadowSocksConfiguration, eventLoopGroup, requestResolver);
}
 
Example #18
Source File: PostgresWireProtocol.java    From crate with Apache License 2.0 5 votes vote down vote up
/**
 * Flush Message
 * | 'H' | int32 len
 * <p>
 * Flush forces the backend to deliver any data pending in it's output buffers.
 */
private void handleFlush(Channel channel) {
    try {
        // If we have deferred any executions we need to trigger a sync now because the client is expecting data
        // (That we've been holding back, as we don't eager react to `execute` requests. (We do that to optimize batch inserts))
        // The sync will also trigger a flush eventually if there are deferred executions.
        if (session.hasDeferredExecutions()) {
            session.sync();
        } else {
            channel.flush();
        }
    } catch (Throwable t) {
        Messages.sendErrorResponse(channel, t);
    }
}
 
Example #19
Source File: NettyClientRequestWrapper.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Override
public String getDestinationId() {
    if (this.channelHandlerContext != null) {
        final Channel channel = this.channelHandlerContext.channel();
        if (channel != null) {
            return NettyUtils.getEndPoint(channel.remoteAddress());
        }
    }
    return "Unknown";
}
 
Example #20
Source File: NativeController.java    From proxyee-down with Apache License 2.0 5 votes vote down vote up
@RequestMapping("installCert")
public FullHttpResponse installCert(Channel channel, FullHttpRequest request) throws Exception {
  Map<String, Object> data = new HashMap<>();
  boolean status;
  if (OsUtil.isUnix() || OsUtil.isWindowsXP()) {
    if (!AppUtil.checkIsInstalledCert()) {
      ExtensionCertUtil.buildCert(AppUtil.SSL_PATH, AppUtil.SUBJECT);
    }
    Desktop.getDesktop().open(new File(AppUtil.SSL_PATH));
    status = true;
  } else {
    //再检测一次,确保不重复安装
    if (!AppUtil.checkIsInstalledCert()) {
      if (ExtensionCertUtil.existsCert(AppUtil.SUBJECT)) {
        //存在无用证书需要卸载
        ExtensionCertUtil.uninstallCert(AppUtil.SUBJECT);
      }
      //生成新的证书
      ExtensionCertUtil.buildCert(AppUtil.SSL_PATH, AppUtil.SUBJECT);
      //安装
      ExtensionCertUtil.installCert(new File(AppUtil.CERT_PATH));
      //检测是否安装成功,可能点了取消就没安装成功
      status = AppUtil.checkIsInstalledCert();
    } else {
      status = true;
    }
  }
  data.put("status", status);
  if (status && !PDownProxyServer.isStart) {
    new Thread(() -> {
      try {
        AppUtil.startProxyServer();
      } catch (IOException e) {
        LOGGER.error("Start proxy server error", e);
      }
    }).start();
  }
  return HttpHandlerUtil.buildJson(data);
}
 
Example #21
Source File: H2ParentConnectionContext.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
H2ParentConnectionContext(final Channel channel, final BufferAllocator allocator, final Executor executor,
                          final FlushStrategy flushStrategy, @Nullable final Long idleTimeoutMs,
                          final HttpExecutionStrategy executionStrategy,
                          final KeepAliveManager keepAliveManager) {
    super(channel, executor);
    this.executionContext = new DefaultHttpExecutionContext(allocator, fromNettyEventLoop(channel.eventLoop()),
            executor, executionStrategy);
    this.flushStrategyHolder = new FlushStrategyHolder(flushStrategy);
    this.idleTimeoutMs = idleTimeoutMs;
    this.keepAliveManager = keepAliveManager;
    // Just in case the channel abruptly closes, we should complete the onClosing Completable.
    onClose().subscribe(onClosing::onComplete);
}
 
Example #22
Source File: Http2MultiplexedChannelPoolTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void failedConnectionAcquireNotifiesPromise() throws InterruptedException {
    IOException exception = new IOException();
    ChannelPool connectionPool = mock(ChannelPool.class);
    when(connectionPool.acquire()).thenReturn(new FailedFuture<>(loopGroup.next(), exception));

    ChannelPool pool = new Http2MultiplexedChannelPool(connectionPool, loopGroup.next(), null);

    Future<Channel> acquirePromise = pool.acquire().await();
    assertThat(acquirePromise.isSuccess()).isFalse();
    assertThat(acquirePromise.cause()).isEqualTo(exception);
}
 
Example #23
Source File: DefaultRegistry.java    From Jupiter with Apache License 2.0 5 votes vote down vote up
private static boolean attachPublishEventOnChannel(RegisterMeta meta, Channel channel) {
    Attribute<ConcurrentSet<RegisterMeta>> attr = channel.attr(C_PUBLISH_KEY);
    ConcurrentSet<RegisterMeta> registerMetaSet = attr.get();
    if (registerMetaSet == null) {
        ConcurrentSet<RegisterMeta> newRegisterMetaSet = new ConcurrentSet<>();
        registerMetaSet = attr.setIfAbsent(newRegisterMetaSet);
        if (registerMetaSet == null) {
            registerMetaSet = newRegisterMetaSet;
        }
    }

    return registerMetaSet.add(meta);
}
 
Example #24
Source File: SocketManager.java    From Raincat with GNU Lesser General Public License v3.0 5 votes vote down vote up
public Channel getChannelByModelName(final String name) {
    if (CollectionUtils.isNotEmpty(clients)) {
        final Optional<Channel> first = clients.stream().filter(channel ->
                Objects.equals(channel.remoteAddress().toString(), name))
                .findFirst();
        return first.orElse(null);
    }
    return null;
}
 
Example #25
Source File: SSLEngineTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
private static void verifyApplicationLevelProtocol(Channel channel, String expectedApplicationProtocol) {
    SslHandler handler = channel.pipeline().get(SslHandler.class);
    assertNotNull(handler);
    String appProto = handler.applicationProtocol();
    assertEquals(appProto, expectedApplicationProtocol);

    SSLEngine engine = handler.engine();
    if (engine instanceof Java9SslEngine) {
        // Also verify the Java9 exposed method.
        Java9SslEngine java9SslEngine = (Java9SslEngine) engine;
        assertEquals(expectedApplicationProtocol == null ? StringUtil.EMPTY_STRING : expectedApplicationProtocol,
                java9SslEngine.getApplicationProtocol());
    }
}
 
Example #26
Source File: ClientProtocolProcess.java    From ext-opensource-netty with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * B - S
 * @param channel
 * @param mqttMessage
 */
public void processUnSubBack(Channel channel, MqttMessage mqttMessage) {
	int messageId;
	if (mqttMessage instanceof MqttUnsubAckMessage) {
		MqttUnsubAckMessage mqttUnsubAckMessage = (MqttUnsubAckMessage) mqttMessage;
		messageId = mqttUnsubAckMessage.variableHeader().messageId();
	} else {
		MqttMessageIdVariableHeader o = (MqttMessageIdVariableHeader) mqttMessage.variableHeader();
		messageId = o.messageId();
		NettyLog.error("not UnsubAckMessage:{}", messageId);
	}
	this.consumerProcess.processUnSubBack(messageId);
}
 
Example #27
Source File: UdpClientConfig.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Override
protected ChannelFactory<? extends Channel> connectionFactory(EventLoopGroup elg, boolean isDomainSocket) {
	if (isDomainSocket) {
		throw new UnsupportedOperationException();
	}
	if (isPreferNative()) {
		return () -> loopResources().onChannel(DatagramChannel.class, elg);
	}
	else {
		return () -> new NioDatagramChannel(family());
	}
}
 
Example #28
Source File: BuilderUtils.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the correct Channel that wraps the given filedescriptor or {@code null} if not supported.
 *
 * @param group        the {@link EventLoopGroup} for which the class is needed
 * @param address      the filedescriptor to wrap.
 * @return the class that should be used for bootstrapping
 */
@Nullable
public static Channel socketChannel(EventLoopGroup group, FileDescriptorSocketAddress address) {
    if (useEpoll(group)) {
        return new EpollSocketChannel(address.getValue());
    }
    if (useKQueue(group)) {
        return new KQueueSocketChannel(address.getValue());
    }
    return null;
}
 
Example #29
Source File: Call.java    From xrpc with Apache License 2.0 5 votes vote down vote up
public ListenableFuture<FullHttpResponse> execute() throws URISyntaxException {
  Preconditions.checkState(request != null);
  final SettableFuture<FullHttpResponse> error = SettableFuture.create();
  final SettableFuture<FullHttpResponse> response = SettableFuture.create();
  final ListenableFuture<ChannelFuture> connectFuture =
      connect(XUrl.inetSocket(uri), client.bootstrap(), buildRetryLoop());

  Futures.addCallback(
      connectFuture,
      new FutureCallback<ChannelFuture>() {
        @Override
        public void onSuccess(ChannelFuture result) {
          try {
            Channel channel = result.await().channel();
            channel.writeAndFlush(request);

            HttpResponseHandler responseHandler =
                (HttpResponseHandler) channel.pipeline().get("responseHandler");
            response.setFuture(responseHandler.response());
          } catch (InterruptedException e) {
            response.cancel(true);
            error.setException(e);
          }
        }

        @Override
        public void onFailure(Throwable t) {
          response.cancel(true);
          error.setException(t);
        }
      },
      MoreExecutors.directExecutor());

  if (response.isCancelled()) {
    return error;
  } else {
    return response;
  }
}
 
Example #30
Source File: AbstractBounceHandler.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Nullable
protected String getIp(Channel channel) {
	SocketAddress address = channel.remoteAddress();
	if(address instanceof InetSocketAddress) {
		return ((InetSocketAddress) address).getAddress().getHostAddress();
	}
	else {
		logger.warn("Non inet socket address from client: {}", address);
		return null;
	}
}