org.apache.thrift.TFieldIdEnum Java Examples

The following examples show how to use org.apache.thrift.TFieldIdEnum. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AuditableLogbackThriftLogger.java    From singer with Apache License 2.0 6 votes vote down vote up
public void init(Class<?> thriftClazz) {
  try {
    Map m = (Map) thriftClazz.getDeclaredField("metaDataMap").get(null);
    for (Object o : m.keySet()) {
      TFieldIdEnum tf = (TFieldIdEnum) o;
      if ("loggingAuditHeaders".equalsIgnoreCase(tf.getFieldName())) {
        this.loggingAuditHeadersField = tf;
        LOG.info("Found loggingAuditHeaders field for {}", thriftClazz.getName());
        break;
      }
    }
    if (this.loggingAuditHeadersField == null) {
      throw new NoSuchFieldException(
          "Cannot find loggingAuditHeaders field for " + thriftClazz.getName());
    }
  } catch (Exception e) {
    OpenTsdbMetricConverter.incr(AUDIT_THRIFT_LOGGER_ERROR_INIT, "topic=" + topic,
        "host=" + HOST_NAME);
    LOG.error("Init method cannot finish successfully due to {}", e.getMessage());
  }
}
 
Example #2
Source File: JStormUtils.java    From jstorm with Apache License 2.0 6 votes vote down vote up
public static Map<String, Object> thriftToMap(
        org.apache.thrift.TBase thriftObj) {
    Map<String, Object> ret = new HashMap<>();

    int i = 1;
    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;
}
 
Example #3
Source File: Consumers.java    From parquet-mr with Apache License 2.0 6 votes vote down vote up
/**
 * To consume a list of elements
 * @param c the class of the list content
 * @param consumer the consumer that will receive the list
 * @param <T> the type of the list content
 * @return a ListConsumer that can be passed to the DelegatingFieldConsumer
 */
public static <T extends TBase<T,? extends TFieldIdEnum>> ListConsumer listOf(Class<T> c, final Consumer<List<T>> consumer) {
  class ListConsumer implements Consumer<T> {
    List<T> list;
    @Override
    public void consume(T t) {
      list.add(t);
    }
  }
  final ListConsumer co = new ListConsumer();
  return new DelegatingListElementsConsumer(struct(c, co)) {
    @Override
    public void consumeList(TProtocol protocol,
        EventBasedThriftReader reader, TList tList) throws TException {
      co.list = new ArrayList<T>();
      super.consumeList(protocol, reader, tList);
      consumer.consume(co.list);
    }
  };
}
 
Example #4
Source File: Consumers.java    From parquet-format with Apache License 2.0 6 votes vote down vote up
/**
 * To consume a list of elements
 * @param c the type of the list content
 * @param consumer the consumer that will receive the list
 * @return a ListConsumer that can be passed to the DelegatingFieldConsumer
 */
public static <T extends TBase<T,? extends TFieldIdEnum>> ListConsumer listOf(Class<T> c, final Consumer<List<T>> consumer) {
  class ListConsumer implements Consumer<T> {
    List<T> list;
    @Override
    public void consume(T t) {
      list.add(t);
    }
  }
  final ListConsumer co = new ListConsumer();
  return new DelegatingListElementsConsumer(struct(c, co)) {
    @Override
    public void consumeList(TProtocol protocol,
        EventBasedThriftReader reader, TList tList) throws TException {
      co.list = new ArrayList<T>();
      super.consumeList(protocol, reader, tList);
      consumer.consume(co.list);
    }
  };
}
 
Example #5
Source File: ThriftFunction.java    From armeria with Apache License 2.0 6 votes vote down vote up
/**
 * Converts the specified {@code result} into a Java object.
 */
@Nullable
public Object getResult(TBase<?, ?> result) throws TException {
    for (TFieldIdEnum fieldIdEnum : exceptionFields()) {
        if (ThriftFieldAccess.isSet(result, fieldIdEnum)) {
            throw (TException) ThriftFieldAccess.get(result, fieldIdEnum);
        }
    }

    final TFieldIdEnum successField = successField();
    if (successField == null) { //void method
        return null;
    } else if (ThriftFieldAccess.isSet(result, successField)) {
        return ThriftFieldAccess.get(result, successField);
    } else {
        throw new TApplicationException(
                TApplicationException.MISSING_RESULT,
                result.getClass().getName() + '.' + successField.getFieldName());
    }
}
 
