Example usage for org.apache.commons.lang3.reflect FieldUtils readField

List of usage examples for org.apache.commons.lang3.reflect FieldUtils readField

Introduction

In this page you can find the example usage for org.apache.commons.lang3.reflect FieldUtils readField.

Prototype

public static Object readField(final Object target, final String fieldName, final boolean forceAccess)
        throws IllegalAccessException 

Source Link

Document

Reads the named Field .

Usage

From source file:com.github.htfv.maven.plugins.eclipseconfigurator.ConfigureMojo.java

public <T> T connectorGetParameter(final String expression, final Class<T> expectedType) {
    if (StringUtils.isEmpty(expression)) {
        return null;
    }//w  ww .  j av  a 2s .  c  om

    final String[] fieldNames = expression.split("\\.");
    Object value = this;

    for (int i = 0; i < fieldNames.length; i += 1) {
        try {
            value = FieldUtils.readField(value, fieldNames[i], true);

            if (value == null) {
                return null;
            }
        } catch (final IllegalAccessException e) {
            return null;
        }
    }

    return ECELUtils.getValue(getELContext(), value.toString(), expectedType);
}

From source file:com.hlex.ondb.entity.AnnoEntityHelper.java

/**
 * Seek for @Major key and create/*from   w ww . j  a v  a  2  s.c o m*/
 * "fieldname/fieldvalue/fieldname/fieldvalue/"
 *
 *
 * @param type FindingAnnoation Target : MajorKey or MinorKey
 * @return
 * @throws com.hlex.ondb.exception.NullKeyException
 */
