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

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

Introduction

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

Prototype


public abstract TMessage readMessageBegin() throws TException;

Source Link

Document

Reading methods.

Usage

From source file:com.alibaba.dubbo.rpc.protocol.swift.ThriftCodec.java

License:Open Source License

private Object decode(String serviceName, TProtocol protocol) throws IOException {

    TMessage message;/*  w  ww .  ja  v a  2s  . c om*/

    try {
        message = protocol.readMessageBegin();
    } catch (TException e) {
        throw new IOException(e.getMessage(), e);
    }

    if (message.type == TMessageType.CALL) {

        RpcInvocation result = new RpcInvocation();
        result.setAttachment(Constants.INTERFACE_KEY, serviceName);
        result.setMethodName(message.name);

        String argsClassName = ExtensionLoader.getExtensionLoader(ClassNameGenerator.class)
                .getExtension(ThriftClassNameGenerator.NAME).generateArgsClassName(serviceName, message.name);

        if (StringUtils.isEmpty(argsClassName)) {
            throw new RpcException(RpcException.SERIALIZATION_EXCEPTION,
                    "The specified interface name incorrect.");
        }

        Class clazz = cachedClass.get(argsClassName);

        if (clazz == null) {
            try {

                clazz = ClassHelper.forNameWithThreadContextClassLoader(argsClassName);

                cachedClass.putIfAbsent(argsClassName, clazz);

            } catch (ClassNotFoundException e) {
                throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
            }
        }

        TBase args;

        try {
            args = (TBase) clazz.newInstance();
        } catch (InstantiationException e) {
            throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
        } catch (IllegalAccessException e) {
            throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
        }

        try {
            args.read(protocol);
            protocol.readMessageEnd();
        } catch (TException e) {
            throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
        }

        List<Object> parameters = new ArrayList<Object>();
        List<Class<?>> parameterTypes = new ArrayList<Class<?>>();
        int index = 1;

        while (true) {

            TFieldIdEnum fieldIdEnum = args.fieldForId(index++);

            if (fieldIdEnum == null) {
                break;
            }

            String fieldName = fieldIdEnum.getFieldName();

            String getMethodName = ThriftUtils.generateGetMethodName(fieldName);

            Method getMethod;

            try {
                getMethod = clazz.getMethod(getMethodName);
            } catch (NoSuchMethodException e) {
                throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
            }

            parameterTypes.add(getMethod.getReturnType());
            try {
                parameters.add(getMethod.invoke(args));
            } catch (IllegalAccessException e) {
                throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
            } catch (InvocationTargetException e) {
                throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
            }

        }

        result.setArguments(parameters.toArray());
        result.setParameterTypes(parameterTypes.toArray(new Class[parameterTypes.size()]));

        Request request = new Request(message.seqid);
        request.setData(result);

        cachedRequest.putIfAbsent(message.seqid, RequestData.create(message.seqid, serviceName, message.name));

        return request;

    } else if (message.type == TMessageType.EXCEPTION) {

        TApplicationException exception;

        try {
            exception = TApplicationException.read(protocol);
            protocol.readMessageEnd();
        } catch (TException e) {
            throw new IOException(e.getMessage(), e);
        }

        RpcResult result = new RpcResult();

        result.setException(new RpcException(exception.getMessage()));

        Response response = new Response();

        response.setResult(result);

        response.setId(message.seqid);

        return response;

    } else if (message.type == TMessageType.REPLY) {

        String resultClassName = ExtensionLoader.getExtensionLoader(ClassNameGenerator.class)
                .getExtension(ThriftClassNameGenerator.NAME).generateResultClassName(serviceName, message.name);

        if (StringUtils.isEmpty(resultClassName)) {
            throw new IllegalArgumentException(new StringBuilder(32)
                    .append("Could not infer service result class name from service name ").append(serviceName)
                    .append(", the service name you specified may not generated by thrift idl compiler")
                    .toString());
        }

        Class<?> clazz = cachedClass.get(resultClassName);

        if (clazz == null) {

            try {

                clazz = ClassHelper.forNameWithThreadContextClassLoader(resultClassName);

                cachedClass.putIfAbsent(resultClassName, clazz);

            } catch (ClassNotFoundException e) {
                throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
            }

        }

        TBase<?, ? extends TFieldIdEnum> result;
        try {
            result = (TBase<?, ?>) clazz.newInstance();
        } catch (InstantiationException e) {
            throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
        } catch (IllegalAccessException e) {
            throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
        }

        try {
            result.read(protocol);
            protocol.readMessageEnd();
        } catch (TException e) {
            throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
        }

        Object realResult = null;

        int index = 0;

        while (true) {

            TFieldIdEnum fieldIdEnum = result.fieldForId(index++);

            if (fieldIdEnum == null) {
                break;
            }

            Field field;

            try {
                field = clazz.getDeclaredField(fieldIdEnum.getFieldName());
                field.setAccessible(true);
            } catch (NoSuchFieldException e) {
                throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
            }

            try {
                realResult = field.get(result);
            } catch (IllegalAccessException e) {
                throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
            }

            if (realResult != null) {
                break;
            }

        }

        Response response = new Response();

        response.setId(message.seqid);

        RpcResult rpcResult = new RpcResult();

        if (realResult instanceof Throwable) {
            rpcResult.setException((Throwable) realResult);
        } else {
            rpcResult.setValue(realResult);
        }

        response.setResult(rpcResult);

        return response;

    } else {
        // Impossible
        throw new IOException();
    }

}

