Example usage for org.apache.thrift.transport TMemoryBuffer length

List of usage examples for org.apache.thrift.transport TMemoryBuffer length

Introduction

In this page you can find the example usage for org.apache.thrift.transport TMemoryBuffer length.

Prototype

public int length() 

Source Link

Usage

From source file:com.baidu.oped.apm.common.util.BytesUtilsTest.java

License:Apache License

@Test
public void compactProtocolVint() throws TException {
    TMemoryBuffer tMemoryBuffer = writeVInt32(BytesUtils.zigzagToInt(64));
    logger.trace("length:{}", tMemoryBuffer.length());

    TMemoryBuffer tMemoryBuffer2 = writeVInt32(64);
    logger.trace("length:{}", tMemoryBuffer2.length());

}

From source file:com.linecorp.armeria.client.thrift.ThriftClientDelegate.java

License:Apache License

@Override
public ThriftReply execute(ClientRequestContext ctx, ThriftCall call) throws Exception {
    final int seqId = call.seqId();
    final String method = call.method();
    final List<Object> args = call.params();
    final ThriftReply reply = new ThriftReply(seqId);

    ctx.requestLogBuilder().serializationFormat(serializationFormat);
    ctx.requestLogBuilder().attr(RequestLog.RPC_REQUEST).set(call);
    ctx.responseLogBuilder().attr(ResponseLog.RPC_RESPONSE).set(reply);

    final ThriftFunction func;
    try {//from w w w  . ja va 2 s . c  o  m
        func = metadata(call.serviceType()).function(method);
        if (func == null) {
            throw new IllegalArgumentException("Thrift method not found: " + method);
        }
    } catch (Throwable cause) {
        reply.completeExceptionally(cause);
        return reply;
    }

    try {
        final TMemoryBuffer outTransport = new TMemoryBuffer(128);
        final TProtocol tProtocol = protocolFactory.getProtocol(outTransport);
        final TMessage tMessage = new TMessage(method, func.messageType(), seqId);

        tProtocol.writeMessageBegin(tMessage);
        @SuppressWarnings("rawtypes")
        final TBase tArgs = func.newArgs(args);
        tArgs.write(tProtocol);
        tProtocol.writeMessageEnd();

        final DefaultHttpRequest httpReq = new DefaultHttpRequest(
                HttpHeaders.of(HttpMethod.POST, path).set(HttpHeaderNames.CONTENT_TYPE, mediaType), true);
        httpReq.write(HttpData.of(outTransport.getArray(), 0, outTransport.length()));
        httpReq.close();

        final CompletableFuture<AggregatedHttpMessage> future = httpClient.execute(ctx, httpReq).aggregate();

        future.handle(voidFunction((res, cause) -> {
            if (cause != null) {
                completeExceptionally(reply, func,
                        cause instanceof ExecutionException ? cause.getCause() : cause);
                return;
            }

            final HttpStatus status = res.headers().status();
            if (status.code() != HttpStatus.OK.code()) {
                completeExceptionally(reply, func, new InvalidResponseException(status.toString()));
                return;
            }

            try {
                reply.complete(decodeResponse(func, res.content()));
            } catch (Throwable t) {
                completeExceptionally(reply, func, t);
            }
        })).exceptionally(CompletionActions::log);
    } catch (Throwable cause) {
        completeExceptionally(reply, func, cause);
    }

    return reply;
}

From source file:com.linecorp.armeria.client.thrift.THttpClientDelegate.java

License:Apache License

@Override
public RpcResponse execute(ClientRequestContext ctx, RpcRequest call) throws Exception {
    final int seqId = nextSeqId.incrementAndGet();
    final String method = call.method();
    final List<Object> args = call.params();
    final DefaultRpcResponse reply = new DefaultRpcResponse();

    ctx.logBuilder().serializationFormat(serializationFormat);

    final ThriftFunction func;
    try {/*from  w w w .j a va  2  s .com*/
        func = metadata(call.serviceType()).function(method);
        if (func == null) {
            throw new IllegalArgumentException("Thrift method not found: " + method);
        }
    } catch (Throwable cause) {
        reply.completeExceptionally(cause);
        return reply;
    }

    try {
        final TMemoryBuffer outTransport = new TMemoryBuffer(128);
        final TProtocol tProtocol = protocolFactory.getProtocol(outTransport);
        final TMessage header = new TMessage(fullMethod(ctx, method), func.messageType(), seqId);

        tProtocol.writeMessageBegin(header);
        @SuppressWarnings("rawtypes")
        final TBase tArgs = func.newArgs(args);
        tArgs.write(tProtocol);
        tProtocol.writeMessageEnd();

        ctx.logBuilder().requestContent(call, new ThriftCall(header, tArgs));

        final DefaultHttpRequest httpReq = new DefaultHttpRequest(
                HttpHeaders.of(HttpMethod.POST, path).set(HttpHeaderNames.CONTENT_TYPE, mediaType), true);
        httpReq.write(HttpData.of(outTransport.getArray(), 0, outTransport.length()));
        httpReq.close();

        ctx.logBuilder().deferResponseContent();

        final CompletableFuture<AggregatedHttpMessage> future = httpClient.execute(ctx, httpReq).aggregate();

        future.handle(voidFunction((res, cause) -> {
            if (cause != null) {
                handlePreDecodeException(ctx, reply, func,
                        cause instanceof ExecutionException ? cause.getCause() : cause);
                return;
            }

            final HttpStatus status = res.headers().status();
            if (status.code() != HttpStatus.OK.code()) {
                handlePreDecodeException(ctx, reply, func, new InvalidResponseException(status.toString()));
                return;
            }

            try {
                handle(ctx, reply, func, res.content());
            } catch (Throwable t) {
                handlePreDecodeException(ctx, reply, func, t);
            }
        })).exceptionally(CompletionActions::log);
    } catch (Throwable cause) {
        handlePreDecodeException(ctx, reply, func, cause);
    }

    return reply;
}

