Java Examples for io.netty.channel.ChannelHandler

The following java examples will help you to understand the usage of io.netty.channel.ChannelHandler. These source code samples are taken from different open source projects.

Example 1
Project: moco-master  File: MocoClient.java View source code
public void run(final String host, final int port, final ChannelHandler pipelineFactory) {
    EventLoopGroup group = new NioEventLoopGroup();
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(group).channel(NioSocketChannel.class).remoteAddress(host, port).option(ChannelOption.TCP_NODELAY, true).handler(pipelineFactory);
    try {
        Channel channel = bootstrap.connect().sync().channel();
        ChannelFuture future = channel.closeFuture().sync();
        future.addListener(ChannelFutureListener.CLOSE);
    } catch (InterruptedException e) {
        throw new MocoException(e);
    } finally {
        group.shutdownGracefully();
    }
}
Example 2
Project: netty-cookbook-master  File: BootstrapTemplate.java View source code
public static void newHttpClientBootstrap(String url, ChannelHandler handler) throws Exception {
    URI uri = new URI(url);
    String scheme = uri.getScheme() == null ? "http" : uri.getScheme();
    String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
    int port = uri.getPort();
    if (port == -1) {
        if ("http".equalsIgnoreCase(scheme)) {
            port = 80;
        } else if ("https".equalsIgnoreCase(scheme)) {
            port = 443;
        }
    }
    if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) {
        System.err.println("Only HTTP(S) is supported.");
        return;
    }
    // Configure SSL context if necessary.
    final boolean ssl = "https".equalsIgnoreCase(scheme);
    final SslContext sslCtx;
    if (ssl) {
        sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
    } else {
        sslCtx = null;
    }
    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new HttpDownloadertInitializer(sslCtx, handler));
        // Make the connection attempt.
        Channel ch = b.connect(host, port).sync().channel();
        // Prepare the HTTP request.
        HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath());
        HttpHeaders headers = request.headers();
        headers.set(HttpHeaders.Names.HOST, host);
        headers.set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
        headers.set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);
        // Set some example cookies.
        headers.set(HttpHeaders.Names.COOKIE, ClientCookieEncoder.encode(new DefaultCookie("my-cookie", "foo")));
        ch.writeAndFlush(request);
        // Wait for the server to close the connection.
        ch.closeFuture().sync();
        Thread.sleep(1000);
    } finally {
        // Shut down executor threads to exit.
        group.shutdownGracefully();
    }
}
Example 3
Project: activemq-artemis-master  File: CertificateUtil.java View source code
public static X509Certificate[] getCertsFromChannel(Channel channel) {
    X509Certificate[] certificates = null;
    ChannelHandler channelHandler = channel.pipeline().get("ssl");
    if (channelHandler != null && channelHandler instanceof SslHandler) {
        SslHandler sslHandler = (SslHandler) channelHandler;
        try {
            certificates = sslHandler.engine().getSession().getPeerCertificateChain();
        } catch (SSLPeerUnverifiedException e) {
        }
    }
    return certificates;
}
Example 4
Project: armeria-master  File: HttpSession.java View source code
static HttpSession get(Channel ch) {
    final ChannelHandler lastHandler = ch.pipeline().last();
    if (lastHandler instanceof HttpSession) {
        return (HttpSession) lastHandler;
    }
    for (ChannelHandler h : ch.pipeline().toMap().values()) {
        if (h instanceof HttpSession) {
            return (HttpSession) h;
        }
    }
    return INACTIVE;
}
Example 5
Project: barchart-udt-master  File: UdtNetty.java View source code
public static void main(final String[] args) throws Exception {
    log.info("init");
    TrafficControl.delay(0);
    final AtomicBoolean isOn = new AtomicBoolean(true);
    final InetSocketAddress addr1 = UnitHelp.localSocketAddress();
    final InetSocketAddress addr2 = UnitHelp.localSocketAddress();
    final ChannelHandler handler1 = new EchoMessageHandler(rate, size);
    final ChannelHandler handler2 = new EchoMessageHandler(null, size);
    final Bootstrap peerBoot1 = BootHelp.messagePeerBoot(addr1, addr2, handler1);
    final Bootstrap peerBoot2 = BootHelp.messagePeerBoot(addr2, addr1, handler2);
    final ChannelFuture peerFuture1 = peerBoot1.connect();
    final ChannelFuture peerFuture2 = peerBoot2.connect();
    CustomReporter.enable(3, TimeUnit.SECONDS);
    Thread.sleep(time);
    isOn.set(false);
    Thread.sleep(1 * 1000);
    peerFuture1.channel().close().sync();
    peerFuture2.channel().close().sync();
    Thread.sleep(1 * 1000);
    peerBoot1.shutdown();
    peerBoot2.shutdown();
    Metrics.defaultRegistry().shutdown();
    TrafficControl.delay(0);
    log.info("done");
}
Example 6
Project: Bukkit-Connect-master  File: NettyInjector.java View source code
@SuppressWarnings("unchecked")
public static int injectAndFindPort(Server server, NettyInjectHandler handler) throws Exception {
    Method serverGetHandle = server.getClass().getDeclaredMethod("getServer");
    Object minecraftServer = serverGetHandle.invoke(server);
    // Get Server Connection
    Method serverConnectionMethod = null;
    for (Method method : minecraftServer.getClass().getSuperclass().getDeclaredMethods()) {
        if (!method.getReturnType().getSimpleName().equals("ServerConnection")) {
            continue;
        }
        serverConnectionMethod = method;
        break;
    }
    Object serverConnection = serverConnectionMethod.invoke(minecraftServer);
    // Get ChannelFuture List // TODO find the field dynamically
    List<ChannelFuture> channelFutureList = ReflectionUtils.getPrivateField(serverConnection.getClass(), serverConnection, List.class, ConnectPlugin.getProtocol().getNettyInjectorChannelFutureList());
    // Iterate ChannelFutures
    int commonPort = 0;
    for (ChannelFuture channelFuture : channelFutureList) {
        // Get ChannelPipeline
        ChannelPipeline channelPipeline = channelFuture.channel().pipeline();
        // Get ServerBootstrapAcceptor
        ChannelHandler serverBootstrapAcceptor = channelPipeline.last();
        // Get Old ChildHandler
        ChannelInitializer<SocketChannel> oldChildHandler = ReflectionUtils.getPrivateField(serverBootstrapAcceptor.getClass(), serverBootstrapAcceptor, ChannelInitializer.class, "childHandler");
        // Set New ChildHandler
        ReflectionUtils.setFinalField(serverBootstrapAcceptor.getClass(), serverBootstrapAcceptor, "childHandler", new NettyChannelInitializer(handler, oldChildHandler));
        // Update Common Port
        commonPort = ((InetSocketAddress) channelFuture.channel().localAddress()).getPort();
    }
    return commonPort;
}
Example 7
Project: giraph-master  File: PipelineUtils.java View source code
/**
   * Add a handler to pipeline if it is not already added
   * and configure the handler to use an executor group based on equality
   * of compareTo and handlerName
   *
   * @param handlerName string name of the handler
   * @param handler channelhandler object
   * @param compareTo string name to compare to for executorgroup usage check
   * @param executor executorgroup instance
   * @param channel netty channel
   */
public static void addLastWithExecutorCheck(String handlerName, ChannelHandler handler, String compareTo, EventExecutorGroup executor, Channel channel) {
    ChannelPipeline pipeline = channel.pipeline();
    if (channel.pipeline().get(handlerName) != null) {
        return;
    }
    if (compareTo.equals(handlerName)) {
        pipeline.addLast(executor, handlerName, handler);
    } else {
        pipeline.addLast(handlerName, handler);
    }
}
Example 8
Project: hasor-master  File: HproseProtocolHandler.java View source code
@Override
public ChannelHandler[] channelHandler(Connector connector, AppContext appContext) {
    RsfContext rsfContext = appContext.getInstance(RsfContext.class);
    RsfDuplexHandler inHandler = new //
    RsfDuplexHandler(//
    new HttpRequestDecoder(), //
    new HttpResponseEncoder());
    RsfDuplexHandler outHandler = new //
    RsfDuplexHandler(//
    new HttpResponseDecoder(), //
    new HttpRequestEncoder());
    return new ChannelHandler[] { //
    inHandler, //
    new HproseHttpCoder(rsfContext) };
}
Example 9
Project: netty-utils-master  File: HttpPipeline.java View source code
@Override
protected void initChannel(Channel ch) throws Exception {
    ch.pipeline().addLast(new ProxyHandler());
    ch.pipeline().addLast(new HttpServerCodec());
    ch.pipeline().addLast(new HttpObjectAggregator(1024 * 10));
    ch.pipeline().addLast(new AutoCloseHandler());
    ch.pipeline().addLast(new HttpResponseDecorator());
    ch.pipeline().addLast("catchall", new HttpCatchAllHandler());
    for (Provider<? extends ChannelHandler> provider : appHandlers) {
        try {
            ChannelHandler handler = provider.get();
            ch.pipeline().addBefore("catchall", handler.getClass().getName(), handler);
        } catch (Exception e) {
            LOG.error(e.getMessage());
            ch.pipeline().fireExceptionCaught(e);
        }
    }
}
Example 10
Project: NettyThrift-master  File: HttpThriftBufDecoder.java View source code
/**
	 * handle WebSocket request,then, the the RPC could happen in WebSocket.
	 * 
	 * @param ctx
	 * @param request
	 */
protected void handleWebSocket(final ChannelHandlerContext ctx, FullHttpRequest request) {
    if (logger.isDebugEnabled()) {
        logger.debug("handleWebSocket request: uri={}", request.uri());
    }
    // Handshake
    WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(request.uri(), null, true);
    WebSocketServerHandshaker handshaker = wsFactory.newHandshaker(request);
    if (handshaker == null) {
        WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
        return;
    }
    ChannelFutureListener callback = websocketHandshakeListener(ctx, request);
    ChannelFuture future = handshaker.handshake(ctx.channel(), request);
    if (callback != null) {
        future.addListener(callback);
    }
    ChannelPipeline pipe = ctx.pipeline();
    if (pipe.get(WebsocketFrameHandler.class) == null) {
        pipe.addAfter(ctx.name(), "wsFrameHandler", new WebsocketFrameHandler(handshaker));
        ChannelHandler handlerAws = pipe.get(AwsProxyProtocolDecoder.class);
        if (handlerAws != null) {
            pipe.remove(handlerAws);
        }
        // Remove current Handler
        pipe.remove(ctx.name());
    }
}
Example 11
Project: odp-ovsdb-master  File: ConnectionService.java View source code
@Override
public void initChannel(SocketChannel channel) throws Exception {
    if (handlers == null) {
        channel.pipeline().addLast(//new LoggingHandler(LogLevel.INFO),
        new JsonRpcDecoder(100000), new StringEncoder(CharsetUtil.UTF_8));
    } else {
        for (ChannelHandler handler : handlers) {
            channel.pipeline().addLast(handler);
        }
    }
}
Example 12
Project: tajo-master  File: NettyRestHandlerContainerProviderTest.java View source code
@Test
public void testCreation() throws Exception {
    ChannelHandler handler = provider.createContainer(ChannelHandler.class, applicationHandler);
    assertNotNull(handler);
    ChannelInboundHandler inboundHandler = provider.createContainer(ChannelInboundHandler.class, applicationHandler);
    assertNotNull(inboundHandler);
    NettyRestHandlerContainer container = provider.createContainer(NettyRestHandlerContainer.class, applicationHandler);
    assertNotNull(container);
}
Example 13
Project: infinispan-master  File: NettyJaxrsServer.java View source code
private void setupHandlers(SocketChannel ch, RequestDispatcher dispatcher, RestEasyHttpRequestDecoder.Protocol protocol) {
    ChannelPipeline channelPipeline = ch.pipeline();
    channelPipeline.addLast(channelHandlers.toArray(new ChannelHandler[channelHandlers.size()]));
    channelPipeline.addLast(new HttpRequestDecoder(maxInitialLineLength, maxHeaderSize, maxChunkSize));
    channelPipeline.addLast(new HttpObjectAggregator(maxRequestSize));
    channelPipeline.addLast(new HttpResponseEncoder());
    channelPipeline.addLast(httpChannelHandlers.toArray(new ChannelHandler[httpChannelHandlers.size()]));
    channelPipeline.addLast(new RestEasyHttpRequestDecoder(dispatcher.getDispatcher(), root, protocol));
    channelPipeline.addLast(new RestEasyHttpResponseEncoder());
    if (idleTimeout > 0) {
        channelPipeline.addLast("idleStateHandler", new IdleStateHandler(0, 0, idleTimeout));
    }
    channelPipeline.addLast(eventExecutor, new RequestHandler(dispatcher));
}
Example 14
Project: Resteasy-master  File: NettyJaxrsServer.java View source code
private void setupHandlers(SocketChannel ch, RequestDispatcher dispatcher, RestEasyHttpRequestDecoder.Protocol protocol) {
    ChannelPipeline channelPipeline = ch.pipeline();
    channelPipeline.addLast(channelHandlers.toArray(new ChannelHandler[channelHandlers.size()]));
    channelPipeline.addLast(new HttpRequestDecoder(maxInitialLineLength, maxHeaderSize, maxChunkSize));
    channelPipeline.addLast(new HttpObjectAggregator(maxRequestSize));
    channelPipeline.addLast(new HttpResponseEncoder());
    channelPipeline.addLast(httpChannelHandlers.toArray(new ChannelHandler[httpChannelHandlers.size()]));
    channelPipeline.addLast(new RestEasyHttpRequestDecoder(dispatcher.getDispatcher(), root, protocol));
    channelPipeline.addLast(new RestEasyHttpResponseEncoder());
    if (idleTimeout > 0) {
        channelPipeline.addLast("idleStateHandler", new IdleStateHandler(0, 0, idleTimeout));
    }
    channelPipeline.addLast(eventExecutor, new RequestHandler(dispatcher));
}
Example 15
Project: jframe-master  File: HttpReqDispatcher.java View source code
/**
	 * request regular expression
	 */
// public final static Pattern Req_Regx = Pattern
// .compile("\\/(.*?)\\/(.*?)(?:\\/(.*))?");
@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
    if (msg instanceof HttpRequest) {
        HttpRequest req = (HttpRequest) msg;
        if (LOG.isDebugEnabled()) {
            LOG.debug("Dispatch req path {}", req.getUri());
        }
        // pay client req
        final String reqUrl = req.getUri();
        Map<String, WeakReference<String>> cache = _cache;
        WeakReference<String> wr = cache.get(reqUrl);
        String clazz = wr != null && wr.get() != null ? wr.get() : null;
        if (clazz != null) {
            if (reqUrl.startsWith("/img/down/")) {
                ctx.pipeline().addLast("http aggregator", new HttpObjectAggregator(65536));
                ctx.pipeline().addLast("http chunk", new ChunkedWriteHandler());
            }
            ctx.pipeline().addLast((ChannelHandler) getClass().getClassLoader().loadClass(clazz).newInstance());
        } else {
            List<Dispatcher> list = _dispatcher;
            for (Dispatcher d : list) {
                if (Pattern.matches(d.getUrl(), reqUrl)) {
                    if (d.getId().equals("img.down")) {
                        ctx.pipeline().remove("http compressor");
                        ctx.pipeline().addLast("http aggregator", new HttpObjectAggregator(// 
                        65536));
                        ctx.pipeline().addLast("http chunk", new ChunkedWriteHandler());
                    }
                    ctx.pipeline().addLast((ChannelHandler) getClass().getClassLoader().loadClass(d.getClazz()).newInstance());
                    cache.put(reqUrl, new WeakReference<String>(d.getClazz()));
                    break;
                }
            }
        }
    }
    //		ReferenceCountUtil.retain(msg);
    ctx.fireChannelRead(msg);
}
Example 16
Project: BuildCraft-master  File: ThreadSafeUtils.java View source code
/**
	 * This function assumes that you're using BC's ChannelHandler system, which only has one
	 * channel handler. This might get very messy otherwise.
	 * TODO: HACK - Can we rewrite this for BC 7.1 along with the whole network system to be somewhat more sane? Please?
	 *
	 * @param packet
	 * @param channel
	 * @return
	 */