From source file:com.alibaba.dubbo.rpc.protocol.thrift.ThriftCodec.java

License:Open Source License

private Object decode(TProtocol protocol) throws IOException {

    // version/* w  w  w  . j  ava2s. c  o m*/
    String serviceName;
    long id;

    TMessage message;

    try {
        protocol.readI16();
        protocol.readByte();
        serviceName = protocol.readString();
        id = protocol.readI64();
        message = protocol.readMessageBegin();
    } catch (TException e) {
        throw new IOException(e.getMessage(), e);
    }

    if (message.type == TMessageType.CALL) {

        RpcInvocation result = new RpcInvocation();
        result.setAttachment(Constants.INTERFACE_KEY, serviceName);
        result.setMethodName(message.name);

        String argsClassName = ExtensionLoader.getExtensionLoader(ClassNameGenerator.class)
                .getExtension(ThriftClassNameGenerator.NAME).generateArgsClassName(serviceName, message.name);

        if (StringUtils.isEmpty(argsClassName)) {
            throw new RpcException(RpcException.SERIALIZATION_EXCEPTION,
                    "The specified interface name incorrect.");
        }

        Class clazz = cachedClass.get(argsClassName);

        if (clazz == null) {
            try {

                clazz = ClassHelper.forNameWithThreadContextClassLoader(argsClassName);

                cachedClass.putIfAbsent(argsClassName, clazz);

            } catch (ClassNotFoundException e) {
                throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
            }
        }

        TBase args;

        try {
            args = (TBase) clazz.newInstance();
        } catch (InstantiationException e) {
            throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
        } catch (IllegalAccessException e) {
            throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
        }

        try {
            args.read(protocol);
            protocol.readMessageEnd();
        } catch (TException e) {
            throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
        }

        List<Object> parameters = new ArrayList<Object>();
        List<Class<?>> parameterTypes = new ArrayList<Class<?>>();
        int index = 1;

        while (true) {

            TFieldIdEnum fieldIdEnum = args.fieldForId(index++);

            if (fieldIdEnum == null) {
                break;
            }

            String fieldName = fieldIdEnum.getFieldName();

            String getMethodName = ThriftUtils.generateGetMethodName(fieldName);

            Method getMethod;

            try {
                getMethod = clazz.getMethod(getMethodName);
            } catch (NoSuchMethodException e) {
                throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
            }

            parameterTypes.add(getMethod.getReturnType());
            try {
                parameters.add(getMethod.invoke(args));
            } catch (IllegalAccessException e) {
                throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
            } catch (InvocationTargetException e) {
                throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
            }

        }

        result.setArguments(parameters.toArray());
        result.setParameterTypes(parameterTypes.toArray(new Class[parameterTypes.size()]));

        Request request = new Request(id);
        request.setData(result);

        cachedRequest.putIfAbsent(id, RequestData.create(message.seqid, serviceName, message.name));

        return request;

    } else if (message.type == TMessageType.EXCEPTION) {

        TApplicationException exception;

        try {
            exception = TApplicationException.read(protocol);
            protocol.readMessageEnd();
        } catch (TException e) {
            throw new IOException(e.getMessage(), e);
        }

        RpcResult result = new RpcResult();

        result.setException(new RpcException(exception.getMessage()));

        Response response = new Response();

        response.setResult(result);

        response.setId(id);

        return response;

    } else if (message.type == TMessageType.REPLY) {

        String resultClassName = ExtensionLoader.getExtensionLoader(ClassNameGenerator.class)
                .getExtension(ThriftClassNameGenerator.NAME).generateResultClassName(serviceName, message.name);

        if (StringUtils.isEmpty(resultClassName)) {
            throw new IllegalArgumentException(new StringBuilder(32)
                    .append("Could not infer service result class name from service name ").append(serviceName)
                    .append(", the service name you specified may not generated by thrift idl compiler")
                    .toString());
        }

        Class<?> clazz = cachedClass.get(resultClassName);

        if (clazz == null) {

            try {

                clazz = ClassHelper.forNameWithThreadContextClassLoader(resultClassName);

                cachedClass.putIfAbsent(resultClassName, clazz);

            } catch (ClassNotFoundException e) {
                throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
            }

        }

        TBase<?, ? extends TFieldIdEnum> result;
        try {
            result = (TBase<?, ?>) clazz.newInstance();
        } catch (InstantiationException e) {
            throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
        } catch (IllegalAccessException e) {
            throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
        }

        try {
            result.read(protocol);
            protocol.readMessageEnd();
        } catch (TException e) {
            throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
        }

        Object realResult = null;

        int index = 0;

        while (true) {

            TFieldIdEnum fieldIdEnum = result.fieldForId(index++);

            if (fieldIdEnum == null) {
                break;
            }

            Field field;

            try {
                field = clazz.getDeclaredField(fieldIdEnum.getFieldName());
                field.setAccessible(true);
            } catch (NoSuchFieldException e) {
                throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
            }

            try {
                realResult = field.get(result);
            } catch (IllegalAccessException e) {
                throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
            }

            if (realResult != null) {
                break;
            }

        }

        Response response = new Response();

        response.setId(id);

        RpcResult rpcResult = new RpcResult();

        if (realResult instanceof Throwable) {
            rpcResult.setException((Throwable) realResult);
        } else {
            rpcResult.setValue(realResult);
        }

        response.setResult(rpcResult);

        return response;

    } else {
        // Impossible
        throw new IOException();
    }

}

