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:ccwihr.client.t2.Http2Client.java

License:Apache License

public static void main(String[] args) throws Exception {
    //        // Configure SSL.
    //        final SslContext sslCtx;
    //        if (SSL) {
    //            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;
    //        }//from  w w  w  . j a  va2s .  c  o m

    EventLoopGroup workerGroup = new NioEventLoopGroup();
    //        Http2ClientInitializer initializer = new Http2ClientInitializer(sslCtx, Integer.MAX_VALUE);
    Http2ClientInitializer initializer = new Http2ClientInitializer(null, 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 (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)");

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

From source file:com.beeswax.hexbid.handler.BidHandler.java

License:Apache License

/**
 * /*  ww  w .  j  a v a2s  .c  o m*/
 * Process full bid request with following error codes:</br>
 * </br>
 * 200 if it sets bid price in {@link BidAgentResponse} successfully.</br>
 * 204 if no bid is made for this request</br>
 * 400 if there is a parsing error {@link BidAgentRequest} or it fails to get bidding strategy.</br>
 * 500 if server experienced an error.</br>
 * 
 * @param ChannelHandlerContext
 * 
 * @return FullHttpResponse
 * 
 */
public FullHttpResponse processRequest(ChannelHandlerContext ctx, FullHttpRequest request) {
    LOGGER.debug("/bid request");

    try {
        final BidAgentRequest bidRequest = (BidAgentRequest) BidProtobufParser
                .parseProtoBytebuf(request.content(), BidAgentRequest.newBuilder());
        final Optional<BidAgentResponse> bidResponse = bidder.SetBid(bidRequest);

        if (!bidResponse.isPresent()) {
            LOGGER.debug("No Bid");
            return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NO_CONTENT);
        }

        final FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                HttpResponseStatus.OK, Unpooled.wrappedBuffer(bidResponse.get().toByteArray()));
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, new AsciiString("application/x-protobuf"));
        return response;

    } catch (InvalidProtocolBufferException | IllegalArgumentException e) {
        return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST,
                Unpooled.wrappedBuffer("Bad request".getBytes()));
    } catch (Exception e) {
        LOGGER.error("Unexpected error when setting bid", e);
        return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR,
                Unpooled.wrappedBuffer("Internal error when setting bid".getBytes()));
    }
}

From source file:com.flysoloing.learning.network.netty.http2.helloworld.client.Http2Client.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.com*/
        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 (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.write(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,
                    wrappedBuffer(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.write(request), channel.newPromise());
        }
        channel.flush();
        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:com.flysoloing.learning.network.netty.http2.helloworld.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   ww w. j a va2 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"));
        encoder().writeHeaders(ctx, 1, headers, 0, true, ctx.newPromise());
    }
    super.userEventTriggered(ctx, evt);
}

From source file:com.hop.hhxx.example.http2.helloworld.client.Http2Client.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {/*  w  w w. j  ava2  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();
    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 (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)");

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

From source file:com.linecorp.armeria.common.http.HttpHeaderNames.java

License:Apache License

public static AsciiString of(String name) {
    requireNonNull(name, "name");
    name = name.toLowerCase(Locale.US);
    final AsciiString asciiName = map.get(name);
    return asciiName != null ? asciiName : new AsciiString(name);
}

From source file:com.linecorp.armeria.common.http.HttpStatusClass.java

License:Apache License

HttpStatusClass(int min, int max, String defaultReasonPhrase) {
    this.min = min;
    this.max = max;
    this.defaultReasonPhrase = new AsciiString(defaultReasonPhrase);
}

From source file:com.otcdlink.chiron.downend.Http11ProxyHandler.java

License:Apache License

public Http11ProxyHandler(SocketAddress proxyAddress, String username, String password) {
    super(proxyAddress);
    if (username == null) {
        throw new NullPointerException("username");
    }/*from ww w  .j a va  2 s. c o  m*/
    if (password == null) {
        throw new NullPointerException("password");
    }
    this.username = username;
    this.password = password;

    ByteBuf authz = Unpooled.copiedBuffer(username + ':' + password, CharsetUtil.UTF_8);
    ByteBuf authzBase64 = Base64.encode(authz, false);

    authorization = new AsciiString("Basic " + authzBase64.toString(CharsetUtil.US_ASCII));

    authz.release();
    authzBase64.release();
}

