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:io.grpc.netty.UtilsTest.java

License:Apache License

@Test
public void convertClientHeaders_sanitizes() {
    Metadata metaData = new Metadata();

    // Intentionally being explicit here rather than relying on any pre-defined lists of headers,
    // since the goal of this test is to validate the correctness of such lists in the first place.
    metaData.put(GrpcUtil.CONTENT_TYPE_KEY, "to-be-removed");
    metaData.put(GrpcUtil.USER_AGENT_KEY, "to-be-removed");
    metaData.put(GrpcUtil.TE_HEADER, "to-be-removed");
    metaData.put(userKey, userValue);//w ww .  ja v a 2  s  .  co m

    String scheme = "https";
    String userAgent = "user-agent";
    String method = "POST";
    String authority = "authority";
    String path = "//testService/test";

    Http2Headers output = Utils.convertClientHeaders(metaData, new AsciiString(scheme), new AsciiString(path),
            new AsciiString(authority), new AsciiString(method), new AsciiString(userAgent));
    DefaultHttp2Headers headers = new DefaultHttp2Headers();
    for (Map.Entry<CharSequence, CharSequence> entry : output) {
        headers.add(entry.getKey(), entry.getValue());
    }

    // 7 reserved headers, 1 user header
    assertEquals(7 + 1, headers.size());
    // Check the 3 reserved headers that are non pseudo
    // Users can not create pseudo headers keys so no need to check for them here
    assertEquals(GrpcUtil.CONTENT_TYPE_GRPC, headers.get(GrpcUtil.CONTENT_TYPE_KEY.name()).toString());
    assertEquals(userAgent, headers.get(GrpcUtil.USER_AGENT_KEY.name()).toString());
    assertEquals(GrpcUtil.TE_TRAILERS, headers.get(GrpcUtil.TE_HEADER.name()).toString());
    // Check the user header is in tact
    assertEquals(userValue, headers.get(userKey.name()).toString());
}

From source file:io.jsync.http.HttpHeaders.java

License:Open Source License

/**
 * Create an optimized {@link CharSequence} which can be used as header name or value.
 * This should be used if you expect to use it multiple times liked for example adding the same header name or value
 * for multiple responses or requests./* w  w  w  .j  a va2s.  c o  m*/
 */
public static CharSequence createOptimized(String value) {
    return new AsciiString(value);
}

From source file:io.jsync.http.impl.ClientConnection.java

License:Open Source License

private boolean isConnectionCloseHeader(DefaultHttpClientResponse response) {
    if (response != null) {
        List<String> connectionHeaderValues = response.headers().getAll(HttpHeaderNames.CONNECTION);
        if (connectionHeaderValues != null) {
            for (String connectionHeaderValue : connectionHeaderValues) {
                if (HttpHeaderValues.CLOSE.equals(new AsciiString(connectionHeaderValue))) {
                    return true;
                }/*from  w ww .j a  v  a2  s .  com*/
            }
        }
    }
    return false;
}

From source file:io.jsync.http.impl.DefaultHttpServerRequest.java

License:Open Source License

@Override
public HttpServerRequest expectMultiPart(boolean expect) {
    if (expect) {
        String contentType = request.headers().get(HttpHeaderNames.CONTENT_TYPE);
        if (contentType != null) {
            HttpMethod method = request.method();
            AsciiString lowerCaseContentType = new AsciiString(contentType.toLowerCase());
            boolean isURLEncoded = lowerCaseContentType
                    .startsWith(HttpHeaderValues.APPLICATION_X_WWW_FORM_URLENCODED);
            if ((lowerCaseContentType.startsWith(HttpHeaderValues.MULTIPART_FORM_DATA) || isURLEncoded)
                    && (method.equals(HttpMethod.POST) || method.equals(HttpMethod.PUT)
                            || method.equals(HttpMethod.PATCH))) {
                decoder = new HttpPostRequestDecoder(new DataFactory(), request);
            }//from   w w w .  j  a  v  a  2 s.c  om
        }
    } else {
        decoder = null;
    }
    return this;
}

