Example usage for io.netty.util AsciiString AsciiString

List of usage examples for io.netty.util AsciiString AsciiString

Introduction

In this page you can find the example usage for io.netty.util AsciiString AsciiString.

Prototype

public AsciiString(CharSequence value) 

Source Link

Document

Create a copy of value into this instance assuming ASCII encoding.

Usage

From source file:com.vela.iot.active.netty.http2.server.HelloWorldHttp2Handler.java

License:Apache License

/**
 * Handles the cleartext HTTP upgrade event. If an upgrade occurred, sends a simple response via HTTP/2
 * on stream 1 (the stream specifically reserved for cleartext HTTP upgrade).
 *//*from w  ww .  j  a v a 2 s  .  c o  m*/
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
    if (evt instanceof HttpServerUpgradeHandler.UpgradeEvent) {
        // Write an HTTP/2 response to the upgrade request
        Http2Headers headers = new DefaultHttp2Headers().status(OK.codeAsText())
                .set(new AsciiString(Http2ExampleUtil.UPGRADE_RESPONSE_HEADER), new AsciiString("true"));
        encoder().writeHeaders(ctx, 1, headers, 0, true, ctx.newPromise());
    }
    super.userEventTriggered(ctx, evt);
}

From source file:http.HTTPClient.java

License:Open Source License

public HTTPClient(boolean ssl, String host, int port) throws Exception {

    try {/*from   ww w. j a  va 2  s.  c o  m*/

        final SslContext sslCtx;
        if (ssl) {
            SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK;
            sslCtx = SslContextBuilder.forClient().sslProvider(provider)
                    .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                    .trustManager(InsecureTrustManagerFactory.INSTANCE)
                    .applicationProtocolConfig(new ApplicationProtocolConfig(Protocol.ALPN,
                            // NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK providers.
                            SelectorFailureBehavior.NO_ADVERTISE,
                            // ACCEPT is currently the only mode supported by both OpenSsl and JDK providers.
                            SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2,
                            ApplicationProtocolNames.HTTP_1_1))
                    .build();
        } else {
            sslCtx = null;
        }
        workerGroup = new NioEventLoopGroup();
        HTTPClientInitializer initializer = new HTTPClientInitializer(sslCtx, Integer.MAX_VALUE);

        // Configure the client.
        Bootstrap b = new Bootstrap();
        b.group(workerGroup);
        b.channel(NioSocketChannel.class);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.remoteAddress(host, port);
        b.handler(initializer);

        // Start the client.
        channel = b.connect().syncUninterruptibly().channel();
        log.info("Connected to [" + host + ':' + port + ']');

        // Wait for the HTTP/2 upgrade to occur.
        //            HTTPSettingsHandler http2SettingsHandler = initializer.settingsHandler();
        //            http2SettingsHandler.awaitSettings(TestUtil.HTTP2_RESPONSE_TIME_OUT, TestUtil.HTTP2_RESPONSE_TIME_UNIT);
        //            responseHandler = initializer.responseHandler();
        scheme = ssl ? HttpScheme.HTTPS : HttpScheme.HTTP;
        hostName = new AsciiString(host + ':' + port);

    } catch (Exception ex) {
        log.error("Error while initializing http2 client " + ex);
        this.close();
    }

}

From source file:http.HTTPClient2.java

License:Open Source License

public HTTPClient2(boolean ssl, String host, int port) throws Exception {

    try {//from   w w w.  jav a 2  s . co m

        final SslContext sslCtx;
        if (ssl) {
            SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK;
            sslCtx = SslContextBuilder.forClient().sslProvider(provider)
                    .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                    .trustManager(InsecureTrustManagerFactory.INSTANCE)
                    .applicationProtocolConfig(new ApplicationProtocolConfig(Protocol.ALPN,
                            // NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK providers.
                            SelectorFailureBehavior.NO_ADVERTISE,
                            // ACCEPT is currently the only mode supported by both OpenSsl and JDK providers.
                            SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2,
                            ApplicationProtocolNames.HTTP_1_1))
                    .build();
        } else {
            sslCtx = null;
        }
        workerGroup = new NioEventLoopGroup();
        HTTPClientInitializer initializer = new HTTPClientInitializer(sslCtx, Integer.MAX_VALUE);

        // Configure the client.
        Bootstrap b = new Bootstrap();
        b.group(workerGroup);
        b.channel(NioSocketChannel.class);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.remoteAddress(host, port);
        b.handler(initializer);

        // Start the client.
        channel = b.connect().syncUninterruptibly().channel();
        log.info("Connected to [" + host + ':' + port + ']');

        // Wait for the HTTP/2 upgrade to occur.
        HTTPSettingsHandler http2SettingsHandler = initializer.settingsHandler();
        http2SettingsHandler.awaitSettings(TestUtil.HTTP2_RESPONSE_TIME_OUT, TestUtil.HTTP2_RESPONSE_TIME_UNIT);
        responseHandler = initializer.responseHandler();
        scheme = ssl ? HttpScheme.HTTPS : HttpScheme.HTTP;
        hostName = new AsciiString(host + ':' + port);

    } catch (Exception ex) {
        log.error("Error while initializing http2 client " + ex);
        this.close();
    }

}

