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:netty.http2.ConcurrentHttp2Client.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {//from   www .  j a v  a  2 s .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();
    ConcurrentHttp2ClientInitializer initializer = new ConcurrentHttp2ClientInitializer();

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

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

        HttpScheme scheme = SSL ? HttpScheme.HTTPS : HttpScheme.HTTP;
        AsciiString hostName = new AsciiString(HOST + ':' + PORT);
        System.err.println("Sending request(s)...");
        if (URL != null) {
            // Create a simple GET request.
            for (int i = 0; i < 1; i++) {
                StreamRequest request = new StreamRequestBuilder(new URI(URL)).setMethod("GET")
                        //.setMethod("POST")
                        .setHeader(HttpHeaderNames.HOST.toString(), hostName.toString())
                        //.build(EntityStreams.emptyStream());
                        .build(EntityStreams
                                .newEntityStream(new ByteStringWriter(ByteString.copy(new byte[0 * 1024]))));
                channel.writeAndFlush(request);
                System.err.println("Sent request #" + i);
            }
        }
        System.err.println("Finished HTTP/2 request(s)");
        long start = System.currentTimeMillis();

        // Wait until the connection is closed.
        channel.closeFuture().sync();

        long end = System.currentTimeMillis();
        System.err.println("Server Idled for: " + (end - start) + " milliseconds");
    } finally {
        workerGroup.shutdownGracefully();
    }
}

From source file:netty.mmb.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 www  .j a v a  2s .co  m
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
    if (evt instanceof HttpServerUpgradeHandler.UpgradeEvent) {
        // Http/2
        // 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"));
        encoder().writeHeaders(ctx, 1, headers, 0, true, ctx.newPromise());
    }
    super.userEventTriggered(ctx, evt);
}

From source file:netty.mmb.http2.Server.Http2Handler.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).
 *//* ww w  .  j a  v  a  2s. co  m*/
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
    if (evt instanceof HttpServerUpgradeHandler.UpgradeEvent) {
        // HTTP/2
        // Write an HTTP/2 response to the upgrade request
        //            Http2httphttp2
        Http2Headers headers = new DefaultHttp2Headers().status(OK.codeAsText())
                .set(new AsciiString(UPGRADE_RESPONSE_HEADER), new AsciiString("true"));
        encoder().writeHeaders(ctx, 1, headers, 0, true, ctx.newPromise());
    }
    super.userEventTriggered(ctx, evt);
}

From source file:org.ballerinalang.test.util.http2.HTTP2Client.java

License:Open Source License

public HTTP2Client(boolean ssl, String host, int port) throws Exception {
    try {/*from www  . java 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();
        HTTP2ClientInitializer initializer = new HTTP2ClientInitializer(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.
        HTTP2SettingsHandler http2SettingsHandler = initializer.settingsHandler();
        http2SettingsHandler.awaitSettings(TestConstant.HTTP2_RESPONSE_TIME_OUT,
                TestConstant.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:org.cloudfoundry.reactor.tokenprovider.AbstractUaaTokenProvider.java

License:Apache License

private HttpClientRequest addAuthorization(HttpClientRequest request) {
    String encoded = Base64.getEncoder()
            .encodeToString(new AsciiString(getClientId()).concat(":").concat(getClientSecret()).toByteArray());
    return request.header(AUTHORIZATION, String.format("Basic %s", encoded));
}

From source file:org.cloudfoundry.reactor.uaa.AbstractUaaOperations.java

License:Apache License

protected final HttpOutbound basicAuth(HttpOutbound outbound, String clientId, String clientSecret) {
    String encoded = Base64.getEncoder()
            .encodeToString(new AsciiString(clientId).concat(":").concat(clientSecret).toByteArray());
    outbound.headers().set(AUTHORIZATION, BASIC_PREAMBLE + encoded);
    return outbound;
}

From source file:org.cloudfoundry.reactor.uaa.BasicAuthorizationBuilder.java

License:Apache License

public static void augment(HttpClientRequest outbound, Object request) {
    if (request instanceof BasicAuthorized) {
        BasicAuthorized basicAuthorized = (BasicAuthorized) request;
        String encoded = Base64.getEncoder().encodeToString(new AsciiString(basicAuthorized.getClientId())
                .concat(":").concat(basicAuthorized.getClientSecret()).toByteArray());
        outbound.headers().set(AUTHORIZATION, BASIC_PREAMBLE + encoded);
    }/* w  ww . j  a  v a  2  s. c o m*/
}

From source file:org.cloudfoundry.reactor.uaa.serverinformation.ReactorServerInformation.java

License:Apache License

@Override
public Mono<GetAutoLoginAuthenticationCodeResponse> getAuthenticationCode(
        GetAutoLoginAuthenticationCodeRequest request) {
    return post(request, GetAutoLoginAuthenticationCodeResponse.class,
            builder -> builder.pathSegment("autologin"), outbound -> outbound.map(r -> {
                String encoded = Base64.getEncoder().encodeToString(new AsciiString(request.getClientId())
                        .concat(":").concat(request.getClientSecret()).toByteArray());
                r.requestHeaders().set(AUTHORIZATION, BASIC_PREAMBLE + encoded);
                return r;
            })).checkpoint();//  w ww  .ja va2 s  .  c om
}

From source file:org.cloudfoundry.reactor.uaa.tokens.ReactorTokens.java

License:Apache License

@Override
public Mono<CheckTokenResponse> check(CheckTokenRequest request) {
    return post(request, CheckTokenResponse.class, builder -> builder.pathSegment("check_token"),
            outbound -> outbound.map(r -> {
                String encoded = Base64.getEncoder().encodeToString(new AsciiString(request.getClientId())
                        .concat(":").concat(request.getClientSecret()).toByteArray());
                r.requestHeaders().set(AUTHORIZATION, BASIC_PREAMBLE + encoded);
                return r;
            })).checkpoint();/*from  ww w  . j  av  a2  s .c o  m*/
}

From source file:org.cloudfoundry.reactor.util.MultipartHttpClientRequest.java

License:Apache License

private static AsciiString generateMultipartBoundary() {
    byte[] boundary = new byte[RND.nextInt(11) + 30];
    for (int i = 0; i < boundary.length; i++) {
        boundary[i] = BOUNDARY_CHARS[RND.nextInt(BOUNDARY_CHARS.length)];
    }/*  ww w . j a  va  2 s  . c  om*/
    return new AsciiString(boundary);
}