public static net.minecraft.network.Packet generatePacketFrom(Packet packet, FMLEmbeddedChannel channel) {
    ByteBuf data = Unpooled.buffer();
    for (io.netty.channel.ChannelHandler h : channel.pipeline().toMap().values()) {
        if (h instanceof ChannelHandler) {
            data.writeByte(((ChannelHandler) h).getDiscriminator(packet.getClass()));
            break;
        }
    }
    packet.writeData(data);
    return new FMLProxyPacket(data.copy(), channel.attr(NetworkRegistry.FML_CHANNEL).get());
}
Example 17
Project: camel-master  File: NettyProducer.java View source code
public void processWithConnectedChannel(final Exchange exchange, final BodyReleaseCallback callback, final ChannelFuture channelFuture, final Object body) {
    // remember channel so we can reuse it
    final Channel channel = channelFuture.channel();
    if (getConfiguration().isReuseChannel() && exchange.getProperty(NettyConstants.NETTY_CHANNEL) == null) {
        exchange.setProperty(NettyConstants.NETTY_CHANNEL, channel);
        // and defer closing the channel until we are done routing the exchange
        exchange.addOnCompletion(new SynchronizationAdapter() {

            @Override
            public void onComplete(Exchange exchange) {
                // should channel be closed after complete?
                Boolean close;
                if (ExchangeHelper.isOutCapable(exchange)) {
                    close = exchange.getOut().getHeader(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE, Boolean.class);
                } else {
                    close = exchange.getIn().getHeader(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE, Boolean.class);
                }
                // should we disconnect, the header can override the configuration
                boolean disconnect = getConfiguration().isDisconnect();
                if (close != null) {
                    disconnect = close;
                }
                if (disconnect) {
                    LOG.trace("Closing channel {} as routing the Exchange is done", channel);
                    NettyHelper.close(channel);
                }
                releaseChannel(channelFuture);
            }
        });
    }
    if (exchange.getIn().getHeader(NettyConstants.NETTY_REQUEST_TIMEOUT) != null) {
        long timeoutInMs = exchange.getIn().getHeader(NettyConstants.NETTY_REQUEST_TIMEOUT, Long.class);
        ChannelHandler oldHandler = channel.pipeline().get("timeout");
        ReadTimeoutHandler newHandler = new ReadTimeoutHandler(timeoutInMs, TimeUnit.MILLISECONDS);
        if (oldHandler == null) {
            channel.pipeline().addBefore("handler", "timeout", newHandler);
        } else {
            channel.pipeline().replace(oldHandler, "timeout", newHandler);
        }
    }
    //This will refer to original callback since netty will release body by itself
    final AsyncCallback producerCallback;
    if (configuration.isReuseChannel()) {
        // use callback as-is because we should not put it back in the pool as NettyProducerCallback would do
        // as when reuse channel is enabled it will put the channel back in the pool when exchange is done using on completion
        producerCallback = callback.getOriginalCallback();
    } else {
        producerCallback = new NettyProducerCallback(channelFuture, callback.getOriginalCallback());
    }
    // setup state as attachment on the channel, so we can access the state later when needed
    putState(channel, new NettyCamelState(producerCallback, exchange));
    // here we need to setup the remote address information here
    InetSocketAddress remoteAddress = null;
    if (!isTcp()) {
        remoteAddress = new InetSocketAddress(configuration.getHost(), configuration.getPort());
    }
    // write body
    NettyHelper.writeBodyAsync(LOG, channel, remoteAddress, body, exchange, new ChannelFutureListener() {

        public void operationComplete(ChannelFuture channelFuture) throws Exception {
            LOG.trace("Operation complete {}", channelFuture);
            if (!channelFuture.isSuccess()) {
                // no success then exit, (any exception has been handled by ClientChannelHandler#exceptionCaught)
                return;
            }
            // if we do not expect any reply then signal callback to continue routing
            if (!configuration.isSync()) {
                try {
                    // should channel be closed after complete?
                    Boolean close;
                    if (ExchangeHelper.isOutCapable(exchange)) {
                        close = exchange.getOut().getHeader(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE, Boolean.class);
                    } else {
                        close = exchange.getIn().getHeader(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE, Boolean.class);
                    }
                    // should we disconnect, the header can override the configuration
                    boolean disconnect = getConfiguration().isDisconnect();
                    if (close != null) {
                        disconnect = close;
                    }
                    // we should not close if we are reusing the channel
                    if (!configuration.isReuseChannel() && disconnect) {
                        if (LOG.isTraceEnabled()) {
                            LOG.trace("Closing channel when complete at address: {}", getEndpoint().getConfiguration().getAddress());
                        }
                        NettyHelper.close(channel);
                    }
                } finally {
                    // signal callback to continue routing
                    producerCallback.done(false);
                }
            }
        }
    });
}
Example 18
Project: craft-master  File: ThreadSafeUtils.java View source code
/**
	 * This function assumes that you're using BC's ChannelHandler system, which only has one
	 * channel handler. This might get very messy otherwise.
	 * TODO: HACK - Can we rewrite this for BC 7.1 along with the whole network system to be somewhat more sane? Please?
	 *
	 * @param packet
	 * @param channel
	 * @return
	 */
public static net.minecraft.network.Packet generatePacketFrom(Packet packet, FMLEmbeddedChannel channel) {
    ByteBuf data = Unpooled.buffer();
    for (io.netty.channel.ChannelHandler h : channel.pipeline().toMap().values()) {
        if (h instanceof ChannelHandler) {
            data.writeByte(((ChannelHandler) h).getDiscriminator(packet.getClass()));
            break;
        }
    }
    packet.writeData(data);
    return new FMLProxyPacket(data.copy(), channel.attr(NetworkRegistry.FML_CHANNEL).get());
}
Example 19
Project: flink-master  File: KvStateClientTest.java View source code
// ------------------------------------------------------------------------
private Channel createServerChannel(final ChannelHandler... handlers) throws UnknownHostException, InterruptedException {
    ServerBootstrap bootstrap = new ServerBootstrap().localAddress(// Bind address and port
    InetAddress.getLocalHost(), 0).group(// NIO server channels
    NIO_GROUP).channel(NioServerSocketChannel.class).childHandler(// See initializer for pipeline details
    new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4)).addLast(handlers);
        }
    });
    return bootstrap.bind().sync().channel();
}
Example 20
Project: forge-master  File: ThreadSafeUtils.java View source code
/**
	 * This function assumes that you're using BC's ChannelHandler system, which only has one
	 * channel handler. This might get very messy otherwise.
	 * TODO: HACK - Can we rewrite this for BC 7.1 along with the whole network system to be somewhat more sane? Please?
	 *
	 * @param packet
	 * @param channel
	 * @return
	 */
public static net.minecraft.network.Packet generatePacketFrom(Packet packet, FMLEmbeddedChannel channel) {
    ByteBuf data = Unpooled.buffer();
    for (io.netty.channel.ChannelHandler h : channel.pipeline().toMap().values()) {
        if (h instanceof ChannelHandler) {
            data.writeByte(((ChannelHandler) h).getDiscriminator(packet.getClass()));
            break;
        }
    }
    packet.writeData(data);
    return new FMLProxyPacket(data.copy(), channel.attr(NetworkRegistry.FML_CHANNEL).get());
}
Example 21
Project: gruffalo-master  File: GraphiteClientPool.java View source code
private void initClients(final String[] hosts, final EventLoopGroup eventLoopGroup, final StringDecoder decoder, final StringEncoder encoder, final Throttler throttler, final int inFlightBatchesHighThreshold, final MetricFactory metricFactory) {
    for (int i = 0; i < hosts.length; i++) {
        final String[] hostAndPort = hosts[i].split(":");
        final String host = hostAndPort[0];
        final int port = Integer.parseInt(hostAndPort[1]);
        final NettyGraphiteClient client = new NettyGraphiteClient(throttler, inFlightBatchesHighThreshold, metricFactory, hosts[i]);
        pool[i] = client;
        final ChannelHandler graphiteChannelHandler = new GraphiteChannelInboundHandler(client, hosts[i], throttler);
        final GraphiteClientChannelInitializer channelInitializer = new GraphiteClientChannelInitializer(host, port, eventLoopGroup, decoder, encoder, graphiteChannelHandler);
        client.setChannelInitializer(channelInitializer);
    }
}
Example 22
Project: JibbrJabbr-master  File: HttpServerChannelInitializerTest.java View source code
@Test
public void test() throws Exception {
    // given
    given(engineProvider.get()).willReturn(engine);
    given(ch.pipeline()).willReturn(pipeline);
    given(pipeline.addLast(anyString(), any(ChannelHandler.class))).willReturn(pipeline);
    // when
    hsci.initChannel(ch);
    // then
    InOrder i = inOrder(pipeline);
    i.verify(pipeline).addLast(eq(Decoder.toString()), isA(HttpRequestDecoder.class));
    i.verify(pipeline).addLast(eq(Aggregator.toString()), isA(HttpObjectAggregator.class));
    i.verify(pipeline).addLast(eq(Encoder.toString()), isA(HttpResponseEncoder.class));
    i.verify(pipeline).addLast(eq(ChunkedWriter.toString()), isA(ChunkedWriteHandler.class));
    i.verify(pipeline).addLast(JJEngine.toString(), engine);
    // this test acts as an inventory of the handlers, so
    // ensure nothing else happened
    verifyNoMoreInteractions(pipeline);
}
Example 23
Project: liferay-portal-master  File: NettyUtilTest.java View source code
@Test
public void testCreateEmptyChannelPipeline() {
    ChannelPipeline channelPipeline = NettyUtil.createEmptyChannelPipeline();
    Assert.assertEquals(Collections.<String, ChannelHandler>emptyMap(), channelPipeline.toMap());
    Channel channel = channelPipeline.channel();
    Assert.assertTrue(channel.isActive());
    Assert.assertTrue(channel.isOpen());
    Assert.assertTrue(channel.isRegistered());
}
Example 24
Project: mediation-master  File: PipelineHandlerBuilderUtil.java View source code
/**
     * build a ChannelHandler instance from a String
     *
     * @param handlerClass the pipeline handler class given in the configuration
     * @return ChannelHandler instance of the pipeline handler
     */
public static ChannelHandler stringToPipelineHandlers(String handlerClass) {
    ChannelInboundHandlerAdapter hand = null;
    if (handlerClass != null) {
        try {
            Class c = Class.forName(handlerClass);
            Constructor cons = c.getConstructor();
            ChannelHandler handlerInstance = (ChannelHandler) cons.newInstance();
            return handlerInstance;
        } catch (ClassNotFoundException e) {
            String msg = "Class " + handlerClass + " not found. Please check the required class is added to the classpath.";
            log.error(msg, e);
            throw new SynapseException(e);
        } catch (NoSuchMethodException e) {
            String msg = "Required constructor is not implemented.";
            log.error(msg, e);
            throw new SynapseException(e);
        } catch (InstantiationExceptionIllegalAccessException | java.lang.reflect.InvocationTargetException |  e) {
            String msg = "Couldn't create the class instance.";
            log.error(msg, e);
            throw new SynapseException(e);
        }
    }
    return hand;
}
Example 25
Project: MyseliaStem-master  File: HttpHandshakeConnectionState.java View source code
/**
	 * This method sets up the channel pipeline to contain the proper codecs for websocket payload transportation
	 *
	 */
