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

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

Introduction

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

Prototype

public static List<Field> getFieldsListWithAnnotation(final Class<?> cls,
        final Class<? extends Annotation> annotationCls) 

Source Link

Document

Gets all fields of the given class and its parents (if any) that are annotated with the given annotation.

Usage

From source file:com.validation.manager.test.AbstractVMTestCase.java

public List<Field> getAuditableFields(Versionable v) {
    List<Field> r = new ArrayList<>();
    FieldUtils.getFieldsListWithAnnotation(v.getClass(), Auditable.class).stream()
            .filter((field) -> (field.isAnnotationPresent(Auditable.class))).forEachOrdered((field) -> {
                r.add(field);//from w w  w  .  j  a v  a2s .co  m
            });
    return r;
}

From source file:com.jedi.oracle.OracleCall.java

private String createSQL(String queryName) {
    List<Field> fields = FieldUtils.getFieldsListWithAnnotation(getClass(), OracleParameterMapping.class);
    String retVal = "";
    String params = "";

    if (fields != null && !fields.isEmpty()) {
        List<Field> orderingFields = Ordering.natural().nullsFirst().onResultOf(new Function<Field, Integer>() {
            public Integer apply(Field field) {
                OracleParameterMapping mapping = field.getAnnotation(OracleParameterMapping.class);
                return mapping.index();
            }//from   ww w. jav a 2  s  .c  o  m
        }).sortedCopy(fields);

        for (Field field : orderingFields) {
            OracleParameterMapping mapping = field.getAnnotation(OracleParameterMapping.class);
            switch (mapping.direction()) {
            case ReturnValue:
                retVal = "? :=";
                break;
            default:
                if (params.indexOf(',') == -1) {
                    params += mapping.name() + "?";
                } else {
                    params += ", " + mapping.name() + "?";
                }
                break;
            }
        }
    }

    StringBuilder sb = new StringBuilder();
    sb.append("BEGIN");
    sb.append(" ");
    if (!retVal.isEmpty()) {
        sb.append(retVal);
        sb.append(" ");
    }
    sb.append(queryName);
    sb.append("(");
    if (!params.isEmpty()) {
        sb.append(params);
    }
    sb.append(");");
    sb.append(" ");
    sb.append("END;");

    return sb.toString();

}

From source file:com.validation.manager.core.history.VersionableTest.java

@Test
public void testVersioning() {
    try {/* w  ww.j a  va2 s  .c om*/
        DemoBuilder.buildDemoProject();
        EntityManager em = DataBaseManager.getEntityManager();
        //Populate with demo classes.
        for (EntityType<?> entity : em.getMetamodel().getEntities()) {
            if (Versionable.class.isAssignableFrom(entity.getJavaType())) {
                final String className = entity.getName();
                System.out.println("Testing class: " + className);
                //Make sure they have at least one auditable field.
                List<Field> fields = FieldUtils.getFieldsListWithAnnotation(entity.getJavaType(),
                        Auditable.class);
                assertEquals(false, fields.isEmpty());
                //Get one from the demo data
                Versionable v = (Versionable) DataBaseManager
                        .createdQuery("Select a from " + entity.getJavaType().getSimpleName() + " a").get(0);
                assertNotNull(v);
                v.updateHistory();
                int count = v.getHistoryList().size();
                for (Field f : fields) {
                    //Now pick one of the Auditable fields
                    assertEquals(count, v.getHistoryList().size());
                    History history = v.getHistoryList().get(v.getHistoryList().size() - 1);
                    assertEquals(count == 1 ? "audit.general.creation" : "audit.general.modified",
                            history.getReason());
                    assertEquals(0, history.getMajorVersion());
                    assertEquals(0, history.getMidVersion());
                    assertEquals(count++, history.getMinorVersion());
                    assertEquals(1, (int) history.getModifierId().getId());
                    assertNotNull(history.getModificationTime());
                    assertTrue(checkHistory(v));
                    assertFalse(Versionable.auditable(v));
                    System.out.println(
                            "Changing field: " + f.getName() + " Type: " + f.getType().getSimpleName());
                    f.setAccessible(true);
                    if (f.getType() == Integer.class) {
                        Integer current = (Integer) f.get(v);
                        Integer newValue = current + 1;
                        showChange(current, newValue);
                        f.set(v, newValue);
                    } else if (f.getType() == String.class) {
                        String current = (String) f.get(v);
                        String newValue = current + 1;
                        showChange(current, newValue);
                        f.set(v, newValue);
                    } else if (f.getType() == byte[].class) {
                        byte[] current = (byte[]) f.get(v);
                        byte[] append = "1".getBytes();
                        byte[] newValue = new byte[current.length + append.length];
                        showChange(current, newValue);
                        f.set(v, newValue);
                    } else if (f.getType() == Boolean.class) {
                        Boolean current = (Boolean) f.get(v);
                        Boolean newValue = !current;
                        showChange(current, newValue);
                        f.set(v, newValue);
                    } else {
                        fail("Unexpected field type: " + f.getType().getSimpleName());
                    }
                    assertTrue(Versionable.auditable(v));
                    v.updateHistory();
                    assertEquals(count, v.getHistoryList().size());
                    history = v.getHistoryList().get(v.getHistoryList().size() - 1);
                    assertEquals(0, history.getMajorVersion());
                    assertEquals(0, history.getMidVersion());
                    assertEquals(count, history.getMinorVersion());
                    assertEquals(1, (int) history.getModifierId().getId());
                    assertEquals("audit.general.modified", history.getReason());
                    assertNotNull(history.getModificationTime());
                    assertTrue(checkHistory(v));
                    assertFalse(Versionable.auditable(v));
                    int total = new HistoryJpaController(DataBaseManager.getEntityManagerFactory())
                            .getHistoryCount();
                    //Test for issue #25 https://github.com/javydreamercsw/validation-manager/issues/25
                    v = (Versionable) DataBaseManager.getEntityManager().find(entity.getJavaType(),
                            DataBaseManager.getEntityManagerFactory().getPersistenceUnitUtil()
                                    .getIdentifier(v));
                    assertTrue(checkHistory(v));
                    assertEquals(total, new HistoryJpaController(DataBaseManager.getEntityManagerFactory())
                            .getHistoryCount());
                    assertEquals(count, v.getHistoryList().size());
                }
            }
        }
    } catch (Exception ex) {
        Exceptions.printStackTrace(ex);
        fail();
    }
}