Example #6
Source File: THttpService.java    From armeria with Apache License 2.0 6 votes vote down vote up
private static RpcRequest toRpcRequest(Class<?> serviceType, String method, TBase<?, ?> thriftArgs) {
    requireNonNull(thriftArgs, "thriftArgs");

    // NB: The map returned by FieldMetaData.getStructMetaDataMap() is an EnumMap,
    //     so the parameter ordering is preserved correctly during iteration.
    final Set<? extends TFieldIdEnum> fields =
            FieldMetaData.getStructMetaDataMap(thriftArgs.getClass()).keySet();

    // Handle the case where the number of arguments is 0 or 1.
    final int numFields = fields.size();
    switch (numFields) {
        case 0:
            return RpcRequest.of(serviceType, method);
        case 1:
            return RpcRequest.of(serviceType, method,
                                 ThriftFieldAccess.get(thriftArgs, fields.iterator().next()));
    }

    // Handle the case where the number of arguments is greater than 1.
    final List<Object> list = new ArrayList<>(numFields);
    for (TFieldIdEnum field : fields) {
        list.add(ThriftFieldAccess.get(thriftArgs, field));
    }

    return RpcRequest.of(serviceType, method, list);
}
 
Example #7
Source File: ThriftIDLSerializer.java    From octo-rpc with Apache License 2.0 6 votes vote down vote up
private void serializeArguments(RpcInvocation rpcInvocation, TBinaryProtocol protocol) throws TException {
    String argsClassName = ThriftUtil.generateArgsClassName(
            rpcInvocation.getServiceInterface().getName(), rpcInvocation.getMethod().getName());
    TBase argsClassObj = getClazzInstance(argsClassName);

    if (rpcInvocation.getArguments() == null) {
        argsClassObj.write(protocol);
        return;
    }

    String argsFieldsClassName = ThriftUtil.generateIDLFieldsClassName(argsClassName);
    Class<?> argsFieldsClazz = getClazz(argsFieldsClassName);

    Object[] fieldEnums = argsFieldsClazz.getEnumConstants();
    if (fieldEnums == null && fieldEnums.length != rpcInvocation.getArguments().length) {
        throw new ProtocolException("argument num is " + rpcInvocation.getArguments().length + " is not match with fields in " + argsFieldsClassName);
    }
    for (int i = 0; i < fieldEnums.length; i++) {
        TFieldIdEnum fieldIdEnum = (TFieldIdEnum) fieldEnums[i];
        if (fieldIdEnum == null) {
            continue;
        }
        argsClassObj.setFieldValue(fieldIdEnum, rpcInvocation.getArguments()[i]);
    }
    argsClassObj.write(protocol);
}
 
Example #8
Source File: BaseArray.java    From nettythrift with Apache License 2.0 6 votes vote down vote up
/**
 * Struct use only.
 * 
 * @return
 */
public TField newField() {
	if (createIndex < obj.length()) {
		Map.Entry<TFieldIdEnum, FieldMetaData> entry = null;
		if (addStep == 2) {
			String fieldName = obj.getString(createIndex << 1);
			entry = elementMetas.get(fieldName);
			createIndex++;
		} else {
			int i = createIndex;
			Object o;
			while (i < obj.length() && ((o = obj.get(i)) == null || o == JSONObject.NULL)) {
				currentIndex();// array index: +1
				i++;
			}
			entry = elementMetaArr[i];
			createIndex = i + 1;
		}
		FieldMetaData fm = entry.getValue();
		prevFieldMetaData = fm;
		return new TField(fm.fieldName, fm.valueMetaData.type, entry.getKey().getThriftFieldId());
	}
	return null;
}
 
Example #9
Source File: BaseThriftLogger.java    From singer with Apache License 2.0 5 votes vote down vote up
/**
 * Messages to be consumed by Secor must have an i64 timestamp
 * as the first field.
 */
private boolean validateThriftMessageForSecor(TBase thriftMessage) {
  TFieldIdEnum fieldEnum = thriftMessage.fieldForId(1);
  if (fieldEnum == null) {
    return false;
  }
  if (!thriftMessage.isSet(fieldEnum)) {
    return false;
  }
  Object value = thriftMessage.getFieldValue(fieldEnum);
  if (value == null || value.getClass() != Long.class) {
    return false;
  }
  return true;
}
 
