Example usage for io.netty.handler.codec Delimiters nulDelimiter

List of usage examples for io.netty.handler.codec Delimiters nulDelimiter

Introduction

In this page you can find the example usage for io.netty.handler.codec Delimiters nulDelimiter.

Prototype

public static ByteBuf[] nulDelimiter() 

Source Link

Document

Returns a NUL (0x00) delimiter, which could be used for Flash XML socket or any similar protocols.

Usage

From source file:connexion.ClientInitializer.java

@Override
public void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();

    // Add SSL handler first to encrypt and decrypt everything.
    // In this example, we use a bogus certificate in the server side
    // and accept any invalid certificates in the client side.
    // You will need something more complicated to identify both
    // and server in the real world.
    pipeline.addLast(sslCtx.newHandler(ch.alloc(), ClientSocket.HOST, ClientSocket.PORT));

    // On top of the SSL handler, add the text line codec.
    pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.nulDelimiter()));
    pipeline.addLast(new StringDecoder());
    pipeline.addLast(new StringEncoder());

    // and then business logic.
    pipeline.addLast(new ClientHandler());
    ClientSocket.handler = new ClientHandler();
    pipeline.addLast(ClientSocket.handler);
}

From source file:connexion.ServerInitializer.java

@Override
public void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();

    // Add SSL handler first to encrypt and decrypt everything.
    // In this example, we use a bogus certificate in the server side
    // and accept any invalid certificates in the client side.
    // You will need something more complicated to identify both
    // and server in the real world.
    pipeline.addLast(sslCtx.newHandler(ch.alloc()));

    // On top of the SSL handler, add the text line codec.
    pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.nulDelimiter()));
    pipeline.addLast(new StringDecoder());
    pipeline.addLast(new StringEncoder());

    // and then business logic.
    ServerSocket.handler = new ServerHandler();
    pipeline.addLast(ServerSocket.handler);
}

From source file:org.apache.camel.component.netty4.NettyConfiguration.java

License:Apache License