From source file:com.adobe.acs.commons.mcp.util.AnnotatedFieldDeserializer.java

public static Map<String, FieldComponent> getFormFields(Class source, SlingScriptHelper sling) {
    return FieldUtils.getFieldsListWithAnnotation(source, FormField.class).stream()
            .collect(Collectors.toMap(Field::getName, f -> {
                FormField fieldDefinition = f.getAnnotation(FormField.class);
                FieldComponent component;
                try {
                    component = fieldDefinition.component().newInstance();
                    component.setup(f.getName(), f, fieldDefinition, sling);
                    return component;
                } catch (InstantiationException | IllegalAccessException ex) {
                    LOG.error("Unable to instantiate field component for " + f.getName(), ex);
                }//from w w w  . j av  a  2s .c  o m
                return null;
            }, (a, b) -> a, LinkedHashMap::new));
}

From source file:com.hurence.logisland.util.kura.Metrics.java

public static <T> T readFrom(final T object, final Map<String, Object> metrics) {
    Objects.requireNonNull(object);

    for (final Field field : FieldUtils.getFieldsListWithAnnotation(object.getClass(), Metric.class)) {
        final Metric m = field.getAnnotation(Metric.class);
        final boolean optional = field.isAnnotationPresent(Optional.class);

        final Object value = metrics.get(m.value());
        if (value == null && !optional) {
            throw new IllegalArgumentException(
                    String.format("Field '%s' is missing metric '%s'", field.getName(), m.value()));
        }//w w  w  .ja  v a  2  s.co m

        if (value == null) {
            // not set but optional
            continue;
        }

        try {
            FieldUtils.writeField(field, object, value, true);
        } catch (final IllegalArgumentException e) {
            // provide a better message
            throw new IllegalArgumentException(String.format("Failed to assign '%s' (%s) to field '%s'", value,
                    value.getClass().getName(), field.getName()), e);
        } catch (final IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    for (final Method method : MethodUtils.getMethodsListWithAnnotation(object.getClass(), Metric.class)) {
        final Metric m = method.getAnnotation(Metric.class);
        final boolean optional = method.isAnnotationPresent(Optional.class);

        final Object value = metrics.get(m.value());
        if (value == null && !optional) {
            throw new IllegalArgumentException(
                    String.format("Method '%s' is missing metric '%s'", method.getName(), m.value()));
        }

        if (value == null) {
            // not set but optional
            continue;
        }

        try {
            method.invoke(object, value);
        } catch (final IllegalArgumentException e) {
            // provide a better message
            throw new IllegalArgumentException(String.format("Failed to call '%s' (%s) with method '%s'", value,
                    value.getClass().getName(), method.getName()), e);
        } catch (IllegalAccessException | InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }

    return object;
}

From source file:com.github.jinahya.sql.database.metadata.bind.MetadataContext.java

private <T> T bindSingle(final ResultSet resultSet, final Class<T> beanClass, final T beanInstance)
        throws SQLException, ReflectiveOperationException {

    if (resultSet != null) {
        final Set<String> resultLabels = ResultSets.getColumnLabels(resultSet);
        //            @SuppressWarnings("unchecked")
        //            final List<Field> fields
        //                = Reflections.fields(beanClass, Label.class);
        final Field[] fields = FieldUtils.getFieldsWithAnnotation(beanClass, Label.class);
        for (final Field field : fields) {
            final String label = field.getAnnotation(Label.class).value();
            final String suppression = suppression(beanClass, field);
            final String info = String.format("field=%s, label=%s, suppression=%s", field, label, suppression);
            if (suppressed(suppression)) {
                logger.log(Level.FINE, "suppressed; {0}", info);
                continue;
            }/* w ww.  j  a v a  2 s. co m*/
            if (!resultLabels.remove(label)) {
                final String message = "unknown column; " + info;
                if (!suppressUnknownColumns()) {
                    throw new RuntimeException(message);
                }
                logger.warning(message);
                continue;
            }
            final Object value;
            try {
                value = resultSet.getObject(label);
            } catch (final Exception e) {
                final String message = "failed to get value; " + info;
                logger.severe(message);
                if (e instanceof SQLException) {
                    throw (SQLException) e;
                }
                throw new RuntimeException(e);
            }
            Values.set(field.getName(), beanInstance, value);
            //Reflections.fieldValue(field, beanInstance, value);
            //FieldUtils.writeField(field, beanInstance, value);
            //FieldUtils.writeField(field, beanInstance, value, true);
        }
        if (!resultLabels.isEmpty()) {
            for (final String resultLabel : resultLabels) {
                final Object resultValue = resultSet.getObject(resultLabel);
                logger.log(Level.WARNING, "unknown result; {0}({1})",
                        new Object[] { resultLabel, resultValue });
            }
        }
    }

    //        @SuppressWarnings("unchecked")
    //        final List<Field> fields
    //            = Reflections.fields(beanClass, Invocation.class);
    final List<Field> fields = FieldUtils.getFieldsListWithAnnotation(beanClass, Invocation.class);
    for (final Field field : fields) {
        final Invocation invocation = field.getAnnotation(Invocation.class);
        final String suppression = suppression(beanClass, field);
        final String info = String.format("field=%s, invocation=%s, suppression=%s", field, invocation,
                suppression);
        if (suppressed(suppression)) {
            logger.log(Level.FINE, "suppressed; {0}", new Object[] { info });
            continue;
        }
        final String name = invocation.name();
        getMethodNames().remove(name);
        final Class<?>[] types = invocation.types();
        final Method method;
        try {
            method = DatabaseMetaData.class.getMethod(name, types);
        } catch (final NoSuchMethodException nsme) {
            final String message = "unknown methods; " + info;
            if (!suppressUnknownMethods()) {
                throw new RuntimeException(message);
            }
            logger.warning(message);
            continue;
        }
        for (final InvocationArgs invocationArgs : invocation.argsarr()) {
            final String[] names = invocationArgs.value();
            final Object[] args = Invocations.args(beanClass, beanInstance, types, names);
            final Object value;
            try {
                value = method.invoke(database, args);
            } catch (final Exception e) {
                logger.log(Level.SEVERE, "failed to invoke" + info, e);
                throw new RuntimeException(e);
            } catch (final AbstractMethodError ame) {
                logger.log(Level.SEVERE, "failed by abstract" + info, ame);
                throw ame;
            }
            setValue(field, beanInstance, value, args);
        }
    }

    if (TableDomain.class.isAssignableFrom(beanClass)) {
        getMethodNames().remove("getCrossReference");
        final List<Table> tables = ((TableDomain) beanInstance).getTables();
        final List<CrossReference> crossReferences = getCrossReferences(tables);
        ((TableDomain) beanInstance).setCrossReferences(crossReferences);
    }

    return beanInstance;
}

From source file:com.validation.manager.core.history.Versionable.java

public static synchronized boolean auditable(Versionable v) {
    History current;/*from   w w  w.jav  a 2  s. c  o m*/
    boolean result = false;
    if (v.getHistoryList() != null && !v.getHistoryList().isEmpty()) {
        current = v.getHistoryList().get(v.getHistoryList().size() - 1);
        for (HistoryField hf : current.getHistoryFieldList()) {
            try {
                //Compare audit field vs. the record in history.
                Object o = FieldUtils.readField(FieldUtils.getField(v.getClass(), hf.getFieldName(), true), v);
                if ((o == null && !hf.getFieldValue().equals("null"))
                        || (!(o instanceof byte[]) && o != null && !o.toString().equals(hf.getFieldValue()))
                        || ((o instanceof byte[]) && !new String((byte[]) o, StandardCharsets.UTF_8)
                                .equals(hf.getFieldValue()))) {
                    result = true;
                    break;
                }
            } catch (SecurityException | IllegalArgumentException | IllegalAccessException ex) {
                LOG.log(Level.SEVERE, null, ex);
            }
        }
        //As last check the version fields for changes (i.e. baselineing, etc.)
        if (!result) {
            result = current.getMajorVersion() < v.getMajorVersion()
                    || current.getMidVersion() < v.getMidVersion()
                    || current.getMinorVersion() < v.getMinorVersion();
        }
        return result;
    }
    //No history so it is auditable if it has marked fields for audit.
    return !FieldUtils.getFieldsListWithAnnotation(v.getClass(), Auditable.class).isEmpty();
}

From source file:com.validation.manager.core.history.Versionable.java

private synchronized void updateFields(HistoryServer hs, Versionable v)
        throws IllegalArgumentException, IllegalAccessException, Exception {
    for (Field field : FieldUtils.getFieldsListWithAnnotation(v.getClass(), Auditable.class)) {
        Class type = field.getType();
        String name = field.getName();
        FieldType ft = FieldTypeServer.findType(type.getSimpleName());
        if (ft == null) {
            FieldTypeServer fts = new FieldTypeServer();
            fts.setTypeName(type.getSimpleName());
            fts.write2DB();/*from   ww w .  j  av  a 2  s.co  m*/
            ft = fts.getEntity();
        }
        HistoryFieldServer hf = new HistoryFieldServer(ft.getId(), hs.getId());
        hf.setFieldName(name);
        hf.setFieldType(ft);
        hf.setHistory(hs.getEntity());
        field.setAccessible(true);
        Object value = field.get(v);
        if (value instanceof byte[]) {
            byte[] bytes = (byte[]) value;
            value = new String(bytes, StandardCharsets.UTF_8);
        }
        hf.setFieldValue(value == null ? "null" : value.toString());
        hf.write2DB();
        hs.getHistoryFieldList().add(hf.getEntity());
    }
    hs.write2DB();
    v.addHistory(hs.getEntity());
}

From source file:com.feilong.tools.jsonlib.JsonUtil.java

/**
 * Builds the json format config.// www  .  j a va 2 s. c  o m
 *
 * @param obj
 *            the obj
 * @return the json format config
 * @since 1.6.3
 */
private static JsonFormatConfig buildJsonFormatConfig(Object obj) {
    List<Field> fieldsListWithAnnotation = FieldUtils.getFieldsListWithAnnotation(obj.getClass(),
            SensitiveWords.class);
    if (isNotNullOrEmpty(fieldsListWithAnnotation)) {
        Map<String, JsonValueProcessor> propertyNameAndJsonValueProcessorMap = new HashMap<String, JsonValueProcessor>();
        for (Field field : fieldsListWithAnnotation) {
            propertyNameAndJsonValueProcessorMap.put(field.getName(), SENSITIVE_WORDS_JSONVALUE_PROCESSOR);
        }
        return new JsonFormatConfig(propertyNameAndJsonValueProcessorMap);
    }
    return null;
}

From source file:com.feilong.core.bean.BeanUtil.java

/**
 * ??? klass {@link Alias} , ?? {@link Alias#name()} ?map .
 *
 * @param klass/*from   ww  w .  j  a  v a 2 s.  c om*/
 *            the klass
 * @return <code>klass</code>  {@link Alias} , {@link Collections#emptyMap()}
 * @throws NullPointerException
 *              <code>klass</code> null
 * @since 1.8.1
 */
private static Map<String, String> buildPropertyNameAndAliasMap(Class<?> klass) {
    Validate.notNull(klass, "klass can't be null!");
    List<Field> aliasFieldsList = FieldUtils.getFieldsListWithAnnotation(klass, Alias.class);
    if (isNullOrEmpty(aliasFieldsList)) {
        return emptyMap();
    }
    //??key
    Map<String, String> propertyNameAndAliasMap = newHashMap(aliasFieldsList.size());
    for (Field field : aliasFieldsList) {
        Alias alias = field.getAnnotation(Alias.class);
        propertyNameAndAliasMap.put(field.getName(), alias.name());
    }
    return propertyNameAndAliasMap;
}