Example #10
Source File: GsonMessageBodyHandler.java    From attic-aurora with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({"unchecked", "rawtypes"})
private static TUnion<?, ?> createUnion(
    Class<?> unionType,
    TFieldIdEnum setField,
    Object fieldValue) throws IllegalAccessException, InstantiationException {

  TUnion union = (TUnion) unionType.newInstance();
  union.setFieldValue(setField, fieldValue);
  return union;
}
 
Example #11
Source File: ThriftIDLSerializer.java    From octo-rpc with Apache License 2.0 5 votes vote down vote up
private Object deserializeResult(TProtocol protocol, String ifaceName, String methodName) {
    String resultClassName = ThriftUtil.generateResultClassName(ifaceName, methodName);
    TBase resultClassObj = getClazzInstance(resultClassName);
    try {
        resultClassObj.read(protocol);
    } catch (TException e) {
        throw new ProtocolException("Thrift deserialize result failed.", e);
    }
    Object realResult = null;
    String resultFieldsClassName = ThriftUtil.generateIDLFieldsClassName(resultClassObj.getClass().getName());
    Class<?> resultFieldsClazz = getClazz(resultFieldsClassName);
    Object[] resultFieldsEnums = resultFieldsClazz.getEnumConstants();
    if (resultFieldsEnums == null) {
        return realResult;
    }
    // 避免基本类型默认值导致异常返回被忽略, 从后面开始获取值
    for (int i = resultFieldsEnums.length - 1; i >= 0; i--) {
        TFieldIdEnum fieldIdEnum = (TFieldIdEnum) resultFieldsEnums[i];
        if (fieldIdEnum == null) {
            continue;
        }
        Object fieldValue = resultClassObj.getFieldValue(fieldIdEnum);
        if (fieldValue != null) {
            if (BYTE_ARRAY_CLASS_NAME.equals(fieldValue.getClass().getName())) {
                fieldValue = ByteBuffer.wrap((byte[]) fieldValue);
            }
            realResult = fieldValue;
            break;
        }
    }
    return realResult;
}
 
Example #12
Source File: ThriftFunction.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the exception field of the specified {@code result} to the specified {@code cause}.
 */
public boolean setException(TBase<?, ?> result, Throwable cause) {
    final Class<?> causeType = cause.getClass();
    for (Entry<Class<Throwable>, TFieldIdEnum> e : exceptionFields.entrySet()) {
        if (e.getKey().isAssignableFrom(causeType)) {
            ThriftFieldAccess.set(result, e.getValue(), cause);
            return true;
        }
    }
    return false;
}
 
Example #13
Source File: ThriftFunction.java    From armeria with Apache License 2.0 5 votes vote down vote up
private static TFieldIdEnum[] getArgFields0(Type type, Class<?> funcClass, String methodName) {
    final String fieldIdEnumTypeName = typeName(type, funcClass, methodName, methodName + "_args$_Fields");
    try {
        final Class<?> fieldIdEnumType =
                Class.forName(fieldIdEnumTypeName, false, funcClass.getClassLoader());
        return (TFieldIdEnum[]) requireNonNull(fieldIdEnumType.getEnumConstants(),
                                               "field enum may not be empty.");
    } catch (Exception e) {
        throw new IllegalStateException("cannot determine the arg fields of method: " + methodName, e);
    }
}
 
Example #14
Source File: ThriftFieldAccess.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the value of the specified struct field.
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public static Object get(TBase<?, ?> struct, TFieldIdEnum field) {
    final Object value = ((TBase) struct).getFieldValue(field);
    if (value instanceof byte[]) {
        return ByteBuffer.wrap((byte[]) value);
    } else {
        return value;
    }
}
 