From source file:com.facebook.nifty.client.AbstractClientChannel.java

License:Apache License

protected int extractSequenceId(ChannelBuffer messageBuffer) throws TTransportException {
    try {//from  www  . j  av  a  2  s  .c om
        messageBuffer.markReaderIndex();
        TTransport inputTransport = new TChannelBufferInputTransport(messageBuffer);
        TProtocol inputProtocol = getProtocolFactory().getInputProtocolFactory().getProtocol(inputTransport);
        TMessage message = inputProtocol.readMessageBegin();
        messageBuffer.resetReaderIndex();
        return message.seqid;
    } catch (Throwable t) {
        throw new TTransportException("Could not find sequenceId in Thrift message");
    }
}

From source file:com.facebook.nifty.client.TNiftyClientChannelTransport.java

License:Apache License

private boolean inOneWayRequest() throws TException {
    boolean isOneWayMethod = false;

    // Create a temporary transport wrapping the output buffer, so that we can read the method name for this message
    TChannelBufferInputTransport requestReadTransport = new TChannelBufferInputTransport(
            requestBufferTransport.getOutputBuffer().duplicate());
    TProtocol protocol = channel.getProtocolFactory().getOutputProtocolFactory()
            .getProtocol(requestReadTransport);
    TMessage message = protocol.readMessageBegin();
    String methodName = message.name;

    isOneWayMethod = clientClassHasReceiveHelperMethod(methodName);

    return isOneWayMethod;
}

From source file:com.facebook.nifty.codec.DefaultThriftFrameDecoder.java

License:Apache License

