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

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

Introduction

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

Prototype

public byte[] getArray() 

Source Link

Usage

From source file:com.kromatik.dasshy.server.thrift.TUtils.java

License:Open Source License

/**
 * Serialize the thrift entity using Compact protocol
 *
 * @param tEntity thrift entity/*from  ww w.  j  a v a  2 s.com*/
 * @return byte[]
 * @throws TException
 */
public static byte[] serializeCompact(final TBase tEntity) throws TException {
    final TMemoryBuffer memoryBuffer = new TMemoryBuffer(1);
    tEntity.write(new TCompactProtocol(memoryBuffer));
    memoryBuffer.flush();
    try {
        return memoryBuffer.getArray();
    } finally {
        memoryBuffer.close();
    }
}

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 {// www. j  a  v a2  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 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 {//ww  w .j ava2 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 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);//from  w  w w.j a  va 2s . co  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 {/*w w  w  .  ja v  a 2  s  . c om*/
        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. jav a 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.nearinfinity.blur.analysis.BlurAnalyzer.java

License:Apache License

public String toJSON() {
    TMemoryBuffer trans = new TMemoryBuffer(1024);
    TJSONProtocol protocol = new TJSONProtocol(trans);
    try {/*from ww  w  .ja v  a  2s  .  c  om*/
        _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;
    }/*ww  w.ja v a  2  s  . c  o 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:io.zipkin.internal.ThriftCodec.java

License:Apache License

private static <T> byte[] write(ThriftAdapter<T> adapter, T value) {
    TMemoryBuffer transport = new TMemoryBuffer(0);
    TBinaryProtocol protocol = new TBinaryProtocol(transport);
    try {// w w w .j  ava 2s.  c o  m
        adapter.write(value, protocol);
    } catch (Exception e) {
        return null;
    }
    return transport.getArray();
}

From source file:zipkin.finagle.scribe.ScribeSender.java

License:Apache License

/** This doesn't use thrift sequence ids because scrooge doesn't */
@Override/*from ww w .  ja v  a2 s  .  co  m*/
protected ThriftClientRequest makeRequest(List<byte[]> spans) throws TException {
    int encodedSize = InternalScribeCodec.messageSizeInBytes(category, spans);
    TMemoryBuffer mem = new TMemoryBuffer(encodedSize);
    TBinaryProtocol prot = new TBinaryProtocol(mem);
    InternalScribeCodec.writeLogRequest(category, spans, 0, prot);
    return new ThriftClientRequest(mem.getArray(), false);
}