public List<String> getKeyByAnnotation(Object o, Class<? extends Annotation> type) throws NullKeyException {

    //returned variable
    List<String> key = new ArrayList();

    //field all field for @MajorKey
    Field[] fs = FieldUtils.getAllFields(o.getClass());
    for (Field f : fs) {
        Annotation mjk = f.getAnnotation(type);
        Object value = null;
        if (mjk != null) {
            try {
                value = FieldUtils.readField(o, f.getName(), true);
                //null value case
                if (value == null) {
                    throw new NullKeyException(f.getName() + " has null value");
                }

                //add /fieldname/fieldvalue
                key.add(f.getName());
                key.add(value.toString());

            } catch (IllegalAccessException ex) {
                Logger.getLogger(AnnoEntityHelper.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    }

    //no @majorkey case
    if (key.isEmpty()) {
        throw new NullKeyException("no " + type.getSimpleName() + " key");
    }

    return key;
}

From source file:fi.jumi.core.util.EqualityMatchers.java

private static String findDifference(String path, Object obj1, Object obj2) {
    if (obj1 == null || obj2 == null) {
        return obj1 == obj2 ? null : path;
    }//from   w w  w . j  ava  2  s .c o m
    if (obj1.getClass() != obj2.getClass()) {
        return path;
    }

    // collections have a custom equals, but we want deep equality on every collection element
    // TODO: support other collection types? comparing Sets should be order-independent
    if (obj1 instanceof List) {
        List<?> col1 = (List<?>) obj1;
        List<?> col2 = (List<?>) obj2;

        int size1 = col1.size();
        int size2 = col2.size();
        if (size1 != size2) {
            return path + ".size()";
        }

        for (int i = 0; i < Math.min(size1, size2); i++) {
            String diff = findDifference(path + ".get(" + i + ")", col1.get(i), col2.get(i));
            if (diff != null) {
                return diff;
            }
        }
        return null;
    }

    // use custom equals method if exists
    try {
        Method equals = obj1.getClass().getMethod("equals", Object.class);
        if (equals.getDeclaringClass() != Object.class) {
            return obj1.equals(obj2) ? null : path;
        }
    } catch (NoSuchMethodException e) {
        throw new RuntimeException(e);
    }

    // arrays
    if (obj2.getClass().isArray()) {
        int length1 = Array.getLength(obj1);
        int length2 = Array.getLength(obj2);
        if (length1 != length2) {
            return path + ".length";
        }

        for (int i = 0; i < Math.min(length1, length2); i++) {
            String diff = findDifference(path + "[" + i + "]", Array.get(obj1, i), Array.get(obj2, i));
            if (diff != null) {
                return diff;
            }
        }
        return null;
    }

    // structural equality
    for (Class<?> cl = obj2.getClass(); cl != null; cl = cl.getSuperclass()) {
        for (Field field : cl.getDeclaredFields()) {
            try {
                String diff = findDifference(path + "." + field.getName(),
                        FieldUtils.readField(field, obj1, true), FieldUtils.readField(field, obj2, true));
                if (diff != null) {
                    return diff;
                }
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }
    }
    return null;
}

From source file:io.github.moosbusch.lumpi.util.LumpiUtil.java

public static Map<String, Object> getBXMLFieldValues(Bindable obj) throws IllegalAccessException {
    Map<String, Object> result = new HashMap<>();
    Class<?> type = obj.getClass();
    Field[] allFields = FieldUtils.getAllFields(type);

    if (ArrayUtils.isNotEmpty(allFields)) {
        for (Field field : allFields) {
            BXML bxmlAnnotation = field.getAnnotation(BXML.class);

            if (bxmlAnnotation != null) {
                String id = bxmlAnnotation.id();
                Object fieldValue = FieldUtils.readField(field, obj, true);

                if (StringUtils.isNotBlank(id)) {
                    result.put(id, fieldValue);
                } else {
                    result.put(field.getName(), fieldValue);
                }/*from w  w w.j  a v  a  2s . co m*/
            }
        }
    }

    return result;
}

From source file:com.astamuse.asta4d.util.annotation.AnnotatedPropertyInfo.java

public Object retrieveValue(Object instance)
        throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    if (this.field == null) {
        return getter.invoke(instance);
    } else {//  w w  w  . j  a  v a  2  s  .  co  m
        return FieldUtils.readField(field, instance, true);
    }
}

From source file:core.plugin.mybatis.PageInterceptor.java

@Override
public Object intercept(Invocation inv) throws Throwable {
    // prepare?Connection
    Connection connection = (Connection) inv.getArgs()[0];
    String dbType = connection.getMetaData().getDatabaseProductName();
    L.debug(dbType);/*  w  w w. j ava  2 s  .  co  m*/
    Dialect dialect = null;
    if (StringUtils.equalsIgnoreCase("ORACLE", dbType)) {
        dialect = new OracleDialect();
    } else if (StringUtils.equalsIgnoreCase("H2", dbType)) {
        dialect = new H2Dialect();
    } else {
        throw new AppRuntimeException("A404: Not Support ['" + dbType + "'] Pagination Yet!");
    }

    StatementHandler target = (StatementHandler) inv.getTarget();
    BoundSql boundSql = target.getBoundSql();
    String sql = boundSql.getSql();
    if (StringUtils.isBlank(sql)) {
        return inv.proceed();
    }
    // ?select??
    if (sql.matches(SQL_SELECT_REGEX) && !Pattern.matches(SQL_COUNT_REGEX, sql)) {
        Object obj = FieldUtils.readField(target, "delegate", true);
        // ??? RowBounds 
        RowBounds rowBounds = (RowBounds) FieldUtils.readField(obj, "rowBounds", true);
        // ??SQL
        if (rowBounds != null && rowBounds != RowBounds.DEFAULT) {
            FieldUtils.writeField(boundSql, "sql", dialect.getSqlWithPagination(sql, rowBounds), true);
            // ???(?)
            FieldUtils.writeField(rowBounds, "offset", RowBounds.NO_ROW_OFFSET, true);
            FieldUtils.writeField(rowBounds, "limit", RowBounds.NO_ROW_LIMIT, true);
        }
    }
    return inv.proceed();
}

From source file:com.carmanconsulting.cassidy.util.CassidyUtils.java

public static Object getFieldValue(Object target, String fieldName) {
    try {/*from   ww w .j ava  2  s .co  m*/
        LOGGER.debug("Getting field {} value from object {} (type={})...", fieldName, target,
                getClassName(target));
        return FieldUtils.readField(target, fieldName, true);
    } catch (IllegalAccessException e) {
        throw new CassidyException(String.format("Unable to read field %s value from object of type %s.",
                fieldName, getClassName(target)), e);
    }
}

From source file:mtsar.processors.meta.ZenCrowd.java

@Nonnull
@Override/*from w  w  w  .ja va  2 s  . co  m*/
public Map<Integer, WorkerRanking> rank(@Nonnull Collection<Worker> workers) {
    requireNonNull(stage, "the stage provider should not provide null");
    if (workers.isEmpty())
        return Collections.emptyMap();
    final Map<Integer, Worker> workerIds = workers.stream()
            .collect(Collectors.toMap(Worker::getId, Function.identity()));
    final Models.ZenModel<Integer, Integer, String> zenModel = compute(stage, answerDAO, getTaskMap())
            .getZenModel();
    final ZenCrowdEM<Integer, Integer, String> zenCrowd = new ZenCrowdEM<>(zenModel);
    zenCrowd.computeLabelEstimates();
    try {
        @SuppressWarnings("unchecked")
        final Map<Integer, Double> reliability = (Map<Integer, Double>) FieldUtils.readField(zenCrowd,
                "workerReliabilityMap", true);
        final Map<Integer, WorkerRanking> rankings = reliability.entrySet().stream()
                .filter(entry -> workerIds.containsKey(entry.getKey()))
                .collect(Collectors.toMap(Map.Entry::getKey, entry -> new WorkerRanking.Builder()
                        .setWorker(workerIds.get(entry.getKey())).setReputation(entry.getValue()).build()));
        return rankings;
    } catch (IllegalAccessException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:com.thinkbiganalytics.policy.BasePolicyAnnotationTransformer.java

/**
 * For a given domain policy class extract the user interface {@link FieldRuleProperty} classes parsing the fields annotated with the {@link PolicyProperty}
 *
 * @param policy the domain policy object to parse
 * @return a list of user interface fields annotated with the {@link PolicyProperty}
 *///from   w w  w  . ja v a 2 s  .  c o m
private List<FieldRuleProperty> getUiProperties(P policy) {
    AnnotationFieldNameResolver annotationFieldNameResolver = new AnnotationFieldNameResolver(
            PolicyProperty.class);
    List<AnnotatedFieldProperty> list = annotationFieldNameResolver.getProperties(policy.getClass());
    List<FieldRuleProperty> properties = new ArrayList<>();
    Map<String, Integer> groupOrder = new HashMap<>();
    Map<String, List<FieldRuleProperty>> groupedProperties = new HashMap<>();
    if (hasConstructor(policy.getClass())) {

        for (AnnotatedFieldProperty<PolicyProperty> annotatedFieldProperty : list) {
            PolicyProperty prop = annotatedFieldProperty.getAnnotation();
            String value = null;
            try {
                Object fieldValue = FieldUtils.readField(annotatedFieldProperty.getField(), policy, true);
                if (fieldValue != null) {
                    value = fieldValue.toString();
                }
            } catch (IllegalAccessException e) {

            }
            String group = prop.group();
            Integer order = 0;
            if (!groupOrder.containsKey(group)) {
                groupOrder.put(group, order);
            }
            order = groupOrder.get(group);
            order++;
            groupOrder.put(group, order);
            FieldRuleProperty rule = new FieldRulePropertyBuilder(prop.name())
                    .displayName(StringUtils.isNotBlank(prop.displayName()) ? prop.displayName() : prop.name())
                    .hint(prop.hint()).type(PolicyPropertyTypes.PROPERTY_TYPE.valueOf(prop.type().name()))
                    .objectProperty(annotatedFieldProperty.getName()).placeholder(prop.placeholder())
                    .value(value).required(prop.required()).group(group).groupOrder(order)
                    .pattern(prop.pattern()).patternInvalidMessage(prop.patternInvalidMessage())
                    .hidden(prop.hidden()).addSelectableValues(convertToLabelValue(prop.selectableValues()))
                    .addSelectableValues(convertToLabelValue(prop.labelValues())).build();
            properties.add(rule);
            if (!group.equals("")) {
                if (!groupedProperties.containsKey(group)) {
                    groupedProperties.put(group, new ArrayList<FieldRuleProperty>());
                }
                groupedProperties.get(group).add(rule);
            }
        }
        //update layout property
        for (Collection<FieldRuleProperty> groupProps : groupedProperties.values()) {
            for (FieldRuleProperty property : groupProps) {
                property.setLayout("row");
            }
        }

    }
    return properties;
}

From source file:com.joyent.manta.http.MantaConnectionFactoryTest.java

public void willConfigureClientToUseProvidedManager() throws IOException, ReflectiveOperationException {
    final MantaConnectionFactoryConfigurator conf = new MantaConnectionFactoryConfigurator(builder);
    connectionFactory = new MantaConnectionFactory(config, conf);

    final HttpClientConnectionManager configuredManager = (HttpClientConnectionManager) FieldUtils
            .readField(builder, "connManager", true);

    Assert.assertEquals(manager, configuredManager);
}