protected ChannelBuffer tryDecodeUnframedMessage(ChannelHandlerContext ctx, Channel channel,
        ChannelBuffer buffer, TProtocolFactory inputProtocolFactory) throws TException {
    // Perform a trial decode, skipping through
    // the fields, to see whether we have an entire message available.

    int messageLength = 0;
    int messageStartReaderIndex = buffer.readerIndex();

    try {/*from   w ww. j  a v  a 2s.  com*/
        TNiftyTransport decodeAttemptTransport = new TNiftyTransport(channel, buffer,
                ThriftTransportType.UNFRAMED);
        int initialReadBytes = decodeAttemptTransport.getReadByteCount();
        TProtocol inputProtocol = inputProtocolFactory.getProtocol(decodeAttemptTransport);

        // Skip through the message
        inputProtocol.readMessageBegin();
        TProtocolUtil.skip(inputProtocol, TType.STRUCT);
        inputProtocol.readMessageEnd();

        messageLength = decodeAttemptTransport.getReadByteCount() - initialReadBytes;
    } catch (TTransportException | IndexOutOfBoundsException e) {
        // No complete message was decoded: ran out of bytes
        return null;
    } finally {
        if (buffer.readerIndex() - messageStartReaderIndex > maxFrameSize) {
            Channels.fireExceptionCaught(ctx,
                    new TooLongFrameException("Maximum frame size of " + maxFrameSize + " exceeded"));
        }

        buffer.readerIndex(messageStartReaderIndex);
    }

    if (messageLength <= 0) {
        return null;
    }

    // We have a full message in the read buffer, slice it off
    ChannelBuffer messageBuffer = extractFrame(buffer, messageStartReaderIndex, messageLength);
    buffer.readerIndex(messageStartReaderIndex + messageLength);
    return messageBuffer;
}

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

License:Apache License

private void readFirstChunk(TProtocol inProtocol) throws TException {
    inProtocol.readMessageBegin();
    inProtocol.readString();
}

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

License:Apache License

private TTransport tryDecodeUnframedMessage(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer)
        throws TException {
    // Perform a trial decode, skipping through
    // the fields, to see whether we have an entire message available.

    int messageLength = 0;
    int messageStartReaderIndex = buffer.readerIndex();

    try {// www.j  a v  a 2 s. co  m
        TNiftyTransport decodeAttemptTransport = new TNiftyTransport(channel, buffer,
                ThriftTransportType.UNFRAMED);
        TProtocol inputProtocol = this.inputProtocolFactory.getProtocol(decodeAttemptTransport);

        // Skip through the message
        inputProtocol.readMessageBegin();
        TProtocolUtil.skip(inputProtocol, TType.STRUCT);
        inputProtocol.readMessageEnd();

        messageLength = buffer.readerIndex() - messageStartReaderIndex;
    } catch (IndexOutOfBoundsException e) {
        // No complete message was decoded: ran out of bytes
        return null;
    } finally {
        if (buffer.readerIndex() - messageStartReaderIndex > maxFrameSize) {
            Channels.fireExceptionCaught(ctx,
                    new TooLongFrameException("Maximum frame size of " + maxFrameSize + " exceeded"));
        }

        buffer.readerIndex(messageStartReaderIndex);
    }

    if (messageLength <= 0) {
        return null;
    }

    // We have a full message in the read buffer, slice it off
    ChannelBuffer messageBuffer = extractFrame(buffer, messageStartReaderIndex, messageLength);
    buffer.readerIndex(messageStartReaderIndex + messageLength);
    return new TNiftyTransport(channel, messageBuffer, ThriftTransportType.UNFRAMED);
}

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

License:Apache License

private void waitForResponse(TProtocol in, int sequenceId) throws TException {
    TMessage message = in.readMessageBegin();
    if (message.type == EXCEPTION) {
        TApplicationException exception = TApplicationException.read(in);
        in.readMessageEnd();//from   w  w  w  .j av a  2s.c  om
        throw exception;
    }
    if (message.type != REPLY) {
        throw new TApplicationException(INVALID_MESSAGE_TYPE,
                "Received invalid message type " + message.type + " from server");
    }
    if (!message.name.equals(this.name)) {
        throw new TApplicationException(WRONG_METHOD_NAME,
                "Wrong method name in reply: expected " + this.name + " but received " + message.name);
    }
    if (message.seqid != sequenceId) {
        throw new TApplicationException(BAD_SEQUENCE_ID, name + " failed: out of sequence response");
    }
}

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

