Example usage for org.apache.thrift TBase getFieldValue

List of usage examples for org.apache.thrift TBase getFieldValue

Introduction

In this page you can find the example usage for org.apache.thrift TBase getFieldValue.

Prototype

public Object getFieldValue(F field);

Source Link

Document

Get a field's value by field variable.

Usage

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 . ja v a2s .com
    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.cloudera.exhibit.thrift.ThriftObsDescriptor.java

License:Open Source License

Object getFieldValue(int i, TBase tBase) {
    return tBase.getFieldValue(fields.get(i).id);
}

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

License:Apache License

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override// ww w  . ja v a 2s . 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());
}

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

License:Apache License

private Object decodeResponse(ThriftFunction method, HttpData content) throws TException {
    if (content.isEmpty()) {
        if (method.isOneway()) {
            return null;
        }/*from  ww  w.j a  v a 2 s  .co  m*/
        throw new TApplicationException(TApplicationException.MISSING_RESULT);
    }

    final TMemoryInputTransport inputTransport = new TMemoryInputTransport(content.array(), content.offset(),
            content.length());
    final TProtocol inputProtocol = protocolFactory.getProtocol(inputTransport);

    final TMessage msg = inputProtocol.readMessageBegin();
    if (msg.type == TMessageType.EXCEPTION) {
        TApplicationException ex = TApplicationException.read(inputProtocol);
        inputProtocol.readMessageEnd();
        throw ex;
    }

    if (!method.name().equals(msg.name)) {
        throw new TApplicationException(TApplicationException.WRONG_METHOD_NAME, msg.name);
    }
    TBase<? extends TBase<?, ?>, TFieldIdEnum> result = method.newResult();
    result.read(inputProtocol);
    inputProtocol.readMessageEnd();

    for (TFieldIdEnum fieldIdEnum : method.exceptionFields()) {
        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 result.getFieldValue(successField);
    }

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

From source file:com.linecorp.armeria.internal.thrift.ThriftFieldAccess.java

License:Apache License

/**
 * Gets a field value from the specified struct.
 *///from   w  ww. java 2s  .c o m
public static Object get(TBase<? extends TBase<?, ?>, TFieldIdEnum> struct, TFieldIdEnum field) {
    Object value = struct.getFieldValue(field);
    if (value instanceof byte[]) {
        return ByteBuffer.wrap((byte[]) value);
    } else {
        return value;
    }
}

From source file:com.linkedin.pinot.core.data.readers.ThriftRecordReader.java

License:Apache License

@Override
public GenericRow next(GenericRow reuse) throws IOException {
    TBase t = null;
    try {/*from  w  ww. j a va  2 s  .c o  m*/
        t = this._thriftClass.newInstance();
        t.read(_binaryIn);
    } catch (Exception e) {
        throw new RuntimeException("Caught exception while serialize thrift instance", e);
    }
    for (FieldSpec fieldSpec : _schema.getAllFieldSpecs()) {
        String fieldName = fieldSpec.getName();
        if (_fieldNameToIndexMap.containsKey(fieldName)) {
            int tFieldId = _fieldNameToIndexMap.get(fieldName);
            TFieldIdEnum tFieldIdEnum = t.fieldForId(tFieldId);
            Object thriftValue = t.getFieldValue(tFieldIdEnum);
            Object value = null;
            if (fieldSpec.isSingleValueField()) {
                String token = thriftValue != null ? thriftValue.toString() : null;
                value = RecordReaderUtils.convertToDataType(token, fieldSpec);
            } else {
                if (thriftValue instanceof ArrayList) {
                    value = RecordReaderUtils.convertToDataTypeArray((ArrayList) thriftValue, fieldSpec);
                } else if (thriftValue instanceof HashSet) {
                    value = RecordReaderUtils.convertToDataTypeSet((HashSet) thriftValue, fieldSpec);
                }
            }
            reuse.putField(fieldName, value);
        }
    }
    return reuse;
}

From source file:com.netflix.astyanax.thrift.ThriftUtils.java

License:Apache License

/**
 * Quick and dirty implementation that converts thrift DDL to a Properties object by flattening
 * the parameters//  w  w w  . j  a  va 2  s .c o m
 * @param prefix
 * @param properties
 * @param entity
 * @throws Exception
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void setPropertiesFromThrift(String prefix, Properties properties, org.apache.thrift.TBase entity)
        throws Exception {
    Field field = entity.getClass().getDeclaredField("metaDataMap");
    Map<org.apache.thrift.TFieldIdEnum, org.apache.thrift.meta_data.FieldMetaData> fields = (Map<org.apache.thrift.TFieldIdEnum, FieldMetaData>) field
            .get(entity);

    for (Entry<org.apache.thrift.TFieldIdEnum, FieldMetaData> f : fields.entrySet()) {
        ThriftTypes type = ThriftTypes.values()[f.getValue().valueMetaData.type];
        Object value = entity.getFieldValue(f.getKey());
        if (value == null)
            continue;

        switch (type) {
        case VOID:
            break;
        case BOOL:
        case BYTE:
        case DOUBLE:
        case I16:
        case I32:
        case I64:
        case STRING:
        case ENUM:
            if (value instanceof byte[]) {
                properties.put(prefix + f.getKey().getFieldName(), Base64.encodeBase64String((byte[]) value));
            } else if (value instanceof ByteBuffer) {
                properties.put(prefix + f.getKey().getFieldName(), base64Encode((ByteBuffer) value));
            } else {
                properties.put(prefix + f.getKey().getFieldName(), value.toString());
            }
            break;
        case MAP: {
            String newPrefix = prefix + f.getKey().getFieldName() + ".";
            org.apache.thrift.meta_data.MapMetaData meta = (org.apache.thrift.meta_data.MapMetaData) f
                    .getValue().valueMetaData;
            if (!meta.keyMetaData.isStruct() && !meta.keyMetaData.isContainer()) {
                Map<Object, Object> map = (Map<Object, Object>) value;
                for (Entry<Object, Object> entry : map.entrySet()) {
                    properties.put(newPrefix + entry.getKey(), entry.getValue().toString());
                }
            } else {
                LOG.error(String.format("Unable to serializer field '%s' key type '%s' not supported",
                        f.getKey().getFieldName(), meta.keyMetaData.getTypedefName()));
            }
            break;
        }
        case LIST: {
            String newPrefix = prefix + f.getKey().getFieldName() + ".";

            List<Object> list = (List<Object>) value;
            org.apache.thrift.meta_data.ListMetaData listMeta = (org.apache.thrift.meta_data.ListMetaData) f
                    .getValue().valueMetaData;
            for (Object entry : list) {
                String id;
                if (entry instanceof CfDef) {
                    id = ((CfDef) entry).name;
                } else if (entry instanceof ColumnDef) {
                    ByteBuffer name = ((ColumnDef) entry).name;
                    id = base64Encode(name);
                } else {
                    LOG.error("Don't know how to convert to properties "
                            + listMeta.elemMetaData.getTypedefName());
                    continue;
                }

                if (listMeta.elemMetaData.isStruct()) {
                    setPropertiesFromThrift(newPrefix + id + ".", properties, (org.apache.thrift.TBase) entry);
                } else {
                    properties.put(newPrefix + id, entry);
                }
            }

            break;
        }
        case STRUCT: {
            setPropertiesFromThrift(prefix + f.getKey().getFieldName() + ".", properties,
                    (org.apache.thrift.TBase) value);
            break;
        }
        case SET:
        default:
            LOG.error("Unhandled value : " + f.getKey().getFieldName() + " " + type);
            break;
        }
    }
}

From source file:com.onesite.sdk.api.ApiMethod.java

License:Apache License

/**
 * Call the API via the OnesiteClient and populate the TBase obj. A OnesiteException
 * will be returned if an error occured during deserialization of the TBase obj
 * // w ww  .ja v  a2 s . c  o m
 * @param path
 * @param params
 * @param type
 * 
 * @throws Exception
 */
protected void get(String path, Map<String, String> params, TBase obj) throws Exception {
    try {
        this.client.get(path, params);
    } catch (Exception e) {
        log.error("Error occurred during client call to " + path);
        throw e;
    }

    if (this.client.getHttpStatusCode() == HttpStatus.SC_OK) {

        try {
            TDeserializer deserializer = new TDeserializer();
            deserializer.fromString(obj, this.client.getHttpResult());

            Status status = (Status) obj.getFieldValue(obj.fieldForId(1));

            if (status.getCode() != OnesiteResultCode.OK) {
                throw new OnesiteException(status.getCode(), status.getMessage());
            }
        } catch (Exception e) {
            throw new Exception("Error deserializing result ", e);
        }
    } else {
        throw new OnesiteException(this.client.getHttpStatusCode(), this.client.getHttpStatusMessage());
    }
}

From source file:com.sleepycat.server.util.Adapters.java

License:Open Source License

private static <F extends TFieldIdEnum, B> B updateBdbObject(B bdbObj, TBase<?, F> tObj, F[] fields,
        Map<F, BiConsumer<B, Object>> setters) {
    if (tObj == null)
        return bdbObj;
    try {/*  w w w .  ja  v  a  2s  .c om*/
        Map<String, PropertyDescriptor> properties = getProperties(bdbObj);
        for (F f : fields) {
            if (tObj.isSet(f)) {
                Object value = tObj.getFieldValue(f);
                if (setters != null && setters.containsKey(f)) {
                    setters.get(f).accept(bdbObj, value);
                } else {
                    PropertyDescriptor p = properties.get(f.getFieldName());
                    p.getWriteMethod().invoke(bdbObj, value);
                }
            }
        }
        return bdbObj;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.twitter.common.thrift.Util.java

License:Apache License

/**
 * Prints a TBase.//w w w  .  j a  va2 s  .c  om
 *
 * @param t The object to print.
 * @param depth The print nesting level.
 * @return The pretty-printed version of the TBase.
 */
private static String printTbase(TBase t, int depth) {
    List<String> fields = Lists.newArrayList();
    for (Map.Entry<? extends TFieldIdEnum, FieldMetaData> entry : FieldMetaData
            .getStructMetaDataMap(t.getClass()).entrySet()) {
        @SuppressWarnings("unchecked")
        Object value = t.getFieldValue(entry.getKey());
        fields.add(tabs(depth) + entry.getValue().fieldName + ": " + printValue(value, depth));
    }

    return Joiner.on("\n").join(fields);
}