Example usage for org.apache.thrift.protocol TMessageType REPLY

List of usage examples for org.apache.thrift.protocol TMessageType REPLY

Introduction

In this page you can find the example usage for org.apache.thrift.protocol TMessageType REPLY.

Prototype

byte REPLY

To view the source code for org.apache.thrift.protocol TMessageType REPLY.

Click Source Link

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  . j  ava2  s . com

    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.swift.ThriftCodec.java

License:Open Source License

private void encodeResponse(Channel channel, ChannelBuffer buffer, Response response) throws IOException {

    RpcResult result = (RpcResult) response.getResult();

    RequestData rd = cachedRequest.get((int) response.getId());
    String service = channel.getUrl().getParameter(ThriftConstants.CLASS_NAME_GENERATOR_KEY,
            ThriftClassNameGenerator.NAME);
    ClassNameGenerator generator = ExtensionLoader.getExtensionLoader(ClassNameGenerator.class)
            .getExtension(service);/*from w w  w. j  a va  2  s . c o  m*/
    String resultClassName = generator.generateResultClassName(rd.serviceName, rd.methodName);

    if (StringUtils.isEmpty(resultClassName)) {
        throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, new StringBuilder(32)
                .append("Could not encode response, the specified interface may be incorrect.").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 resultObj;

    try {
        resultObj = (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);
    }

    TApplicationException applicationException = null;
    TMessage message;

    if (result.hasException()) {
        Throwable throwable = result.getException();
        int index = 1;
        boolean found = false;
        while (true) {
            TFieldIdEnum fieldIdEnum = resultObj.fieldForId(index++);
            if (fieldIdEnum == null) {
                break;
            }
            String fieldName = fieldIdEnum.getFieldName();
            String getMethodName = ThriftUtils.generateGetMethodName(fieldName);
            String setMethodName = ThriftUtils.generateSetMethodName(fieldName);
            Method getMethod;
            Method setMethod;
            try {
                getMethod = clazz.getMethod(getMethodName);
                if (getMethod.getReturnType().equals(throwable.getClass())) {
                    found = true;
                    setMethod = clazz.getMethod(setMethodName, throwable.getClass());
                    setMethod.invoke(resultObj, throwable);
                }
            } catch (NoSuchMethodException e) {
                throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
            } catch (InvocationTargetException e) {
                throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
            } catch (IllegalAccessException e) {
                throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
            }
        }

        if (!found) {
            applicationException = new TApplicationException(throwable.getMessage());
        }

    } else {
        Object realResult = result.getResult();
        // result field id is 0
        String fieldName = resultObj.fieldForId(0).getFieldName();
        String setMethodName = ThriftUtils.generateSetMethodName(fieldName);
        String getMethodName = ThriftUtils.generateGetMethodName(fieldName);
        Method getMethod;
        Method setMethod;
        try {
            getMethod = clazz.getMethod(getMethodName);
            setMethod = clazz.getMethod(setMethodName, getMethod.getReturnType());
            setMethod.invoke(resultObj, realResult);
        } catch (NoSuchMethodException e) {
            throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
        } catch (InvocationTargetException e) {
            throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
        } catch (IllegalAccessException e) {
            throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
        }

    }

    if (applicationException != null) {
        message = new TMessage(rd.methodName, TMessageType.EXCEPTION, rd.id);
    } else {
        message = new TMessage(rd.methodName, TMessageType.REPLY, rd.id);
    }

    RandomAccessByteArrayOutputStream bos = new RandomAccessByteArrayOutputStream(1024);

    TIOStreamTransport transport = new TIOStreamTransport(bos);

    TBinaryProtocol protocol = new TBinaryProtocol(transport);

    try {
        protocol.writeMessageBegin(message);
        switch (message.type) {
        case TMessageType.EXCEPTION:
            applicationException.write(protocol);
            break;
        case TMessageType.REPLY:
            resultObj.write(protocol);
            break;
        }
        protocol.writeMessageEnd();
        protocol.getTransport().flush();
    } catch (TException e) {
        throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
    }

    buffer.writeBytes(bos.toByteArray());

}

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

License:Open Source License

private Object decode(TProtocol protocol) throws IOException {

    // version// ww  w .  ja  v  a 2  s.  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.alibaba.dubbo.rpc.protocol.thrift.ThriftCodec.java

License:Open Source License

private void encodeResponse(Channel channel, OutputStream output, Response response) throws IOException {

    RpcResult result = (RpcResult) response.getResult();

    RequestData rd = cachedRequest.get(response.getId());

    String resultClassName = ExtensionLoader
            .getExtensionLoader(ClassNameGenerator.class).getExtension(channel.getUrl()
                    .getParameter(ThriftConstants.CLASS_NAME_GENERATOR_KEY, ThriftClassNameGenerator.NAME))
            .generateResultClassName(rd.serviceName, rd.methodName);

    if (StringUtils.isEmpty(resultClassName)) {
        throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, new StringBuilder(32)
                .append("Could not encode response, the specified interface may be incorrect.").toString());
    }/*from   www.j  a  v a 2  s  .c o  m*/

    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 resultObj;

    try {
        resultObj = (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);
    }

    TApplicationException applicationException = null;
    TMessage message;

    if (result.hasException()) {
        Throwable throwable = result.getException();
        int index = 1;
        boolean found = false;
        while (true) {
            TFieldIdEnum fieldIdEnum = resultObj.fieldForId(index++);
            if (fieldIdEnum == null) {
                break;
            }
            String fieldName = fieldIdEnum.getFieldName();
            String getMethodName = ThriftUtils.generateGetMethodName(fieldName);
            String setMethodName = ThriftUtils.generateSetMethodName(fieldName);
            Method getMethod;
            Method setMethod;
            try {
                getMethod = clazz.getMethod(getMethodName);
                if (getMethod.getReturnType().equals(throwable.getClass())) {
                    found = true;
                    setMethod = clazz.getMethod(setMethodName, throwable.getClass());
                    setMethod.invoke(resultObj, throwable);
                }
            } catch (NoSuchMethodException e) {
                throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
            } catch (InvocationTargetException e) {
                throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
            } catch (IllegalAccessException e) {
                throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
            }
        }

        if (!found) {
            applicationException = new TApplicationException(throwable.getMessage());
        }

    } else {
        Object realResult = result.getResult();
        // result field id is 0
        String fieldName = resultObj.fieldForId(0).getFieldName();
        String setMethodName = ThriftUtils.generateSetMethodName(fieldName);
        String getMethodName = ThriftUtils.generateGetMethodName(fieldName);
        Method getMethod;
        Method setMethod;
        try {
            getMethod = clazz.getMethod(getMethodName);
            setMethod = clazz.getMethod(setMethodName, getMethod.getReturnType());
            setMethod.invoke(resultObj, realResult);
        } catch (NoSuchMethodException e) {
            throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
        } catch (InvocationTargetException e) {
            throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
        } catch (IllegalAccessException e) {
            throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
        }

    }

    if (applicationException != null) {
        message = new TMessage(rd.methodName, TMessageType.EXCEPTION, rd.id);
    } else {
        message = new TMessage(rd.methodName, TMessageType.REPLY, rd.id);
    }

    RandomAccessByteArrayOutputStream bos = new RandomAccessByteArrayOutputStream(1024);

    TIOStreamTransport transport = new TIOStreamTransport(bos);

    TBinaryProtocol protocol = new TBinaryProtocol(transport);

    int messageLength;
    int headerLength;

    byte[] bytes = new byte[4];
    try {
        // magic
        protocol.writeI16(MAGIC);
        // message length
        protocol.writeI32(Integer.MAX_VALUE);
        // message header length
        protocol.writeI16(Short.MAX_VALUE);
        // version
        protocol.writeByte(VERSION);
        // service name
        protocol.writeString(rd.serviceName);
        // id
        protocol.writeI64(response.getId());
        protocol.getTransport().flush();
        headerLength = bos.size();

        // message
        protocol.writeMessageBegin(message);
        switch (message.type) {
        case TMessageType.EXCEPTION:
            applicationException.write(protocol);
            break;
        case TMessageType.REPLY:
            resultObj.write(protocol);
            break;
        }
        protocol.writeMessageEnd();
        protocol.getTransport().flush();
        int oldIndex = messageLength = bos.size();

        try {
            TFramedTransport.encodeFrameSize(messageLength, bytes);
            bos.setWriteIndex(MESSAGE_LENGTH_INDEX);
            protocol.writeI32(messageLength);
            bos.setWriteIndex(MESSAGE_HEADER_LENGTH_INDEX);
            protocol.writeI16((short) (0xffff & headerLength));
        } finally {
            bos.setWriteIndex(oldIndex);
        }

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

    output.write(bytes);
    bos.writeTo(output);
    output.flush();

}

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

License:Open Source License

@Test
public void testDecodeReplyResponse() throws Exception {

    URL url = URL.valueOf(ThriftProtocol.NAME + "://127.0.0.1:40880/" + Demo.Iface.class.getName());

    Channel channel = new MockedChannel(url);

    RandomAccessByteArrayOutputStream bos = new RandomAccessByteArrayOutputStream(128);

    Request request = createRequest();

    DefaultFuture future = new DefaultFuture(channel, request, 10);

    TMessage message = new TMessage("echoString", TMessageType.REPLY, ThriftCodec.getSeqId());

    Demo.echoString_result methodResult = new Demo.echoString_result();

    methodResult.success = "Hello, World!";

    TTransport transport = new TIOStreamTransport(bos);

    TBinaryProtocol protocol = new TBinaryProtocol(transport);

    int messageLength, headerLength;
    // prepare/*from  w  w  w  . j a va 2 s.com*/
    protocol.writeI16(ThriftCodec.MAGIC);
    protocol.writeI32(Integer.MAX_VALUE);
    protocol.writeI16(Short.MAX_VALUE);
    protocol.writeByte(ThriftCodec.VERSION);
    protocol.writeString(Demo.Iface.class.getName());
    protocol.writeI64(request.getId());
    protocol.getTransport().flush();
    headerLength = bos.size();

    protocol.writeMessageBegin(message);
    methodResult.write(protocol);
    protocol.writeMessageEnd();
    protocol.getTransport().flush();
    int oldIndex = messageLength = bos.size();

    try {
        bos.setWriteIndex(ThriftCodec.MESSAGE_LENGTH_INDEX);
        protocol.writeI32(messageLength);
        bos.setWriteIndex(ThriftCodec.MESSAGE_HEADER_LENGTH_INDEX);
        protocol.writeI16((short) (0xffff & headerLength));
    } finally {
        bos.setWriteIndex(oldIndex);
    }
    // prepare

    byte[] buf = new byte[4 + bos.size()];
    System.arraycopy(bos.toByteArray(), 0, buf, 4, bos.size());

    ByteArrayInputStream bis = new ByteArrayInputStream(buf);

    Object obj = codec.decode((Channel) null, bis);

    Assert.assertNotNull(obj);

    Assert.assertEquals(true, obj instanceof Response);

    Response response = (Response) obj;

    Assert.assertEquals(request.getId(), response.getId());

    Assert.assertTrue(response.getResult() instanceof RpcResult);

    RpcResult result = (RpcResult) response.getResult();

    Assert.assertTrue(result.getResult() instanceof String);

    Assert.assertEquals(methodResult.success, result.getResult());

}

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

License:Open Source License

@Test
public void testEncodeReplyResponse() throws Exception {

    URL url = URL.valueOf(ThriftProtocol.NAME + "://127.0.0.1:40880/" + Demo.Iface.class.getName());

    Channel channel = new MockedChannel(url);

    Request request = createRequest();

    RpcResult rpcResult = new RpcResult();
    rpcResult.setResult("Hello, World!");

    Response response = new Response();
    response.setResult(rpcResult);/*  ww w.ja  va  2s  .  c  o m*/
    response.setId(request.getId());
    RandomAccessByteArrayOutputStream bos = new RandomAccessByteArrayOutputStream(1024);

    ThriftCodec.RequestData rd = ThriftCodec.RequestData.create(ThriftCodec.getSeqId(),
            Demo.Iface.class.getName(), "echoString");
    ThriftCodec.cachedRequest.putIfAbsent(request.getId(), rd);
    codec.encode(channel, bos, response);

    byte[] buf = new byte[bos.size() - 4];
    System.arraycopy(bos.toByteArray(), 4, buf, 0, bos.size() - 4);

    ByteArrayInputStream bis = new ByteArrayInputStream(buf);

    if (bis.markSupported()) {
        bis.mark(0);
    }

    TIOStreamTransport transport = new TIOStreamTransport(bis);
    TBinaryProtocol protocol = new TBinaryProtocol(transport);

    Assert.assertEquals(ThriftCodec.MAGIC, protocol.readI16());
    Assert.assertEquals(protocol.readI32() + 4, bos.toByteArray().length);
    int headerLength = protocol.readI16();

    Assert.assertEquals(ThriftCodec.VERSION, protocol.readByte());
    Assert.assertEquals(Demo.Iface.class.getName(), protocol.readString());
    Assert.assertEquals(request.getId(), protocol.readI64());

    if (bis.markSupported()) {
        bis.reset();
        bis.skip(headerLength);
    }

    TMessage message = protocol.readMessageBegin();
    Assert.assertEquals("echoString", message.name);
    Assert.assertEquals(TMessageType.REPLY, message.type);
    Assert.assertEquals(ThriftCodec.getSeqId(), message.seqid);
    Demo.echoString_result result = new Demo.echoString_result();
    result.read(protocol);
    protocol.readMessageEnd();

    Assert.assertEquals(rpcResult.getResult(), result.getSuccess());
}

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

License:Apache License

public ListenableFuture<Boolean> process(TProtocol in, final TProtocol out, final int sequenceId,
        final ContextChain contextChain) throws Exception {
    // read args//from   w w  w.j av  a2 s . c o m
    contextChain.preRead();
    Object[] args = readArguments(in);
    contextChain.postRead(args);
    final RequestContext requestContext = RequestContexts.getCurrentContext();

    in.readMessageEnd();

    // invoke method
    final ListenableFuture<?> invokeFuture = invokeMethod(args);
    final SettableFuture<Boolean> resultFuture = SettableFuture.create();

    Futures.addCallback(invokeFuture, new FutureCallback<Object>() {
        @Override
        public void onSuccess(Object result) {
            if (oneway) {
                resultFuture.set(true);
            } else {
                RequestContext oldRequestContext = RequestContexts.getCurrentContext();
                RequestContexts.setCurrentContext(requestContext);

                // write success reply
                try {
                    contextChain.preWrite(result);

                    writeResponse(out, sequenceId, TMessageType.REPLY, "success", (short) 0, successCodec,
                            result);

                    contextChain.postWrite(result);

                    resultFuture.set(true);
                } catch (Exception e) {
                    // An exception occurred trying to serialize a return value onto the output protocol
                    resultFuture.setException(e);
                } finally {
                    RequestContexts.setCurrentContext(oldRequestContext);
                }
            }
        }

        @Override
        public void onFailure(Throwable t) {
            RequestContext oldRequestContext = RequestContexts.getCurrentContext();
            RequestContexts.setCurrentContext(requestContext);

            try {
                contextChain.preWriteException(t);
                if (!oneway) {
                    ExceptionProcessor exceptionCodec = exceptionCodecs.get(t.getClass());

                    if (exceptionCodec == null) {
                        // In case the method throws a subtype of one of its declared
                        // exceptions, exact lookup will fail. We need to simulate it.
                        // (This isn't a problem for normal returns because there the
                        // output codec is decided in advance.)
                        for (Map.Entry<Class<?>, ExceptionProcessor> entry : exceptionCodecs.entrySet()) {
                            if (entry.getKey().isAssignableFrom(t.getClass())) {
                                exceptionCodec = entry.getValue();
                                break;
                            }
                        }
                    }

                    if (exceptionCodec != null) {
                        contextChain.declaredUserException(t, exceptionCodec.getCodec());
                        // write expected exception response
                        writeResponse(out, sequenceId, TMessageType.REPLY, "exception", exceptionCodec.getId(),
                                exceptionCodec.getCodec(), t);
                        contextChain.postWriteException(t);
                    } else {
                        contextChain.undeclaredUserException(t);
                        // unexpected exception
                        TApplicationException applicationException = ThriftServiceProcessor
                                .createAndWriteApplicationException(out, requestContext, method.getName(),
                                        sequenceId, INTERNAL_ERROR,
                                        "Internal error processing " + method.getName() + ": " + t.getMessage(),
                                        t);

                        contextChain.postWriteException(applicationException);
                    }
                }

                resultFuture.set(true);
            } catch (Exception e) {
                // An exception occurred trying to serialize an exception onto the output protocol
                resultFuture.setException(e);
            } finally {
                RequestContexts.setCurrentContext(oldRequestContext);
            }
        }
    });

    return resultFuture;
}

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

License:Apache License

@Test(timeout = 10000)
public void testMessageLogsForCall() throws Exception {
    HelloService.Iface client = Clients.newClient(clientFactory(), getURI(Handlers.HELLO),
            Handlers.HELLO.iface(), clientOptions);
    recordMessageLogs = true;/* w  ww.ja v a2s. com*/
    client.hello("trustin");

    final RequestLog log = requestLogs.take();

    assertThat(log.requestEnvelope()).isInstanceOf(HttpHeaders.class);
    assertThat(log.requestContent()).isInstanceOf(RpcRequest.class);
    assertThat(log.rawRequestContent()).isInstanceOf(ThriftCall.class);

    final RpcRequest request = (RpcRequest) log.requestContent();
    assertThat(request.serviceType()).isEqualTo(HelloService.Iface.class);
    assertThat(request.method()).isEqualTo("hello");
    assertThat(request.params()).containsExactly("trustin");

    final ThriftCall rawRequest = (ThriftCall) log.rawRequestContent();
    assertThat(rawRequest.header().type).isEqualTo(TMessageType.CALL);
    assertThat(rawRequest.header().name).isEqualTo("hello");
    assertThat(rawRequest.args()).isInstanceOf(HelloService.hello_args.class);
    assertThat(((HelloService.hello_args) rawRequest.args()).getName()).isEqualTo("trustin");

    assertThat(log.responseEnvelope()).isInstanceOf(HttpHeaders.class);
    assertThat(log.responseContent()).isInstanceOf(RpcResponse.class);
    assertThat(log.rawResponseContent()).isInstanceOf(ThriftReply.class);

    final RpcResponse response = (RpcResponse) log.responseContent();
    assertThat(response.get()).isEqualTo("Hello, trustin!");

    final ThriftReply rawResponse = (ThriftReply) log.rawResponseContent();
    assertThat(rawResponse.header().type).isEqualTo(TMessageType.REPLY);
    assertThat(rawResponse.header().name).isEqualTo("hello");
    assertThat(rawResponse.result()).isInstanceOf(HelloService.hello_result.class);
    assertThat(((HelloService.hello_result) rawResponse.result()).getSuccess()).isEqualTo("Hello, trustin!");
}

From source file:com.linecorp.armeria.common.thrift.ApacheThriftMessage.java

License:Apache License

static String typeStr(byte type) {
    switch (type) {
    case TMessageType.CALL:
        return "CALL";
    case TMessageType.ONEWAY:
        return "ONEWAY";
    case TMessageType.REPLY:
        return "REPLY";
    case TMessageType.EXCEPTION:
        return "EXCEPTION";
    default:// w ww.ja  v a 2 s .com
        return "UNKNOWN(" + (type & 0xFF) + ')';
    }
}

From source file:com.linecorp.armeria.common.thrift.ApacheThriftReply.java

License:Apache License

/**
 * Creates a new instance that contains a Thrift {@link TMessageType#REPLY} message.
 *///  w w w.j a va  2s . co m
public ApacheThriftReply(TMessage header, TBase<?, ?> result) {
    super(header);
    if (header.type != TMessageType.REPLY) {
        throw new IllegalArgumentException("header.type: " + typeStr(header.type) + " (expected: REPLY)");
    }

    this.result = requireNonNull(result, "result");
    exception = null;
}