private void setupPipeline(Channel ch) {
    ChannelPipeline pipeline = ch.pipeline();
    //Decoders
    pipeline.remove("frameDecoder");
    pipeline.replace("stringDecoder", "webSocketFrameDecoder", new WebSocket13FrameDecoder(true, false, 4096));
    pipeline.addAfter("webSocketFrameDecoder", "webSocketDecoder", new WebSocketDecoder());
    pipeline.addAfter("webSocketDecoder", "transmissionDecoder", new StringToTransmissionDecoder());
    //Encoders
    pipeline.replace("stringEncoder", "transmissionEncoder", new TransmissionToWebSocketEncoder());
    pipeline.addFirst("webSocketFrameEncoder", new WebSocket13FrameEncoder(false));
    System.err.println("[HTTP Handshaker] ~~ Pipeline Setup Complete");
    Iterator<Entry<String, ChannelHandler>> it = pipeline.iterator();
    while (it.hasNext()) {
        Entry<String, ChannelHandler> s = it.next();
        System.out.println("Entry is: " + s.getKey());
        System.out.println("\t->Handler: " + s.toString());
    }
}
Example 26
Project: netty-study-master  File: DefaultCommonClientConnector.java View source code
public ChannelHandler[] handlers() {
    return new ChannelHandler[] { this, //�隔30s的时间触�一次userEventTriggered的方法,并且指定IdleState的状��是WRITER_IDLE
    new IdleStateHandler(0, 30, 0, TimeUnit.SECONDS), //实现userEventTriggered方法,并在state是WRITER_IDLE的时候��一个心跳包到sever端,告诉server端我还活�
    idleStateTrigger, new MessageDecoder(), encoder, ackEncoder, handler };
}
Example 27
Project: ovsdb-master  File: NettyBootStrapper.java View source code
public ChannelFuture startServer(int localPort, final ChannelHandler... handlers) throws Exception {
    // Configure the server.
    bossGroup = new NioEventLoopGroup();
    workerGroup = new NioEventLoopGroup();
    ServerBootstrap serverBootstrap = new ServerBootstrap();
    serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 100).localAddress(localPort).childOption(ChannelOption.TCP_NODELAY, true).childHandler(new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            for (ChannelHandler handler : handlers) {
                ch.pipeline().addLast(handler);
            }
        }
    });
    // Start the server.
    channelFuture = serverBootstrap.bind().sync();
    return channelFuture;
}
Example 28
Project: thundernetwork-master  File: ChannelInit.java View source code
@Override
protected void initChannel(SocketChannel ch) throws Exception {
    if (serverMode) {
        node = new NodeClient();
        node.isServer = true;
    }
    //        ch.pipeline().addLast(new DumpHexHandler());
    //        ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
    //        ch.pipeline().addLast(new NodeConnectionHandler(context, node));
    ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(2147483647, 0, 4, 0, 4));
    ch.pipeline().addLast(new LengthFieldPrepender(4));
    MessageSerializer messageSerializer = contextFactory.getMessageSerializer();
    ch.pipeline().addLast(new ByteToMessageObjectHandler(messageSerializer));
    ch.pipeline().addLast(new MessageObjectToByteHandler(messageSerializer));
    ChannelHandler pingHandler = new PingHandler();
    ch.pipeline().addLast(pingHandler);
    Processor encryptionProcessor = contextFactory.getEncryptionProcessor(node);
    ch.pipeline().addLast(new ProcessorHandler(encryptionProcessor, "Encryption"));
    Processor authenticationProcessor = contextFactory.getAuthenticationProcessor(node);
    ch.pipeline().addLast(new ProcessorHandler(authenticationProcessor, "Authentication"));
    Processor gossipProcessor = contextFactory.getGossipProcessor(node);
    ch.pipeline().addLast(new ProcessorHandler(gossipProcessor, "Gossip"));
    Processor peerSeedProcessor = contextFactory.getPeerSeedProcessor(node);
    ch.pipeline().addLast(new ProcessorHandler(peerSeedProcessor, "PeerSeed"));
    Processor syncProcessor = contextFactory.getSyncProcessor(node);
    ch.pipeline().addLast(new ProcessorHandler(syncProcessor, "Sync"));
    Processor lnEstablishProcessor = contextFactory.getLNEstablishProcessor(node);
    ch.pipeline().addLast(new ProcessorHandler(lnEstablishProcessor, "LNEstablish"));
    Processor lnPaymentProcessor = contextFactory.getLNPaymentProcessor(node);
    ch.pipeline().addLast(new ProcessorHandler(lnPaymentProcessor, "LNPayment"));
}
Example 29
Project: blynk-server-master  File: SessionPerfTest.java View source code
private ChannelHandler newChannelHandler(final HardwareStateHolder hardwareStateHolder) {
    return new BaseSimpleChannelInboundHandler<Object>(Object.class, new Limits(new ServerProperties(Collections.emptyMap()))) {

        @Override
        public void messageReceived(ChannelHandlerContext ctx, Object msg) {
            throw new UnsupportedOperationException();
        }

        @Override
        public StateHolderBase getState() {
            return hardwareStateHolder;
        }
    };
}
Example 30
Project: carbon-transports-master  File: SourceHandler.java View source code
protected CarbonMessage setupCarbonMessage(HttpMessage httpMessage) throws URISyntaxException {
    cMsg = new HTTPCarbonMessage();
    boolean isSecuredConnection = false;
    if (HTTPTransportContextHolder.getInstance().getHandlerExecutor() != null) {
        HTTPTransportContextHolder.getInstance().getHandlerExecutor().executeAtSourceRequestReceiving(cMsg);
    }
    cMsg.setProperty(Constants.PORT, ((InetSocketAddress) ctx.channel().remoteAddress()).getPort());
    cMsg.setProperty(Constants.HOST, ((InetSocketAddress) ctx.channel().remoteAddress()).getHostName());
    HttpRequest httpRequest = (HttpRequest) httpMessage;
    cMsg.setProperty(Constants.CHNL_HNDLR_CTX, this.ctx);
    cMsg.setProperty(Constants.SRC_HANDLER, this);
    cMsg.setProperty(Constants.HTTP_VERSION, httpRequest.getProtocolVersion().text());
    cMsg.setProperty(Constants.HTTP_METHOD, httpRequest.getMethod().name());
    cMsg.setProperty(org.wso2.carbon.messaging.Constants.LISTENER_PORT, ((InetSocketAddress) ctx.channel().localAddress()).getPort());
    cMsg.setProperty(org.wso2.carbon.messaging.Constants.LISTENER_INTERFACE_ID, listenerConfiguration.getId());
    cMsg.setProperty(org.wso2.carbon.messaging.Constants.PROTOCOL, Constants.PROTOCOL_NAME);
    if (listenerConfiguration.getSslConfig() != null) {
        isSecuredConnection = true;
    }
    cMsg.setProperty(Constants.IS_SECURED_CONNECTION, isSecuredConnection);
    cMsg.setProperty(Constants.LOCAL_ADDRESS, ctx.channel().localAddress());
    cMsg.setProperty(Constants.LOCAL_NAME, ((InetSocketAddress) ctx.channel().localAddress()).getHostName());
    cMsg.setProperty(Constants.REMOTE_ADDRESS, ctx.channel().remoteAddress());
    cMsg.setProperty(Constants.REMOTE_HOST, ((InetSocketAddress) ctx.channel().remoteAddress()).getHostName());
    cMsg.setProperty(Constants.REMOTE_PORT, ((InetSocketAddress) ctx.channel().remoteAddress()).getPort());
    cMsg.setProperty(Constants.REQUEST_URL, httpRequest.getUri());
    ChannelHandler handler = ctx.handler();
    cMsg.setProperty(Constants.CHANNEL_ID, ((SourceHandler) handler).getListenerConfiguration().getId());
    cMsg.setProperty(Constants.TO, httpRequest.getUri());
    cMsg.setHeaders(Util.getHeaders(httpRequest).getAll());
    //Added protocol name as a string
    return cMsg;
}
Example 31
Project: lettuce-master  File: ConnectionBuilder.java View source code
protected List<ChannelHandler> buildHandlers() {
    LettuceAssert.assertState(channelGroup != null, "ChannelGroup must be set");
    LettuceAssert.assertState(connectionEvents != null, "ConnectionEvents must be set");
    LettuceAssert.assertState(connection != null, "Connection must be set");
    LettuceAssert.assertState(clientResources != null, "ClientResources must be set");
    List<ChannelHandler> handlers = new ArrayList<>();
    connection.setOptions(clientOptions);
    handlers.add(new ChannelGroupListener(channelGroup));
    handlers.add(new CommandEncoder());
    handlers.add(commandHandler);
    handlers.add(connection);
    handlers.add(new ConnectionEventTrigger(connectionEvents, connection, clientResources.eventBus()));
    if (clientOptions.isAutoReconnect()) {
        handlers.add(createConnectionWatchdog());
    }
    return handlers;
}
Example 32
Project: mediaserver-master  File: AsyncNettyNetworkChannelTest.java View source code
@SuppressWarnings("unchecked")
@Test
public void testLifecycle() {
    // given
    final SocketAddress localAddress = new InetSocketAddress("127.0.0.1", 2427);
    final SocketAddress remoteAddress = new InetSocketAddress("127.0.0.1", 2727);
    final ChannelHandler channelHandler = mock(ChannelHandler.class);
    this.eventGroup = new NioEventLoopGroup();
    final Bootstrap bootstrap = new Bootstrap().group(eventGroup).handler(channelHandler).channel(NioDatagramChannel.class);
    final NettyNetworkManager networkManager = new NettyNetworkManager(bootstrap);
    final AsyncNettyNetworkChannel<Object> networkChannel = new AsyncNettyNetworkChannel<>(networkManager);
    final FutureCallback<Void> openCallback = mock(FutureCallback.class);
    final FutureCallback<Void> bindCallback = mock(FutureCallback.class);
    final FutureCallback<Void> connectCallback = mock(FutureCallback.class);
    final FutureCallback<Void> disconnectCallback = mock(FutureCallback.class);
    final FutureCallback<Void> closeCallback = mock(FutureCallback.class);
    // when - open
    networkChannel.open(openCallback);
    // then
    verify(openCallback, timeout(100)).onSuccess(null);
    assertTrue(networkChannel.isOpen());
    assertFalse(networkChannel.isBound());
    assertFalse(networkChannel.isConnected());
    // when - bind
    networkChannel.bind(localAddress, bindCallback);
    // then
    verify(bindCallback, timeout(100)).onSuccess(null);
    assertTrue(networkChannel.isOpen());
    assertTrue(networkChannel.isBound());
    assertFalse(networkChannel.isConnected());
    // when - connect
    networkChannel.connect(remoteAddress, connectCallback);
    // then
    verify(connectCallback, timeout(100)).onSuccess(null);
    assertTrue(networkChannel.isOpen());
    assertTrue(networkChannel.isBound());
    assertTrue(networkChannel.isConnected());
    // when - disconnect
    networkChannel.disconnect(disconnectCallback);
    // then
    verify(disconnectCallback, timeout(100)).onSuccess(null);
    assertTrue(networkChannel.isOpen());
    assertTrue(networkChannel.isBound());
    assertFalse(networkChannel.isConnected());
    // when - close
    networkChannel.close(closeCallback);
    // then
    verify(closeCallback, timeout(100)).onSuccess(null);
    assertFalse(networkChannel.isOpen());
    assertFalse(networkChannel.isBound());
    assertFalse(networkChannel.isConnected());
}
Example 33
Project: netty-master  File: DefaultChannelPipelineTest.java View source code
private void setUp(final ChannelHandler... handlers) throws Exception {
    final AtomicReference<Channel> peerRef = new AtomicReference<Channel>();
    ServerBootstrap sb = new ServerBootstrap();
    sb.group(group).channel(LocalServerChannel.class);
    sb.childHandler(new ChannelInboundHandlerAdapter() {

        @Override
        public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
            peerRef.set(ctx.channel());
        }

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            ReferenceCountUtil.release(msg);
        }
    });
    ChannelFuture bindFuture = sb.bind(LocalAddress.ANY).sync();
    Bootstrap b = new Bootstrap();
    b.group(group).channel(LocalChannel.class);
    b.handler(new ChannelInitializer<LocalChannel>() {

        @Override
        protected void initChannel(LocalChannel ch) throws Exception {
            ch.pipeline().addLast(handlers);
        }
    });
    self = b.connect(bindFuture.channel().localAddress()).sync().channel();
    peer = peerRef.get();
    bindFuture.channel().close().sync();
}
Example 34
Project: netty4.0.27Learn-master  File: DefaultChannelPipelineTest.java View source code
private void setUp(final ChannelHandler... handlers) throws Exception {
    final AtomicReference<Channel> peerRef = new AtomicReference<Channel>();
    ServerBootstrap sb = new ServerBootstrap();
    sb.group(group).channel(LocalServerChannel.class);
    sb.childHandler(new ChannelInboundHandlerAdapter() {

        @Override
        public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
            peerRef.set(ctx.channel());
        }

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            ReferenceCountUtil.release(msg);
        }
    });
    ChannelFuture bindFuture = sb.bind(LocalAddress.ANY).sync();
    Bootstrap b = new Bootstrap();
    b.group(group).channel(LocalChannel.class);
    b.handler(new ChannelInitializer<LocalChannel>() {

        @Override
        protected void initChannel(LocalChannel ch) throws Exception {
            ch.pipeline().addLast(handlers);
        }
    });
    self = b.connect(bindFuture.channel().localAddress()).sync().channel();
    peer = peerRef.get();
    bindFuture.channel().close().sync();
}
Example 35
Project: netty4study-master  File: DefaultChannelPipelineTest.java View source code
private void setUp(final ChannelHandler... handlers) throws Exception {
    final AtomicReference<Channel> peerRef = new AtomicReference<Channel>();
    ServerBootstrap sb = new ServerBootstrap();
    sb.group(group).channel(LocalServerChannel.class);
    sb.childHandler(new ChannelInboundHandlerAdapter() {

        @Override
        public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
            peerRef.set(ctx.channel());
        }

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            ReferenceCountUtil.release(msg);
        }
    });
    ChannelFuture bindFuture = sb.bind(LocalAddress.ANY).sync();
    Bootstrap b = new Bootstrap();
    b.group(group).channel(LocalChannel.class);
    b.handler(new ChannelInitializer<LocalChannel>() {

        @Override
        protected void initChannel(LocalChannel ch) throws Exception {
            ch.pipeline().addLast(handlers);
        }
    });
    self = b.connect(bindFuture.channel().localAddress()).sync().channel();
    peer = peerRef.get();
    bindFuture.channel().close().sync();
}
Example 36
Project: PUMA-master  File: MockedPumaServer.java View source code
@Override
public Map<String, ChannelHandler> getHandlers() {
    Map<String, ChannelHandler> result = new LinkedHashMap<String, ChannelHandler>();
    result.put("channelHolderHandler", channelHolderHandler);
    result.put("HttpRequestDecoder", new HttpRequestDecoder());
    result.put("HttpContentDecompressor", new HttpContentDecompressor());
    result.put("HttpResponseEncoder", new io.netty.handler.codec.http.HttpResponseEncoder());
    result.put("HttpContentCompressor", new HttpContentCompressor());
    result.put("HttpEntityEncoder", HttpResponseEncoder.INSTANCE);
    result.put("HttpObjectAggregator", new HttpObjectAggregator(1024 * 1024 * 32));
    result.put("HttpRouterHandler", HttpRouterHandler.INSTANCE);
    result.put("BinlogSubscriptionHandler", new BinlogSubscriptionHandler());
    result.put("BinlogQueryHandler", new BinlogGetHandler());
    result.put("BinlogAckHandler", new BinlogAckHandler());
    result.put("ExceptionHandler", ExceptionHandler.INSTANCE);
    return result;
}
Example 37
Project: RxNetty-master  File: HttpClientRequestImplTest.java View source code
@Override
public void evaluate() throws Throwable {
    @SuppressWarnings("unchecked") TcpClient<ByteBuf, HttpClientResponse<ByteBuf>> clientMock = (TcpClient<ByteBuf, HttpClientResponse<ByteBuf>>) Mockito.mock(TcpClient.class);
    channel = new EmbeddedChannel(new ChannelDuplexHandler() {

        @Override
        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
            if (evt instanceof ConnectionInputSubscriberEvent) {
                @SuppressWarnings({ "rawtypes", "unchecked" }) ConnectionInputSubscriberEvent cise = (ConnectionInputSubscriberEvent) evt;
                cis = cise.getSubscriber();
            }
            super.userEventTriggered(ctx, evt);
        }
    });
    TcpClientEventPublisher eventPublisher = new TcpClientEventPublisher();
    channel.attr(EventAttributeKeys.EVENT_PUBLISHER).set(eventPublisher);
    channel.attr(EventAttributeKeys.CLIENT_EVENT_LISTENER).set(eventPublisher);
    channel.attr(EventAttributeKeys.CONNECTION_EVENT_LISTENER).set(eventPublisher);
    connMock = ConnectionImpl.fromChannel(channel);
    @SuppressWarnings("unchecked") final TcpConnectionRequestMock<ByteBuf, HttpClientResponse<ByteBuf>> connReqMock = new TcpConnectionRequestMock(Observable.just(connMock));
    Mockito.when(clientMock.createConnectionRequest()).thenAnswer(new Answer<Object>() {

        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            return connReqMock;
        }
    });
    Answer<Object> returnThisMock = new Answer<Object>() {

        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            return invocation.getMock();
        }
    };
    Mockito.when(clientMock.addChannelHandlerFirst(anyString(), Matchers.<Func0<ChannelHandler>>anyObject())).thenAnswer(returnThisMock);
    Mockito.when(clientMock.addChannelHandlerFirst(Matchers.<EventExecutorGroup>anyObject(), anyString(), Matchers.<Func0<ChannelHandler>>anyObject())).thenAnswer(returnThisMock);
    Mockito.when(clientMock.addChannelHandlerLast(anyString(), Matchers.<Func0<ChannelHandler>>anyObject())).thenAnswer(returnThisMock);
    Mockito.when(clientMock.addChannelHandlerLast(Matchers.<EventExecutorGroup>anyObject(), anyString(), Matchers.<Func0<ChannelHandler>>anyObject())).thenAnswer(returnThisMock);
    Mockito.when(clientMock.addChannelHandlerBefore(anyString(), anyString(), Matchers.<Func0<ChannelHandler>>anyObject())).thenAnswer(returnThisMock);
    Mockito.when(clientMock.addChannelHandlerBefore(Matchers.<EventExecutorGroup>anyObject(), anyString(), anyString(), Matchers.<Func0<ChannelHandler>>anyObject())).thenAnswer(returnThisMock);
    Mockito.when(clientMock.addChannelHandlerAfter(anyString(), anyString(), Matchers.<Func0<ChannelHandler>>anyObject())).thenAnswer(returnThisMock);
    Mockito.when(clientMock.addChannelHandlerAfter(Matchers.<EventExecutorGroup>anyObject(), anyString(), anyString(), Matchers.<Func0<ChannelHandler>>anyObject())).thenAnswer(returnThisMock);
    Mockito.when(clientMock.pipelineConfigurator(Matchers.<Action1<ChannelPipeline>>anyObject())).thenAnswer(returnThisMock);
    Mockito.when(clientMock.enableWireLogging(anyString(), Matchers.<LogLevel>anyObject())).thenAnswer(returnThisMock);
    RequestRule.this.clientMock = clientMock;
    request = HttpClientRequestImpl.create(HttpVersion.HTTP_1_1, HttpMethod.GET, "/", RequestRule.this.clientMock);
    base.evaluate();
}
Example 38
Project: spring-framework-master  File: RxNettyWebSocketSession.java View source code
/**
	 * Insert an {@link WebSocketFrameAggregator} after the
	 * {@code WebSocketFrameDecoder} for receiving full messages.
	 * @param channel the channel for the session
	 * @param frameDecoderName the name of the WebSocketFrame decoder
	 */
