Example usage for org.apache.thrift.protocol TProtocol writeMessageBegin

List of usage examples for org.apache.thrift.protocol TProtocol writeMessageBegin

Introduction

In this page you can find the example usage for org.apache.thrift.protocol TProtocol writeMessageBegin.

Prototype


public abstract void writeMessageBegin(TMessage message) throws TException;

Source Link

Document

Writing methods.

Usage

From source file:com.facebook.nifty.core.TestNiftyTransport.java

License:Apache License

private <T extends TTransport> T writeFirstChunk(T outTransport) throws TException {
    TProtocol outProtocol = new TBinaryProtocol(outTransport);

    outProtocol.writeMessageBegin(new TMessage());
    outProtocol.writeString("hello world");

    return outTransport;
}

From source file:com.facebook.swift.service.ThriftMethodHandler.java

License:Apache License

private void writeArguments(TProtocol out, int sequenceId, Object[] args) throws Exception {
    // Note that though setting message type to ONEWAY can be helpful when looking at packet
    // captures, some clients always send CALL and so servers are forced to rely on the "oneway"
    // attribute on thrift method in the interface definition, rather than checking the message
    // type./*from   w  w  w .ja  v a 2s  .c  o m*/
    out.writeMessageBegin(new TMessage(name, oneway ? ONEWAY : CALL, sequenceId));

    // write the parameters
    TProtocolWriter writer = new TProtocolWriter(out);
    writer.writeStructBegin(name + "_args");
    for (int i = 0; i < args.length; i++) {
        Object value = args[i];
        ParameterHandler parameter = parameterCodecs.get(i);
        writer.writeField(parameter.getName(), parameter.getId(), parameter.getCodec(), value);
    }
    writer.writeStructEnd();

    out.writeMessageEnd();
    out.getTransport().flush();
}

From source file:com.facebook.swift.service.ThriftMethodProcessor.java

License:Apache License

private <T> void writeResponse(TProtocol out, int sequenceId, byte responseType, String responseFieldName,
        short responseFieldId, ThriftCodec<T> responseCodec, T result) throws Exception {
    out.writeMessageBegin(new TMessage(name, responseType, sequenceId));

    TProtocolWriter writer = new TProtocolWriter(out);
    writer.writeStructBegin(resultStructName);
    writer.writeField(responseFieldName, (short) responseFieldId, responseCodec, result);
    writer.writeStructEnd();//from www  . j  a  v a 2  s. c o  m

    out.writeMessageEnd();
    out.getTransport().flush();
}

From source file:com.facebook.swift.service.ThriftServiceProcessor.java

License:Apache License

public static TApplicationException writeApplicationException(TProtocol outputProtocol,
        RequestContext requestContext, String methodName, int sequenceId,
        TApplicationException applicationException) throws TException {
    LOG.error(applicationException, applicationException.getMessage());
    TNiftyTransport requestTransport = requestContext instanceof NiftyRequestContext
            ? ((NiftyRequestContext) requestContext).getNiftyTransport()
            : null;// ww w.j  a  v  a 2s .c o  m

    // Application exceptions are sent to client, and the connection can be reused
    outputProtocol.writeMessageBegin(new TMessage(methodName, TMessageType.EXCEPTION, sequenceId));
    applicationException.write(outputProtocol);
    outputProtocol.writeMessageEnd();
    if (requestTransport != null) {
        requestTransport.setTApplicationException(applicationException);
    }
    outputProtocol.getTransport().flush();

    return applicationException;
}

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

License:Apache License

@Override
@SuppressWarnings("rawtypes")
public EncodeResult encodeRequest(Channel channel, Method method, Object[] args) {
    requireNonNull(channel, "channel");
    requireNonNull(method, "method");
    final ThriftMethod thriftMethod = methodMap.get(method.getName());
    if (thriftMethod == null) {
        throw new IllegalStateException("Thrift method not found: " + method.getName());
    }/*  w w  w .ja  v a2s.  c  o  m*/
    try {
        final ByteBuf outByteBuf = channel.alloc().buffer();
        final TByteBufOutputTransport outTransport = new TByteBufOutputTransport(outByteBuf);
        final TProtocol tProtocol = protocolFactory.getProtocol(outTransport);
        final TMessage tMessage = new TMessage(method.getName(), thriftMethod.methodType(),
                seq.incrementAndGet());

        tProtocol.writeMessageBegin(tMessage);
        final TBase tArgs = thriftMethod.createArgs(isAsyncClient, args);
        tArgs.write(tProtocol);
        tProtocol.writeMessageEnd();

        AsyncMethodCallback asyncMethodCallback = null;
        if (isAsyncClient) {
            asyncMethodCallback = ThriftMethod.asyncCallback(args);
        }
        return new ThriftInvocation(channel, scheme, uri.getHost(), uri.getPath(), uri.getPath(), loggerName,
                outByteBuf, tMessage, thriftMethod, tArgs, asyncMethodCallback);
    } catch (Exception e) {
        Exception decodedException = decodeException(e, thriftMethod.declaredThrowableException());
        return new ThriftEncodeFailureResult(decodedException, scheme, uri);
    }
}

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  ww.  j a v  a  2  s  .  co  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 www  . jav a2  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.thrift.ThriftServiceCodec.java

License:Apache License

private ByteBuf encodeSuccess(ThriftServiceInvocationContext ctx, TBase<TBase<?, ?>, TFieldIdEnum> result) {

    final TProtocol outProto = this.outProto.get();
    final TByteBufTransport outTransport = (TByteBufTransport) outProto.getTransport();
    final ByteBuf out = ctx.alloc().buffer();
    outTransport.reset(out);/*from www. ja  v a 2s.c  o m*/
    try {
        outProto.writeMessageBegin(new TMessage(ctx.method(), TMessageType.REPLY, ctx.seqId));
        result.write(outProto);
        outProto.writeMessageEnd();
    } catch (TException e) {
        throw new Error(e); // Should never reach here.
    } finally {
        outTransport.clear();
    }

    return out;
}

From source file:com.linecorp.armeria.server.thrift.ThriftServiceCodec.java

License:Apache License

private ByteBuf encodeException(ByteBufAllocator alloc, String methodName, int seqId,
        TApplicationException cause) {/* w  w w  .java2s  .c  om*/

    final TProtocol outProto = this.outProto.get();
    final TByteBufTransport outTransport = (TByteBufTransport) outProto.getTransport();
    final ByteBuf out = alloc.buffer();

    outTransport.reset(out);
    try {
        outProto.writeMessageBegin(new TMessage(methodName, TMessageType.EXCEPTION, seqId));
        cause.write(outProto);
        outProto.writeMessageEnd();
    } catch (TException e) {
        throw new Error(e); // Should never reach here.
    } finally {
        outTransport.clear();
    }

    return out;
}

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 {/*from  ww w.  j  av a2 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());
}