From source file:com.linecorp.armeria.server.logging.structured.StructuredLogJsonFormat.java

License:Apache License

private static String writeThriftObjectAsTText(Consumer<TProtocol> writer) {
    TMemoryBuffer buffer = new TMemoryBuffer(1024);
    TProtocol protocol = new TTextProtocol.Factory().getProtocol(buffer);
    writer.accept(protocol);/*ww w. j  av  a  2s .c  o m*/
    return new String(buffer.getArray(), 0, buffer.length());
}

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<TBase<?, ?>, TFieldIdEnum> result) {

    final TMemoryBuffer buf = new TMemoryBuffer(128);
    final TProtocol outProto = ThriftProtocolFactories.get(serializationFormat).getProtocol(buf);

    try {/*  ww  w. j  a  v a  2 s.c o m*/
        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));
    } catch (TException e) {
        throw new Error(e); // Should never reach here.
    }

    return HttpData.of(buf.getArray(), 0, buf.length());
}

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 {/*from w  w  w.j  a va 2  s .c  o 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 TMemoryBuffer buf = new TMemoryBuffer(128);
    final TProtocol outProto = ThriftProtocolFactories.get(serializationFormat).getProtocol(buf);

    try {
        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));
    } catch (TException e) {
        throw new Error(e); // Should never reach here.
    }

    return HttpData.of(buf.getArray(), 0, buf.length());
}

From source file:com.navercorp.pinpoint.common.util.BytesUtilsTest.java

License:Apache License

@Test
public void compactProtocolVint() throws TException {
    TMemoryBuffer tMemoryBuffer = writeVInt32(BytesUtils.zigzagToInt(64));
    logger.debug("length:{}", tMemoryBuffer.length());

    TMemoryBuffer tMemoryBuffer2 = writeVInt32(64);
    logger.debug("length:{}", tMemoryBuffer2.length());

}

From source file:com.nearinfinity.blur.analysis.BlurAnalyzer.java

License:Apache License

public String toJSON() {
    TMemoryBuffer trans = new TMemoryBuffer(1024);
    TJSONProtocol protocol = new TJSONProtocol(trans);
    try {//from  w  w  w .j  a va2  s. c o  m
        _analyzerDefinition.write(protocol);
    } catch (TException e) {
        throw new RuntimeException(e);
    }
    trans.close();
    byte[] array = trans.getArray();
    return new String(array, 0, trans.length());
}

From source file:com.nearinfinity.blur.utils.BlurUtil.java

License:Apache License

public static byte[] read(TBase<?, ?> base) {
    if (base == null) {
        return null;
    }//from ww  w .  j a  va2  s.co m
    TMemoryBuffer trans = new TMemoryBuffer(1024);
    TJSONProtocol protocol = new TJSONProtocol(trans);
    try {
        base.write(protocol);
    } catch (TException e) {
        throw new RuntimeException(e);
    }
    trans.close();
    byte[] buf = new byte[trans.length()];
    System.arraycopy(trans.getArray(), 0, buf, 0, trans.length());
    return buf;
}

From source file:com.qq.servlet.demo.thrift.netty.client.NettyThriftClient.java

License:Apache License

public void run() throws Exception {
    EventLoopGroup group = new NioEventLoopGroup(2);
    try {/*from   w w w.j  a  va2  s . c om*/
        final Bootstrap b = new Bootstrap();
        b.group(group);
        b.channel(NioSocketChannel.class);
        b.handler(new NettyThriftClientInitializer());

        // Start the connection attempt.
        ChannelFuture future = b.connect(host, port);
        ChannelFuture sync = future.sync();
        Channel ch = sync.channel();

        AttributeKey<String> key = AttributeKey.valueOf("ASYNC_CONTEXT");
        Attribute<String> attr = ch.attr(key);
        String andSet = attr.getAndSet(Thread.currentThread().getName());

        TMemoryBuffer transportr = new TMemoryBuffer(1024);
        TProtocol protocol = new TBinaryProtocol(transportr);
        TMultiplexedProtocol multiProtocol3 = new TMultiplexedProtocol(protocol,
                IdGenService.class.getSimpleName());
        IdGenService.Client aoClient = new IdGenService.Client(multiProtocol3);
        IdGenReq req = new IdGenReq();
        req.setTableName("t_lottery_append_task-----------");
        req.setSource(andSet);
        aoClient.send_idGen(req);
        int length = transportr.length();
        byte[] buf = new byte[length];
        transportr.read(buf, 0, length);
        System.out.println(Arrays.toString(buf));

        ChannelFuture lastWriteFuture = ch.writeAndFlush(buf);
        // Wait until all messages are flushed before closing the channel.
        if (lastWriteFuture != null) {
            lastWriteFuture.sync();
        }

        System.in.read();
    } finally {
        group.shutdownGracefully();
    }
}