From source file:http2.client.Http2Client.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {//from   w w  w .  j  a  v a 2s  .  c o m
        SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK;
        sslCtx = SslContextBuilder.forClient().sslProvider(provider)
                /* NOTE: the cipher filter may not include all ciphers required by the HTTP/2 specification.
                 * Please refer to the HTTP/2 specification for cipher requirements. */
                .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                .trustManager(InsecureTrustManagerFactory.INSTANCE)
                .applicationProtocolConfig(new ApplicationProtocolConfig(Protocol.ALPN,
                        // NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK providers.
                        SelectorFailureBehavior.NO_ADVERTISE,
                        // ACCEPT is currently the only mode supported by both OpenSsl and JDK providers.
                        SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2,
                        ApplicationProtocolNames.HTTP_1_1))
                .build();
    } else {
        sslCtx = null;
    }

    EventLoopGroup workerGroup = new NioEventLoopGroup();
    Http2ClientInitializer initializer = new Http2ClientInitializer(sslCtx, Integer.MAX_VALUE);

    try {
        // Configure the client.
        Bootstrap b = new Bootstrap();
        b.group(workerGroup);
        b.channel(NioSocketChannel.class);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.remoteAddress(HOST, PORT);
        b.handler(initializer);

        // Start the client.
        Channel channel = b.connect().syncUninterruptibly().channel();
        System.out.println("Connected to [" + HOST + ':' + PORT + ']');

        // Wait for the HTTP/2 upgrade to occur.
        Http2SettingsHandler http2SettingsHandler = initializer.settingsHandler();
        http2SettingsHandler.awaitSettings(5, TimeUnit.SECONDS);

        HttpResponseHandler responseHandler = initializer.responseHandler();

        int streamId = 3;
        HttpScheme scheme = SSL ? HttpScheme.HTTPS : HttpScheme.HTTP;
        AsciiString hostName = new AsciiString(HOST + ':' + PORT);
        System.err.println("Sending request(s)...");

        if (URL2 != null) {
            logger.info("send url2");
            // Create a simple POST request with a body.
            FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, POST, URL2,
                    Unpooled.copiedBuffer(URL2DATA.getBytes(CharsetUtil.UTF_8)));
            request.headers().add(HttpHeaderNames.HOST, hostName);
            request.headers().add(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), scheme.name());
            request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);
            request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.DEFLATE);
            responseHandler.put(streamId, channel.writeAndFlush(request), channel.newPromise());
            streamId += 2;
        }

        responseHandler.awaitResponses(5, TimeUnit.SECONDS);

        System.out.println("Finished HTTP/2 request(s)");

        // Wait until the connection is closed.
        channel.close().syncUninterruptibly();
    } finally {
        workerGroup.shutdownGracefully();
    }
}

From source file:http2.server.HelloWorldHttp2Handler.java

License:Apache License

/**
 * Handles the cleartext HTTP upgrade event. If an upgrade occurred, sends a simple response via HTTP/2
 * on stream 1 (the stream specifically reserved for cleartext HTTP upgrade).
 * ????/*www  .  j  a v a  2  s.co  m*/
 */
// @Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
    if (evt instanceof HttpServerUpgradeHandler.UpgradeEvent) {
        // Write an HTTP/2 response to the upgrade request
        Http2Headers headers = new DefaultHttp2Headers().status(OK.codeAsText())
                .set(new AsciiString(UPGRADE_RESPONSE_HEADER), new AsciiString("true"));
        // 1 ?
        encoder().writeHeaders(ctx, 1, headers, 0, true, ctx.newPromise());
    }
    super.userEventTriggered(ctx, evt);
}

From source file:io.bsoa.rpc.grpc.client12.Http2Client.java

License:Apache License