From source file:io.nebo.container.NettyEmbeddedContext.java

License:Apache License

NettyEmbeddedContext(String contextPath, ClassLoader classLoader, String serverInfo) {
    this.contextPath = contextPath;
    this.classLoader = classLoader;
    this.serverInfo = new AsciiString(serverInfo);
}

From source file:io.netty.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  a v  a  2s.c  om*/
        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, Unpooled.EMPTY_BUFFER);
            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:io.vertx.benchmarks.HttpServerHandlerBenchmark.java

License:Open Source License

@Setup
public void setup() {
    vertx = (VertxInternal) Vertx.vertx();
    HttpServerOptions options = new HttpServerOptions();
    vertxChannel = new EmbeddedChannel(
            new HttpRequestDecoder(options.getMaxInitialLineLength(), options.getMaxHeaderSize(),
                    options.getMaxChunkSize(), false, options.getDecoderInitialBufferSize()),
            new HttpResponseEncoder());
    vertxChannel.config().setAllocator(new Alloc());

    ContextInternal context = new EventLoopContext(vertx, vertxChannel.eventLoop(), null, null, null,
            new JsonObject(), Thread.currentThread().getContextClassLoader());
    Handler<HttpServerRequest> app = request -> {
        HttpServerResponse response = request.response();
        MultiMap headers = response.headers();
        headers.add(HEADER_CONTENT_TYPE, RESPONSE_TYPE_PLAIN).add(HEADER_SERVER, SERVER)
                .add(HEADER_DATE, DATE_STRING).add(HEADER_CONTENT_LENGTH, HELLO_WORLD_LENGTH);
        response.end(HELLO_WORLD_BUFFER);
    };/*  ww  w.j  a  va2 s  .  c  om*/
    HandlerHolder<HttpHandlers> holder = new HandlerHolder<>(context, new HttpHandlers(app, null, null, null));
    Http1xServerHandler handler = new Http1xServerHandler(null, new HttpServerOptions(), "localhost", holder,
            null);
    vertxChannel.pipeline().addLast("handler", handler);

    nettyChannel = new EmbeddedChannel(
            new HttpRequestDecoder(options.getMaxInitialLineLength(), options.getMaxHeaderSize(),
                    options.getMaxChunkSize(), false, options.getDecoderInitialBufferSize()),
            new HttpResponseEncoder(), new SimpleChannelInboundHandler<HttpRequest>() {

                private final byte[] STATIC_PLAINTEXT = "Hello, World!".getBytes(CharsetUtil.UTF_8);
                private final int STATIC_PLAINTEXT_LEN = STATIC_PLAINTEXT.length;
                private final ByteBuf PLAINTEXT_CONTENT_BUFFER = Unpooled
                        .unreleasableBuffer(Unpooled.directBuffer().writeBytes(STATIC_PLAINTEXT));
                private final CharSequence PLAINTEXT_CLHEADER_VALUE = new AsciiString(
                        String.valueOf(STATIC_PLAINTEXT_LEN));

                private final CharSequence TYPE_PLAIN = new AsciiString("text/plain");
                private final CharSequence SERVER_NAME = new AsciiString("Netty");
                private final CharSequence CONTENT_TYPE_ENTITY = HttpHeaderNames.CONTENT_TYPE;
                private final CharSequence DATE_ENTITY = HttpHeaderNames.DATE;
                private final CharSequence CONTENT_LENGTH_ENTITY = HttpHeaderNames.CONTENT_LENGTH;
                private final CharSequence SERVER_ENTITY = HttpHeaderNames.SERVER;

                private final DateFormat FORMAT = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z");
                private final CharSequence date = new AsciiString(FORMAT.format(new Date()));

                @Override
                protected void channelRead0(ChannelHandlerContext ctx, HttpRequest msg) throws Exception {
                    writeResponse(ctx, msg, PLAINTEXT_CONTENT_BUFFER.duplicate(), TYPE_PLAIN,
                            PLAINTEXT_CLHEADER_VALUE);
                }

                @Override
                public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
                    ctx.flush();
                }

                private void writeResponse(ChannelHandlerContext ctx, HttpRequest request, ByteBuf buf,
                        CharSequence contentType, CharSequence contentLength) {

                    // Build the response object.
                    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                            HttpResponseStatus.OK, buf, false);
                    HttpHeaders headers = response.headers();
                    headers.set(CONTENT_TYPE_ENTITY, contentType);
                    headers.set(SERVER_ENTITY, SERVER_NAME);
                    headers.set(DATE_ENTITY, date);
                    headers.set(CONTENT_LENGTH_ENTITY, contentLength);

                    // Close the non-keep-alive connection after the write operation is done.
                    ctx.write(response, ctx.voidPromise());
                }
            });
    nettyChannel.config().setAllocator(new Alloc());

    GET = Unpooled.unreleasableBuffer(Unpooled.copiedBuffer(("GET / HTTP/1.1\r\n" + "\r\n").getBytes()));
    readerIndex = GET.readerIndex();
    writeIndex = GET.writerIndex();
}