public RxNettyWebSocketSession aggregateFrames(Channel channel, String frameDecoderName) {
    ChannelPipeline pipeline = channel.pipeline();
    if (pipeline.context(FRAME_AGGREGATOR_NAME) != null) {
        return this;
    }
    ChannelHandlerContext frameDecoder = pipeline.context(frameDecoderName);
    if (frameDecoder == null) {
        throw new IllegalArgumentException("WebSocketFrameDecoder not found: " + frameDecoderName);
    }
    ChannelHandler frameAggregator = new WebSocketFrameAggregator(DEFAULT_FRAME_MAX_SIZE);
    pipeline.addAfter(frameDecoder.name(), FRAME_AGGREGATOR_NAME, frameAggregator);
    return this;
}
Example 39
Project: WaarpR66-master  File: NetworkSslServerHandler.java View source code
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    Channel networkChannel = ctx.channel();
    logger.debug("Add channel to ssl");
    WaarpSslUtility.addSslOpenedChannel(networkChannel);
    isSSL = true;
    // Check first if allowed
    if (NetworkTransaction.isBlacklisted(networkChannel)) {
        logger.warn("Connection refused since Partner is in BlackListed from " + networkChannel.remoteAddress().toString());
        isBlackListed = true;
        if (Configuration.configuration.getR66Mib() != null) {
            Configuration.configuration.getR66Mib().notifyError("Black Listed connection temptative", "During Handshake");
        }
        // close immediately the connection
        WaarpSslUtility.closingSslChannel(networkChannel);
        return;
    }
    // Get the SslHandler in the current pipeline.
    // We added it in NetworkSslServerInitializer.
    final ChannelHandler handler = ctx.pipeline().first();
    if (handler instanceof SslHandler) {
        final SslHandler sslHandler = (SslHandler) handler;
        sslHandler.handshakeFuture().addListener(new GenericFutureListener<Future<? super Channel>>() {

            public void operationComplete(Future<? super Channel> future) throws Exception {
                if (!future.isSuccess()) {
                    if (Configuration.configuration.getR66Mib() != null) {
                        Configuration.configuration.getR66Mib().notifyError("SSL Connection Error", "During Handshake");
                    }
                }
            }
        });
    } else {
        logger.error("SSL Not found");
    }
    super.channelActive(ctx);
}
Example 40
Project: acteur-master  File: ServerModule.java View source code
@Override
@SuppressWarnings("deprecation")
protected void configure() {
    bind(Server.class).to(ServerImpl.class);
    bind(ReentrantScope.class).toInstance(scope);
    bind(Application.class).to(appType).asEagerSingleton();
    bind(ChannelHandler.class).to(UpstreamHandlerImpl.class);
    bind(new CISC()).to(PipelineFactoryImpl.class);
    bind(ServerBootstrap.class).toProvider(new ServerBootstrapProvider(binder().getProvider(Settings.class), binder().getProvider(ByteBufAllocator.class)));
    scope.bindTypes(binder(), Event.class, HttpEvent.class, RequestID.class, Page.class, BasicCredentials.class, Closables.class);
    ImplicitBindings implicit = appType.getAnnotation(ImplicitBindings.class);
    if (implicit != null) {
        scope.bindTypes(binder(), implicit.value());
    }
    scope.bindTypesAllowingNulls(binder(), EventChannelName.class);
    // Acteurs can ask for a Deferral to pause execution while some
    // other operation completes, such as making an external HTTP request
    // to another server
    install(new ActeurBaseModule(scope));
    Provider<ApplicationControl> appControlProvider = binder().getProvider(ApplicationControl.class);
    Provider<Settings> set = binder().getProvider(Settings.class);
    TF eventThreadFactory = new TF(EVENT_THREADS, appControlProvider);
    TF workerThreadFactory = new TF(WORKER_THREADS, appControlProvider);
    TF backgroundThreadFactory = new TF(BACKGROUND_THREAD_POOL_NAME, appControlProvider);
    bind(ThreadGroup.class).annotatedWith(Names.named(BACKGROUND_THREAD_POOL_NAME)).toInstance(backgroundThreadFactory.tg);
    bind(ThreadGroup.class).annotatedWith(Names.named(WORKER_THREADS)).toInstance(workerThreadFactory.tg);
    bind(ThreadGroup.class).annotatedWith(Names.named(EVENT_THREADS)).toInstance(eventThreadFactory.tg);
    ThreadCount workerThreadCount = new ThreadCount(set, 8, workerThreads, WORKER_THREADS);
    ThreadCount eventThreadCount = new ThreadCount(set, 8, eventThreads, EVENT_THREADS);
    ThreadCount backgroundThreadCount = new ThreadCount(set, 128, backgroundThreads, BACKGROUND_THREADS);
    bind(ThreadCount.class).annotatedWith(Names.named(EVENT_THREADS)).toInstance(eventThreadCount);
    bind(ThreadCount.class).annotatedWith(Names.named(WORKER_THREADS)).toInstance(workerThreadCount);
    bind(ThreadCount.class).annotatedWith(Names.named(BACKGROUND_THREAD_POOL_NAME)).toInstance(backgroundThreadCount);
    bind(ThreadFactory.class).annotatedWith(Names.named(WORKER_THREADS)).toInstance(workerThreadFactory);
    bind(ThreadFactory.class).annotatedWith(Names.named(EVENT_THREADS)).toInstance(eventThreadFactory);
    bind(ThreadFactory.class).annotatedWith(Names.named(BACKGROUND_THREAD_POOL_NAME)).toInstance(backgroundThreadFactory);
    Provider<ExecutorService> workerProvider = new ExecutorServiceProvider(workerThreadFactory, workerThreadCount, set);
    Provider<ExecutorService> backgroundProvider = new ExecutorServiceProvider(backgroundThreadFactory, backgroundThreadCount, set);
    bind(ExecutorService.class).annotatedWith(Names.named(WORKER_THREAD_POOL_NAME)).toProvider(workerProvider);
    bind(ExecutorService.class).annotatedWith(Names.named(BACKGROUND_THREAD_POOL_NAME)).toProvider(backgroundProvider);
    bind(ExecutorService.class).annotatedWith(Names.named(SCOPED_WORKER_THREAD_POOL_NAME)).toProvider(new WrappedWorkerThreadPoolProvider(workerProvider, scope));
    bind(ExecutorService.class).annotatedWith(Names.named(SCOPED_BACKGROUND_THREAD_POOL_NAME)).toProvider(new WrappedWorkerThreadPoolProvider(backgroundProvider, scope));
    bind(DateTime.class).toInstance(DateTime.now());
    bind(Duration.class).toProvider(UptimeProvider.class);
    bind(new CKTL()).toProvider(CookiesProvider.class);
    //XXX anything using this?
    bind(String.class).annotatedWith(Names.named("application")).toInstance(this.appType.getSimpleName());
    bind(ServerImpl.class).asEagerSingleton();
    for (Module m : otherModules) {
        install(m);
    }
    bind(Charset.class).toProvider(CharsetProvider.class);
    bind(ByteBufAllocator.class).toProvider(ByteBufAllocatorProvider.class);
    bind(new ETL()).toProvider(EventProvider.class).in(scope);
    bind(Codec.class).to(CodecImpl.class);
    bind(ApplicationControl.class).toProvider(ApplicationControlProvider.class).in(Scopes.SINGLETON);
    bind(ExceptionEvaluatorRegistry.class).asEagerSingleton();
    bind(KeysValues.class).toProvider(KeysValuesProvider.class);
    bind(InvalidInputExceptionEvaluator.class).asEagerSingleton();
    bind(Channel.class).toProvider(ChannelProvider.class);
    bind(HttpMethod.class).toProvider(MethodProvider.class);
    bind(Method.class).toProvider(MethodProvider2.class);
    bind(Path.class).toProvider(PathProvider.class);
    bind(BuiltInPageAnnotationHandler.class).asEagerSingleton();
    bind(ResponseHeaders.class).toProvider(ResponseHeadersProvider.class);
    bind(ScheduledExecutorService.class).annotatedWith(Names.named(DELAY_EXECUTOR)).toProvider(DelayExecutorProvider.class);
    // allow Chain<Acteur> to be injected
    bind(new CL()).toProvider(ChainProvider.class);
}
Example 41
Project: tomp2p_5-master  File: TestReservation.java View source code
@Override
public void operationComplete(final FutureChannelCreator future) throws Exception {
    final ChannelCreator cc = future.getChannelCreator();
    final int timeout = 2000;
    final CountDownLatch countDownLatch = new CountDownLatch(conn);
    for (int k = 0; k < conn; k++) {
        ChannelFuture channelFuture = cc.createTCP(SOCKET_ADDRESS, timeout, new HashMap<String, ChannelHandler>());
        channelFuture.addListener(new GenericFutureListener<ChannelFuture>() {

            @Override
            public void operationComplete(final ChannelFuture future) throws Exception {
                future.channel().close();
                countDownLatch.countDown();
            }
        });
    }
    countDownLatch.await();
    cc.shutdown().awaitUninterruptibly();
}
Example 42
Project: Android-wamp-client-master  File: WampServerWebsocketHandler.java View source code
private void tryWebsocketHandshake(final ChannelHandlerContext ctx, FullHttpRequest request) {
    String wsLocation = getWebSocketLocation(ctx, request);
    WebSocketServerHandshaker handshaker = new WebSocketServerHandshakerFactory(wsLocation, WampHandlerConfiguration.WAMP_WEBSOCKET_PROTOCOLS, false, WampHandlerConfiguration.MAX_WEBSOCKET_FRAME_SIZE).newHandshaker(request);
    if (handshaker == null) {
        WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
    } else {
        handshakeInProgress = true;
        final ChannelFuture handshakeFuture = handshaker.handshake(ctx.channel(), request);
        String actualProtocol = handshaker.selectedSubprotocol();
        if (actualProtocol != null && actualProtocol.equals("wamp.2.json")) {
            serialization = Serialization.Json;
        }
        // invalid packets anyway
        if (serialization == Serialization.Invalid) {
            handshakeFuture.addListener(ChannelFutureListener.CLOSE);
            return;
        }
        // Remove all handlers after this one - we don't need them anymore since we switch to WAMP
        ChannelHandler last = ctx.pipeline().last();
        while (last != null && last != this) {
            ctx.pipeline().removeLast();
            last = ctx.pipeline().last();
        }
        if (last == null) {
            throw new IllegalStateException("Can't find the WAMP server handler in the pipeline");
        }
        // Remove the WampServerWebSocketHandler and replace it with the protocol handler
        // which processes pings and closes
        ProtocolHandler protocolHandler = new ProtocolHandler();
        ctx.pipeline().replace(this, "wamp-websocket-protocol-handler", protocolHandler);
        final ChannelHandlerContext protocolHandlerCtx = ctx.pipeline().context(protocolHandler);
        // Handle websocket fragmentation before the deserializer
        protocolHandlerCtx.pipeline().addLast(new WebSocketFrameAggregator(WampHandlerConfiguration.MAX_WEBSOCKET_FRAME_SIZE));
        // Install the serializer and deserializer
        protocolHandlerCtx.pipeline().addLast("wamp-serializer", new WampSerializationHandler(serialization, router.objectMapper()));
        protocolHandlerCtx.pipeline().addLast("wamp-deserializer", new WampDeserializationHandler(serialization, router.objectMapper()));
        // Install the router in the pipeline
        protocolHandlerCtx.pipeline().addLast(router.eventLoop(), "wamp-router", router.createRouterHandler());
        handshakeFuture.addListener(new ChannelFutureListener() {

            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (!future.isSuccess()) {
                    ctx.fireExceptionCaught(future.cause());
                } else {
                    // We successfully sent out the handshake
                    // Notify the activation to everything new
                    ctx.fireChannelActive();
                }
            }
        });
    }
}
Example 43
Project: bgpcep-master  File: SynchronizationAndExceptionTest.java View source code
@Before
public void setUp() throws Exception {
    super.setUp();
    new EmbeddedChannel();
    final List<BgpParameters> tlvs = Lists.newArrayList();
    this.classicOpen = new OpenBuilder().setMyAsNumber(AS_NUMBER.getValue().intValue()).setHoldTimer(HOLD_TIMER).setVersion(new ProtocolVersion((short) 4)).setBgpParameters(tlvs).setBgpIdentifier(BGP_ID).build();
    final List<OptionalCapabilities> capa = Lists.newArrayList();
    capa.add(new OptionalCapabilitiesBuilder().setCParameters(new CParametersBuilder().addAugmentation(CParameters1.class, new CParameters1Builder().setMultiprotocolCapability(new MultiprotocolCapabilityBuilder().setAfi(this.ipv4tt.getAfi()).setSafi(this.ipv4tt.getSafi()).build()).setGracefulRestartCapability(new GracefulRestartCapabilityBuilder().build()).build()).setAs4BytesCapability(new As4BytesCapabilityBuilder().setAsNumber(AS_NUMBER).build()).build()).build());
    capa.add(new OptionalCapabilitiesBuilder().setCParameters(BgpExtendedMessageUtil.EXTENDED_MESSAGE_CAPABILITY).build());
    tlvs.add(new BgpParametersBuilder().setOptionalCapabilities(capa).build());
    doReturn(null).when(mock(ChannelFuture.class)).addListener(any());
    doReturn(this.eventLoop).when(this.speakerListener).eventLoop();
    doReturn(true).when(this.speakerListener).isActive();
    doAnswer( invocation -> {
        final Runnable command = (Runnable) invocation.getArguments()[0];
        final long delay = (long) invocation.getArguments()[1];
        final TimeUnit unit = (TimeUnit) invocation.getArguments()[2];
        GlobalEventExecutor.INSTANCE.schedule(command, delay, unit);
        return null;
    }).when(this.eventLoop).schedule(any(Runnable.class), any(long.class), any(TimeUnit.class));
    doReturn("TestingChannel").when(this.speakerListener).toString();
    doReturn(true).when(this.speakerListener).isWritable();
    doReturn(new InetSocketAddress(InetAddress.getByName(BGP_ID.getValue()), 179)).when(this.speakerListener).remoteAddress();
    doReturn(new InetSocketAddress(InetAddress.getByName(LOCAL_IP), LOCAL_PORT)).when(this.speakerListener).localAddress();
    doReturn(this.pipeline).when(this.speakerListener).pipeline();
    doReturn(this.pipeline).when(this.pipeline).replace(any(ChannelHandler.class), any(String.class), any(ChannelHandler.class));
    doReturn(null).when(this.pipeline).replace(Matchers.<Class<ChannelHandler>>any(), any(String.class), any(ChannelHandler.class));
    doReturn(this.pipeline).when(this.pipeline).addLast(any(ChannelHandler.class));
    final ChannelFuture futureChannel = mock(ChannelFuture.class);
    doReturn(null).when(futureChannel).addListener(any());
    doReturn(futureChannel).when(this.speakerListener).close();
    doReturn(futureChannel).when(this.speakerListener).writeAndFlush(any(Notify.class));
    doReturn(this.domChain).when(this.domBroker).createTransactionChain(any());
    doReturn(this.tx).when(this.domChain).newWriteOnlyTransaction();
    final DOMDataTreeChangeService dOMDataTreeChangeService = mock(DOMDataTreeChangeService.class);
    final ListenerRegistration listener = mock(ListenerRegistration.class);
    Mockito.doReturn(listener).when(dOMDataTreeChangeService).registerDataTreeChangeListener(any(), any());
    Mockito.doNothing().when(listener).close();
    Mockito.doReturn(Collections.singletonMap(DOMDataTreeChangeService.class, dOMDataTreeChangeService)).when(this.domBroker).getSupportedExtensions();
    Mockito.doNothing().when(this.tx).merge(eq(LogicalDatastoreType.OPERATIONAL), any(YangInstanceIdentifier.class), any(NormalizedNode.class));
    Mockito.doNothing().when(this.tx).put(Mockito.eq(LogicalDatastoreType.OPERATIONAL), any(YangInstanceIdentifier.class), any(NormalizedNode.class));
    Mockito.doNothing().when(this.tx).delete(Mockito.any(LogicalDatastoreType.class), Mockito.any(YangInstanceIdentifier.class));
    final CheckedFuture future = mock(CheckedFuture.class);
    Mockito.doAnswer( invocation -> {
        final Runnable callback = (Runnable) invocation.getArguments()[0];
        callback.run();
        return null;
    }).when(future).addListener(Mockito.any(Runnable.class), Mockito.any(Executor.class));
    Mockito.doReturn(future).when(this.tx).submit();
    Mockito.doReturn(mock(Optional.class)).when(future).checkedGet();
}
Example 44
Project: Framework-GL-master  File: Network.java View source code
private void createClient(String host, int port, Supplier<ChannelHandler> channelHandlerSupplier) {
    // Create event loops
    clientWorkerGroup = new NioEventLoopGroup();
    // Create channel initializer
    ChannelInitializer<SocketChannel> channelInit = new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            if (debug) {
                p.addLast(new LoggingHandler(logLevel));
            }
            p.addLast(channelHandlerSupplier.get());
        }
    };
    // Bootstrap the client
    client = new Bootstrap();
    if (debug) {
        client.handler(new LoggingHandler(logLevel));
    }
    client.group(clientWorkerGroup).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, keepAlive).option(ChannelOption.TCP_NODELAY, tcpNoDelay).handler(channelInit);
    // Connect to the host and port
    client.connect(host, port);
}
Example 45
Project: grpc-java-master  File: ProtocolNegotiators.java View source code
@Override
public Handler newHandler(GrpcHttp2ConnectionHandler handler) {
    ChannelHandler sslBootstrap = new ChannelHandlerAdapter() {

        @Override
        public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
            SSLEngine sslEngine = sslContext.newEngine(ctx.alloc(), host, port);
            SSLParameters sslParams = new SSLParameters();
            sslParams.setEndpointIdentificationAlgorithm("HTTPS");
            sslEngine.setSSLParameters(sslParams);
            ctx.pipeline().replace(this, null, new SslHandler(sslEngine, false));
        }
    };
    return new BufferUntilTlsNegotiatedHandler(sslBootstrap, handler);
}
Example 46
Project: java-driver-master  File: NettyOptionsTest.java View source code
private void should_invoke_netty_options_hooks(int hosts, int coreConnections) throws Exception {
    NettyOptions nettyOptions = mock(NettyOptions.class, CALLS_REAL_METHODS.get());
    EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
    Timer timer = new HashedWheelTimer();
    doReturn(eventLoopGroup).when(nettyOptions).eventLoopGroup(any(ThreadFactory.class));
    doReturn(timer).when(nettyOptions).timer(any(ThreadFactory.class));
    final ChannelHandler handler = mock(ChannelHandler.class);
    doAnswer(new Answer() {

        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            SocketChannel channel = (SocketChannel) invocation.getArguments()[0];
            channel.pipeline().addLast("test-handler", handler);
            return null;
        }
    }).when(nettyOptions).afterChannelInitialized(any(SocketChannel.class));
    Cluster cluster = register(Cluster.builder().addContactPoints(getContactPoints().get(0)).withPort(ccm().getBinaryPort()).withPoolingOptions(new PoolingOptions().setConnectionsPerHost(HostDistance.LOCAL, coreConnections, coreConnections)).withNettyOptions(nettyOptions).build());
    // when
    // force session creation to populate pools
    cluster.connect();
    int expectedNumberOfCalls = TestUtils.numberOfLocalCoreConnections(cluster) * hosts + 1;
    // If the driver supports a more recent protocol version than C*, the negotiation at startup
    // will open an additional connection for each protocol version tried.
    ProtocolVersion version = ProtocolVersion.NEWEST_SUPPORTED;
    ProtocolVersion usedVersion = ccm().getProtocolVersion();
    while (version != usedVersion && version != null) {
        version = version.getLowerSupported();
        expectedNumberOfCalls++;
    }
    cluster.close();
    // then
    verify(nettyOptions, times(1)).eventLoopGroup(any(ThreadFactory.class));
    verify(nettyOptions, times(1)).channelClass();
    verify(nettyOptions, times(1)).timer(any(ThreadFactory.class));
    // per-connection hooks will be called coreConnections * hosts + 1 times:
    // the extra call is for the control connection
    verify(nettyOptions, times(expectedNumberOfCalls)).afterBootstrapInitialized(any(Bootstrap.class));
    verify(nettyOptions, times(expectedNumberOfCalls)).afterChannelInitialized(any(SocketChannel.class));
    verify(handler, times(expectedNumberOfCalls)).handlerAdded(any(ChannelHandlerContext.class));
    verify(handler, times(expectedNumberOfCalls)).handlerRemoved(any(ChannelHandlerContext.class));
    verify(nettyOptions, times(1)).onClusterClose(eventLoopGroup);
    verify(nettyOptions, times(1)).onClusterClose(timer);
    verifyNoMoreInteractions(nettyOptions);
}
Example 47
Project: jsonapi-master  File: NettyInjector.java View source code
/**
     * Inject into the spigot connection class.
     */