public static void main(String[] args) throws Exception {

    EventLoopGroup workerGroup = new NioEventLoopGroup();

    try {/*from   w ww . ja v a2 s.co m*/
        // Configure the client.
        Bootstrap b = new Bootstrap();
        b.group(workerGroup);
        b.channel(NioSocketChannel.class);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.remoteAddress(HOST, PORT);

        Http2ClientInitializer initializer = new Http2ClientInitializer(Integer.MAX_VALUE);
        b.handler(initializer);

        // Start the client.
        Channel channel = b.connect().syncUninterruptibly().channel();
        System.out.println("Connected to [" + HOST + ':' + PORT + ']');

        // Wait for the HTTP/2 upgrade to occur.
        Http2SettingsHandler http2SettingsHandler = initializer.settingsHandler();
        http2SettingsHandler.awaitSettings(500, TimeUnit.SECONDS);

        HttpResponseHandler responseHandler = initializer.responseHandler();
        int streamId = 3;
        HttpScheme scheme = HttpScheme.HTTP;
        AsciiString hostName = new AsciiString(HOST + ':' + PORT);
        System.err.println("Sending request(s)...");

        while (true) {
            try {
                if (URL != null) {
                    // Create a simple GET request.
                    FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, GET, URL);
                    request.headers().add(HttpHeaderNames.HOST, hostName);
                    request.headers().add(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), scheme.name());
                    request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);
                    request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.DEFLATE);
                    responseHandler.put(streamId, channel.writeAndFlush(request), channel.newPromise());
                    streamId += 2;
                }
                if (URL2 != null) {
                    // Create a simple POST request with a body.
                    FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, POST, URL2,
                            Unpooled.copiedBuffer(URL2DATA.getBytes(CharsetUtil.UTF_8)));
                    request.headers().add(HttpHeaderNames.HOST, hostName);
                    request.headers().add(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), scheme.name());
                    request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);
                    request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.DEFLATE);
                    responseHandler.put(streamId, channel.writeAndFlush(request), channel.newPromise());
                    streamId += 2;
                }
                responseHandler.awaitResponses(5, TimeUnit.SECONDS);
                System.out.println("Finished HTTP/2 request(s)");

            } catch (Exception e) {
                e.printStackTrace();
            }

            try {
                Thread.sleep(5000);
            } catch (Exception e) {
                // TODO
            }
        }
        // Wait until the connection is closed.
        //            channel.close().syncUninterruptibly();
    } finally {
        workerGroup.shutdownGracefully();
    }
}

From source file:io.bsoa.rpc.grpc.server12.HelloWorldHttp2Handler.java

License:Apache License

/**
 * Handles the cleartext HTTP upgrade event. If an upgrade occurred, sends a simple response via HTTP/2
 * on stream 1 (the stream specifically reserved for cleartext HTTP upgrade).
 *///  www  .ja v  a2s. c o  m
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
    if (evt instanceof HttpServerUpgradeHandler.UpgradeEvent) {
        // Write an HTTP/2 response to the upgrade request
        Http2Headers headers = new DefaultHttp2Headers().status(OK.codeAsText())
                .set(new AsciiString("http-to-http2-upgrade"), new AsciiString("true"));
        encoder().writeHeaders(ctx, 1, headers, 0, true, ctx.newPromise());
    }
    super.userEventTriggered(ctx, evt);
}

From source file:io.grpc.netty.GrpcHttp2InboundHeadersTest.java

License:Apache License

@Test
public void binaryHeadersShouldBeBase64Decoded() {
    Http2Headers headers = new GrpcHttp2RequestHeaders(1);

    byte[] data = new byte[100];
    new Random().nextBytes(data);
    headers.add(of("foo-bin"), of(BASE64_ENCODING_OMIT_PADDING.encode(data)));

    assertEquals(1, headers.size());/*from   w  ww  .  j a v a 2 s. c o  m*/

    byte[][] namesAndValues = ((GrpcHttp2InboundHeaders) headers).namesAndValues();

    assertEquals(of("foo-bin"), new AsciiString(namesAndValues[0]));
    assertNotSame(data, namesAndValues[1]);
    assertArrayEquals(data, namesAndValues[1]);
}

From source file:io.grpc.netty.MethodDescriptorBenchmark.java

License:Apache License

/** Foo bar. */
@Benchmark/* ww  w.j a  va2 s  .c o  m*/
@BenchmarkMode(Mode.SampleTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public AsciiString old() {
    return new AsciiString("/" + method.getFullMethodName());
}

From source file:io.grpc.netty.MethodDescriptorBenchmark.java

License:Apache License

/** Foo bar. */
@Benchmark/*from www  . j  av  a  2  s  .  co  m*/
@BenchmarkMode(Mode.SampleTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public AsciiString transportSpecific() {
    AsciiString path;
    if ((path = (AsciiString) imd.geRawMethodName(method)) != null) {
        path = new AsciiString("/" + method.getFullMethodName());
        imd.setRawMethodName(method, path);
    }
    return path;
}