public void parseURI(URI uri, Map<String, Object> parameters, NettyComponent component,
        String... supportedProtocols) throws Exception {
    protocol = uri.getScheme();/*from   w  w w  . j  a v a2  s .c  o  m*/

    boolean found = false;
    for (String supportedProtocol : supportedProtocols) {
        if (protocol != null && protocol.equalsIgnoreCase(supportedProtocol)) {
            found = true;
            break;
        }
    }

    if (!found) {
        throw new IllegalArgumentException("Unrecognized Netty protocol: " + protocol + " for uri: " + uri);
    }

    setHost(uri.getHost());
    setPort(uri.getPort());

    ssl = component.getAndRemoveOrResolveReferenceParameter(parameters, "ssl", boolean.class, false);
    sslHandler = component.getAndRemoveOrResolveReferenceParameter(parameters, "sslHandler", SslHandler.class,
            sslHandler);
    passphrase = component.getAndRemoveOrResolveReferenceParameter(parameters, "passphrase", String.class,
            passphrase);
    keyStoreFormat = component.getAndRemoveOrResolveReferenceParameter(parameters, "keyStoreFormat",
            String.class, keyStoreFormat == null ? "JKS" : keyStoreFormat);
    securityProvider = component.getAndRemoveOrResolveReferenceParameter(parameters, "securityProvider",
            String.class, securityProvider == null ? "SunX509" : securityProvider);
    keyStoreFile = component.getAndRemoveOrResolveReferenceParameter(parameters, "keyStoreFile", File.class,
            keyStoreFile);
    trustStoreFile = component.getAndRemoveOrResolveReferenceParameter(parameters, "trustStoreFile", File.class,
            trustStoreFile);
    keyStoreResource = component.getAndRemoveOrResolveReferenceParameter(parameters, "keyStoreResource",
            String.class, keyStoreResource);
    trustStoreResource = component.getAndRemoveOrResolveReferenceParameter(parameters, "trustStoreResource",
            String.class, trustStoreResource);
    clientPipelineFactory = component.getAndRemoveOrResolveReferenceParameter(parameters,
            "clientPipelineFactory", ClientPipelineFactory.class, clientPipelineFactory);
    serverPipelineFactory = component.getAndRemoveOrResolveReferenceParameter(parameters,
            "serverPipelineFactory", ServerPipelineFactory.class, serverPipelineFactory);

    // set custom encoders and decoders first
    List<ChannelHandler> referencedEncoders = component.resolveAndRemoveReferenceListParameter(parameters,
            "encoders", ChannelHandler.class, null);
    addToHandlersList(encoders, referencedEncoders, ChannelHandler.class);
    List<ChannelHandler> referencedDecoders = component.resolveAndRemoveReferenceListParameter(parameters,
            "decoders", ChannelHandler.class, null);
    addToHandlersList(decoders, referencedDecoders, ChannelHandler.class);

    // then set parameters with the help of the camel context type converters
    EndpointHelper.setReferenceProperties(component.getCamelContext(), this, parameters);
    EndpointHelper.setProperties(component.getCamelContext(), this, parameters);

    // additional netty options, we don't want to store an empty map, so set it as null if empty
    options = IntrospectionSupport.extractProperties(parameters, "option.");
    if (options != null && options.isEmpty()) {
        options = null;
    }

    // add default encoders and decoders
    if (encoders.isEmpty() && decoders.isEmpty()) {
        if (allowDefaultCodec) {
            if ("udp".equalsIgnoreCase(protocol)) {
                encoders.add(ChannelHandlerFactories.newDatagramPacketEncoder());
            }
            // are we textline or object?
            if (isTextline()) {
                Charset charset = getEncoding() != null ? Charset.forName(getEncoding()) : CharsetUtil.UTF_8;
                encoders.add(ChannelHandlerFactories.newStringEncoder(charset, protocol));
                ByteBuf[] delimiters = delimiter == TextLineDelimiter.LINE ? Delimiters.lineDelimiter()
                        : Delimiters.nulDelimiter();
                decoders.add(ChannelHandlerFactories.newDelimiterBasedFrameDecoder(decoderMaxLineLength,
                        delimiters, protocol));
                decoders.add(ChannelHandlerFactories.newStringDecoder(charset, protocol));

                if (LOG.isDebugEnabled()) {
                    LOG.debug(
                            "Using textline encoders and decoders with charset: {}, delimiter: {} and decoderMaxLineLength: {}",
                            new Object[] { charset, delimiter, decoderMaxLineLength });
                }
            } else {
                // object serializable is then used
                encoders.add(ChannelHandlerFactories.newObjectEncoder(protocol));
                decoders.add(ChannelHandlerFactories.newObjectDecoder(protocol));

                LOG.debug("Using object encoders and decoders");
            }
            if ("udp".equalsIgnoreCase(protocol)) {
                decoders.add(ChannelHandlerFactories.newDatagramPacketDecoder());
            }
        } else {
            LOG.debug("No encoders and decoders will be used");
        }
    } else {
        LOG.debug("Using configured encoders and/or decoders");
    }
}

From source file:org.graylog2.inputs.transports.netty.LenientDelimiterBasedFrameDecoderTest.java

License:Open Source License

@Test
public void testFailSlowTooLongFrameRecovery() throws Exception {
    EmbeddedChannel ch = new EmbeddedChannel(
            new LenientDelimiterBasedFrameDecoder(1, true, false, false, Delimiters.nulDelimiter()));

    for (int i = 0; i < 2; i++) {
        ch.writeInbound(Unpooled.wrappedBuffer(new byte[] { 1, 2 }));
        try {/* w  w w  . j  a v  a2s.  c  o m*/
            assertTrue(ch.writeInbound(Unpooled.wrappedBuffer(new byte[] { 0 })));
            fail(DecoderException.class.getSimpleName() + " must be raised.");
        } catch (TooLongFrameException e) {
            // Expected
        }

        ch.writeInbound(Unpooled.wrappedBuffer(new byte[] { 'A', 0 }));
        ByteBuf buf = ch.readInbound();
        assertEquals("A", buf.toString(CharsetUtil.ISO_8859_1));

        buf.release();
    }
}

From source file:org.graylog2.inputs.transports.netty.LenientDelimiterBasedFrameDecoderTest.java

License:Open Source License