@SuppressWarnings("unchecked")
public synchronized void inject() {
    if (injected)
        throw new IllegalStateException("Cannot inject twice.");
    try {
        FuzzyReflection fuzzyServer = FuzzyReflection.fromClass(MinecraftReflection.getMinecraftServerClass());
        Method serverConnectionMethod = fuzzyServer.getMethodByParameters("getServerConnection", MinecraftReflection.getServerConnectionClass(), new Class[] {});
        // Get the server connection
        Object server = fuzzyServer.getSingleton();
        Object serverConnection = serverConnectionMethod.invoke(server);
        // Handle connected channels
        final ChannelInboundHandler endInitProtocol = new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel channel) throws Exception {
                try {
                    // This can take a while, so we need to stop the main thread from interfering
                    synchronized (networkManagers) {
                        injectChannel(channel);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        // This is executed before Minecraft's channel handler
        final ChannelInboundHandler beginInitProtocol = new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel channel) throws Exception {
                // Our only job is to add init protocol
                channel.pipeline().addLast(endInitProtocol);
            }
        };
        // Add our handler to newly created channels
        final ChannelHandler connectionHandler = new ChannelInboundHandlerAdapter() {

            @Override
            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                Channel channel = (Channel) msg;
                // Prepare to initialize ths channel
                channel.pipeline().addFirst(beginInitProtocol);
                ctx.fireChannelRead(msg);
            }
        };
        // Get the current NetworkMananger list
        networkManagers = (List<Object>) FuzzyReflection.fromObject(serverConnection, true).invokeMethod(null, "getNetworkManagers", List.class, serverConnection);
        // Insert ProtocolLib's connection interceptor
        bootstrapFields = getBootstrapFields(serverConnection);
        for (VolatileField field : bootstrapFields) {
            final List<Object> list = (List<Object>) field.getValue();
            // We don't have to override this list
            if (list == networkManagers) {
                continue;
            }
            // Synchronize with each list before we attempt to replace them.
            field.setValue(new BootstrapList(list, connectionHandler));
        }
        injected = true;
    } catch (Exception e) {
        throw new RuntimeException("Unable to inject channel futures.", e);
    }
}
Example 48
Project: kaa-master  File: HttpTransport.java View source code
@Override
protected ChannelInitializer<SocketChannel> configureInitializer() throws Exception {
    return new DefaultHttpServerInitializer() {

        @Override
        protected SimpleChannelInboundHandler<AbstractCommand> getMainHandler(UUID uuid) {
            return new HttpHandler(uuid, HttpTransport.this.handler);
        }

        @Override
        public int getClientMaxBodySize() {
            return maxBodySize;
        }

        @Override
        protected ChannelHandler getRequestDecoder() {
            return new RequestDecoder(factory);
        }
    };
}
Example 49
Project: lettuce-core-master  File: SslConnectionBuilder.java View source code
@Override
protected void initChannel(Channel channel) throws Exception {
    SSLParameters sslParams = new SSLParameters();
    SslContextBuilder sslContextBuilder = SslContextBuilder.forClient().sslProvider(sslOptions.getSslProvider());
    if (redisURI.isVerifyPeer()) {
        sslParams.setEndpointIdentificationAlgorithm("HTTPS");
    } else {
        sslContextBuilder.trustManager(InsecureTrustManagerFactory.INSTANCE);
    }
    if (sslOptions.getTruststore() != null) {
        try (InputStream is = sslOptions.getTruststore().openStream()) {
            sslContextBuilder.trustManager(createTrustManagerFactory(is, sslOptions.getTruststorePassword().length == 0 ? null : sslOptions.getTruststorePassword()));
        }
    }
    SslContext sslContext = sslContextBuilder.build();
    SSLEngine sslEngine = sslContext.newEngine(channel.alloc(), redisURI.getHost(), redisURI.getPort());
    sslEngine.setSSLParameters(sslParams);
    removeIfExists(channel.pipeline(), SslHandler.class);
    if (channel.pipeline().get("first") == null) {
        channel.pipeline().addFirst("first", new ChannelDuplexHandler() {

            @Override
            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                clientResources.eventBus().publish(new ConnectedEvent(local(ctx), remote(ctx)));
                super.channelActive(ctx);
            }

            @Override
            public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                clientResources.eventBus().publish(new DisconnectedEvent(local(ctx), remote(ctx)));
                super.channelInactive(ctx);
            }
        });
    }
    SslHandler sslHandler = new SslHandler(sslEngine, redisURI.isStartTls());
    channel.pipeline().addLast(sslHandler);
    if (channel.pipeline().get("channelActivator") == null) {
        channel.pipeline().addLast("channelActivator", new RedisChannelInitializerImpl() {

            private AsyncCommand<?, ?, ?> pingCommand;

            @Override
            public CompletableFuture<Boolean> channelInitialized() {
                return initializedFuture;
            }

            @Override
            public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                initializedFuture = new CompletableFuture<>();
                pingCommand = null;
                super.channelInactive(ctx);
            }

            @Override
            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                if (initializedFuture.isDone()) {
                    super.channelActive(ctx);
                }
            }

            @Override
            public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                if (evt instanceof SslHandshakeCompletionEvent && !initializedFuture.isDone()) {
                    SslHandshakeCompletionEvent event = (SslHandshakeCompletionEvent) evt;
                    if (event.isSuccess()) {
                        if (pingCommandSupplier != PlainChannelInitializer.NO_PING) {
                            pingCommand = pingCommandSupplier.get();
                            pingBeforeActivate(pingCommand, initializedFuture, ctx, clientResources, timeout, timeUnit);
                        } else {
                            ctx.fireChannelActive();
                        }
                    } else {
                        initializedFuture.completeExceptionally(event.cause());
                    }
                }
                if (evt instanceof ConnectionEvents.Close) {
                    if (ctx.channel().isOpen()) {
                        ctx.channel().close();
                    }
                }
                if (evt instanceof ConnectionEvents.Activated) {
                    if (!initializedFuture.isDone()) {
                        initializedFuture.complete(true);
                        clientResources.eventBus().publish(new ConnectionActivatedEvent(local(ctx), remote(ctx)));
                    }
                }
                super.userEventTriggered(ctx, evt);
            }

            @Override
            public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                if (cause instanceof SSLHandshakeException || cause.getCause() instanceof SSLException) {
                    initializedFuture.completeExceptionally(cause);
                }
                super.exceptionCaught(ctx, cause);
            }
        });
    }
    for (ChannelHandler handler : handlers) {
        removeIfExists(channel.pipeline(), handler.getClass());
        channel.pipeline().addLast(handler);
    }
    clientResources.nettyCustomizer().afterChannelInitialized(channel);
}
Example 50
Project: netty-zmtp-master  File: EndToEndTest.java View source code
private Channel bind(final SocketAddress address, final ChannelHandler codec, final ChannelHandler handler) {
    final ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(new NioEventLoopGroup(1), new NioEventLoopGroup());
    bootstrap.channel(NioServerSocketChannel.class);
    bootstrap.childHandler(new ChannelInitializer<NioSocketChannel>() {

        @Override
        protected void initChannel(final NioSocketChannel ch) throws Exception {
            ch.pipeline().addLast(codec, handler);
        }
    });
    return bootstrap.bind(address).awaitUninterruptibly().channel();
}
Example 51
Project: Pulsar-master  File: ServerCnx.java View source code
@Override
protected void handleConnect(CommandConnect connect) {
    checkArgument(state == State.Start);
    if (service.isAuthenticationEnabled()) {
        try {
            String authMethod = "none";
            if (connect.hasAuthMethodName()) {
                authMethod = connect.getAuthMethodName();
            } else if (connect.hasAuthMethod()) {
                // Legacy client is passing enum
                authMethod = connect.getAuthMethod().name().substring(10).toLowerCase();
            }
            String authData = connect.getAuthData().toStringUtf8();
            ChannelHandler sslHandler = ctx.channel().pipeline().get(PulsarChannelInitializer.TLS_HANDLER);
            SSLSession sslSession = null;
            if (sslHandler != null) {
                sslSession = ((SslHandler) sslHandler).engine().getSession();
            }
            authRole = getBrokerService().getAuthenticationService().authenticate(new AuthenticationDataCommand(authData, remoteAddress, sslSession), authMethod);
            log.info("[{}] Client successfully authenticated with {} role {}", remoteAddress, authMethod, authRole);
        } catch (AuthenticationException e) {
            String msg = "Unable to authenticate";
            log.warn("[{}] {}: {}", remoteAddress, msg, e.getMessage());
            ctx.writeAndFlush(Commands.newError(-1, ServerError.AuthenticationError, msg));
            close();
            return;
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("Received CONNECT from {}", remoteAddress);
    }
    ctx.writeAndFlush(Commands.newConnected(connect));
    state = State.Connected;
    remoteEndpointProtocolVersion = connect.getProtocolVersion();
    String version = connect.hasClientVersion() ? connect.getClientVersion() : null;
    if (isNotBlank(version) && !version.contains(" ")) /* ignore default version: pulsar client */
    {
        this.clientVersion = version;
    }
}
Example 52
Project: alluxio-master  File: AlluxioBlockStoreTest.java View source code
@Before
public void before() throws Exception {
    mMasterClient = PowerMockito.mock(BlockMasterClient.class);
    mChannel = PowerMockito.mock(Channel.class);
    mPipeline = PowerMockito.mock(ChannelPipeline.class);
    mContext = PowerMockito.mock(FileSystemContext.class);
    Mockito.when(mContext.acquireBlockMasterClientResource()).thenReturn(new DummyCloseableResource<>(mMasterClient));
    mLocalAddr = new WorkerNetAddress().setHost(NetworkAddressUtils.getLocalHostName());
    mBlockStore = new AlluxioBlockStore(mContext, WORKER_HOSTNAME_LOCAL);
    Mockito.when(mContext.acquireNettyChannel(Mockito.any(WorkerNetAddress.class))).thenReturn(mChannel);
    Mockito.when(mChannel.pipeline()).thenReturn(mPipeline);
    Mockito.when(mPipeline.last()).thenReturn(new RPCMessageDecoder());
    Mockito.when(mPipeline.addLast(Mockito.any(ChannelHandler.class))).thenReturn(mPipeline);
}
Example 53
Project: cpush-apns-master  File: SSLBootstrap.java View source code
@Override
@SuppressWarnings("unchecked")
void init(Channel channel) throws Exception {
    ChannelPipeline p = channel.pipeline();
    SSLEngine engine = sslContext.createSSLEngine();
    engine.setUseClientMode(true);
    SslHandler sslHandler = new SslHandler(engine);
    p.addFirst(SSL_HANDLER, sslHandler);
    if (handler() != null) {
        p.addLast(handler());
    }
    ChannelHandler[] handlers = initHandlers.get();
    if (handlers != null) {
        p.addLast(handlers);
    }
    final Map<ChannelOption<?>, Object> options = options();
    synchronized (options) {
        for (Entry<ChannelOption<?>, Object> e : options.entrySet()) {
            try {
                if (!channel.config().setOption((ChannelOption<Object>) e.getKey(), e.getValue())) {
                    logger.warn("Unknown channel option: " + e);
                }
            } catch (Throwable t) {
                logger.warn("Failed to set a channel option: " + channel, t);
            }
        }
    }
    final Map<AttributeKey<?>, Object> attrs = attrs();
    synchronized (attrs) {
        for (Entry<AttributeKey<?>, Object> e : attrs.entrySet()) {
            channel.attr((AttributeKey<Object>) e.getKey()).set(e.getValue());
        }
    }
}
Example 54
Project: dungproxy-master  File: HttpHeaderDecoder.java View source code
/**
     * It's called once the http headers is decoded.
     * The decode task will be ended and hand over to {@link HttpBodyDecoder} handler
     */
private void finish(ChannelHandlerContext ctx, ChannelHandler nextHandler, ByteBuf cumulation) {
    // Set reader index to the writer index in order to release it in ByteToMessageDecoder
    ctx.channel().attr(KEEP_ALIVE).set(shouldKeepConnectionAlive);
    cumulation.readerIndex(cumulation.writerIndex());
    decodeFinished = true;
    ctx.pipeline().remove(this);
    ctx.pipeline().addLast(nextHandler);
}
Example 55
Project: eucalyptus-master  File: IoHandlers.java View source code
public static Map<String, ChannelHandler> channelMonitors(final TimeUnit unit, final long timeout) {
    final Map<String, ChannelHandler> monitors = Maps.newHashMap();
    monitors.put("idlehandler", new IdleStateHandler(0L, 0L, timeout, unit));
    monitors.put("idlecloser", new ChannelInboundHandlerAdapter() {

        @Override
        public void userEventTriggered(final ChannelHandlerContext ctx, final Object evt) throws Exception {
            if (evt instanceof IdleStateEvent) {
                IdleStateEvent e = (IdleStateEvent) evt;
                if (e.state() == IdleState.ALL_IDLE) {
                    ctx.channel().close();
                }
            }
        }
    });
    monitors.putAll(extraMonitors);
    return monitors;
}
Example 56
Project: hydra-master  File: HttpStaticFileHandler.java View source code
@Override
public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
    if (!request.getDecoderResult().isSuccess()) {
        sendError(ctx, BAD_REQUEST);
        return;
    }
    // since we are using send file, we must remove the compression unit or it will donk out
    ChannelHandler compressor = ctx.pipeline().get("compressor");
    if (compressor != null) {
        ctx.pipeline().remove("compressor");
    }
    if (request.getMethod() != GET) {
        sendError(ctx, METHOD_NOT_ALLOWED);
        return;
    }
    QueryStringDecoder urlDecoder = new QueryStringDecoder(request.getUri());
    String target = urlDecoder.path();
    final String path = sanitizeUri(target);
    if (path == null) {
        sendError(ctx, FORBIDDEN);
        return;
    }
    Path file = Paths.get(webDir + path);
    log.trace("trying to serve static file {}", file);
    if (Files.isHidden(file) || Files.notExists(file)) {
        sendError(ctx, NOT_FOUND);
        return;
    }
    if (!Files.isRegularFile(file)) {
        sendError(ctx, FORBIDDEN);
        return;
    }
    log.trace("cache validation occuring for {}", file);
    // Cache Validation
    String ifModifiedSince = request.headers().get(IF_MODIFIED_SINCE);
    if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) {
        SimpleDateFormat dateFormatter = new SimpleDateFormat(HttpUtils.HTTP_DATE_FORMAT, Locale.US);
        Date ifModifiedSinceDate = dateFormatter.parse(ifModifiedSince);
        // Only compare up to the second because the datetime format we send to the client
        // does not have milliseconds
        long ifModifiedSinceDateSeconds = ifModifiedSinceDate.getTime() / 1000;
        long fileLastModifiedSeconds = Files.getLastModifiedTime(file).toMillis() / 1000;
        if (ifModifiedSinceDateSeconds == fileLastModifiedSeconds) {
            sendNotModified(ctx);
            return;
        }
    }
    log.trace("sending {}", file);
    FileChannel fileChannel;
    try {
        fileChannel = FileChannel.open(file, StandardOpenOption.READ);
    } catch (IOException fnfe) {
        sendError(ctx, NOT_FOUND);
        return;
    }
    long fileLength = fileChannel.size();
    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
    setContentLength(response, fileLength);
    setContentTypeHeader(response, file);
    try {
        setDateAndCacheHeaders(response, file);
    } catch (IOException ioex) {
        fileChannel.close();
        sendError(ctx, NOT_FOUND);
        return;
    }
    if (isKeepAlive(request)) {
        response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    }
    // Write the initial line and the header.
    ctx.write(response);
    // Write the content.
    ctx.write(new DefaultFileRegion(fileChannel, 0, fileLength));
    // Write the end marker
    ChannelFuture lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
    // Decide whether to close the connection or not.
    if (!isKeepAlive(request)) {
        // Close the connection when the whole content is written out.
        lastContentFuture.addListener(ChannelFutureListener.CLOSE);
    } else {
        ctx.pipeline().remove(this);
        if (compressor != null) {
            ctx.pipeline().addBefore("query", "compressor", compressor);
        }
    }
}
Example 57
Project: solmix-master  File: MyNettyTransceiver.java View source code
@Override
protected void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline p = ch.pipeline();
    if (handlers != null) {
        for (ChannelHandler handler : handlers) {
            p.addLast(handler.getClass().getSimpleName(), handler);
        }
    }
    p.addLast("frameDecoder", new NettyFrameDecoder());
    p.addLast("frameEncoder", new NettyFrameEncoder());
    p.addLast("handler", createNettyClientAvroHandler());
}
Example 58
Project: tachyon-master  File: AlluxioBlockStoreTest.java View source code
@Before
public void before() throws Exception {
    mBlockWorkerClient = PowerMockito.mock(BlockWorkerClient.class);
    mMasterClient = PowerMockito.mock(BlockMasterClient.class);
    mChannel = PowerMockito.mock(Channel.class);
    mPipeline = PowerMockito.mock(ChannelPipeline.class);
    mContext = PowerMockito.mock(FileSystemContext.class);
    // Mock block store context to return our mock clients
    Mockito.when(mContext.createBlockWorkerClient(Mockito.any(WorkerNetAddress.class))).thenReturn(mBlockWorkerClient);
    Mockito.when(mContext.acquireBlockMasterClientResource()).thenReturn(new DummyCloseableResource<>(mMasterClient));
    mLocalAddr = new WorkerNetAddress().setHost(NetworkAddressUtils.getLocalHostName());
    Mockito.when(mBlockWorkerClient.getWorkerNetAddress()).thenReturn(mLocalAddr);
    mBlockStore = new AlluxioBlockStore(mContext, WORKER_HOSTNAME_LOCAL);
    Mockito.when(mContext.acquireNettyChannel(Mockito.any(WorkerNetAddress.class))).thenReturn(mChannel);
    Mockito.when(mChannel.pipeline()).thenReturn(mPipeline);
    Mockito.when(mPipeline.last()).thenReturn(new RPCMessageDecoder());
    Mockito.when(mPipeline.addLast(Mockito.any(ChannelHandler.class))).thenReturn(mPipeline);
}
Example 59
Project: TomP2P-master  File: AbstractHolePStrategy.java View source code
/**
	 * This method does two things. If the initiating peer calls it, he gets
	 * back a {@link List} of new {@link SimpleInboundHandler} to deal with the
	 * replies of the replying peer. If a replying peer is calling this method
	 * it will return a {@link List} of default {@link SimpleInboundHandler}s
	 * from the {@link Dispatcher}.
	 * 
	 * @param futureResponse
	 * @return handlerList
	 */