License:Apache License

@Override
@SuppressWarnings("PMD.EmptyCatchBlock")
public ListenableFuture<Boolean> process(final TProtocol in, TProtocol out, RequestContext requestContext)
        throws TException {
    String methodName = null;/* w  w w  .  ja  v  a  2 s  .c  om*/
    int sequenceId = 0;

    try {
        final SettableFuture<Boolean> resultFuture = SettableFuture.create();
        TMessage message = in.readMessageBegin();
        methodName = message.name;
        sequenceId = message.seqid;

        // lookup method
        ThriftMethodProcessor method = methods.get(methodName);
        if (method == null) {
            TProtocolUtil.skip(in, TType.STRUCT);
            createAndWriteApplicationException(out, requestContext, methodName, sequenceId, UNKNOWN_METHOD,
                    "Invalid method name: '" + methodName + "'", null);
            return Futures.immediateFuture(true);
        }

        switch (message.type) {
        case TMessageType.CALL:
        case TMessageType.ONEWAY:
            // Ideally we'd check the message type here to make the presence/absence of
            // the "oneway" keyword annotating the method matches the message type.
            // Unfortunately most clients send both one-way and two-way messages as CALL
            // message type instead of using ONEWAY message type, and servers ignore the
            // difference.
            break;

        default:
            TProtocolUtil.skip(in, TType.STRUCT);
            createAndWriteApplicationException(out, requestContext, methodName, sequenceId,
                    INVALID_MESSAGE_TYPE, "Received invalid message type " + message.type + " from client",
                    null);
            return Futures.immediateFuture(true);
        }

        // invoke method
        final ContextChain context = new ContextChain(eventHandlers, method.getQualifiedName(), requestContext);
        ListenableFuture<Boolean> processResult = method.process(in, out, sequenceId, context);

        Futures.addCallback(processResult, new FutureCallback<Boolean>() {
            @Override
            public void onSuccess(Boolean result) {
                context.done();
                resultFuture.set(result);
            }

            @Override
            public void onFailure(Throwable t) {
                LOG.error(t, "Failed to process method [" + method.getName() + "] of service ["
                        + method.getServiceName() + "]");
                context.done();
                resultFuture.setException(t);
            }
        });

        return resultFuture;
    } catch (TApplicationException e) {
        // If TApplicationException was thrown send it to the client.
        // This could happen if for example, some of event handlers method threw an exception.
        writeApplicationException(out, requestContext, methodName, sequenceId, e);
        return Futures.immediateFuture(true);
    } catch (Exception e) {
        return Futures.immediateFailedFuture(e);
    }
}

From source file:com.flipkart.phantom.runtime.impl.server.netty.decoder.thrift.ThriftBufferDecoder.java

License:Apache License

/**
 * Interface method implementation. Tries to read the Thrift protocol message. Returns null if unsuccessful, else returns the read byte array. Also
 * resets the {@link ChannelBuffer} reader index to nullify the effect of the read operation.
 * @see org.jboss.netty.handler.codec.replay.ReplayingDecoder#decode(org.jboss.netty.channel.ChannelHandlerContext, org.jboss.netty.channel.Channel, org.jboss.netty.buffer.ChannelBuffer, java.lang.Enum)
 *///  w  w  w .  jav  a  2s.com
protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer, VoidEnum voidEnum)
        throws Exception {
    ThriftNettyChannelBuffer ttransport = new ThriftNettyChannelBuffer(buffer, null); // we dont use the output buffer, so null is fine
    TProtocol iprot = this.protocolFactory.getProtocol(ttransport);
    int beginIndex = buffer.readerIndex();
    buffer.markReaderIndex();

    iprot.readMessageBegin();
    TProtocolUtil.skip(iprot, TType.STRUCT);
    iprot.readMessageEnd();

    int endIndex = buffer.readerIndex();
    buffer.resetReaderIndex();

    return buffer.readSlice(endIndex - beginIndex);
}