Example usage for io.netty.buffer Unpooled buffer

List of usage examples for io.netty.buffer Unpooled buffer

Introduction

In this page you can find the example usage for io.netty.buffer Unpooled buffer.

Prototype

public static ByteBuf buffer() 

Source Link

Document

Creates a new big-endian Java heap buffer with reasonably small initial capacity, which expands its capacity boundlessly on demand.

Usage

From source file:com.digitalpetri.opcua.sdk.client.api.identity.UsernameProvider.java

License:Open Source License

@Override
public Tuple2<UserIdentityToken, SignatureData> getIdentityToken(EndpointDescription endpoint,
        ByteString serverNonce) throws Exception {

    UserTokenPolicy tokenPolicy = Arrays.stream(endpoint.getUserIdentityTokens())
            .filter(t -> t.getTokenType() == UserTokenType.UserName).findFirst()
            .orElseThrow(() -> new Exception("no username token policy found"));

    String policyId = tokenPolicy.getPolicyId();

    SecurityPolicy securityPolicy = SecurityPolicy.None;

    String securityPolicyUri = tokenPolicy.getSecurityPolicyUri();
    try {//www  . j  a v a  2 s  .c  o  m
        if (securityPolicyUri != null && !securityPolicyUri.isEmpty()) {
            securityPolicy = SecurityPolicy.fromUri(securityPolicyUri);
        } else {
            securityPolicyUri = endpoint.getSecurityPolicyUri();
            securityPolicy = SecurityPolicy.fromUri(securityPolicyUri);
        }
    } catch (Throwable t) {
        logger.warn("Error parsing SecurityPolicy for uri={}, falling back to no security.", securityPolicyUri);
    }

    byte[] passwordBytes = password.getBytes("UTF-8");
    byte[] nonceBytes = Optional.ofNullable(serverNonce.bytes()).orElse(new byte[0]);

    ByteBuf buffer = Unpooled.buffer().order(ByteOrder.LITTLE_ENDIAN);

    if (securityPolicy == SecurityPolicy.None) {
        buffer.writeBytes(passwordBytes);
    } else {
        buffer.writeInt(passwordBytes.length + nonceBytes.length);
        buffer.writeBytes(passwordBytes);
        buffer.writeBytes(nonceBytes);

        ByteString bs = endpoint.getServerCertificate();
        X509Certificate certificate = CertificateUtil.decodeCertificate(bs.bytes());

        int plainTextBlockSize = getPlainTextBlockSize(certificate, securityPolicy);
        int blockCount = (buffer.readableBytes() + plainTextBlockSize - 1) / plainTextBlockSize;
        Cipher cipher = getAndInitializeCipher(certificate, securityPolicy);

        ByteBuffer plainTextNioBuffer = buffer.nioBuffer();
        ByteBuffer cipherTextNioBuffer = Unpooled.buffer().order(ByteOrder.LITTLE_ENDIAN).nioBuffer();

        for (int blockNumber = 0; blockNumber < blockCount; blockNumber++) {
            int position = blockNumber * plainTextBlockSize;
            int limit = (blockNumber + 1) * plainTextBlockSize;
            plainTextNioBuffer.position(position).limit(limit);

            cipher.doFinal(plainTextNioBuffer, cipherTextNioBuffer);
        }

        cipherTextNioBuffer.flip();
        buffer = Unpooled.wrappedBuffer(cipherTextNioBuffer);
    }

    byte[] bs = new byte[buffer.readableBytes()];
    buffer.readBytes(bs);

    UserNameIdentityToken token = new UserNameIdentityToken(policyId, username, ByteString.of(bs),
            securityPolicy.getAsymmetricEncryptionAlgorithm().getUri());

    return new Tuple2<>(token, new SignatureData());
}

From source file:com.digitalpetri.opcua.stack.core.channel.messages.TcpMessageEncoder.java

License:Apache License

public static ByteBuf encode(HelloMessage helloMessage) throws UaException {
    return encode(MessageType.Hello, (b) -> HelloMessage.encode(helloMessage, b),
            Unpooled.buffer().order(ByteOrder.LITTLE_ENDIAN));
}

From source file:com.digitalpetri.opcua.stack.core.channel.messages.TcpMessageEncoder.java

License:Apache License

public static ByteBuf encode(AcknowledgeMessage acknowledgeMessage) throws UaException {
    return encode(MessageType.Acknowledge, b -> AcknowledgeMessage.encode(acknowledgeMessage, b),
            Unpooled.buffer().order(ByteOrder.LITTLE_ENDIAN));
}

From source file:com.digitalpetri.opcua.stack.core.channel.messages.TcpMessageEncoder.java

License:Apache License

public static ByteBuf encode(ErrorMessage errorMessage) throws UaException {
    return encode(MessageType.Error, (b) -> ErrorMessage.encode(errorMessage, b),
            Unpooled.buffer().order(ByteOrder.LITTLE_ENDIAN));
}

From source file:com.digitalpetri.opcua.stack.core.serialization.binary.BinarySerializationFixture.java

License:Apache License

@BeforeMethod
public void setUp() {
    buffer = Unpooled.buffer().order(ByteOrder.LITTLE_ENDIAN);

    encoder = new BinaryEncoder().setBuffer(buffer);
    decoder = new BinaryDecoder().setBuffer(buffer);
}

