io.netty.util.AsciiString Java Examples
The following examples show how to use
io.netty.util.AsciiString.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ThriftOverHttp1Test.java From armeria with Apache License 2.0 | 7 votes |
@Override protected TTransport newTransport(String uri, HttpHeaders headers) throws TTransportException { final SSLContext sslContext; try { sslContext = SSLContextBuilder.create() .loadTrustMaterial((TrustStrategy) (chain, authType) -> true) .build(); } catch (GeneralSecurityException e) { throw new TTransportException("failed to initialize an SSL context", e); } final THttpClient client = new THttpClient( uri, HttpClientBuilder.create() .setSSLHostnameVerifier((hostname, session) -> true) .setSSLContext(sslContext) .build()); client.setCustomHeaders( headers.names().stream() .collect(toImmutableMap(AsciiString::toString, name -> String.join(", ", headers.getAll(name))))); return client; }
Example #2
Source File: ArmeriaHttpUtil.java From armeria with Apache License 2.0 | 6 votes |
/** * Converts the specified Armeria HTTP/2 response headers into Netty HTTP/2 headers. * * @param inputHeaders the HTTP/2 response headers to convert. */ public static Http2Headers toNettyHttp2ServerTrailer(HttpHeaders inputHeaders) { final Http2Headers outputHeaders = new DefaultHttp2Headers(false, inputHeaders.size()); for (Entry<AsciiString, String> entry : inputHeaders) { final AsciiString name = entry.getKey(); final String value = entry.getValue(); if (HTTP_TO_HTTP2_HEADER_BLACKLIST.contains(name)) { continue; } if (ADDITIONAL_RESPONSE_HEADER_BLACKLIST.contains(name)) { continue; } if (isTrailerBlacklisted(name)) { continue; } outputHeaders.add(name, value); } return outputHeaders; }
Example #3
Source File: HttpHeadersUtil.java From armeria with Apache License 2.0 | 6 votes |
public static HttpHeaders mergeTrailers(HttpHeaders headers, HttpHeaders additionalTrailers) { if (additionalTrailers.isEmpty()) { return headers; } if (headers.isEmpty()) { return additionalTrailers; } final HttpHeadersBuilder builder = headers.toBuilder(); for (AsciiString name : additionalTrailers.names()) { if (!ADDITIONAL_RESPONSE_HEADER_BLACKLIST.contains(name) && !isTrailerBlacklisted(name)) { builder.remove(name); additionalTrailers.forEachValue(name, value -> builder.add(name, value)); } } return builder.build(); }
Example #4
Source File: GrpcHttp2HeadersUtils.java From grpc-nebula-java with Apache License 2.0 | 6 votes |
@SuppressWarnings("BetaApi") // BaseEncoding is stable in Guava 20.0 protected Http2Headers add(AsciiString name, AsciiString value) { byte[] nameBytes = bytes(name); byte[] valueBytes; if (!name.endsWith(binaryHeaderSuffix)) { valueBytes = bytes(value); addHeader(value, nameBytes, valueBytes); return this; } int startPos = 0; int endPos = -1; while (endPos < value.length()) { int indexOfComma = value.indexOf(',', startPos); endPos = indexOfComma == AsciiString.INDEX_NOT_FOUND ? value.length() : indexOfComma; AsciiString curVal = value.subSequence(startPos, endPos, false); valueBytes = BaseEncoding.base64().decode(curVal); startPos = indexOfComma + 1; addHeader(curVal, nameBytes, valueBytes); } return this; }
Example #5
Source File: HttpToHttp2ConnectionHandlerTest.java From netty-4.1.22 with Apache License 2.0 | 6 votes |
@Test public void testAbsoluteFormRequestTargetHandledFromHeaders() throws Exception { bootstrapEnv(2, 1, 0); final FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, GET, "/pub/WWW/TheProject.html"); final HttpHeaders httpHeaders = request.headers(); httpHeaders.setInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text(), 5); httpHeaders.set(HttpHeaderNames.HOST, "[email protected]:5555"); httpHeaders.set(HttpConversionUtil.ExtensionHeaderNames.PATH.text(), "ignored_path"); httpHeaders.set(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), "https"); final Http2Headers http2Headers = new DefaultHttp2Headers().method(new AsciiString("GET")) .path(new AsciiString("/pub/WWW/TheProject.html")) .authority(new AsciiString("www.example.org:5555")).scheme(new AsciiString("https")); ChannelPromise writePromise = newPromise(); verifyHeadersOnly(http2Headers, writePromise, clientChannel.writeAndFlush(request, writePromise)); }
Example #6
Source File: NettyServerHandlerTest.java From grpc-java with Apache License 2.0 | 6 votes |
private void createStream() throws Exception { Http2Headers headers = new DefaultHttp2Headers() .method(HTTP_METHOD) .set(CONTENT_TYPE_HEADER, CONTENT_TYPE_GRPC) .set(TE_HEADER, TE_TRAILERS) .path(new AsciiString("/foo/bar")); ByteBuf headersFrame = headersFrame(STREAM_ID, headers); channelRead(headersFrame); ArgumentCaptor<NettyServerStream> streamCaptor = ArgumentCaptor.forClass(NettyServerStream.class); ArgumentCaptor<String> methodCaptor = ArgumentCaptor.forClass(String.class); verify(transportListener).streamCreated(streamCaptor.capture(), methodCaptor.capture(), any(Metadata.class)); stream = streamCaptor.getValue(); }
Example #7
Source File: NettyServerHandlerTest.java From grpc-nebula-java with Apache License 2.0 | 6 votes |
@Test public void headersWithInvalidPathShouldFail() throws Exception { manualSetUp(); Http2Headers headers = new DefaultHttp2Headers() .method(HTTP_METHOD) .set(CONTENT_TYPE_HEADER, CONTENT_TYPE_GRPC) .path(new AsciiString("foo/bar")); ByteBuf headersFrame = headersFrame(STREAM_ID, headers); channelRead(headersFrame); Http2Headers responseHeaders = new DefaultHttp2Headers() .set(InternalStatus.CODE_KEY.name(), String.valueOf(Code.UNIMPLEMENTED.value())) .set(InternalStatus.MESSAGE_KEY.name(), "Expected path to start with /: foo/bar") .status("" + 404) .set(CONTENT_TYPE_HEADER, "text/plain; encoding=utf-8"); verifyWrite().writeHeaders(eq(ctx()), eq(STREAM_ID), eq(responseHeaders), eq(0), eq(DEFAULT_PRIORITY_WEIGHT), eq(false), eq(0), eq(false), any(ChannelPromise.class)); }
Example #8
Source File: HttpToHttp2ConnectionHandlerTest.java From netty-4.1.22 with Apache License 2.0 | 6 votes |
@Test public void testHeadersOnlyRequest() throws Exception { bootstrapEnv(2, 1, 0); final FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, GET, "http://[email protected]:5555/example"); final HttpHeaders httpHeaders = request.headers(); httpHeaders.setInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text(), 5); httpHeaders.set(HttpHeaderNames.HOST, "[email protected]:5555"); httpHeaders.set(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), "http"); httpHeaders.add(of("foo"), of("goo")); httpHeaders.add(of("foo"), of("goo2")); httpHeaders.add(of("foo2"), of("goo2")); final Http2Headers http2Headers = new DefaultHttp2Headers().method(new AsciiString("GET")).path(new AsciiString("/example")) .authority(new AsciiString("www.example.org:5555")).scheme(new AsciiString("http")) .add(new AsciiString("foo"), new AsciiString("goo")) .add(new AsciiString("foo"), new AsciiString("goo2")) .add(new AsciiString("foo2"), new AsciiString("goo2")); ChannelPromise writePromise = newPromise(); verifyHeadersOnly(http2Headers, writePromise, clientChannel.writeAndFlush(request, writePromise)); }
Example #9
Source File: NettyServerHandlerTest.java From grpc-java with Apache License 2.0 | 6 votes |
@Test public void headersWithInvalidMethodShouldFail() throws Exception { manualSetUp(); Http2Headers headers = new DefaultHttp2Headers() .method(HTTP_FAKE_METHOD) .set(CONTENT_TYPE_HEADER, CONTENT_TYPE_GRPC) .path(new AsciiString("/foo/bar")); ByteBuf headersFrame = headersFrame(STREAM_ID, headers); channelRead(headersFrame); Http2Headers responseHeaders = new DefaultHttp2Headers() .set(InternalStatus.CODE_KEY.name(), String.valueOf(Code.INTERNAL.value())) .set(InternalStatus.MESSAGE_KEY.name(), "Method 'FAKE' is not supported") .status("" + 405) .set(CONTENT_TYPE_HEADER, "text/plain; encoding=utf-8"); verifyWrite() .writeHeaders( eq(ctx()), eq(STREAM_ID), eq(responseHeaders), eq(0), eq(false), any(ChannelPromise.class)); }
Example #10
Source File: HttpConversionUtil.java From netty-4.1.22 with Apache License 2.0 | 6 votes |
private static void setHttp2Scheme(HttpHeaders in, URI uri, Http2Headers out) { String value = uri.getScheme(); if (value != null) { out.scheme(new AsciiString(value)); return; } // Consume the Scheme extension header if present CharSequence cValue = in.get(ExtensionHeaderNames.SCHEME.text()); if (cValue != null) { out.scheme(AsciiString.of(cValue)); return; } if (uri.getPort() == HTTPS.port()) { out.scheme(HTTPS.name()); } else if (uri.getPort() == HTTP.port()) { out.scheme(HTTP.name()); } else { throw new IllegalArgumentException(":scheme must be specified. " + "see https://tools.ietf.org/html/rfc7540#section-8.1.2.3"); } }
Example #11
Source File: NettyServerStreamTest.java From grpc-java with Apache License 2.0 | 6 votes |
@Test public void closeBeforeClientHalfCloseShouldSucceed() throws Exception { ListMultimap<CharSequence, CharSequence> expectedHeaders = ImmutableListMultimap.copyOf(new DefaultHttp2Headers() .status(new AsciiString("200")) .set(new AsciiString("content-type"), new AsciiString("application/grpc")) .set(new AsciiString("grpc-status"), new AsciiString("0"))); stream().close(Status.OK, new Metadata()); ArgumentCaptor<SendResponseHeadersCommand> sendHeadersCap = ArgumentCaptor.forClass(SendResponseHeadersCommand.class); verify(writeQueue).enqueue(sendHeadersCap.capture(), eq(true)); SendResponseHeadersCommand sendHeaders = sendHeadersCap.getValue(); assertThat(sendHeaders.stream()).isSameInstanceAs(stream.transportState()); assertThat(ImmutableListMultimap.copyOf(sendHeaders.headers())) .containsExactlyEntriesIn(expectedHeaders); assertThat(sendHeaders.endOfStream()).isTrue(); verifyZeroInteractions(serverListener); // Sending complete. Listener gets closed() stream().transportState().complete(); verify(serverListener).closed(Status.OK); assertNull("no message expected", listenerMessageQueue.poll()); }
Example #12
Source File: InternalProtocolNegotiators.java From grpc-java with Apache License 2.0 | 6 votes |
/** Returns a {@link ProtocolNegotiator} for plaintext client channel. */ public static InternalProtocolNegotiator.ProtocolNegotiator plaintext() { final io.grpc.netty.ProtocolNegotiator negotiator = ProtocolNegotiators.plaintext(); final class PlaintextNegotiator implements InternalProtocolNegotiator.ProtocolNegotiator { @Override public AsciiString scheme() { return negotiator.scheme(); } @Override public ChannelHandler newHandler(GrpcHttp2ConnectionHandler grpcHandler) { return negotiator.newHandler(grpcHandler); } @Override public void close() { negotiator.close(); } } return new PlaintextNegotiator(); }
Example #13
Source File: JacksonResponseConverterFunctionTest.java From armeria with Apache License 2.0 | 6 votes |
@Test void aggregatedJson() throws Exception { expectAggregatedJson(Stream.of(TEST_STRINGS)) .expectComplete() .verify(); expectAggregatedJson(Flux.fromArray(TEST_STRINGS)) .expectComplete() .verify(); // Iterable with trailers. final HttpHeaders trailer = HttpHeaders.of(AsciiString.of("x-trailer"), "value"); expectAggregatedJson(Arrays.asList(TEST_STRINGS), JSON_HEADERS, trailer) .expectNext(trailer) .expectComplete() .verify(); }
Example #14
Source File: HpackHuffmanEncoder.java From netty-4.1.22 with Apache License 2.0 | 6 votes |
/** * Returns the number of bytes required to Huffman encode the input string literal. * * @param data the string literal to be Huffman encoded * @return the number of bytes required to Huffman encode {@code data} */ int getEncodedLength(CharSequence data) { if (data instanceof AsciiString) { AsciiString string = (AsciiString) data; try { encodedLengthProcessor.reset(); string.forEachByte(encodedLengthProcessor); return encodedLengthProcessor.length(); } catch (Exception e) { PlatformDependent.throwException(e); return -1; } } else { return getEncodedLengthSlowPath(data); } }
Example #15
Source File: ArmeriaHttpUtil.java From armeria with Apache License 2.0 | 6 votes |
/** * Filter the {@link HttpHeaderNames#TE} header according to the * <a href="https://tools.ietf.org/html/rfc7540#section-8.1.2.2">special rules in the HTTP/2 RFC</a>. * * @param entry the entry whose name is {@link HttpHeaderNames#TE}. * @param out the resulting HTTP/2 headers. */ private static void toHttp2HeadersFilterTE(Entry<CharSequence, CharSequence> entry, HttpHeadersBuilder out) { if (AsciiString.indexOf(entry.getValue(), ',', 0) == -1) { if (AsciiString.contentEqualsIgnoreCase(AsciiString.trim(entry.getValue()), HttpHeaderValues.TRAILERS)) { out.add(HttpHeaderNames.TE, HttpHeaderValues.TRAILERS.toString()); } } else { final List<CharSequence> teValues = StringUtil.unescapeCsvFields(entry.getValue()); for (CharSequence teValue : teValues) { if (AsciiString.contentEqualsIgnoreCase(AsciiString.trim(teValue), HttpHeaderValues.TRAILERS)) { out.add(HttpHeaderNames.TE, HttpHeaderValues.TRAILERS.toString()); break; } } } }
Example #16
Source File: ArmeriaHttpUtil.java From armeria with Apache License 2.0 | 5 votes |
private static String convertHeaderValue(AsciiString name, CharSequence value) { if (!(value instanceof AsciiString)) { return value.toString(); } if (HEADER_VALUE_CACHE != null && CACHED_HEADERS.contains(name)) { final String converted = HEADER_VALUE_CACHE.get((AsciiString) value); assert converted != null; // loader does not return null. return converted; } return value.toString(); }
Example #17
Source File: HpackHuffmanTest.java From netty-4.1.22 with Apache License 2.0 | 5 votes |
private static byte[] decode(HpackHuffmanDecoder decoder, byte[] bytes) throws Http2Exception { ByteBuf buffer = Unpooled.wrappedBuffer(bytes); try { AsciiString decoded = decoder.decode(buffer, buffer.readableBytes()); Assert.assertFalse(buffer.isReadable()); return decoded.toByteArray(); } finally { buffer.release(); } }
Example #18
Source File: CharSequenceValueConverter.java From netty-4.1.22 with Apache License 2.0 | 5 votes |
@Override public long convertToLong(CharSequence value) { if (value instanceof AsciiString) { return ((AsciiString) value).parseLong(); } return Long.parseLong(value.toString()); }
Example #19
Source File: RequestContextExporter.java From armeria with Apache License 2.0 | 5 votes |
RequestContextExporter(Set<ExportEntry<BuiltInProperty>> builtInPropertySet, Set<ExportEntry<AttributeKey<?>>> attrs, Set<ExportEntry<AsciiString>> reqHeaders, Set<ExportEntry<AsciiString>> resHeaders) { if (!builtInPropertySet.isEmpty()) { builtInProperties = new BuiltInProperties(); builtInPropertyArray = builtInPropertySet.toArray(EMPTY_EXPORT_ENTRIES); for (ExportEntry<BuiltInProperty> entry : builtInPropertyArray) { builtInProperties.add(entry.key); } } else { builtInProperties = null; builtInPropertyArray = null; } if (!attrs.isEmpty()) { this.attrs = attrs.toArray(EMPTY_EXPORT_ENTRIES); numAttrs = this.attrs.length; } else { this.attrs = null; numAttrs = 0; } if (!reqHeaders.isEmpty()) { this.reqHeaders = reqHeaders.toArray(EMPTY_EXPORT_ENTRIES); } else { this.reqHeaders = null; } if (!resHeaders.isEmpty()) { this.resHeaders = resHeaders.toArray(EMPTY_EXPORT_ENTRIES); } else { this.resHeaders = null; } }
Example #20
Source File: BedrockUtils.java From Protocol with Apache License 2.0 | 5 votes |
public static AsciiString readLEAsciiString(ByteBuf buffer) { Preconditions.checkNotNull(buffer, "buffer"); int length = buffer.readIntLE(); byte[] bytes = new byte[length]; buffer.readBytes(bytes); return new AsciiString(bytes); }
Example #21
Source File: LoginSerializer_v332.java From Protocol with Apache License 2.0 | 5 votes |
@Override public void serialize(ByteBuf buffer, LoginPacket packet) { buffer.writeInt(packet.getProtocolVersion()); AsciiString chainData = packet.getChainData(); AsciiString skinData = packet.getSkinData(); VarInts.writeUnsignedInt(buffer, chainData.length() + skinData.length() + 8); BedrockUtils.writeLEAsciiString(buffer, chainData); BedrockUtils.writeLEAsciiString(buffer, skinData); }
Example #22
Source File: HeadersBenchmark.java From netty-4.1.22 with Apache License 2.0 | 5 votes |
@Benchmark @BenchmarkMode(Mode.AverageTime) public void httpRemove(Blackhole bh) { for (AsciiString name : httpNames) { bh.consume(httpHeaders.remove(name)); } }
Example #23
Source File: ReadOnlyHttpHeaders.java From netty-4.1.22 with Apache License 2.0 | 5 votes |
private int findNextValue() { for (int i = nextNameIndex; i < nameValuePairs.length; i += 2) { final CharSequence roName = nameValuePairs[i]; if (nameHash == AsciiString.hashCode(roName) && contentEqualsIgnoreCase(name, roName)) { return i; } } return -1; }
Example #24
Source File: HeadersBenchmark.java From netty-4.1.22 with Apache License 2.0 | 5 votes |
@Benchmark @BenchmarkMode(Mode.AverageTime) public void http2Remove(Blackhole bh) { for (AsciiString name : http2Names) { bh.consume(http2Headers.remove(name)); } }
Example #25
Source File: BedrockUtils.java From Protocol with Apache License 2.0 | 5 votes |
public static AsciiString readLEAsciiString(ByteBuf buffer) { Preconditions.checkNotNull(buffer, "buffer"); int length = buffer.readIntLE(); byte[] bytes = new byte[length]; buffer.readBytes(bytes); return new AsciiString(bytes); }
Example #26
Source File: Http2ServerInitializer.java From netty-4.1.22 with Apache License 2.0 | 5 votes |
@Override public UpgradeCodec newUpgradeCodec(CharSequence protocol) { if (AsciiString.contentEquals(Http2CodecUtil.HTTP_UPGRADE_PROTOCOL_NAME, protocol)) { return new Http2ServerUpgradeCodec( Http2FrameCodecBuilder.forServer().build(), new HelloWorldHttp2Handler()); } else { return null; } }
Example #27
Source File: HttpToHttp2ConnectionHandlerTest.java From netty-4.1.22 with Apache License 2.0 | 5 votes |
@Test public void testAsterikFormRequestTargetHandled() throws Exception { bootstrapEnv(2, 1, 0); final FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, OPTIONS, "*"); final HttpHeaders httpHeaders = request.headers(); httpHeaders.setInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text(), 5); httpHeaders.set(HttpHeaderNames.HOST, "www.example.com:80"); httpHeaders.set(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), "http"); final Http2Headers http2Headers = new DefaultHttp2Headers().method(new AsciiString("OPTIONS")).path(new AsciiString("*")) .scheme(new AsciiString("http")).authority(new AsciiString("www.example.com:80")); ChannelPromise writePromise = newPromise(); verifyHeadersOnly(http2Headers, writePromise, clientChannel.writeAndFlush(request, writePromise)); }
Example #28
Source File: Http2FrameRoundtripTest.java From netty-4.1.22 with Apache License 2.0 | 5 votes |
private static Http2Headers headersOfSize(final int minSize) { final AsciiString singleByte = new AsciiString(new byte[]{0}, false); DefaultHttp2Headers headers = new DefaultHttp2Headers(false); for (int size = 0; size < minSize; size += 2) { headers.add(singleByte, singleByte); } return headers; }
Example #29
Source File: HttpToHttp2ConnectionHandlerTest.java From netty-4.1.22 with Apache License 2.0 | 5 votes |
@Test public void testHostFormRequestTargetHandled() throws Exception { bootstrapEnv(2, 1, 0); final FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, GET, "/"); final HttpHeaders httpHeaders = request.headers(); httpHeaders.setInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text(), 5); httpHeaders.set(HttpHeaderNames.HOST, "localhost:80"); httpHeaders.set(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), "http"); final Http2Headers http2Headers = new DefaultHttp2Headers().method(new AsciiString("GET")).path(new AsciiString("/")) .scheme(new AsciiString("http")).authority(new AsciiString("localhost:80")); ChannelPromise writePromise = newPromise(); verifyHeadersOnly(http2Headers, writePromise, clientChannel.writeAndFlush(request, writePromise)); }
Example #30
Source File: Http1RequestDecoder.java From armeria with Apache License 2.0 | 5 votes |
Http1RequestDecoder(ServerConfig cfg, Channel channel, AsciiString scheme, ServerHttp1ObjectEncoder writer) { this.cfg = cfg; this.scheme = scheme; inboundTrafficController = InboundTrafficController.ofHttp1(channel); this.writer = writer; }