From source file:io.vertx.core.ConversionHelperTest.java

License:Open Source License

@Test
public void testToJsonObject() {
    Map<String, Object> map = new HashMap<>();
    map.put("string", "the_string");
    map.put("integer", 4);
    map.put("boolean", true);
    map.put("charsequence", new AsciiString("the_charsequence"));
    map.put("biginteger", new BigInteger("1234567"));
    map.put("binary", Buffer.buffer("hello"));
    map.put("object", Collections.singletonMap("nested", 4));
    map.put("array", Arrays.asList(1, 2, 3));
    JsonObject json = (JsonObject) ConversionHelper.toObject(map);
    assertEquals(8, json.size());/*  w w  w  .  java  2s.  c  o m*/
    assertEquals("the_string", json.getString("string"));
    assertEquals(4, (int) json.getInteger("integer"));
    assertEquals(true, json.getBoolean("boolean"));
    assertEquals("the_charsequence", json.getString("charsequence"));
    assertEquals(1234567, (int) json.getInteger("biginteger"));
    assertEquals("hello", new String(json.getBinary("binary")));
    assertEquals(new JsonObject().put("nested", 4), json.getJsonObject("object"));
    assertEquals(new JsonArray().add(1).add(2).add(3), json.getJsonArray("array"));
}

From source file:io.vertx.core.ConversionHelperTest.java

License:Open Source License

@Test
public void testToJsonArray() {
    List<Object> list = new ArrayList<>();
    list.add("the_string");
    list.add(4);/* w w  w  .jav a  2  s .  c  o m*/
    list.add(true);
    list.add(new AsciiString("the_charsequence"));
    list.add(new BigInteger("1234567"));
    list.add(Buffer.buffer("hello"));
    list.add(Collections.singletonMap("nested", 4));
    list.add(Arrays.asList(1, 2, 3));
    JsonArray json = (JsonArray) ConversionHelper.toObject(list);
    assertEquals(8, json.size());
    assertEquals("the_string", json.getString(0));
    assertEquals(4, (int) json.getInteger(1));
    assertEquals(true, json.getBoolean(2));
    assertEquals("the_charsequence", json.getString(3));
    assertEquals(1234567, (int) json.getInteger(4));
    assertEquals("hello", new String(json.getBinary(5)));
    assertEquals(new JsonObject().put("nested", 4), json.getJsonObject(6));
    assertEquals(new JsonArray().add(1).add(2).add(3), json.getJsonArray(7));
}

From source file:io.vertx.core.ConversionHelperTest.java

License:Open Source License

@Test
public void testToString() {
    assertEquals("the_string", ConversionHelper.toObject(new AsciiString("the_string")));
}