/** * Decodes this data into a {@link String}. * * @param charset the {@link Charset} to use for decoding this data * * @return the decoded {@link String} */ default String toString(Charset charset) { requireNonNull(charset, "charset"); return new String(array(), offset(), length(), charset); }
private static ByteBuf dataChunk(HttpData data, int offset, int chunkSize) { if (data instanceof ByteBufHolder) { final ByteBuf buf = ((ByteBufHolder) data).content(); return buf.retainedSlice(offset, chunkSize); } else { return Unpooled.wrappedBuffer(data.array(), offset, chunkSize); } }
/** * Converts an {@link HttpData} into a {@link DataBuffer}. */ DataBuffer toDataBuffer(HttpData httpData) { requireNonNull(httpData, "httpData"); if (!(httpData instanceof ByteBufHttpData)) { return delegate.wrap( ByteBuffer.wrap(httpData.array(), httpData.offset(), httpData.length())); } return converter.apply((ByteBufHttpData) httpData); }
@Override public int doRead(ApplicationBufferHandler handler) throws IOException { if (!isNeedToRead()) { // Read only once. return -1; } read = true; final int readableBytes = content.length(); handler.setByteBuffer(ByteBuffer.wrap(content.array(), content.offset(), readableBytes)); return readableBytes; }
/** * Returns a new {@link InputStream} that is sourced from this data. */ default InputStream toInputStream() { return new FastByteArrayInputStream(array(), offset(), length()); }
@Override void onHttpData(HttpData data) { responseDataBuffer.write(data.array(), data.offset(), data.length()); }
@Override public int doRead(ByteChunk chunk, Request request) throws IOException { if (read || content.isEmpty()) { // Read only once. return -1; } read = true; final int readableBytes = content.length(); chunk.setBytes(content.array(), content.offset(), readableBytes); return readableBytes; } }
buf = ((ByteBufHolder) data).content(); } else { buf = Unpooled.wrappedBuffer(data.array(), data.offset(), dataLength);
public int doRead(ByteChunk chunk) { if (!isNeedToRead()) { // Read only once. return -1; } read = true; final int readableBytes = content.length(); chunk.setBytes(content.array(), content.offset(), readableBytes); return readableBytes; }
@Override void onHttpData(HttpData data) { if (!responseCalled) { safeOnResponse(Okio.buffer(new ForwardingSource(pipeBuffer.source()) { @Override public long read(Buffer sink, long byteCount) throws IOException { request(1); return super.read(sink, byteCount); } })); responseCalled = true; } pipeBuffer.write(data.array(), data.offset(), data.length()); }
@Override public void onComplete() { final Iterator<HttpObject> it = received.build().iterator(); final HttpHeaders headers = (HttpHeaders) it.next(); assertThat(headers.status()).isEqualTo(HttpStatus.OK); assertThat(headers.contentType()).isEqualTo(MediaType.JSON_SEQ); // JSON Text Sequences: *(Record Separator[0x1E] JSON-text Line Feed[0x0A]) assertThat(((HttpData) it.next()).array()) .isEqualTo(new byte[] { 0x1E, '\"', 'a', '\"', 0x0A }); assertThat(((HttpData) it.next()).array()) .isEqualTo(new byte[] { 0x1E, '\"', 'b', '\"', 0x0A }); assertThat(((HttpData) it.next()).array()) .isEqualTo(new byte[] { 0x1E, '\"', 'c', '\"', 0x0A }); assertThat(((HttpData) it.next()).isEmpty()).isTrue(); assertThat(it.hasNext()).isFalse(); isFinished.set(true); } });
@Override public HttpData decode(HttpData obj) { if (obj instanceof ByteBufHolder) { decoder.writeInbound(((ByteBufHolder) obj).content()); } else { final ByteBuf compressed = Unpooled.wrappedBuffer(obj.array(), obj.offset(), obj.length()); decoder.writeInbound(compressed); } return HttpData.of(fetchDecoderOutput()); }
protected final ByteBuf toByteBuf(HttpData data) { if (data instanceof ByteBufHolder) { return ((ByteBufHolder) data).content(); } final ByteBuf buf = channel().alloc().directBuffer(data.length(), data.length()); buf.writeBytes(data.array(), data.offset(), data.length()); return buf; } }
/** * Converts the specified {@link AggregatedHttpMessage} to an object of {@code expectedResultType}. * This converter allows only {@code byte[]} and {@link HttpData} as its return type, and * {@link AggregatedHttpMessage} would be consumed only if it does not have a {@code Content-Type} header * or if it has {@code Content-Type: application/octet-stream} or {@code Content-Type: application/binary}. */ @Override public Object convertRequest(ServiceRequestContext ctx, AggregatedHttpMessage request, Class<?> expectedResultType) throws Exception { final MediaType mediaType = request.headers().contentType(); if (mediaType == null || mediaType.is(MediaType.OCTET_STREAM) || mediaType.is(MediaType.APPLICATION_BINARY)) { if (expectedResultType == byte[].class) { return request.content().array(); } if (expectedResultType == HttpData.class) { return request.content(); } } return RequestConverterFunction.fallthrough(); } }
@Test public void unframed() throws Exception { final HttpClient client = HttpClient.of(server.httpUri("/")); final AggregatedHttpMessage response = client.execute( HttpHeaders.of(HttpMethod.POST, UnitTestServiceGrpc.getStaticUnaryCallMethod().getFullMethodName()) .set(HttpHeaderNames.CONTENT_TYPE, "application/protobuf"), REQUEST_MESSAGE.toByteArray()).aggregate().get(); final SimpleResponse message = SimpleResponse.parseFrom(response.content().array()); assertThat(message).isEqualTo(RESPONSE_MESSAGE); assertThat(response.headers().getInt(HttpHeaderNames.CONTENT_LENGTH)) .isEqualTo(response.content().length()); checkRequestLog((rpcReq, rpcRes, grpcStatus) -> { assertThat(rpcReq.method()).isEqualTo("armeria.grpc.testing.UnitTestService/StaticUnaryCall"); assertThat(rpcReq.params()).containsExactly(REQUEST_MESSAGE); assertThat(rpcRes.get()).isEqualTo(RESPONSE_MESSAGE); }); }
private void invoke(THttpService service) throws Exception { invoke0(service, HttpData.of(out.getArray(), 0, out.length()), promise); final HttpData res = promise.get(); in.reset(res.array(), res.offset(), res.length()); }
private static void fillRequest( ServiceRequestContext ctx, AggregatedHttpMessage aReq, Request jReq) { jReq.setDispatcherType(DispatcherType.REQUEST); jReq.setAsyncSupported(false, "armeria"); jReq.setSecure(ctx.sessionProtocol().isTls()); jReq.setMetaData(toRequestMetadata(ctx, aReq)); final HttpData content = aReq.content(); if (!content.isEmpty()) { jReq.getHttpInput().addContent(new Content(ByteBuffer.wrap( content.array(), content.offset(), content.length()))); } jReq.getHttpInput().eof(); }
@Test public void unframed_acceptEncoding() throws Exception { final HttpClient client = HttpClient.of(server.httpUri("/")); final AggregatedHttpMessage response = client.execute( HttpHeaders.of(HttpMethod.POST, UnitTestServiceGrpc.getStaticUnaryCallMethod().getFullMethodName()) .set(HttpHeaderNames.CONTENT_TYPE, "application/protobuf") .set(GrpcHeaderNames.GRPC_ACCEPT_ENCODING, "gzip,none"), REQUEST_MESSAGE.toByteArray()).aggregate().get(); final SimpleResponse message = SimpleResponse.parseFrom(response.content().array()); assertThat(message).isEqualTo(RESPONSE_MESSAGE); assertThat(response.headers().getInt(HttpHeaderNames.CONTENT_LENGTH)) .isEqualTo(response.content().length()); checkRequestLog((rpcReq, rpcRes, grpcStatus) -> { assertThat(rpcReq.method()).isEqualTo("armeria.grpc.testing.UnitTestService/StaticUnaryCall"); assertThat(rpcReq.params()).containsExactly(REQUEST_MESSAGE); assertThat(rpcRes.get()).isEqualTo(RESPONSE_MESSAGE); }); }
@Test public void grpcWeb() throws Exception { final HttpClient client = HttpClient.of(server.httpUri("/")); final AggregatedHttpMessage response = client.execute( HttpHeaders.of(HttpMethod.POST, UnitTestServiceGrpc.getStaticUnaryCallMethod().getFullMethodName()) .set(HttpHeaderNames.CONTENT_TYPE, "application/grpc-web"), GrpcTestUtil.uncompressedFrame(GrpcTestUtil.requestByteBuf())).aggregate().get(); final byte[] serializedStatusHeader = "grpc-status: 0\r\n".getBytes(StandardCharsets.US_ASCII); final byte[] serializedTrailers = Bytes.concat( new byte[] { ArmeriaServerCall.TRAILERS_FRAME_HEADER }, Ints.toByteArray(serializedStatusHeader.length), serializedStatusHeader); assertThat(response.content().array()).containsExactly( Bytes.concat( GrpcTestUtil.uncompressedFrame( GrpcTestUtil.protoByteBuf(RESPONSE_MESSAGE)), serializedTrailers)); checkRequestLog((rpcReq, rpcRes, grpcStatus) -> { assertThat(rpcReq.method()).isEqualTo("armeria.grpc.testing.UnitTestService/StaticUnaryCall"); assertThat(rpcReq.params()).containsExactly(REQUEST_MESSAGE); assertThat(rpcRes.get()).isEqualTo(RESPONSE_MESSAGE); }); }
@Test public void testMultipleInheritance() throws Exception { final NameService.Client client1 = new NameService.Client.Factory().getClient(inProto, outProto); client1.send_removeMiddle(new Name(BAZ, BAR, FOO)); assertThat(out.length()).isGreaterThan(0); final HttpData req1 = HttpData.of(out.getArray(), 0, out.length()); out = new TMemoryBuffer(128); outProto = ThriftProtocolFactories.get(defaultSerializationFormat).getProtocol(out); final NameSortService.Client client2 = new NameSortService.Client.Factory().getClient(inProto, outProto); client2.send_sort(Arrays.asList(NAME_C, NAME_B, NAME_A)); assertThat(out.length()).isGreaterThan(0); final HttpData req2 = HttpData.of(out.getArray(), 0, out.length()); final THttpService service = THttpService.of( (UberNameService) (names, callback) -> callback.onComplete( names.stream().sorted().collect(toImmutableList())), defaultSerializationFormat); invoke0(service, req1, promise); invoke0(service, req2, promise2); final HttpData res1 = promise.get(); final HttpData res2 = promise2.get(); in.reset(res1.array(), res1.offset(), res1.length()); assertThat(client1.recv_removeMiddle()).isEqualTo(new Name(BAZ, null, FOO)); in.reset(res2.array(), res2.offset(), res2.length()); assertThat(client2.recv_sort()).containsExactly(NAME_A, NAME_B, NAME_C); }