Example #15
Source File: ThriftIDLSerializer.java    From octo-rpc with Apache License 2.0 5 votes vote down vote up
private void deserializeArguments(String ifaceName, String methodName, TProtocol protocol, List<Object> arguments, List<Class<?>> parameterTypes) {
    String argsClassName = ThriftUtil.generateArgsClassName(
            ifaceName, methodName);
    TBase argsClassObj = getClazzInstance(argsClassName);
    try {
        argsClassObj.read(protocol);
    } catch (TException e) {
        throw new ProtocolException("Thrift deserialize arguments failed.", e);
    }

    String argsFieldsClassName = ThriftUtil.generateIDLFieldsClassName(argsClassName);
    Class<?> argsFieldsClazz = getClazz(argsFieldsClassName);

    if (argsFieldsClazz.getEnumConstants() == null) {
        return;
    }
    for (Object fieldEnum : argsFieldsClazz.getEnumConstants()) {
        TFieldIdEnum fieldIdEnum = (TFieldIdEnum) fieldEnum;
        if (fieldIdEnum == null) {
            continue;
        }
        Object argument = argsClassObj.getFieldValue(fieldIdEnum);
        String fieldName = fieldIdEnum.getFieldName();
        Method getMethod = ThriftUtil.obtainGetMethod(argsClassObj.getClass(), fieldName);
        if (BYTE_ARRAY_CLASS_NAME.equals(getMethod.getReturnType().getName())) {
            parameterTypes.add(ByteBuffer.class);
            arguments.add(ByteBuffer.wrap((byte[]) argument));
        } else {
            parameterTypes.add(getMethod.getReturnType());
            arguments.add(argument);
        }
    }
}
 
Example #16
Source File: StructContext.java    From armeria with Apache License 2.0 4 votes vote down vote up
/**
 * Compute a new field name map for the current thrift message
 * we are parsing.
 */
private Map<String, TField> computeFieldNameMap(Class<?> clazz) {
    final Map<String, TField> map = new HashMap<>();

    if (isTBase(clazz)) {
        // Get the metaDataMap for this Thrift class
        @SuppressWarnings("unchecked")
        final Map<? extends TFieldIdEnum, FieldMetaData> metaDataMap =
                FieldMetaData.getStructMetaDataMap((Class<? extends TBase<?, ?>>) clazz);

        for (Entry<? extends TFieldIdEnum, FieldMetaData> e : metaDataMap.entrySet()) {
            final String fieldName = e.getKey().getFieldName();
            final FieldMetaData metaData = e.getValue();

            final FieldValueMetaData elementMetaData;
            if (metaData.valueMetaData.isContainer()) {
                if (metaData.valueMetaData instanceof SetMetaData) {
                    elementMetaData = ((SetMetaData) metaData.valueMetaData).elemMetaData;
                } else if (metaData.valueMetaData instanceof ListMetaData) {
                    elementMetaData = ((ListMetaData) metaData.valueMetaData).elemMetaData;
                } else if (metaData.valueMetaData instanceof MapMetaData) {
                    elementMetaData = ((MapMetaData) metaData.valueMetaData).valueMetaData;
                } else {
                    // Unrecognized container type, but let's still continue processing without
                    // special enum support.
                    elementMetaData = metaData.valueMetaData;
                }
            } else {
                elementMetaData = metaData.valueMetaData;
            }

            if (elementMetaData instanceof EnumMetaData) {
                classMap.put(fieldName, ((EnumMetaData) elementMetaData).enumClass);
            } else if (elementMetaData instanceof StructMetaData) {
                classMap.put(fieldName, ((StructMetaData) elementMetaData).structClass);
            } else {
                // Workaround a bug where the generated 'FieldMetaData' does not provide
                // a fully qualified class name.
                final String typedefName = elementMetaData.getTypedefName();
                if (typedefName != null) {
                    final String fqcn = clazz.getPackage().getName() + '.' + typedefName;
                    Class<?> fieldClass = fieldMetaDataClassCache.get(fqcn);
                    if (fieldClass == null) {
                        fieldClass = fieldMetaDataClassCache.computeIfAbsent(fqcn, key -> {
                            try {
                                return Class.forName(key);
                            } catch (ClassNotFoundException ignored) {
                                return StructContext.class;
                            }
                        });
                    }
                    if (fieldClass != StructContext.class) {
                        classMap.put(fieldName, fieldClass);
                    }
                }
            }

            // Workaround a bug in the generated thrift message read()
            // method by mapping the ENUM type to the INT32 type
            // The thrift generated parsing code requires that, when expecting
            // a value of enum, we actually parse a value of type int32. The
            // generated read() method then looks up the enum value in a map.
            final byte type = TType.ENUM == metaData.valueMetaData.type ? TType.I32
                                                                        : metaData.valueMetaData.type;

            map.put(fieldName,
                    new TField(fieldName,
                               type,
                               e.getKey().getThriftFieldId()));
        }
    } else { // TApplicationException
        map.put("message", new TField("message", (byte)11, (short)1));
        map.put("type", new TField("type", (byte)8, (short)2));
    }

    return map;
}
 
