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: 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 #2
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 #3
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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
Source File: PoolTradeTest.java    From ftdc with Apache License 2.0 5 votes vote down vote up
public void testFromFutureToBank() throws Exception {
	login();
	Channel ftdcChannel = ApplicationRuntime.getFtdcChannel(brokerid, userid);
	while(ftdcChannel == null) {
		ftdcChannel = ApplicationRuntime.getFtdcChannel(brokerid, userid);
		Thread.sleep(1000);
	}
	
	ByteBuf buffer = ftdcChannel.alloc().buffer();
	ReqFromFutureToBank reqFromFutureToBank = new ReqFromFutureToBank();
	reqFromFutureToBank.setBrokerID(brokerid);
	reqFromFutureToBank.setRequestID(6972);
	reqFromFutureToBank.setBankID("4");
	reqFromFutureToBank.setBankBranchID("0000");
	reqFromFutureToBank.setAccountID(userid);
	reqFromFutureToBank.setPassword("241398");
	reqFromFutureToBank.setTradeAmount(1);
	reqFromFutureToBank.setBankPassWord("241398");
	reqFromFutureToBank.setTradeCode(FtdcTradeCode.FutureToBank);
	reqFromFutureToBank.setSecuPwdFlag(FtdcPwdFlag.FTDC_BlankCheck);
	reqFromFutureToBank.setBankPwdFlag(FtdcPwdFlag.FTDC_NoCheck);
	reqFromFutureToBank.setVerifyCertNoFlag(FtdcYesNoIndicator.TDC_No);
	reqFromFutureToBank.setCurrencyID(FtdcCurrencyID.CNY);
	reqFromFutureToBank.write(buffer.retain());
	FtdcProtocol ftdc = new FtdcProtocol(FtdType.FTDTypeCompressed, buffer, FtdcType.REQ.type(), ri.getReqId(), TID.FromFutureToBankReq.id(), Sequence.FromFutureToBank);
	ftdcChannel.writeAndFlush(ftdc);
	
	Thread.sleep(WATI_TIME);
}
 
Example #13
Source File: Connection.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
/**
 * Return an existing {@link Connection} wrapper or create a simple new one
 *
 * @param channel channel to retrieve the connection reference from
 *
 * @return an existing {@link Connection} wrapper or create a simple new one
 */
static Connection from(Channel channel) {
	if(channel.hasAttr(ReactorNetty.CONNECTION)) {
		return channel.attr(ReactorNetty.CONNECTION)
		              .get();
	}
	return new ReactorNetty.SimpleConnection(channel).bind();
}
 
Example #14
Source File: EpollSocketChannel.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
EpollSocketChannel(Channel parent, int fd, InetSocketAddress remote) {
    super(parent, fd);
    config = new EpollSocketChannelConfig(this);
    // Directly cache the remote and local addresses
    // See https://github.com/netty/netty/issues/2359
    this.remote = remote;
    local = Native.localAddress(fd);
}
 
Example #15
Source File: SocketManager.java    From tx-lcn with Apache License 2.0 5 votes vote down vote up
public boolean noConnect(SocketAddress socketAddress) {
    for (Channel channel : channels) {
        if (channel.remoteAddress().toString().equals(socketAddress.toString())) {
            return false;
        }
    }
    return true;
}
 
Example #16
Source File: RemotingUtil.java    From TakinRPC with Apache License 2.0 5 votes vote down vote up
public static void closeChannel(Channel channel) {
    final String addrRemote = RemotingHelper.parseChannelRemoteAddr(channel);
    channel.close().addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            log.info("closeChannel: close the connection to remote address[{}] result: {}", addrRemote, future.isSuccess());
        }
    });
}
 
Example #17
Source File: PostgresWireProtocol.java    From crate with Apache License 2.0 5 votes vote down vote up
private void finishAuthentication(Channel channel) {
    assert authContext != null : "finishAuthentication() requires an authContext instance";
    try {
        User user = authContext.authenticate();
        String database = properties.getProperty("database");
        session = sqlOperations.createSession(database, user);
        Messages.sendAuthenticationOK(channel)
            .addListener(f -> sendParamsAndRdyForQuery(channel));
    } catch (Exception e) {
        Messages.sendAuthenticationError(channel, e.getMessage());
    } finally {
        authContext.close();
        authContext = null;
    }
}
 
Example #18
Source File: NettyDebugServer.java    From ffwd with Apache License 2.0 5 votes vote down vote up
public AsyncFuture<Void> start() {
    final ResolvableFuture<Void> future = async.future();

    final ServerBootstrap s = new ServerBootstrap();

    s.channel(NioServerSocketChannel.class);
    s.group(boss, worker);

    s.childHandler(new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(final Channel ch) {
            connected.add(ch);
            log.info("Connected {}", ch);

            ch.closeFuture().addListener((ChannelFutureListener) f -> {
                connected.remove(ch);
                log.info("Disconnected {}", ch);
            });
        }
    });

    s.bind(localAddress).addListener((ChannelFutureListener) f -> {
        if (!f.isSuccess()) {
            future.fail(f.cause());
            return;
        }

        log.info("Bound to {}", localAddress);

        if (!server.compareAndSet(null, f.channel())) {
            f.channel().close();
            future.fail(new IllegalStateException("server already started"));
            return;
        }

        future.resolve(null);
    });

    return future;
}
 
Example #19
Source File: ProtobufLengthPrefixedProtocolServer.java    From ffwd with Apache License 2.0 5 votes vote down vote up
@Override
public final ChannelInitializer<Channel> initializer() {
    return new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(Channel ch) throws Exception {
            ch
                .pipeline()
                .addLast(new LengthFieldBasedFrameDecoder(MAX_LENGTH, 0, 4), decoder, handler);
        }
    };
}
 
Example #20
Source File: FtdClientPool.java    From ftdc with Apache License 2.0 5 votes vote down vote up
@Override
  public void channelCreated(Channel ch) {
  	ch.pipeline().addLast(new FtdcDecoder());
ch.pipeline().addLast(new FtdcEncoder());
ch.pipeline().addLast(new IdleStateHandler(ApplicationRuntime.conf().getFtdcReaderIdle(), ApplicationRuntime.conf().getFtdcWriterIdle(), ApplicationRuntime.conf().getFtdcAllIdle(), TimeUnit.SECONDS));
ch.pipeline().addLast(new FtdHeartbeatHandler());
ch.pipeline().addLast(ApplicationRuntime.EEG, new FtdcHandler());
  }
 
Example #21
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;
	}
}
 
Example #22
Source File: ChatPacketInterceptor.java    From ChatMenuAPI with GNU Lesser General Public License v3.0 5 votes vote down vote up
private Channel getChannel(Player player)
{
	handleField.setAccessible(true);
	try
	{
		return (Channel) channelField.get(networkManagerField.get(connectionField.get(handleField.get(player))));
	}catch(IllegalAccessException e)
	{
		e.printStackTrace();
	}
	return null;
}
 
Example #23
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 #24
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 #25
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 #26
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 #27
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 #28
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 #29
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 #30
Source File: RemotingUtil.java    From sofa-bolt with Apache License 2.0 5 votes vote down vote up
/**
 * Parse the remote address of the channel.
 * 
 * @param channel
 * @return
 */
public static String parseRemoteAddress(final Channel channel) {
    if (null == channel) {
        return StringUtils.EMPTY;
    }
    final SocketAddress remote = channel.remoteAddress();
    return doParse(remote != null ? remote.toString().trim() : StringUtils.EMPTY);
}