From source file:com.turo.pushy.apns.auth.AuthenticationToken.java

License:Open Source License

/**
 * Constructs a new authentication token using the given signing key (and associated metadata) issued at the given
 * date.//from ww w  .  ja v  a  2 s.  co  m
 *
 * @param signingKey the signing key from which to derive metadata and with which to sign the token
 * @param issuedAt the time at which the token was issued
 *
 * @throws NoSuchAlgorithmException if the JVM doesn't support the
 * {@value com.turo.pushy.apns.auth.ApnsKey#APNS_SIGNATURE_ALGORITHM} algorithm
 * @throws InvalidKeyException if the given key was invalid for any reason
 * @throws SignatureException if the given key could not be used to sign the token
 */
public AuthenticationToken(final ApnsSigningKey signingKey, final Date issuedAt)
        throws NoSuchAlgorithmException, InvalidKeyException, SignatureException {
    this.header = new AuthenticationTokenHeader(signingKey.getKeyId());
    this.claims = new AuthenticationTokenClaims(signingKey.getTeamId(), issuedAt);

    final String headerJson = GSON.toJson(this.header);
    final String claimsJson = GSON.toJson(this.claims);

    final StringBuilder payloadBuilder = new StringBuilder();
    payloadBuilder.append(encodeUnpaddedBase64UrlString(headerJson.getBytes(StandardCharsets.US_ASCII)));
    payloadBuilder.append('.');
    payloadBuilder.append(encodeUnpaddedBase64UrlString(claimsJson.getBytes(StandardCharsets.US_ASCII)));

    {
        final Signature signature = Signature.getInstance(ApnsKey.APNS_SIGNATURE_ALGORITHM);
        signature.initSign(signingKey);
        signature.update(payloadBuilder.toString().getBytes(StandardCharsets.US_ASCII));

        this.signatureBytes = signature.sign();
    }

    payloadBuilder.append('.');
    payloadBuilder.append(encodeUnpaddedBase64UrlString(this.signatureBytes));

    this.base64EncodedToken = payloadBuilder.toString();
    this.authorizationHeader = new AsciiString("bearer " + payloadBuilder.toString());
}

From source file:com.turo.pushy.apns.auth.AuthenticationToken.java

License:Open Source License

/**
 * Constructs a new authentication token from a Base64-encoded JWT string. Note that successfully creating a token
 * from an encoded string does <em>not</em> imply that the token is valid.
 *
 * @param base64EncodedToken a Base64-encoded JWT string
 *///w w  w .jav  a 2 s  .co  m
public AuthenticationToken(final String base64EncodedToken) {
    Objects.requireNonNull(base64EncodedToken, "Encoded token must not be null.");

    this.base64EncodedToken = base64EncodedToken;
    this.authorizationHeader = new AsciiString("bearer " + base64EncodedToken);

    final String[] jwtSegments = base64EncodedToken.split("\\.");

    if (jwtSegments.length != 3) {
        throw new IllegalArgumentException();
    }

    this.header = GSON.fromJson(
            new String(decodeBase64UrlEncodedString(jwtSegments[0]), StandardCharsets.US_ASCII),
            AuthenticationTokenHeader.class);
    this.claims = GSON.fromJson(
            new String(decodeBase64UrlEncodedString(jwtSegments[1]), StandardCharsets.US_ASCII),
            AuthenticationTokenClaims.class);
    this.signatureBytes = decodeBase64UrlEncodedString(jwtSegments[2]);
}