@Test
public void testFailFastTooLongFrameRecovery() throws Exception {
    EmbeddedChannel ch = new EmbeddedChannel(
            new LenientDelimiterBasedFrameDecoder(1, Delimiters.nulDelimiter()));

    for (int i = 0; i < 2; i++) {
        try {//from  w w  w . j  av a2 s .  c  om
            assertTrue(ch.writeInbound(Unpooled.wrappedBuffer(new byte[] { 1, 2 })));
            fail(DecoderException.class.getSimpleName() + " must be raised.");
        } catch (TooLongFrameException e) {
            // Expected
        }

        ch.writeInbound(Unpooled.wrappedBuffer(new byte[] { 0, 'A', 0 }));
        ByteBuf buf = ch.readInbound();
        assertEquals("A", buf.toString(CharsetUtil.ISO_8859_1));

        buf.release();
    }
}

From source file:org.graylog2.inputs.transports.netty.LenientDelimiterBasedFrameDecoderTest.java

License:Open Source License

@Test
public void testDecodeNulDelimiter() throws Exception {
    EmbeddedChannel ch = new EmbeddedChannel(
            new LenientDelimiterBasedFrameDecoder(8192, true, Delimiters.nulDelimiter()));

    ch.writeInbound(Unpooled.copiedBuffer("first\0second\0third", CharsetUtil.US_ASCII));

    ByteBuf buf = ch.readInbound();/*from   w  w w.j  a  va2s  .  com*/
    assertEquals("first", buf.toString(CharsetUtil.US_ASCII));

    ByteBuf buf2 = ch.readInbound();
    assertEquals("second", buf2.toString(CharsetUtil.US_ASCII));
    assertNull(ch.readInbound());
    ch.finish();

    ReferenceCountUtil.release(ch.readInbound());

    buf.release();
    buf2.release();
}

From source file:org.graylog2.inputs.transports.netty.LenientDelimiterBasedFrameDecoderTest.java

License:Open Source License

@Test
public void testDecodeNulDelimiterAndEmitLastLine() throws Exception {
    EmbeddedChannel ch = new EmbeddedChannel(
            new LenientDelimiterBasedFrameDecoder(8192, true, true, true, Delimiters.nulDelimiter()));

    ch.writeInbound(Unpooled.copiedBuffer("first\0second\0third", CharsetUtil.US_ASCII));

    ByteBuf buf = ch.readInbound();//ww w .j  a  v  a 2  s . c  o  m
    assertEquals("first", buf.toString(CharsetUtil.US_ASCII));

    ByteBuf buf2 = ch.readInbound();
    assertEquals("second", buf2.toString(CharsetUtil.US_ASCII));

    // Close channel
    assertTrue(ch.finish());
    ByteBuf buf3 = ch.readInbound();
    assertEquals("third", buf3.toString(CharsetUtil.US_ASCII));

    assertNull(ch.readInbound());
    assertFalse(ch.finish());

    ReferenceCountUtil.release(ch.readInbound());

    buf.release();
    buf2.release();
}

From source file:org.rzo.yajsw.app.WrapperManagerImpl.java

License:Apache License