protected List<Map<String, Pair<EventExecutorGroup, ChannelHandler>>> prepareHandlers(final boolean initiator, final FutureDone<Message> futureDone) {
    final List<Map<String, Pair<EventExecutorGroup, ChannelHandler>>> handlerList = new ArrayList<Map<String, Pair<EventExecutorGroup, ChannelHandler>>>(numberOfHoles);
    SimpleChannelInboundHandler<Message> inboundHandler;
    Map<String, Pair<EventExecutorGroup, ChannelHandler>> handlers;
    if (initiator) {
        for (int i = 0; i < numberOfHoles; i++) {
            // we need an own futureresponse for every hole we try to punch
            futureResponses.add(new FutureResponse(originalMessage));
            inboundHandler = createAfterHolePHandler(futureDone);
        //TODO: enable
        //handlers = peer.connectionBean().sender().configureHandlers(inboundHandler, futureResponses.get(i), idleUDPSeconds, false);
        //handlerList.add(handlers);
        }
    } else {
        inboundHandler = new DuplicatesHandler(peer.connectionBean().dispatcher());
        for (int i = 0; i < numberOfHoles; i++) {
            // we need an own futureresponse for every hole we try to punch
            futureResponses.add(new FutureResponse(originalMessage));
        //TODO: enable
        //handlers = peer.connectionBean().sender().configureHandlers(inboundHandler, futureResponses.get(i), idleUDPSeconds, false);
        //handlerList.add(handlers);
        }
    }
    return handlerList;
}
Example 60
Project: usc-master  File: UscPlugin.java View source code
protected void initAgentPipeline(ChannelPipeline p, ChannelHandler securityHandler) {
    p.addLast(new LoggingHandler("UscPlugin Handler 6", LogLevel.TRACE));
    // security handler
    p.addLast("securityHandler", securityHandler);
    p.addLast(new LoggingHandler("UscPlugin Handler 5", LogLevel.TRACE));
    // Encoders
    // UscFrameEncoder is Sharable
    p.addLast("frameEncoder", getFrameEncoder());
    p.addLast(new LoggingHandler("UscPlugin Handler 4", LogLevel.TRACE));
    // Decoders
    // UscFrameDecoderUdp is Sharable
    p.addLast("frameDecoder", getFrameDecoder());
    p.addLast(new LoggingHandler("UscPlugin Handler 3", LogLevel.TRACE));
    // add handler for handling response for remote session like a dummy
    // server
    p.addLast(remoteServerHandler);
    p.addLast(new LoggingHandler("UscPlugin Handler 2", LogLevel.TRACE));
    // UscDemultiplexer
    p.addLast("UscDemultiplexer", getDemultiplexer());
    p.addLast(new LoggingHandler("UscPlugin Handler 1", LogLevel.TRACE));
}
Example 61
Project: WaarpCommon-master  File: WaarpSslUtility.java View source code
/**
     * Add a SslHandler in a pipeline when the channel is already active
     * 
     * @param future
     *            might be null, condition to start to add the handler to the pipeline
     * @param pipeline
     * @param sslHandler
     * @param listener
     *            action once the handshake is done
     */
@SuppressWarnings({ "unchecked", "rawtypes" })
public static void addSslHandler(ChannelFuture future, final ChannelPipeline pipeline, final ChannelHandler sslHandler, final GenericFutureListener<? extends Future<? super Channel>> listener) {
    if (future == null) {
        logger.debug("Add SslHandler: " + pipeline.channel());
        pipeline.addFirst("SSL", sslHandler);
        ((SslHandler) sslHandler).handshakeFuture().addListener(listener);
    } else {
        future.addListener(new GenericFutureListener() {

            public void operationComplete(Future future) throws Exception {
                logger.debug("Add SslHandler: " + pipeline.channel());
                pipeline.addFirst("SSL", sslHandler);
                ((SslHandler) sslHandler).handshakeFuture().addListener(listener);
            }
        });
    }
    logger.debug("Checked Ssl Handler to be added: " + pipeline.channel());
}
Example 62
Project: Youtube-Hacked-Client-1.8-master  File: OldServerPinger.java View source code
protected void initChannel(Channel p_initChannel_1_) {
    try {
        p_initChannel_1_.config().setOption(ChannelOption.IP_TOS, Integer.valueOf(24));
    } catch (ChannelException var4) {
        ;
    }
    try {
        p_initChannel_1_.config().setOption(ChannelOption.TCP_NODELAY, Boolean.valueOf(false));
    } catch (ChannelException var3) {
        ;
    }
    p_initChannel_1_.pipeline().addLast(new ChannelHandler[] { new SimpleChannelInboundHandler() {

        private static final String __OBFID = "CL_00000895";

        public void channelActive(ChannelHandlerContext p_channelActive_1_) throws Exception {
            super.channelActive(p_channelActive_1_);
            ByteBuf var2x = Unpooled.buffer();
            try {
                var2x.writeByte(254);
                var2x.writeByte(1);
                var2x.writeByte(250);
                char[] var3 = "MC|PingHost".toCharArray();
                var2x.writeShort(var3.length);
                char[] var4 = var3;
                int var5 = var3.length;
                int var6;
                char var7;
                for (var6 = 0; var6 < var5; ++var6) {
                    var7 = var4[var6];
                    var2x.writeChar(var7);
                }
                var2x.writeShort(7 + 2 * var2.getIP().length());
                var2x.writeByte(127);
                var3 = var2.getIP().toCharArray();
                var2x.writeShort(var3.length);
                var4 = var3;
                var5 = var3.length;
                for (var6 = 0; var6 < var5; ++var6) {
                    var7 = var4[var6];
                    var2x.writeChar(var7);
                }
                var2x.writeInt(var2.getPort());
                p_channelActive_1_.channel().writeAndFlush(var2x).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
            } finally {
                var2x.release();
            }
        }

        protected void channelRead0(ChannelHandlerContext p_channelRead0_1_, ByteBuf p_channelRead0_2_) {
            short var3 = p_channelRead0_2_.readUnsignedByte();
            if (var3 == 255) {
                String var4 = new String(p_channelRead0_2_.readBytes(p_channelRead0_2_.readShort() * 2).array(), Charsets.UTF_16BE);
                String[] var5 = (String[]) Iterables.toArray(OldServerPinger.PING_RESPONSE_SPLITTER.split(var4), String.class);
                if ("§1".equals(var5[0])) {
                    int var6 = MathHelper.parseIntWithDefault(var5[1], 0);
                    String var7 = var5[2];
                    String var8 = var5[3];
                    int var9 = MathHelper.parseIntWithDefault(var5[4], -1);
                    int var10 = MathHelper.parseIntWithDefault(var5[5], -1);
                    server.version = -1;
                    server.gameVersion = var7;
                    server.serverMOTD = var8;
                    server.populationInfo = EnumChatFormatting.GRAY + "" + var9 + "" + EnumChatFormatting.DARK_GRAY + "/" + EnumChatFormatting.GRAY + var10;
                }
            }
            p_channelRead0_1_.close();
        }

        public void exceptionCaught(ChannelHandlerContext p_exceptionCaught_1_, Throwable p_exceptionCaught_2_) {
            p_exceptionCaught_1_.close();
        }

        protected void channelRead0(ChannelHandlerContext p_channelRead0_1_, Object p_channelRead0_2_) {
            this.channelRead0(p_channelRead0_1_, (ByteBuf) p_channelRead0_2_);
        }
    } });
}
Example 63
Project: datacollector-master  File: TestTCPServerSource.java View source code
@Test
public void syslogRecords() {
    Charset charset = Charsets.ISO_8859_1;
    final TCPServerSourceConfig configBean = createConfigBean(charset);
    TCPServerSource source = new TCPServerSource(configBean);
    List<Stage.ConfigIssue> issues = new LinkedList<>();
    EmbeddedChannel ch = new EmbeddedChannel(source.buildByteBufToMessageDecoderChain(issues).toArray(new ChannelHandler[0]));
    ch.writeInbound(Unpooled.copiedBuffer(SYSLOG_RECORD + configBean.nonTransparentFramingSeparatorCharStr, charset));
    assertSyslogRecord(ch);
    assertFalse(ch.finishAndReleaseAll());
    configBean.syslogFramingMode = SyslogFramingMode.OCTET_COUNTING;
    EmbeddedChannel ch2 = new EmbeddedChannel(source.buildByteBufToMessageDecoderChain(issues).toArray(new ChannelHandler[0]));
    ch2.writeInbound(Unpooled.copiedBuffer(SYSLOG_RECORD.length() + " " + SYSLOG_RECORD, charset));
    assertSyslogRecord(ch2);
    assertFalse(ch2.finishAndReleaseAll());
}
Example 64
Project: divconq-master  File: HyperSession.java View source code
public Channel allocateHttpChannel(final ChannelHandler handler, OperationResult or) {
    final AtomicReference<Future<Channel>> sslready = new AtomicReference<>();
    Bootstrap b = new Bootstrap();
    b.group(Hub.instance.getEventLoopGroup()).channel(NioSocketChannel.class).option(ChannelOption.ALLOCATOR, Hub.instance.getBufferAllocator()).handler(new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            if (HyperSession.this.info.isSecurel()) {
                SslHandler sh = new SslHandler(HyperSession.this.sslfac.getClientEngine());
                sslready.set(sh.handshakeFuture());
                pipeline.addLast("ssl", sh);
            }
            pipeline.addLast("decoder", new HttpResponseDecoder());
            pipeline.addLast("encoder", new HttpRequestEncoder());
            // TODO maybe
            //pipeline.addLast("deflater", new HttpContentCompressor());
            pipeline.addLast("handler", handler);
        }
    });
    or.info("Web Client connecting");
    try {
        // must wait here to make sure we don't release connectLock too soon
        // we want channel init (above) to complete before we try connect again
        ChannelFuture f = b.connect(this.info.getAddress()).sync();
        if (!f.isSuccess()) {
            or.error(1, "Web Client unable to successfully connect: " + f.cause());
        }
        // that lets wait for the handshake to be done for sure
        if (sslready.get() != null) {
            Future<Channel> sf = sslready.get().sync();
            if (!sf.isSuccess()) {
                or.error(1, "Web Client unable to securely connect: " + sf.cause());
            }
        }
        if (handler instanceof ClientHandler)
            ((ClientHandler) handler).waitConnect();
        return f.channel();
    } catch (InterruptedException x) {
        or.error(1, "Web Client interrupted while connecting: " + x);
    } catch (Exception x) {
        or.error(1, "Web Client unable to connect: " + x);
    }
    return null;
}
Example 65
Project: GreenBits-master  File: WampServerWebsocketHandler.java View source code
private void tryWebsocketHandshake(final ChannelHandlerContext ctx, FullHttpRequest request) {
    String wsLocation = getWebSocketLocation(ctx, request);
    String subProtocols = WampSerialization.makeWebsocketSubprotocolList(supportedSerializations);
    WebSocketServerHandshaker handshaker = new WebSocketServerHandshakerFactory(wsLocation, subProtocols, false, WampHandlerConfiguration.MAX_WEBSOCKET_FRAME_SIZE).newHandshaker(request);
    if (handshaker == null) {
        WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
    } else {
        handshakeInProgress = true;
        // The next statement will throw if the handshake gets wrong. This will lead to an
        // exception in the channel which will close the channel (which is OK).
        final ChannelFuture handshakeFuture = handshaker.handshake(ctx.channel(), request);
        String actualProtocol = handshaker.selectedSubprotocol();
        serialization = WampSerialization.fromString(actualProtocol);
        // invalid packets anyway
        if (serialization == WampSerialization.Invalid) {
            handshakeFuture.addListener(ChannelFutureListener.CLOSE);
            return;
        }
        // Remove all handlers after this one - we don't need them anymore since we switch to WAMP
        ChannelHandler last = ctx.pipeline().last();
        while (last != null && last != this) {
            ctx.pipeline().removeLast();
            last = ctx.pipeline().last();
        }
        if (last == null) {
            throw new IllegalStateException("Can't find the WAMP server handler in the pipeline");
        }
        // Remove the WampServerWebSocketHandler and replace it with the protocol handler
        // which processes pings and closes
        ProtocolHandler protocolHandler = new ProtocolHandler();
        ctx.pipeline().replace(this, "wamp-websocket-protocol-handler", protocolHandler);
        final ChannelHandlerContext protocolHandlerCtx = ctx.pipeline().context(protocolHandler);
        // Handle websocket fragmentation before the deserializer
        protocolHandlerCtx.pipeline().addLast(new WebSocketFrameAggregator(WampHandlerConfiguration.MAX_WEBSOCKET_FRAME_SIZE));
        // Install the serializer and deserializer
        protocolHandlerCtx.pipeline().addLast("wamp-serializer", new WampSerializationHandler(serialization));
        protocolHandlerCtx.pipeline().addLast("wamp-deserializer", new WampDeserializationHandler(serialization));
        // Retrieve a listener for this new connection
        final IWampConnectionListener connectionListener = connectionAcceptor.createNewConnectionListener();
        // Create a Wamp connection interface on top of that
        final WampServerConnection connection = new WampServerConnection(serialization);
        ChannelHandler routerHandler = new SimpleChannelInboundHandler<WampMessage>() {

            @Override
            public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
                // Gets called once the channel gets added to the pipeline
                connection.ctx = ctx;
            }

            @Override
            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                connectionAcceptor.acceptNewConnection(connection, connectionListener);
            }

            @Override
            public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                connectionListener.transportClosed();
            }

            @Override
            protected void channelRead0(ChannelHandlerContext ctx, WampMessage msg) throws Exception {
                connectionListener.messageReceived(msg);
            }

            @Override
            public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                ctx.close();
                connectionListener.transportError(cause);
            }
        };
        // Install the router in the pipeline
        protocolHandlerCtx.pipeline().addLast("wamp-router", routerHandler);
        handshakeFuture.addListener(new ChannelFutureListener() {

            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (!future.isSuccess()) {
                    // The handshake was not successful. 
                    // Close the channel without registering
                    // TODO: This is a race condition if the router did not yet accept the connection
                    ctx.fireExceptionCaught(future.cause());
                } else {
                    // We successfully sent out the handshake
                    // Notify the router of that fact
                    ctx.fireChannelActive();
                }
            }
        });
    // TODO: Maybe there are frames incoming before the handshakeFuture is resolved
    // This might lead to frames getting sent to the router before it is activated
    }
}
Example 66
Project: hbase-master  File: FanOutOneBlockAsyncDFSOutputHelper.java View source code
@Override
protected void channelRead0(ChannelHandlerContext ctx, BlockOpResponseProto resp) throws Exception {
    Status pipelineStatus = resp.getStatus();
    if (PipelineAck.isRestartOOBStatus(pipelineStatus)) {
        throw new IOException("datanode " + dnInfo + " is restarting");
    }
    String logInfo = "ack with firstBadLink as " + resp.getFirstBadLink();
    if (resp.getStatus() != Status.SUCCESS) {
        if (resp.getStatus() == Status.ERROR_ACCESS_TOKEN) {
            throw new InvalidBlockTokenException("Got access token error" + ", status message " + resp.getMessage() + ", " + logInfo);
        } else {
            throw new IOException("Got error" + ", status=" + resp.getStatus().name() + ", status message " + resp.getMessage() + ", " + logInfo);
        }
    }
    // success
    ChannelPipeline p = ctx.pipeline();
    for (ChannelHandler handler; (handler = p.removeLast()) != null; ) {
        // of pipeline.
        if (handler instanceof IdleStateHandler) {
            break;
        }
    }
    // Disable auto read here. Enable it after we setup the streaming pipeline in
    // FanOutOneBLockAsyncDFSOutput.
    ctx.channel().config().setAutoRead(false);
    promise.trySuccess(ctx.channel());
}
Example 67
Project: jawampa-master  File: WampServerWebsocketHandler.java View source code
private void tryWebsocketHandshake(final ChannelHandlerContext ctx, FullHttpRequest request) {
    String wsLocation = getWebSocketLocation(ctx, request);
    String subProtocols = WampSerialization.makeWebsocketSubprotocolList(supportedSerializations);
    WebSocketServerHandshaker handshaker = new WebSocketServerHandshakerFactory(wsLocation, subProtocols, false, WampHandlerConfiguration.MAX_WEBSOCKET_FRAME_SIZE).newHandshaker(request);
    if (handshaker == null) {
        WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
    } else {
        handshakeInProgress = true;
        // The next statement will throw if the handshake gets wrong. This will lead to an
        // exception in the channel which will close the channel (which is OK).
        final ChannelFuture handshakeFuture = handshaker.handshake(ctx.channel(), request);
        String actualProtocol = handshaker.selectedSubprotocol();
        serialization = WampSerialization.fromString(actualProtocol);
        // invalid packets anyway
        if (serialization == WampSerialization.Invalid) {
            handshakeFuture.addListener(ChannelFutureListener.CLOSE);
            return;
        }
        // Remove all handlers after this one - we don't need them anymore since we switch to WAMP
        ChannelHandler last = ctx.pipeline().last();
        while (last != null && last != this) {
            ctx.pipeline().removeLast();
            last = ctx.pipeline().last();
        }
        if (last == null) {
            throw new IllegalStateException("Can't find the WAMP server handler in the pipeline");
        }
        // Remove the WampServerWebSocketHandler and replace it with the protocol handler
        // which processes pings and closes
        ProtocolHandler protocolHandler = new ProtocolHandler();
        ctx.pipeline().replace(this, "wamp-websocket-protocol-handler", protocolHandler);
        final ChannelHandlerContext protocolHandlerCtx = ctx.pipeline().context(protocolHandler);
        // Handle websocket fragmentation before the deserializer
        protocolHandlerCtx.pipeline().addLast(new WebSocketFrameAggregator(WampHandlerConfiguration.MAX_WEBSOCKET_FRAME_SIZE));
        // Install the serializer and deserializer
        protocolHandlerCtx.pipeline().addLast("wamp-serializer", new WampSerializationHandler(serialization));
        protocolHandlerCtx.pipeline().addLast("wamp-deserializer", new WampDeserializationHandler(serialization));
        // Retrieve a listener for this new connection
        final IWampConnectionListener connectionListener = connectionAcceptor.createNewConnectionListener();
        // Create a Wamp connection interface on top of that
        final WampServerConnection connection = new WampServerConnection(serialization);
        ChannelHandler routerHandler = new SimpleChannelInboundHandler<WampMessage>() {

            @Override
            public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
                // Gets called once the channel gets added to the pipeline
                connection.ctx = ctx;
            }

            @Override
            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                connectionAcceptor.acceptNewConnection(connection, connectionListener);
            }

            @Override
            public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                connectionListener.transportClosed();
            }

            @Override
            protected void channelRead0(ChannelHandlerContext ctx, WampMessage msg) throws Exception {
                connectionListener.messageReceived(msg);
            }

            @Override
            public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                ctx.close();
                connectionListener.transportError(cause);
            }
        };
        // Install the router in the pipeline
        protocolHandlerCtx.pipeline().addLast("wamp-router", routerHandler);
        handshakeFuture.addListener(new ChannelFutureListener() {

            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (!future.isSuccess()) {
                    // The handshake was not successful. 
                    // Close the channel without registering
                    // TODO: This is a race condition if the router did not yet accept the connection
                    ctx.fireExceptionCaught(future.cause());
                } else {
                    // We successfully sent out the handshake
                    // Notify the router of that fact
                    ctx.fireChannelActive();
                }
            }
        });
    // TODO: Maybe there are frames incoming before the handshakeFuture is resolved
    // This might lead to frames getting sent to the router before it is activated
    }
}
Example 68
Project: mongo-java-driver-master  File: NettyStream.java View source code
private void adjustTimeout(final boolean disable) {
    ChannelHandler timeoutHandler = channel.pipeline().get(READ_HANDLER_NAME);
    if (timeoutHandler != null) {
        final ReadTimeoutHandler readTimeoutHandler = (ReadTimeoutHandler) timeoutHandler;
        final ChannelHandlerContext handlerContext = channel.pipeline().context(timeoutHandler);
        EventExecutor executor = handlerContext.executor();
        if (disable) {
            if (executor.inEventLoop()) {
                readTimeoutHandler.removeTimeout(handlerContext);
            } else {
                executor.submit(new Runnable() {

                    @Override
                    public void run() {
                        readTimeoutHandler.removeTimeout(handlerContext);
                    }
                });
            }
        } else {
            if (executor.inEventLoop()) {
                readTimeoutHandler.scheduleTimeout(handlerContext);
            } else {
                executor.submit(new Runnable() {

                    @Override
                    public void run() {
                        readTimeoutHandler.scheduleTimeout(handlerContext);
                    }
                });
            }
        }
    }
}
Example 69
Project: WildAnimalsPlus-1.7.10-master  File: NetworkRegistry.java View source code
/**
     * Create a new synchronous message channel pair based on netty.
     *
     * There are two preconstructed models available:
     * <ul>
     * <li> {@link #newSimpleChannel(String)} provides {@link SimpleNetworkWrapper}, a simple implementation of a netty handler, suitable for those who don't
     * wish to dive too deeply into netty.
     * <li> {@link #newEventChannel(String)} provides {@link FMLEventChannel} an event driven implementation, with lower level
     * access to the network data stream, for those with advanced bitbanging needs that don't wish to poke netty too hard.
     * <li> Alternatively, simply use the netty features provided here and implement the full power of the netty stack.
     * </ul>
     *
     * There are two channels created : one for each logical side (considered as the source of an outbound message)
     * The returned map will contain a value for each logical side, though both will only be working in the
     * integrated server case.
     *
     * The channel expects to read and write using {@link FMLProxyPacket}. All operation is synchronous, as the
     * asynchronous behaviour occurs at a lower level in netty.
     *
     * The first handler in the pipeline is special and should not be removed or moved from the head - it transforms
     * packets from the outbound of this pipeline into custom packets, based on the current {@link AttributeKey} value
     * {@link NetworkRegistry#FML_MESSAGETARGET} and {@link NetworkRegistry#FML_MESSAGETARGETARGS} set on the channel.
     * For the client to server channel (source side : CLIENT) this is fixed as "TOSERVER". For SERVER to CLIENT packets,
     * several possible values exist.
     *
     * Mod Messages should be transformed using a something akin to a {@link MessageToMessageCodec}. FML provides
     * a utility codec, {@link FMLIndexedMessageToMessageCodec} that transforms from {@link FMLProxyPacket} to a mod
     * message using a message discriminator byte. This is optional, but highly recommended for use.
     *
     * Note also that the handlers supplied need to be {@link ChannelHandler.Shareable} - they are injected into two
     * channels.
     *
     * @param name
     * @param handlers
     * @return
     */
