List of usage examples for io.netty.buffer ByteBuf release
boolean release();
From source file:com.linecorp.armeria.internal.grpc.GrpcTestUtil.java
License:Apache License
public static byte[] compressedFrame(ByteBuf uncompressed) { ByteBuf compressed = Unpooled.buffer(); try (ByteBufInputStream is = new ByteBufInputStream(uncompressed, true); GZIPOutputStream os = new GZIPOutputStream(new ByteBufOutputStream(compressed))) { ByteStreams.copy(is, os);//from w ww. ja v a 2 s . com } catch (IOException e) { throw new UncheckedIOException(e); } ByteBuf buf = Unpooled.buffer(); buf.writeByte(1); buf.writeInt(compressed.readableBytes()); buf.writeBytes(compressed); compressed.release(); byte[] result = ByteBufUtil.getBytes(buf); buf.release(); return result; }
From source file:com.linecorp.armeria.server.grpc.ArmeriaServerCall.java
License:Apache License
private HttpData serializeTrailersAsMessage(HttpHeaders trailers) { final ByteBuf serialized = ctx.alloc().buffer(); boolean success = false; try {//w w w. j av a 2 s . c om serialized.writeByte(TRAILERS_FRAME_HEADER); // Skip, we'll set this after serializing the headers. serialized.writeInt(0); for (Map.Entry<AsciiString, String> trailer : trailers) { encodeHeader(trailer.getKey(), trailer.getValue(), serialized); } final int messageSize = serialized.readableBytes() - 5; serialized.setInt(1, messageSize); success = true; } finally { if (!success) { serialized.release(); } } return new ByteBufHttpData(serialized, true); }
From source file:com.linecorp.armeria.server.grpc.UnframedGrpcService.java
License:Apache License
private void frameAndServe(ServiceRequestContext ctx, HttpHeaders grpcHeaders, AggregatedHttpMessage clientRequest, CompletableFuture<HttpResponse> res) { final HttpRequest grpcRequest; try (ArmeriaMessageFramer framer = new ArmeriaMessageFramer(ctx.alloc(), ArmeriaMessageFramer.NO_MAX_OUTBOUND_MESSAGE_SIZE)) { final HttpData content = clientRequest.content(); final ByteBuf message; if (content instanceof ByteBufHolder) { message = ((ByteBufHolder) content).content(); } else {//from w ww .j a va 2s . c om message = ctx.alloc().buffer(content.length()); message.writeBytes(content.array(), content.offset(), content.length()); } final HttpData frame; boolean success = false; try { frame = framer.writePayload(message); success = true; } finally { if (!success) { message.release(); } } grpcRequest = HttpRequest.of(grpcHeaders, frame); } final HttpResponse grpcResponse; try { grpcResponse = delegate().serve(ctx, grpcRequest); } catch (Exception e) { res.completeExceptionally(e); return; } grpcResponse.aggregate().whenCompleteAsync((framedResponse, t) -> { if (t != null) { res.completeExceptionally(t); } else { deframeAndRespond(ctx, framedResponse, res); } }, ctx.eventLoop()); }
From source file:com.linecorp.armeria.server.http.jetty.JettyServiceInvocationHandler.java
License:Apache License
@Override public void invoke(ServiceInvocationContext ctx, Executor blockingTaskExecutor, Promise<Object> promise) throws Exception { final ArmeriaConnector connector = this.connector; final FullHttpRequest aReq = ctx.originalRequest(); final ByteBuf out = ctx.alloc().ioBuffer(); boolean submitted = false; try {//from ww w . j av a 2 s . c o m final ArmeriaHttpTransport transport = new ArmeriaHttpTransport(out); final HttpChannel httpChannel = new HttpChannel(connector, connector.getHttpConfiguration(), new ArmeriaEndPoint(hostname, connector.getScheduler(), ctx.localAddress(), ctx.remoteAddress()), transport); fillRequest(ctx, aReq, httpChannel.getRequest()); blockingTaskExecutor.execute(() -> invoke(ctx, promise, transport, httpChannel)); submitted = true; } catch (Throwable t) { ctx.rejectPromise(promise, t); } finally { if (!submitted) { out.release(); } } }
From source file:com.linecorp.armeria.server.http.jetty.JettyServiceInvocationHandler.java
License:Apache License
private void invoke(ServiceInvocationContext ctx, Promise<Object> promise, ArmeriaHttpTransport transport, HttpChannel httpChannel) {/*from ww w .j av a 2 s . c o m*/ final ByteBuf out = transport.out; boolean success = false; try { server.handle(httpChannel); httpChannel.getResponse().getHttpOutput().flush(); final Throwable cause = transport.cause; if (cause == null) { ctx.resolvePromise(promise, toFullHttpResponse(transport, out)); success = true; } else { ctx.rejectPromise(promise, cause); } } catch (Throwable t) { ctx.rejectPromise(promise, t); } finally { if (!success) { out.release(); } } }
From source file:com.linecorp.armeria.server.thrift.THttp2Client.java
License:Apache License
@Override public void flush() throws TTransportException { THttp2ClientInitializer initHandler = new THttp2ClientInitializer(); Bootstrap b = new Bootstrap(); b.group(group);/*from w ww. j a v a 2s . co m*/ b.channel(NioSocketChannel.class); b.handler(initHandler); Channel ch = null; try { ch = b.connect(host, port).syncUninterruptibly().channel(); THttp2ClientHandler handler = initHandler.THttp2ClientHandler; // Wait until HTTP/2 upgrade is finished. assertTrue(handler.settingsPromise.await(5, TimeUnit.SECONDS)); handler.settingsPromise.get(); // Send a Thrift request. FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, path, Unpooled.wrappedBuffer(out.getArray(), 0, out.length())); request.headers().add(HttpHeaderNames.HOST, host); request.headers().set(ExtensionHeaderNames.SCHEME.text(), uri.getScheme()); ch.writeAndFlush(request).sync(); // Wait until the Thrift response is received. assertTrue(handler.responsePromise.await(5, TimeUnit.SECONDS)); ByteBuf response = handler.responsePromise.get(); // Pass the received Thrift response to the Thrift client. final byte[] array = new byte[response.readableBytes()]; response.readBytes(array); in = new TMemoryInputTransport(array); response.release(); } catch (Exception e) { throw new TTransportException(TTransportException.UNKNOWN, e); } finally { if (ch != null) { ch.close(); } } }
From source file:com.linecorp.armeria.server.thrift.THttpService.java
License:Apache License
private void decodeAndInvoke(ServiceRequestContext ctx, AggregatedHttpMessage req, SerializationFormat serializationFormat, CompletableFuture<HttpResponse> httpRes) { final HttpData content = req.content(); final ByteBuf buf; if (content instanceof ByteBufHolder) { buf = ((ByteBufHolder) content).content(); } else {/* w ww. j av a2 s .c o m*/ buf = ctx.alloc().buffer(content.length()); buf.writeBytes(content.array(), content.offset(), content.length()); } final TByteBufTransport inTransport = new TByteBufTransport(buf); final TProtocol inProto = ThriftProtocolFactories.get(serializationFormat).getProtocol(inTransport); final int seqId; final ThriftFunction f; final RpcRequest decodedReq; try { final TMessage header; final TBase<?, ?> args; try { header = inProto.readMessageBegin(); } catch (Exception e) { logger.debug("{} Failed to decode Thrift header:", ctx, e); httpRes.complete(HttpResponse.of(HttpStatus.BAD_REQUEST, MediaType.PLAIN_TEXT_UTF_8, "Failed to decode Thrift header: " + Throwables.getStackTraceAsString(e))); return; } seqId = header.seqid; final byte typeValue = header.type; final int colonIdx = header.name.indexOf(':'); final String serviceName; final String methodName; if (colonIdx < 0) { serviceName = ""; methodName = header.name; } else { serviceName = header.name.substring(0, colonIdx); methodName = header.name.substring(colonIdx + 1); } // Basic sanity check. We usually should never fail here. if (typeValue != TMessageType.CALL && typeValue != TMessageType.ONEWAY) { final TApplicationException cause = new TApplicationException( TApplicationException.INVALID_MESSAGE_TYPE, "unexpected TMessageType: " + typeString(typeValue)); handlePreDecodeException(ctx, httpRes, cause, serializationFormat, seqId, methodName); return; } // Ensure that such a method exists. final ThriftServiceEntry entry = entries().get(serviceName); f = entry != null ? entry.metadata.function(methodName) : null; if (f == null) { final TApplicationException cause = new TApplicationException(TApplicationException.UNKNOWN_METHOD, "unknown method: " + header.name); handlePreDecodeException(ctx, httpRes, cause, serializationFormat, seqId, methodName); return; } // Decode the invocation parameters. try { args = f.newArgs(); args.read(inProto); inProto.readMessageEnd(); decodedReq = toRpcRequest(f.serviceType(), header.name, args); ctx.logBuilder().requestContent(decodedReq, new ThriftCall(header, args)); } catch (Exception e) { // Failed to decode the invocation parameters. logger.debug("{} Failed to decode Thrift arguments:", ctx, e); final TApplicationException cause = new TApplicationException(TApplicationException.PROTOCOL_ERROR, "failed to decode arguments: " + e); handlePreDecodeException(ctx, httpRes, cause, serializationFormat, seqId, methodName); return; } } finally { buf.release(); ctx.logBuilder().requestContent(null, null); } invoke(ctx, serializationFormat, seqId, f, decodedReq, httpRes); }
From source file:com.linecorp.armeria.server.thrift.THttpService.java
License:Apache License
private static HttpData encodeSuccess(ServiceRequestContext ctx, RpcResponse reply, SerializationFormat serializationFormat, String methodName, int seqId, TBase<?, ?> result) { final ByteBuf buf = ctx.alloc().buffer(128); boolean success = false; try {// w ww. j a va 2s. co m final TTransport transport = new TByteBufTransport(buf); final TProtocol outProto = ThriftProtocolFactories.get(serializationFormat).getProtocol(transport); final TMessage header = new TMessage(methodName, TMessageType.REPLY, seqId); outProto.writeMessageBegin(header); result.write(outProto); outProto.writeMessageEnd(); ctx.logBuilder().responseContent(reply, new ThriftReply(header, result)); final HttpData encoded = new ByteBufHttpData(buf, false); success = true; return encoded; } catch (TException e) { throw new Error(e); // Should never reach here. } finally { if (!success) { buf.release(); } } }
From source file:com.linecorp.armeria.server.thrift.THttpService.java
License:Apache License
private static HttpData encodeException(ServiceRequestContext ctx, RpcResponse reply, SerializationFormat serializationFormat, int seqId, String methodName, Throwable cause) { final TApplicationException appException; if (cause instanceof TApplicationException) { appException = (TApplicationException) cause; } else {/* w w w . ja v a 2 s .co m*/ appException = new TApplicationException(TApplicationException.INTERNAL_ERROR, "internal server error:" + System.lineSeparator() + "---- BEGIN server-side trace ----" + System.lineSeparator() + Throwables.getStackTraceAsString(cause) + "---- END server-side trace ----"); } final ByteBuf buf = ctx.alloc().buffer(128); boolean success = false; try { final TTransport transport = new TByteBufTransport(buf); final TProtocol outProto = ThriftProtocolFactories.get(serializationFormat).getProtocol(transport); final TMessage header = new TMessage(methodName, TMessageType.EXCEPTION, seqId); outProto.writeMessageBegin(header); appException.write(outProto); outProto.writeMessageEnd(); ctx.logBuilder().responseContent(reply, new ThriftReply(header, appException)); final HttpData encoded = new ByteBufHttpData(buf, false); success = true; return encoded; } catch (TException e) { throw new Error(e); // Should never reach here. } finally { if (!success) { buf.release(); } } }
From source file:com.linecorp.armeria.unsafe.ByteBufHttpData.java
License:Apache License
/** * Constructs a new {@link ByteBufHttpData}. Ownership of {@code buf} is taken by this * {@link ByteBufHttpData}, which must not be mutated anymore. *///from www.j a v a 2s . co m public ByteBufHttpData(ByteBuf buf, boolean endOfStream) { length = requireNonNull(buf, "buf").readableBytes(); if (length != 0) { this.buf = buf; } else { buf.release(); this.buf = Unpooled.EMPTY_BUFFER; } this.endOfStream = endOfStream; }