Example usage for org.apache.thrift TFieldIdEnum getFieldName

List of usage examples for org.apache.thrift TFieldIdEnum getFieldName

Introduction

In this page you can find the example usage for org.apache.thrift TFieldIdEnum getFieldName.

Prototype

public String getFieldName();

Source Link

Document

Get the field's name, exactly as in the IDL.

Usage

From source file:cereal.impl.ThriftStructMapping.java

License:Apache License

@Override
public List<Field> getFields(E obj) {
    checkNotNull(obj, "The struct was null");

    List<Field> fields;
    try {//from  w ww . j a  v  a  2  s . co  m
        @SuppressWarnings("rawtypes")
        Class<? extends TBase> tbaseClz = obj.getClass();
        if (null == getFieldValue) {
            synchronized (this) {
                if (null == getFieldValue) {
                    Class<?> fieldsClz = Class.forName(obj.getClass().getName() + "$_Fields");
                    getFieldValue = tbaseClz.getMethod("getFieldValue", fieldsClz);
                    isSet = tbaseClz.getMethod("isSet", fieldsClz);
                }
            }
        }

        Map<? extends TFieldIdEnum, FieldMetaData> thriftFields = FieldMetaData.getStructMetaDataMap(tbaseClz);
        fields = new ArrayList<>();

        for (Entry<? extends TFieldIdEnum, FieldMetaData> entry : thriftFields.entrySet()) {
            TFieldIdEnum field = entry.getKey();
            FieldMetaData fMetaData = entry.getValue();
            if ((boolean) isSet.invoke(obj, field)) {
                Object value = getFieldValue.invoke(obj, field);
                FieldValueMetaData fvMetaData = fMetaData.valueMetaData;
                switch (fvMetaData.type) {
                case TType.BOOL:
                    Boolean booleanVal = (Boolean) value;
                    fields.add(new FieldImpl(text(fMetaData.fieldName), getGrouping(fMetaData),
                            getVisibility(fMetaData), value(booleanVal.toString())));
                    break;
                case TType.BYTE:
                    Byte byteVal = (Byte) value;
                    fields.add(new FieldImpl(text(fMetaData.fieldName), getGrouping(fMetaData),
                            getVisibility(fMetaData), value(byteVal.toString())));
                    break;
                case TType.DOUBLE:
                    Double dblVal = (Double) value;
                    fields.add(new FieldImpl(text(fMetaData.fieldName), getGrouping(fMetaData),
                            getVisibility(fMetaData), value(dblVal.toString())));
                    break;
                case TType.I16:
                    Short shortVal = (Short) value;
                    fields.add(new FieldImpl(text(fMetaData.fieldName), getGrouping(fMetaData),
                            getVisibility(fMetaData), value(shortVal.toString())));
                    break;
                case TType.I32:
                    Integer intVal = (Integer) value;
                    fields.add(new FieldImpl(text(fMetaData.fieldName), getGrouping(fMetaData),
                            getVisibility(fMetaData), value(intVal.toString())));
                    break;
                case TType.I64:
                    Long longVal = (Long) value;
                    fields.add(new FieldImpl(text(fMetaData.fieldName), getGrouping(fMetaData),
                            getVisibility(fMetaData), value(longVal.toString())));
                    break;
                case TType.STRING:
                    byte[] bytes;
                    if (fvMetaData.isBinary()) {
                        bytes = (byte[]) value;
                    } else {
                        String strVal = (String) value;
                        bytes = strVal.getBytes(UTF_8);
                    }
                    fields.add(new FieldImpl(text(fMetaData.fieldName), getGrouping(fMetaData),
                            getVisibility(fMetaData), new Value(bytes)));
                    break;
                default:
                    log.warn("Ignoring field: {}", field.getFieldName());
                    break;
                }
            }
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    return fields;
}

From source file:cereal.impl.ThriftStructMapping.java

License:Apache License

@Override
public void update(Iterable<Entry<Key, Value>> iter, InstanceOrBuilder<E> instOrBuilder) {
    checkNotNull(iter, "Iterator is null");
    checkNotNull(instOrBuilder, "InstOrBuilder is null");
    checkArgument(Type.INSTANCE == instOrBuilder.getType(), "Expected INSTANCE in InstanceOrBuilder");

    try {//from www. j a v a  2 s. c om
        @SuppressWarnings("rawtypes")
        Class<? extends TBase> tbaseClz = instOrBuilder.getWrappedClass();
        if (null == setFieldValue) {
            synchronized (this) {
                if (null == setFieldValue) {
                    Class<?> fieldsClz = Class.forName(instOrBuilder.getWrappedClass().getName() + "$_Fields");
                    setFieldValue = tbaseClz.getMethod("setFieldValue", fieldsClz, Object.class);
                }
            }
        }

        for (Entry<Key, Value> entry : iter) {
            String fieldName = entry.getKey().getColumnQualifier().toString();
            Map<? extends TFieldIdEnum, FieldMetaData> thriftFields = FieldMetaData
                    .getStructMetaDataMap(tbaseClz);
            for (Entry<? extends TFieldIdEnum, FieldMetaData> fieldEntry : thriftFields.entrySet()) {
                TFieldIdEnum fieldId = fieldEntry.getKey();
                if (fieldName.equals(fieldId.getFieldName())) {
                    FieldValueMetaData fvMetaData = fieldEntry.getValue().valueMetaData;
                    Value v = entry.getValue();
                    Object obj = instOrBuilder.get();
                    switch (fvMetaData.type) {
                    case TType.BOOL:
                        Boolean booleanVal = Boolean.parseBoolean(v.toString());
                        setFieldValue.invoke(obj, fieldId, booleanVal);
                        break;
                    case TType.BYTE:
                        Byte byteVal = Byte.parseByte(v.toString());
                        setFieldValue.invoke(obj, fieldId, byteVal);
                        break;
                    case TType.DOUBLE:
                        Double dblVal = Double.parseDouble(v.toString());
                        setFieldValue.invoke(obj, fieldId, dblVal);
                        break;
                    case TType.I16:
                        Short shortVal = Short.parseShort(v.toString());
                        setFieldValue.invoke(obj, fieldId, shortVal);
                        break;
                    case TType.I32:
                        Integer intVal = Integer.parseInt(v.toString());
                        setFieldValue.invoke(obj, fieldId, intVal);
                        break;
                    case TType.I64:
                        Long longVal = Long.parseLong(v.toString());
                        setFieldValue.invoke(obj, fieldId, longVal);
                        break;
                    case TType.STRING:
                        if (fvMetaData.isBinary()) {
                            setFieldValue.invoke(obj, fieldId, ByteBuffer.wrap(v.get()));
                        } else {
                            String strVal = v.toString();
                            setFieldValue.invoke(obj, fieldId, strVal);
                        }
                        break;
                    default:
                        log.warn("Ignoring field: {}", fieldName);
                        break;
                    }
                }
            }
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

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;/*  ww  w.j  av  a 2  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 encodeRequest(Channel channel, ChannelBuffer buffer, Request request) throws IOException {

    RpcInvocation inv = (RpcInvocation) request.getData();

    int seqId = new Long(request.getId()).intValue();

    String serviceName = inv.getAttachment(Constants.INTERFACE_KEY);

    if (StringUtils.isEmpty(serviceName)) {
        throw new IllegalArgumentException(
                new StringBuilder(32).append("Could not find service name in attachment with key ")
                        .append(Constants.INTERFACE_KEY).toString());
    }//from  w w  w.jav a  2s. c o m

    TMessage message = new TMessage(inv.getMethodName(), TMessageType.CALL, seqId);

    ExtensionLoader<ClassNameGenerator> loader = ExtensionLoader.getExtensionLoader(ClassNameGenerator.class);
    String name = channel.getUrl().getParameter(ThriftConstants.CLASS_NAME_GENERATOR_KEY,
            ThriftClassNameGenerator.NAME);
    ClassNameGenerator generator = loader.getExtension(name);
    String methodName = inv.getMethodName();
    String methodArgs = generator.generateArgsClassName(serviceName, methodName);

    if (StringUtils.isEmpty(methodArgs)) {
        throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, new StringBuilder(32)
                .append("Could not encode request, the specified interface may be incorrect.").toString());
    }

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

    if (clazz == null) {

        try {

            clazz = ClassHelper.forNameWithThreadContextClassLoader(methodArgs);

            cachedClass.putIfAbsent(methodArgs, 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);
    }

    for (int i = 0; i < inv.getArguments().length; i++) {

        Object obj = inv.getArguments()[i];

        if (obj == null) {
            continue;
        }

        TFieldIdEnum field = args.fieldForId(i + 1);

        String setMethodName = ThriftUtils.generateSetMethodName(field.getFieldName());

        Method method;

        try {
            method = clazz.getMethod(setMethodName, inv.getParameterTypes()[i]);
        } catch (NoSuchMethodException e) {
            throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
        }

        try {
            method.invoke(args, obj);
        } catch (IllegalAccessException e) {
            throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
        } catch (InvocationTargetException e) {
            throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
        }

    }

    RandomAccessByteArrayOutputStream bos = new RandomAccessByteArrayOutputStream(1024);

    TIOStreamTransport transport = new TIOStreamTransport(bos);

    TBinaryProtocol protocol = new TBinaryProtocol(transport);

    try {
        protocol.writeMessageBegin(message);
        args.write(protocol);
        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.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);/* w  w w  . jav a2  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//from  w  ww  . ja va2 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 encodeRequest(Channel channel, OutputStream output, Request request) throws IOException {

    RpcInvocation inv = (RpcInvocation) request.getData();

    int seqId = nextSeqId();

    String serviceName = inv.getAttachment(Constants.INTERFACE_KEY);

    if (StringUtils.isEmpty(serviceName)) {
        throw new IllegalArgumentException(
                new StringBuilder(32).append("Could not find service name in attachment with key ")
                        .append(Constants.INTERFACE_KEY).toString());
    }/* ww  w .  j a v  a  2  s.co m*/

    TMessage message = new TMessage(inv.getMethodName(), TMessageType.CALL, seqId);

    String methodArgs = ExtensionLoader
            .getExtensionLoader(ClassNameGenerator.class).getExtension(channel.getUrl()
                    .getParameter(ThriftConstants.CLASS_NAME_GENERATOR_KEY, ThriftClassNameGenerator.NAME))
            .generateArgsClassName(serviceName, inv.getMethodName());

    if (StringUtils.isEmpty(methodArgs)) {
        throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, new StringBuilder(32)
                .append("Could not encode request, the specified interface may be incorrect.").toString());
    }

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

    if (clazz == null) {

        try {

            clazz = ClassHelper.forNameWithThreadContextClassLoader(methodArgs);

            cachedClass.putIfAbsent(methodArgs, 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);
    }

    for (int i = 0; i < inv.getArguments().length; i++) {

        Object obj = inv.getArguments()[i];

        if (obj == null) {
            continue;
        }

        TFieldIdEnum field = args.fieldForId(i + 1);

        String setMethodName = ThriftUtils.generateSetMethodName(field.getFieldName());

        Method method;

        try {
            method = clazz.getMethod(setMethodName, inv.getParameterTypes()[i]);
        } catch (NoSuchMethodException e) {
            throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
        }

        try {
            method.invoke(args, obj);
        } catch (IllegalAccessException e) {
            throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
        } catch (InvocationTargetException e) {
            throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e);
        }

    }

    RandomAccessByteArrayOutputStream bos = new RandomAccessByteArrayOutputStream(1024);

    TIOStreamTransport transport = new TIOStreamTransport(bos);

    TBinaryProtocol protocol = new TBinaryProtocol(transport);

    int headerLength, messageLength;

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

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

        // fill in message length and header length
        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.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  w w w  .j  a  v a 2 s  . co  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.jstorm.utils.JStormUtils.java

License:Apache License

public static Map<String, Object> thriftToMap(org.apache.thrift.TBase thriftObj) {
    Map<String, Object> ret = new HashMap<String, Object>();

    int i = 1;/*from   w  w  w.  j  a  va 2 s . c  o m*/
    TFieldIdEnum field = thriftObj.fieldForId(i);
    while (field != null) {
        if (thriftObj.isSet(field)) {
            Object obj = thriftObj.getFieldValue(field);
            ret.put(field.getFieldName(), thriftToObject(obj));

        }
        field = thriftObj.fieldForId(++i);
    }

    return ret;
}

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

License:Apache License

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override/*w  w  w.java  2 s  .  c o m*/
public <T> T decodeResponse(ServiceInvocationContext ctx, ByteBuf content, Object originalResponse)
        throws Exception {
    if (content == null) {
        return null;
    }

    if (!content.isReadable()) {
        ThriftMethod thriftMethod = getThriftMethod(ctx);
        if (thriftMethod != null && thriftMethod.isOneWay()) {
            return null;
        }
        throw new TApplicationException(TApplicationException.MISSING_RESULT, ctx.toString());
    }

    TByteBufInputTransport inputTransport = new TByteBufInputTransport(content);
    TProtocol inputProtocol = protocolFactory.getProtocol(inputTransport);
    TMessage msg = inputProtocol.readMessageBegin();
    if (msg.type == TMessageType.EXCEPTION) {
        TApplicationException ex = TApplicationException.read(inputProtocol);
        inputProtocol.readMessageEnd();
        throw ex;
    }
    ThriftMethod method = methodMap.get(msg.name);
    if (method == null) {
        throw new TApplicationException(TApplicationException.WRONG_METHOD_NAME, msg.name);
    }
    TBase<? extends TBase, TFieldIdEnum> result = method.createResult();
    result.read(inputProtocol);
    inputProtocol.readMessageEnd();

    for (TFieldIdEnum fieldIdEnum : method.getExceptionFields()) {
        if (result.isSet(fieldIdEnum)) {
            throw (TException) result.getFieldValue(fieldIdEnum);
        }
    }

    TFieldIdEnum successField = method.successField();
    if (successField == null) { //void method
        return null;
    }
    if (result.isSet(successField)) {
        return (T) result.getFieldValue(successField);
    }

    throw new TApplicationException(TApplicationException.MISSING_RESULT,
            result.getClass().getName() + '.' + successField.getFieldName());
}