public EnumMap<Side, FMLEmbeddedChannel> newChannel(String name, ChannelHandler... handlers) {
    if (channels.containsKey(name) || name.startsWith("MC|") || name.startsWith("") || name.startsWith("FML")) {
        throw new RuntimeException("That channel is already registered");
    }
    EnumMap<Side, FMLEmbeddedChannel> result = Maps.newEnumMap(Side.class);
    for (Side side : Side.values()) {
        FMLEmbeddedChannel channel = new FMLEmbeddedChannel(name, side, handlers);
        channels.get(side).put(name, channel);
        result.put(side, channel);
    }
    return result;
}
Example 70
Project: consulo-master  File: SocketLock.java View source code
@NotNull
public ActivateStatus lock(@NotNull String[] args) throws Exception {
    log("enter: lock(config=%s system=%s)", myConfigPath, mySystemPath);
    return underLocks(() -> {
        File portMarkerC = new File(myConfigPath, PORT_FILE);
        File portMarkerS = new File(mySystemPath, PORT_FILE);
        MultiMap<Integer, String> portToPath = MultiMap.createSmart();
        addExistingPort(portMarkerC, myConfigPath, portToPath);
        addExistingPort(portMarkerS, mySystemPath, portToPath);
        if (!portToPath.isEmpty()) {
            for (Map.Entry<Integer, Collection<String>> entry : portToPath.entrySet()) {
                ActivateStatus status = tryActivate(entry.getKey(), entry.getValue(), args);
                if (status != ActivateStatus.NO_INSTANCE) {
                    log("exit: lock(): " + status);
                    return status;
                }
            }
        }
        if (isShutdownCommand()) {
            System.exit(0);
        }
        myToken = UUID.randomUUID().toString();
        String[] lockedPaths = { myConfigPath, mySystemPath };
        int workerCount = 1;
        NotNullProducer<ChannelHandler> handler = () -> new MyChannelInboundHandler(lockedPaths, myActivateListener, myToken);
        myServer = BuiltInServer.startNioOrOio(workerCount, 6942, 50, false, handler);
        byte[] portBytes = Integer.toString(myServer.getPort()).getBytes(CharsetToolkit.UTF8_CHARSET);
        FileUtil.writeToFile(portMarkerC, portBytes);
        FileUtil.writeToFile(portMarkerS, portBytes);
        File tokenFile = new File(mySystemPath, TOKEN_FILE);
        FileUtil.writeToFile(tokenFile, myToken.getBytes(CharsetToolkit.UTF8_CHARSET));
        PosixFileAttributeView view = Files.getFileAttributeView(tokenFile.toPath(), PosixFileAttributeView.class);
        if (view != null) {
            try {
                view.setPermissions(ContainerUtil.newHashSet(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE));
            } catch (IOException e) {
                log(e);
            }
        }
        log("exit: lock(): succeed");
        return ActivateStatus.NO_INSTANCE;
    });
}
Example 71
Project: FML-master  File: NetworkRegistry.java View source code
/**
     * Create a new synchronous message channel pair based on netty.
     *
     * There are two preconstructed models available:
     * <ul>
     * <li> {@link #newSimpleChannel(String)} provides {@link SimpleNetworkWrapper}, a simple implementation of a netty handler, suitable for those who don't
     * wish to dive too deeply into netty.
     * <li> {@link #newEventChannel(String)} provides {@link FMLEventChannel} an event driven implementation, with lower level
     * access to the network data stream, for those with advanced bitbanging needs that don't wish to poke netty too hard.
     * <li> Alternatively, simply use the netty features provided here and implement the full power of the netty stack.
     * </ul>
     *
     * There are two channels created : one for each logical side (considered as the source of an outbound message)
     * The returned map will contain a value for each logical side, though both will only be working in the
     * integrated server case.
     *
     * The channel expects to read and write using {@link FMLProxyPacket}. All operation is synchronous, as the
     * asynchronous behaviour occurs at a lower level in netty.
     *
     * The first handler in the pipeline is special and should not be removed or moved from the head - it transforms
     * packets from the outbound of this pipeline into custom packets, based on the current {@link AttributeKey} value
     * {@link NetworkRegistry#FML_MESSAGETARGET} and {@link NetworkRegistry#FML_MESSAGETARGETARGS} set on the channel.
     * For the client to server channel (source side : CLIENT) this is fixed as "TOSERVER". For SERVER to CLIENT packets,
     * several possible values exist.
     *
     * Mod Messages should be transformed using a something akin to a {@link MessageToMessageCodec}. FML provides
     * a utility codec, {@link FMLIndexedMessageToMessageCodec} that transforms from {@link FMLProxyPacket} to a mod
     * message using a message discriminator byte. This is optional, but highly recommended for use.
     *
     * Note also that the handlers supplied need to be {@link ChannelHandler.Shareable} - they are injected into two
     * channels.
     *
     * @param name
     * @param handlers
     * @return
     */
public EnumMap<Side, FMLEmbeddedChannel> newChannel(String name, ChannelHandler... handlers) {
    if (channels.containsKey(name) || name.startsWith("MC|") || name.startsWith("") || name.startsWith("FML")) {
        throw new RuntimeException("That channel is already registered");
    }
    EnumMap<Side, FMLEmbeddedChannel> result = Maps.newEnumMap(Side.class);
    for (Side side : Side.values()) {
        FMLEmbeddedChannel channel = new FMLEmbeddedChannel(name, side, handlers);
        channels.get(side).put(name, channel);
        result.put(side, channel);
    }
    return result;
}
Example 72
Project: folsom-master  File: DefaultRawMemcacheClient.java View source code
public static ListenableFuture<RawMemcacheClient> connect(final HostAndPort address, final int outstandingRequestLimit, final boolean binary, final Executor executor, final long timeoutMillis, final Charset charset, final Metrics metrics, final int maxSetLength) {
    final ChannelInboundHandler decoder;
    if (binary) {
        decoder = new BinaryMemcacheDecoder();
    } else {
        decoder = new AsciiMemcacheDecoder(charset);
    }
    final ChannelHandler initializer = new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(final Channel ch) throws Exception {
            ch.pipeline().addLast(new TcpTuningHandler(), decoder, // Downstream
            new MemcacheEncoder());
        }
    };
    final SettableFuture<RawMemcacheClient> clientFuture = SettableFuture.create();
    final Bootstrap bootstrap = new Bootstrap().group(EVENT_LOOP_GROUP).handler(initializer).channel(NioSocketChannel.class).option(ChannelOption.MESSAGE_SIZE_ESTIMATOR, SimpleSizeEstimator.INSTANCE);
    final ChannelFuture connectFuture = bootstrap.connect(new InetSocketAddress(address.getHostText(), address.getPort()));
    connectFuture.addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(final ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                // Create client
                final RawMemcacheClient client = new DefaultRawMemcacheClient(address, future.channel(), outstandingRequestLimit, executor, timeoutMillis, metrics, maxSetLength);
                clientFuture.set(client);
            } else {
                clientFuture.setException(future.cause());
            }
        }
    });
    return onExecutor(clientFuture, executor);
}
Example 73
Project: intellij-community-master  File: SocketLock.java View source code
@NotNull
public ActivateStatus lock(@NotNull String[] args) throws Exception {
    log("enter: lock(config=%s system=%s)", myConfigPath, mySystemPath);
    return underLocks(() -> {
        File portMarkerC = new File(myConfigPath, PORT_FILE);
        File portMarkerS = new File(mySystemPath, PORT_FILE);
        MultiMap<Integer, String> portToPath = MultiMap.createSmart();
        addExistingPort(portMarkerC, myConfigPath, portToPath);
        addExistingPort(portMarkerS, mySystemPath, portToPath);
        if (!portToPath.isEmpty()) {
            for (Map.Entry<Integer, Collection<String>> entry : portToPath.entrySet()) {
                ActivateStatus status = tryActivate(entry.getKey(), entry.getValue(), args);
                if (status != ActivateStatus.NO_INSTANCE) {
                    log("exit: lock(): " + status);
                    return status;
                }
            }
        }
        if (isShutdownCommand()) {
            System.exit(0);
        }
        myToken = UUID.randomUUID().toString();
        String[] lockedPaths = { myConfigPath, mySystemPath };
        int workerCount = PlatformUtils.isIdeaCommunity() || PlatformUtils.isDatabaseIDE() || PlatformUtils.isCidr() ? 1 : 2;
        NotNullProducer<ChannelHandler> handler = () -> new MyChannelInboundHandler(lockedPaths, myActivateListener, myToken);
        myServer = BuiltInServer.startNioOrOio(workerCount, 6942, 50, false, handler);
        byte[] portBytes = Integer.toString(myServer.getPort()).getBytes(CharsetToolkit.UTF8_CHARSET);
        FileUtil.writeToFile(portMarkerC, portBytes);
        FileUtil.writeToFile(portMarkerS, portBytes);
        File tokenFile = new File(mySystemPath, TOKEN_FILE);
        FileUtil.writeToFile(tokenFile, myToken.getBytes(CharsetToolkit.UTF8_CHARSET));
        PosixFileAttributeView view = Files.getFileAttributeView(tokenFile.toPath(), PosixFileAttributeView.class);
        if (view != null) {
            try {
                view.setPermissions(ContainerUtil.newHashSet(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE));
            } catch (IOException e) {
                log(e);
            }
        }
        log("exit: lock(): succeed");
        return ActivateStatus.NO_INSTANCE;
    });
}
Example 74
Project: MineAPI-master  File: INCHandler.java View source code
@Override
public void addChannel(final Player player) {
    final Object handle = NmsClass.getEntityPlayerByPlayer(player);
    try {
        final Object connection = INCHandler.connection.get(handle);
        final Channel channel = getChannel(network.get(connection));
        this.threadPool.execute(() -> {
            try {
                ChannelHandler handler = new ChannelHandler(player);
                channel.pipeline().addBefore("packet_handler", "MineAPI", handler);
                sendMessageToConsole(DEBUG_PREFIX + handler.getClass().getName() + " added to " + player.getName() + ".", true);
            } catch (Exception ignored) {
            }
        });
    } catch (IllegalArgumentExceptionIllegalAccessException |  e) {
        e.printStackTrace();
    }
}
Example 75
Project: MinecraftForge-master  File: NetworkRegistry.java View source code
/**
     * Create a new synchronous message channel pair based on netty.
     *
     * There are two preconstructed models available:
     * <ul>
     * <li> {@link #newSimpleChannel(String)} provides {@link SimpleNetworkWrapper}, a simple implementation of a netty handler, suitable for those who don't
     * wish to dive too deeply into netty.
     * <li> {@link #newEventDrivenChannel(String)} (String)} provides {@link FMLEventChannel} an event driven implementation, with lower level
     * access to the network data stream, for those with advanced bitbanging needs that don't wish to poke netty too hard.
     * <li> Alternatively, simply use the netty features provided here and implement the full power of the netty stack.
     * </ul>
     *
     * There are two channels created : one for each logical side (considered as the source of an outbound message)
     * The returned map will contain a value for each logical side, though both will only be working in the
     * integrated server case.
     *
     * The channel expects to read and write using {@link FMLProxyPacket}. All operation is synchronous, as the
     * asynchronous behaviour occurs at a lower level in netty.
     *
     * The first handler in the pipeline is special and should not be removed or moved from the head - it transforms
     * packets from the outbound of this pipeline into custom packets, based on the current {@link AttributeKey} value
     * {@link FMLOutboundHandler#FML_MESSAGETARGET} and {@link FMLOutboundHandler#FML_MESSAGETARGETARGS} set on the channel.
     * For the client to server channel (source side : CLIENT) this is fixed as "TOSERVER". For SERVER to CLIENT packets,
     * several possible values exist.
     *
     * Mod Messages should be transformed using a something akin to a {@link MessageToMessageCodec}. FML provides
     * a utility codec, {@link FMLIndexedMessageToMessageCodec} that transforms from {@link FMLProxyPacket} to a mod
     * message using a message discriminator byte. This is optional, but highly recommended for use.
     *
     * Note also that the handlers supplied need to be {@link ChannelHandler.Sharable} - they are injected into two
     * channels.
     *
     * @param name
     * @param handlers
     * @return
     */