Example #17
Source File: NetworkAvailabilityCheckPacket.java    From pinpoint with Apache License 2.0 4 votes vote down vote up
@Override
public void setFieldValue(TFieldIdEnum tFieldIdEnum, Object o) {
}
 
Example #18
Source File: NetworkAvailabilityCheckPacket.java    From pinpoint with Apache License 2.0 4 votes vote down vote up
@Override
public Object getFieldValue(TFieldIdEnum tFieldIdEnum) {
    return null;
}
 
Example #19
Source File: NetworkAvailabilityCheckPacket.java    From pinpoint with Apache License 2.0 4 votes vote down vote up
@Override
public boolean isSet(TFieldIdEnum tFieldIdEnum) {
    return false;
}
 
Example #20
Source File: NetworkAvailabilityCheckPacket.java    From pinpoint with Apache License 2.0 4 votes vote down vote up
@Override
public TFieldIdEnum fieldForId(int i) {
    return null;
}
 
Example #21
Source File: Consumers.java    From parquet-mr with Apache License 2.0 4 votes vote down vote up
public static <T extends TBase<T,? extends TFieldIdEnum>> StructConsumer struct(final Class<T> c, final Consumer<T> consumer) {
  return new TBaseStructConsumer<T>(c, consumer);
}
 
Example #22
Source File: Consumers.java    From parquet-mr with Apache License 2.0 4 votes vote down vote up
public DelegatingFieldConsumer onField(TFieldIdEnum e, TypedConsumer typedConsumer) {
  Map<Short, TypedConsumer> newContexts = new HashMap<Short, TypedConsumer>(contexts);
  newContexts.put(e.getThriftFieldId(), typedConsumer);
  return new DelegatingFieldConsumer(defaultFieldEventConsumer, newContexts);
}
 
Example #23
Source File: Consumers.java    From parquet-format with Apache License 2.0 4 votes vote down vote up
public static <T extends TBase<T,? extends TFieldIdEnum>> StructConsumer struct(final Class<T> c, final Consumer<T> consumer) {
  return new TBaseStructConsumer<T>(c, consumer);
}
 
Example #24
Source File: Consumers.java    From parquet-format with Apache License 2.0 4 votes vote down vote up
public DelegatingFieldConsumer onField(TFieldIdEnum e, TypedConsumer typedConsumer) {
  Map<Short, TypedConsumer> newContexts = new HashMap<Short, TypedConsumer>(contexts);
  newContexts.put(e.getThriftFieldId(), typedConsumer);
  return new DelegatingFieldConsumer(defaultFieldEventConsumer, newContexts);
}
 
Example #25
Source File: ThriftFieldAccess.java    From armeria with Apache License 2.0 4 votes vote down vote up
/**
 * Tells whether the specified struct field is set or not.
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public static boolean isSet(TBase<?, ?> struct, TFieldIdEnum field) {
    return ((TBase) struct).isSet(field);
}
 
Example #26
Source File: ThriftFieldAccess.java    From armeria with Apache License 2.0 4 votes vote down vote up
/**
 * Sets the value of the specified struct field.
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public static void set(TBase<?, ?> struct, TFieldIdEnum field, Object value) {
    ((TBase) struct).setFieldValue(field, value);
}
 
Example #27
Source File: ThriftFunction.java    From armeria with Apache License 2.0 4 votes vote down vote up
private static TFieldIdEnum[] getArgFields(AsyncProcessFunction<?, ?, ?> asyncFunc) {
    return getArgFields0(Type.ASYNC, asyncFunc.getClass(), asyncFunc.getMethodName());
}
 
Example #28
Source File: ThriftFunction.java    From armeria with Apache License 2.0 4 votes vote down vote up
private static TFieldIdEnum[] getArgFields(ProcessFunction<?, ?> func) {
    return getArgFields0(Type.SYNC, func.getClass(), func.getMethodName());
}
 
Example #29
Source File: ThriftFunction.java    From armeria with Apache License 2.0 4 votes vote down vote up
/**
 * Returns the field that holds the exception.
 */
public Collection<TFieldIdEnum> exceptionFields() {
    return exceptionFields.values();
}
 
Example #30
Source File: ThriftFunction.java    From armeria with Apache License 2.0 4 votes vote down vote up
/**
 * Returns the field that holds the successful result.
 */
@Nullable
public TFieldIdEnum successField() {
    return successField;
}