From source file:com.digitalpetri.opcua.stack.SerializationFixture2.java

License:Apache License

protected <T> void assertSerializable(T encoded, BiFunction<T, ByteBuf, ByteBuf> encoder,
        Function<ByteBuf, T> decoder) {

    ByteBuf buffer = Unpooled.buffer().order(ByteOrder.LITTLE_ENDIAN);

    T decoded = decoder.apply(encoder.apply(encoded, buffer));

    assertEquals(encoded, decoded);//ww w .j av  a2s .c  o  m
}

From source file:com.dinstone.netty.Client.java

License:Apache License

public static void main(String[] args) throws IOException, InterruptedException {
    Bootstrap b = new Bootstrap();
    b.group(new NioEventLoopGroup()).channel(NioSocketChannel.class)
            .handler(new ChannelInitializer<NioSocketChannel>() {

                @Override/*ww  w  .j  a v  a  2s . co m*/
                protected void initChannel(NioSocketChannel ch) throws Exception {
                    ch.pipeline().addLast("dd", new ChannelHandlerAdapter() {

                        /**
                         * {@inheritDoc}
                         * 
                         * @see io.netty.channel.ChannelHandlerAdapter#exceptionCaught(io.netty.channel.ChannelHandlerContext,
                         *      java.lang.Throwable)
                         */
                        @Override
                        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
                                throws Exception {
                            System.out.println("error: ");
                            cause.printStackTrace();
                        }
                    });
                }
            });
    b.connect("localhost", 8090).addListener(new ChannelFutureListener() {

        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                future.channel().write(Unpooled.buffer().writeBytes("123".getBytes()));
                future.channel().flush();
            }
        }
    });
}

From source file:com.example.grpc.server.PrometheusServer.java

License:Apache License

public void start() {
    final ServerBootstrap bootstrap = new ServerBootstrap();

    bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<SocketChannel>() {
                @Override/*from  www  .  j  ava2s .c  o  m*/
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    ChannelPipeline pipeline = socketChannel.pipeline();
                    pipeline.addLast("decoder", new HttpRequestDecoder());
                    pipeline.addLast("encoder", new HttpResponseEncoder());
                    pipeline.addLast("prometheus", new SimpleChannelInboundHandler<Object>() {
                        @Override
                        protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object o)
                                throws Exception {
                            if (!(o instanceof HttpRequest)) {
                                return;
                            }

                            HttpRequest request = (HttpRequest) o;

                            if (!"/metrics".equals(request.uri())) {
                                final FullHttpResponse response = new DefaultFullHttpResponse(
                                        HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND);
                                channelHandlerContext.writeAndFlush(response)
                                        .addListener(ChannelFutureListener.CLOSE);
                                return;
                            }

                            if (!HttpMethod.GET.equals(request.method())) {
                                final FullHttpResponse response = new DefaultFullHttpResponse(
                                        HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_ACCEPTABLE);
                                channelHandlerContext.writeAndFlush(response)
                                        .addListener(ChannelFutureListener.CLOSE);
                                return;
                            }

                            ByteBuf buf = Unpooled.buffer();
                            ByteBufOutputStream os = new ByteBufOutputStream(buf);
                            OutputStreamWriter writer = new OutputStreamWriter(os);
                            TextFormat.write004(writer, registry.metricFamilySamples());
                            writer.close();
                            os.close();

                            final FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                                    HttpResponseStatus.OK, buf);
                            response.headers().set(HttpHeaderNames.CONTENT_TYPE, TextFormat.CONTENT_TYPE_004);
                            channelHandlerContext.writeAndFlush(response)
                                    .addListener(ChannelFutureListener.CLOSE);
                        }
                    });

                }
            });

    try {
        this.channel = bootstrap.bind(this.port).sync().channel();
    } catch (InterruptedException e) {
        // do nothing
    }
}

From source file:com.flowpowered.network.fake.ChannelHandlerContextFaker.java

License:MIT License

public static FakeChannelHandlerContext setup() {
    if (context == null) {
        alloc();/*  w  w w.  j  av  a2  s .  c om*/
        context = Mockito.mock(FakeChannelHandlerContext.class, Mockito.CALLS_REAL_METHODS);
        channel = Mockito.mock(Channel.class);
        config = Mockito.mock(ChannelConfig.class);
        Mockito.doReturn(channel).when(context).channel();
        Mockito.when(channel.config()).thenReturn(config);
        Mockito.when(config.getAllocator()).thenReturn(alloc);
        Answer<ByteBuf> answer = invocation -> {
            ByteBuf buffer = Unpooled.buffer();
            return buffer;
        };
        Mockito.when(alloc.buffer()).thenAnswer(answer);
        Mockito.when(alloc.buffer(Mockito.anyInt())).thenAnswer(answer);
    }
    return context;
}

From source file:com.flowpowered.network.util.ByteBufUtilsTest.java

License:MIT License

@Test
public void testVarInt() throws Exception {
    final ByteBuf test = Unpooled.buffer();
    ByteBufUtils.writeVarInt(test, 1);/*from  www. j a v a  2 s  .c o  m*/
    final int varInt = ByteBufUtils.readVarInt(test);
    if (varInt != 1) {
        fail("The buffer had 1 wrote to it but received " + varInt + " instead!");
    }
}