public EnumMap<Side, FMLEmbeddedChannel> newChannel(String name, ChannelHandler... handlers) {
    if (channels.get(Side.CLIENT).containsKey(name) || channels.get(Side.SERVER).containsKey(name) || name.startsWith("MC|") || name.startsWith("") || name.startsWith("FML")) {
        throw new RuntimeException("That channel is already registered");
    }
    EnumMap<Side, FMLEmbeddedChannel> result = Maps.newEnumMap(Side.class);
    for (Side side : Side.values()) {
        FMLEmbeddedChannel channel = new FMLEmbeddedChannel(name, side, handlers);
        channels.get(side).put(name, channel);
        result.put(side, channel);
    }
    return result;
}
Example 76
Project: MinecraftForkage-master  File: NetworkRegistry.java View source code
/**
     * Create a new synchronous message channel pair based on netty.
     *
     * There are two preconstructed models available:
     * <ul>
     * <li> {@link #newSimpleChannel(String)} provides {@link SimpleNetworkWrapper}, a simple implementation of a netty handler, suitable for those who don't
     * wish to dive too deeply into netty.
     * <li> {@link #newEventChannel(String)} provides {@link FMLEventChannel} an event driven implementation, with lower level
     * access to the network data stream, for those with advanced bitbanging needs that don't wish to poke netty too hard.
     * <li> Alternatively, simply use the netty features provided here and implement the full power of the netty stack.
     * </ul>
     *
     * There are two channels created : one for each logical side (considered as the source of an outbound message)
     * The returned map will contain a value for each logical side, though both will only be working in the
     * integrated server case.
     *
     * The channel expects to read and write using {@link FMLProxyPacket}. All operation is synchronous, as the
     * asynchronous behaviour occurs at a lower level in netty.
     *
     * The first handler in the pipeline is special and should not be removed or moved from the head - it transforms
     * packets from the outbound of this pipeline into custom packets, based on the current {@link AttributeKey} value
     * {@link NetworkRegistry#FML_MESSAGETARGET} and {@link NetworkRegistry#FML_MESSAGETARGETARGS} set on the channel.
     * For the client to server channel (source side : CLIENT) this is fixed as "TOSERVER". For SERVER to CLIENT packets,
     * several possible values exist.
     *
     * Mod Messages should be transformed using a something akin to a {@link MessageToMessageCodec}. FML provides
     * a utility codec, {@link FMLIndexedMessageToMessageCodec} that transforms from {@link FMLProxyPacket} to a mod
     * message using a message discriminator byte. This is optional, but highly recommended for use.
     *
     * Note also that the handlers supplied need to be {@link ChannelHandler.Shareable} - they are injected into two
     * channels.
     *
     * @param name
     * @param handlers
     * @return
     */
public EnumMap<Side, FMLEmbeddedChannel> newChannel(String name, ChannelHandler... handlers) {
    if (channels.containsKey(name) || name.startsWith("MC|") || name.startsWith("") || name.startsWith("FML")) {
        throw new RuntimeException("That channel is already registered");
    }
    EnumMap<Side, FMLEmbeddedChannel> result = Maps.newEnumMap(Side.class);
    for (Side side : Side.values()) {
        FMLEmbeddedChannel channel = new FMLEmbeddedChannel(name, side, handlers);
        channels.get(side).put(name, channel);
        result.put(side, channel);
    }
    return result;
}
Example 77
Project: WaarpFtp-master  File: NetworkHandler.java View source code
/**
     * Execute one command and write the following answer
     */
private void messageRunAnswer(final ChannelHandlerContext ctx) {
    boolean error = false;
    logger.debug("Code: " + session.getCurrentCommand().getCode());
    try {
        businessHandler.beforeRunCommand();
        AbstractCommand command = session.getCurrentCommand();
        logger.debug("Run {}", command.getCommand());
        command.exec();
        businessHandler.afterRunCommandOk();
    } catch (CommandAbstractException e) {
        logger.debug("Command in error", e);
        error = true;
        session.setReplyCode(e);
        businessHandler.afterRunCommandKo(e);
    }
    logger.debug("Code: " + session.getCurrentCommand().getCode() + " [" + session.getReplyCode() + "]");
    if (error) {
        if (session.getCurrentCommand().getCode() != FtpCommandCode.INTERNALSHUTDOWN) {
            writeFinalAnswer(ctx);
        }
        // In error so Check that Data is closed
        if (session.getDataConn().isActive()) {
            logger.debug("Closing DataChannel while command is in error");
            try {
                session.getDataConn().getCurrentDataChannel().close();
            } catch (FtpNoConnectionException e) {
            }
        }
        return;
    }
    if (session.getCurrentCommand().getCode() == FtpCommandCode.AUTH || session.getCurrentCommand().getCode() == FtpCommandCode.CCC) {
        controlChannel.config().setAutoRead(false);
        ChannelFuture future = writeIntermediateAnswer(ctx);
        session.setCurrentCommandFinished();
        if (session.getCurrentCommand().getCode() == FtpCommandCode.AUTH) {
            logger.debug("SSL to be added to pipeline");
            ChannelHandler sslHandler = ctx.pipeline().first();
            if (sslHandler instanceof SslHandler) {
                logger.debug("Already got a SslHandler");
            } else {
                logger.debug("Add Explicitely SSL support to Command");
                // add the SSL support
                sslHandler = FtpsInitializer.waarpSslContextFactory.initInitializer(true, FtpsInitializer.waarpSslContextFactory.needClientAuthentication());
                session.prepareSsl();
                WaarpSslUtility.addSslHandler(future, ctx.pipeline(), sslHandler, new GenericFutureListener<Future<? super Channel>>() {

                    public void operationComplete(Future<? super Channel> future) throws Exception {
                        if (!future.isSuccess()) {
                            String error2 = future.cause() != null ? future.cause().getMessage() : "During Handshake";
                            logger.error("Cannot finalize Ssl Command channel " + error2);
                            callForSnmp("SSL Connection Error", error2);
                            session.setSsl(false);
                            ctx.close();
                        } else {
                            logger.debug("End of initialization of SSL and command channel: " + ctx.channel());
                            session.setSsl(true);
                        }
                    }
                });
            }
        } else if (session.getCurrentCommand().getCode() == FtpCommandCode.CCC) {
            logger.debug("SSL to be removed from pipeline");
            // remove the SSL support
            session.prepareSsl();
            WaarpSslUtility.removingSslHandler(future, controlChannel, false);
        }
    } else if (session.getCurrentCommand().getCode() != FtpCommandCode.INTERNALSHUTDOWN) {
        writeFinalAnswer(ctx);
    }
}
Example 78
Project: yamcs-master  File: HttpClient.java View source code
private ChannelFuture setupChannel(URI uri, ChannelHandler... channelHandler) {
    String scheme = uri.getScheme() == null ? "http" : uri.getScheme();
    String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
    int port = uri.getPort();
    if (port == -1) {
        port = 80;
    }
    if (!"http".equalsIgnoreCase(scheme)) {
        throw new IllegalArgumentException("Only HTTP is supported.");
    }
    if (group == null) {
        group = new NioEventLoopGroup();
    }
    Bootstrap b = new Bootstrap();
    b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel ch) {
            ChannelPipeline p = ch.pipeline();
            p.addLast(new HttpClientCodec());
            p.addLast(new HttpContentDecompressor());
            p.addLast(channelHandler);
        }
    });
    return b.connect(host, port);
}
Example 79
Project: jzab-master  File: NettyTransport.java View source code
void sendFile(File file) throws Exception {
    long length = file.length();
    LOG.debug("Got request of sending file {} of length {}.", file, length);
    Message handshake = MessageBuilder.buildFileHeader(length);
    byte[] bytes = handshake.toByteArray();
    // Sends HANDSHAKE first before transferring actual file data, the
    // HANDSHAKE will tell the peer's channel to prepare for the file
    // transferring.
    channel.writeAndFlush(Unpooled.wrappedBuffer(bytes)).sync();
    ChannelHandler prepender = channel.pipeline().get("frameEncoder");
    // Removes length prepender, we don't need this handler for file
    // transferring.
    channel.pipeline().remove(prepender);
    // Adds ChunkedWriteHandler for file transferring.
    ChannelHandler cwh = new ChunkedWriteHandler();
    channel.pipeline().addLast(cwh);
    // Begins file transferring.
    RandomAccessFile raf = new RandomAccessFile(file, "r");
    if (channel.pipeline().get(SslHandler.class) != null) {
        // Zero-Copy file transferring is not supported for ssl.
        channel.writeAndFlush(new ChunkedFile(raf, 0, length, 8912));
    } else {
        // Use Zero-Copy file transferring in non-ssl mode.
        FileRegion region = new DefaultFileRegion(raf.getChannel(), 0, length);
        channel.writeAndFlush(region);
    }
    // Restores pipeline to original state.
    channel.pipeline().remove(cwh);
    channel.pipeline().addLast("frameEncoder", prepender);
}
Example 80
Project: vert.x-master  File: HttpServerImpl.java View source code
private void handshake(FullHttpRequest request, Channel ch, ChannelHandlerContext ctx) throws Exception {
    WebSocketServerHandshaker shake = createHandshaker(ch, request);
    if (shake == null) {
        return;
    }
    HandlerHolder<Handler<ServerWebSocket>> wsHandler = wsHandlerManager.chooseHandler(ch.eventLoop());
    if (wsHandler == null) {
        createConnAndHandle(ctx, ch, request, shake);
    } else {
        wsHandler.context.executeFromIO(() -> {
            URI theURI;
            try {
                theURI = new URI(request.getUri());
            } catch (URISyntaxException e2) {
                throw new IllegalArgumentException("Invalid uri " + request.getUri());
            }
            ServerConnection wsConn = new ServerConnection(vertx, HttpServerImpl.this, ch, wsHandler.context, serverOrigin, shake, metrics);
            wsConn.metric(metrics.connected(wsConn.remoteAddress(), wsConn.remoteName()));
            wsConn.wsHandler(wsHandler.handler);
            Runnable connectRunnable = () -> {
                VertxHttpHandler<ServerConnection> handler = ch.pipeline().get(VertxHttpHandler.class);
                handler.conn = wsConn;
                connectionMap.put(ch, wsConn);
                try {
                    shake.handshake(ch, request);
                } catch (WebSocketHandshakeException e) {
                    wsConn.handleException(e);
                } catch (Exception e) {
                    log.error("Failed to generate shake response", e);
                }
            };
            ServerWebSocketImpl ws = new ServerWebSocketImpl(vertx, theURI.toString(), theURI.getPath(), theURI.getQuery(), new HeadersAdaptor(request.headers()), wsConn, shake.version() != WebSocketVersion.V00, connectRunnable, options.getMaxWebsocketFrameSize(), options().getMaxWebsocketMessageSize());
            ws.setMetric(metrics.connected(wsConn.metric(), ws));
            wsConn.handleWebsocketConnect(ws);
            if (!ws.isRejected()) {
                ChannelHandler handler = ctx.pipeline().get(HttpChunkContentCompressor.class);
                if (handler != null) {
                    // remove compressor as its not needed anymore once connection was upgraded to websockets
                    ctx.pipeline().remove(handler);
                }
                ws.connectNow();
            } else {
                ch.writeAndFlush(new DefaultFullHttpResponse(HTTP_1_1, BAD_GATEWAY));
            }
        });
    }
}
Example 81
Project: dcache-master  File: LoginAuthenticationHandlerFactory.java View source code
@Override
public ChannelHandler createHandler() {
    return new LoginAuthenticationHandler(_authenticationFactory, _loginStrategy);
}
Example 82
Project: dynjs-master  File: AbstractCommand.java View source code
public ChannelHandler newChannelHandler(Debugger debugger) throws IllegalAccessException, InstantiationException {
    return new CommandHandler(this);
}
Example 83
Project: dubbo-plus-master  File: Netty4CodecAdapter.java View source code
public io.netty.channel.ChannelHandler getEncoder() {
    return encoder;
}
Example 84
Project: http2-netty-master  File: Http2OrHttpHandler.java View source code
@Override
protected ChannelHandler createHttp1RequestHandler() {
    return new FallbackRequestHandler();
}
Example 85
Project: mpush-master  File: ConnectClient.java View source code
@Override
public ChannelHandler getChannelHandler() {
    return handler;
}
Example 86
Project: qpid-jms-master  File: NettyEchoServer.java View source code
@Override
protected ChannelHandler getServerHandler() {
    return new EchoServerHandler();
}
Example 87
Project: sxp-master  File: HandlerFactory.java View source code
/**
     * @return Gets all decoders
     */
public synchronized ChannelHandler[] getDecoders() {
    decoders.addFirst(new LengthFieldBasedFrameDecoderImpl());
    ChannelHandler[] out = decoders.toArray(new ChannelHandler[decoders.size()]);
    decoders.pollFirst();
    return out;
}
Example 88
Project: vnluser-master  File: PublicHttpServerInitializer.java View source code
ChannelHandler getLogChannelHandler() {
    return new PublicHttpProcessorRoutingHandler();
}
Example 89
Project: elasticsearch-readonlyrest-plugin-master  File: SSLTransportNetty4.java View source code
public ChannelHandler configureServerChannelHandler() {
    return new SSLHandler(this);
}
Example 90
Project: light-task-scheduler-master  File: NettyCodecFactory.java View source code
public ChannelHandler getEncoder() {
    return new NettyEncoder();
}
Example 91
Project: BungeeCord-master  File: ChannelWrapper.java View source code
public void addBefore(String baseName, String name, ChannelHandler handler) {
    Preconditions.checkState(ch.eventLoop().inEventLoop(), "cannot add handler outside of event loop");
    ch.pipeline().flush();
    ch.pipeline().addBefore(baseName, name, handler);
}
Example 92
Project: jreactive-8583-master  File: Iso8583ChannelInitializer.java View source code
protected ChannelHandler createLoggingHandler(G configuration) {
    return new IsoMessageLoggingHandler(LogLevel.DEBUG, configuration.logSensitiveData(), configuration.logFieldDescription(), configuration.getSensitiveDataFields());
}
Example 93
Project: mockserver-master  File: PortUnificationHandler.java View source code
protected void addLastIfNotPresent(ChannelPipeline pipeline, ChannelHandler channelHandler) {
    if (pipeline.get(channelHandler.getClass()) == null) {
        pipeline.addLast(channelHandler);
    }
}
Example 94
Project: myLib-master  File: NetConnection.java View source code
public void addLast(ChannelHandler handler) {
    future.channel().pipeline().addLast(handler);
}
Example 95
Project: springside-engine-master  File: TNettyServer.java View source code
private ChannelHandler createThriftFramedDecoder() {
    return new ThriftFrameedDecoder();
}
Example 96
Project: tengi-master  File: NegotiationChannelHandler.java View source code
@Override
public void injectChannelHandler(ChannelHandlerContext ctx, ChannelHandler handler) {
    ChannelPipeline pipeline = ctx.pipeline();
    pipeline.addLast(handler);
    pipeline.remove(ctx.handler());
    pipeline.addLast(ctx.handler());
}
Example 97
Project: onos-master  File: ChannelHandlerContextAdapter.java View source code
@Override
public ChannelHandler handler() {
    return null;
}
Example 98
Project: openflowjava-master  File: PublishingChannelInitializerTest.java View source code
/**
     * Test disconnect on new connection rejected
     * @throws UnknownHostException
     */
@Test
public void testinitChannelNoEncryptionAcceptFails() throws UnknownHostException {
    when(mockSwConnHandler.accept(eq(InetAddress.getLocalHost()))).thenReturn(false);
    pubChInitializer.initChannel(mockSocketCh);
    verify(mockSocketCh, times(1)).disconnect();
    verify(mockChPipeline, times(0)).addLast(any(String.class), any(ChannelHandler.class));
}
Example 99
Project: SpongeForge-master  File: SpongeIndexedMessageChannel.java View source code
@Override
protected ChannelHandler[] getHandlers() {
    return new ChannelHandler[] { this.packetCodec = new SpongeMessageCodec() };
}
Example 100
Project: elasticsearch-master  File: Netty4HttpServerPipeliningTests.java View source code
@Override
public ChannelHandler configureServerChannelHandler() {
    return new CustomHttpChannelHandler(this, executorService, Netty4HttpServerPipeliningTests.this.threadPool.getThreadContext());
}
Example 101
Project: jooby-master  File: NettyPipeline.java View source code
private String addAfter(final ChannelPipeline p, final String baseName, final String name, final ChannelHandler h) {
    p.addAfter(baseName, name, h);
    return p.context(h).name();
}