public void start() {
    try {/*from  w w w  .  j  a va 2s . com*/
        // hack: avoid netty hangs on connect
        if (_config.getBoolean("wrapper.console.pipestreams", false)) {
            Socket dummy = new Socket("127.0.0.1", _port);
            OutputStream out = dummy.getOutputStream();
            out.close();
            dummy.close();
        }
    } catch (Throwable e1) {
        if (_debug > 1)
            e1.printStackTrace();
    }

    connector = new Bootstrap();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    // workerGroup.setIoRatio(99);
    connector.group(workerGroup);
    connector.channel(NioSocketChannel.class);

    connector.remoteAddress(new InetSocketAddress("127.0.0.1", _port));
    connector.option(ChannelOption.SO_REUSEADDR, true);
    connector.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10 * 1000);
    connector.option(ChannelOption.TCP_NODELAY, true);

    if (_debugComm)
        connector.handler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline()
                        .addLast(new io.netty.channel.ChannelHandler[] {
                                new SystemOutLoggingFilter("WrapperManager"),
                                new DelimiterBasedFrameDecoder(8192, true, Delimiters.nulDelimiter()),
                                new MessageEncoder(), new MessageDecoder(), new WrapperHandler() }

                );
            }

        });
    else
        connector.handler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline()
                        .addLast(new io.netty.channel.ChannelHandler[] {
                                new DelimiterBasedFrameDecoder(8192, true, Delimiters.nulDelimiter()),
                                new MessageEncoder(), new MessageDecoder(), new WrapperHandler() }

                );
            }

        });

    // pinger is a cycler with high priority threads
    // sends ping messages within a ping interval
    _pinger = new Cycler(getPingInterval(), 0,
            Executors.newCachedThreadPool(new DaemonThreadFactory("pinger", Thread.MAX_PRIORITY)),
            new Runnable() {
                long start = System.currentTimeMillis();

                public void run() {
                    ChannelFuture future;
                    if (_session != null && _session.isActive() && !_stopping && !_appearHanging) {
                        synchronized (_heapDataLock) {
                            if (_sendHeapData) {
                                if (minorGCDuration == -1)
                                    getGCData();
                                future = _session.writeAndFlush(
                                        new Message(Constants.WRAPPER_MSG_PING, "" + currentPercentHeap + ";"
                                                + minorGCDuration + ";" + fullGCDuration + ";" + lastUsedHeap));
                                currentPercentHeap = -1;
                                minorGCDuration = -1;
                                fullGCDuration = -1;
                            } else {
                                future = _session.writeAndFlush(new Message(Constants.WRAPPER_MSG_PING, ""));
                            }
                        }
                        try {
                            future.await(10000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        start = System.currentTimeMillis();
                    } else if ((_haltAppOnWrapper && (System.currentTimeMillis() - start) > _startupTimeout)
                            && !_stopping) {
                        System.out.println("no connection to wrapper during " + (_startupTimeout / 1000)
                                + " seconds -> System.exit(-1)");
                        System.out.println(
                                "if this is due to server overload consider increasing yajsw configuration property wrapper.startup.timeout");
                        System.exit(-1);
                    }
                }
            });
    _pinger.start();

    // connect
    // handler should process messages in a separate thread

    reconnect();
    /*
     * try { if (_config.getInt("wrapper.action.port") > 0) { _actionHandler
     * = new ActionHandler(this, _config); _actionHandler.start(); } } catch
     * (Exception ex) { log.info("could not start action handler " +
     * ex.getMessage()); }
     */

}

From source file:org.rzo.yajsw.controller.jvm.ControllerPipelineFactory.java

License:Apache License

@Override
protected void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline(); // Note the static import.
    if (_debug)//  ww  w .j  a  v  a  2  s . c  o m
        pipeline.addLast("logging1", new LoggingFilter(_controller.getLog(), "controller"));

    // allow new connections only if state != LOGGED_ON
    // and only if state != PROCESS_KILLED
    pipeline.addLast("checkWaiting", new ConditionFilter(new Condition() {
        public boolean isOk(ChannelHandlerContext ctx, Object msg) {
            boolean result = true;
            int currentState = _controller.getState();
            if (currentState == JVMController.STATE_LOGGED_ON) {
                _controller.getLog().info("app already logged on -> rejecting new connection");
                result = false;
            } else if (currentState == JVMController.STATE_PROCESS_KILLED) {
                if (_debug)
                    _controller.getLog().info("app not running -> rejecting new connection");
                result = false;
            }
            return result;
        }
    }));

    // create a firewall allowing only localhosts to connect
    WhitelistFilter firewall = new WhitelistFilter();
    try {
        firewall.allowAll(InetAddress.getAllByName("127.0.0.1"));
        firewall.allow(InetAddress.getLocalHost());
        pipeline.addLast("firewall", firewall);
    } catch (UnknownHostException e) {
        _controller.getLog().throwing(JVMController.class.getName(), "start", e);
    }

    // add a framer to split incoming bytes to message chunks
    pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, true, Delimiters.nulDelimiter()));

    // add messge codec
    pipeline.addLast("messageEncoder", new MessageEncoder());
    pipeline.addLast("messageDecoder", new MessageDecoder());

    if (_debug) {
        pipeline.addLast("logging", new LoggingFilter(_controller.getLog(), "controller"));
        _controller.getLog().info("jvm controller: netty logger set");
    }

    // if we found our partner close all other open connections
    pipeline.addLast("removeConnected", new ChannelGroupFilter(new Condition() {
        public boolean isOk(ChannelHandlerContext ctx, Object msg) {
            boolean result = false;
            if (msg instanceof Message) {
                Message m = (Message) msg;
                result = m.getCode() == Constants.WRAPPER_MSG_OKKEY;
            }
            return result;
        }
    }));

    // at last add the message handler
    pipeline.addLast("handler", new ControllerHandler(_controller));

}