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

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

Introduction

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

Prototype

public static Field getField(final Class<?> cls, final String fieldName, final boolean forceAccess) 

Source Link

Document

Gets an accessible Field by name, breaking scope if requested.

Usage

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

private Object getPropertyValue(BaseUiPolicyRule rule, Class<P> domainPolicyClass,
        PolicyPropertyRef reference) {// w w  w.j a va  2 s. c  o  m
    for (FieldRuleProperty property : rule.getProperties()) {
        String name = property.getName();
        if (name.equalsIgnoreCase(reference.name())) {
            String field = property.getObjectProperty();
            String value = property.getStringValue();
            Field f = FieldUtils.getField(domainPolicyClass, field, true);
            Object objectValue = convertStringToObject(value, f.getType());
            return objectValue;
        }
    }
    return null;
}

From source file:com.thinkbiganalytics.metadata.modeshape.datasource.JcrDatasourceProvider.java

private <J extends JcrDatasource> J createImpl(String name, String descr, Class<? extends Datasource> type) {
    try {// ww  w  .  jav a 2  s  .co m
        JcrTool tool = new JcrTool();
        Class<J> implType = deriveImplType(type);
        Field folderField = FieldUtils.getField(implType, "PATH_NAME", true);
        String subfolderName = (String) folderField.get(null);
        String dsPath = EntityUtil.pathForDataSource();
        Node dsNode = getSession().getNode(dsPath);
        Node subfolderNode = tool.findOrCreateChild(dsNode, subfolderName, "nt:folder");

        Map<String, Object> props = new HashMap<>();
        props.put(JcrDatasource.SYSTEM_NAME, name);

        String encodedName = org.modeshape.jcr.value.Path.DEFAULT_ENCODER.encode(name);
        final boolean isNew = !hasEntityNode(subfolderNode.getPath(), encodedName);

        @SuppressWarnings("unchecked")
        J datasource = (J) findOrCreateEntity(subfolderNode.getPath(), encodedName, implType, props);

        if (isNew && JcrUserDatasource.class.isAssignableFrom(type)) {
            if (this.accessController.isEntityAccessControlled()) {
                final List<SecurityRole> roles = roleProvider.getEntityRoles(SecurityRole.DATASOURCE);
                actionsProvider.getAvailableActions(AllowedActions.DATASOURCE)
                        .ifPresent(actions -> ((JcrUserDatasource) datasource).enableAccessControl(
                                (JcrAllowedActions) actions, JcrMetadataAccess.getActiveUser(), roles));
            } else {
                actionsProvider.getAvailableActions(AllowedActions.DATASOURCE)
                        .ifPresent(actions -> ((JcrUserDatasource) datasource).disableAccessControl(
                                (JcrAllowedActions) actions, JcrMetadataAccess.getActiveUser()));
            }
        }

        datasource.setTitle(name);
        datasource.setDescription(descr);
        return datasource;
    } catch (IllegalArgumentException | IllegalAccessException | RepositoryException e) {
        throw new MetadataException("Unable to create datasource: " + type, e);
    }
}

From source file:com.taobao.android.builder.tasks.manager.MtlBaseTaskAction.java

protected void setFieldValueByReflection(Task task, String fieldName, Object value) {
    Field field = FieldUtils.getField(task.getClass(), fieldName, true);
    if (null == field) {
        throw new StopExecutionException(
                "The field with name:" + fieldName + " does not existed in class:" + task.getClass().getName());
    }/*from   w w w .ja  va 2 s .c  om*/
    try {
        FieldUtils.writeField(field, task, value, true);
    } catch (IllegalAccessException e) {
        throw new StopExecutionException(e.getMessage());
    }
}

From source file:com.taobao.android.builder.tasks.awo.AwoPackageConfigAction.java

/**
 * ??task/*from  w ww  .  j  ava2 s  .c  om*/
 *
 * @param packageApp
 * @param fieldName
 * @param value
 */
private void setFieldValueByReflection(PackageApplication packageApp, String fieldName, Object value) {
    Field field = FieldUtils.getField(packageApp.getClass(), fieldName, true);
    if (null == field) {
        throw new StopExecutionException("The field with name:" + fieldName + " does not existed in class:"
                + packageApp.getClass().getName());
    }
    try {
        FieldUtils.writeField(field, packageApp, value, true);
    } catch (IllegalAccessException e) {
        throw new StopExecutionException(e.getMessage());
    }
}

From source file:nz.co.testamation.common.util.ReflectionUtil.java

private static Field getField(Object obj, String fieldName) {
    return FieldUtils.getField(obj.getClass(), fieldName, true);
}

From source file:org.apache.logging.log4j.core.util.ClockFactoryTest.java

public static void resetClock(final Class<?> clazz) throws IllegalAccessException {
    System.clearProperty(ClockFactory.PROPERTY_NAME);
    final Field field = FieldUtils.getField(clazz, "CLOCK", true);
    FieldUtils.removeFinalModifier(field, true);
    FieldUtils.writeStaticField(field, ClockFactory.getClock(), false);
}

From source file:org.broadleafcommerce.openadmin.server.service.persistence.module.BasicPersistenceModule.java

protected void cleanupFailedPersistenceAttempt(Serializable instance) throws IllegalAccessException {
    //Remove the entity from ORM management - no further attempts to persist
    if (getPersistenceManager().getDynamicEntityDao().getStandardEntityManager().contains(instance)) {
        getPersistenceManager().getDynamicEntityDao().getStandardEntityManager().detach(instance);
    }//from   w  ww.ja v a 2 s .co m
    //Remove the id field value, if it's set
    String idFieldName = (String) getPersistenceManager().getDynamicEntityDao()
            .getIdMetadata(instance.getClass()).get("name");
    Field idField = FieldUtils.getField(instance.getClass(), idFieldName, true);
    if (idField == null) {
        throw ExceptionHelper.refineException(new NoSuchFieldException(
                "Entity " + instance.getClass().getName() + " does not contain id field " + idFieldName));
    }
    idField.setAccessible(true);
    if (idField.get(instance) != null) {
        idField.set(instance, null);
    }
}

From source file:org.cristalise.lookup.LookupPropertySearchTest.java

@Override
@Before//from ww w  . j  a  va2  s  .co  m
public void setUp() throws Exception {
    super.setUp();

    itemPath0 = new ItemPath(uuid0.toString());
    itemPath1 = new ItemPath(uuid1.toString());

    propType = new Property("Type", "dummy", false);
    propStyle = new Property("Style", "fluffy", false);

    lookup.add(itemPath0);
    lookup.add(itemPath1);
    lookup.add(new DomainPath("toto/item0", itemPath0));
    lookup.add(new DomainPath("toto/item1", itemPath1));

    lookupPropertiesField = (JooqItemPropertyHandler) FieldUtils
            .getField(JooqLookupManager.class, "properties", true).get(lookup);
    lookupContextField = (DSLContext) FieldUtils.getField(JooqLookupManager.class, "context", true).get(lookup);

    lookupPropertiesField.put(lookupContextField, uuid0, propType);
    lookupPropertiesField.put(lookupContextField, uuid1, propType);
    lookupPropertiesField.put(lookupContextField, uuid1, propStyle);
}

From source file:org.debux.webmotion.server.handler.ExecutorParametersConvertorHandler.java

protected Object convert(ParameterTree parameterTree, Class<?> type, Type genericType) throws Exception {
    Object result = null;//  www  . jav  a 2s . com

    if (parameterTree == null) {
        return null;
    }

    if (genericType == null) {
        genericType = type.getGenericSuperclass();
    }

    Map<String, List<ParameterTree>> parameterArray = parameterTree.getArray();
    Map<String, ParameterTree> parameterObject = parameterTree.getObject();
    Object value = parameterTree.getValue();

    Converter lookup = converter.lookup(type);
    if (lookup != null) {

        // converter found, use it
        result = lookup.convert(type, value);
        return result;
    }

    // Manage enums
    if (type.isEnum()) {
        Object name = value == null ? null : ((Object[]) value)[0];
        if (name != null) {
            result = Enum.valueOf((Class<? extends Enum>) type, name.toString());
        }

        // Manage collection
    } else if (Collection.class.isAssignableFrom(type)) {

        Collection instance;
        if (type.isInterface()) {
            if (List.class.isAssignableFrom(type)) {
                instance = new ArrayList();

            } else if (Set.class.isAssignableFrom(type)) {
                instance = new HashSet();

            } else if (SortedSet.class.isAssignableFrom(type)) {
                instance = new TreeSet();

            } else {
                instance = new ArrayList();
            }
        } else {
            instance = (Collection) type.newInstance();
        }

        Class convertType = String.class;
        if (genericType != null && genericType instanceof ParameterizedType) {
            ParameterizedType parameterizedType = (ParameterizedType) genericType;
            convertType = (Class) parameterizedType.getActualTypeArguments()[0];
        }

        if (parameterObject != null) {
            for (Map.Entry<String, ParameterTree> entry : parameterObject.entrySet()) {
                ParameterTree object = entry.getValue();
                Object converted = convert(object, convertType, null);
                instance.add(converted);
            }
        } else {
            Object[] tab = (Object[]) value;
            for (Object object : tab) {
                Object converted = converter.convert(object, convertType);
                instance.add(converted);
            }
        }

        result = instance;

        // Manage map
    } else if (Map.class.isAssignableFrom(type)) {
        Map instance;
        if (type.isInterface()) {
            if (SortedMap.class.isAssignableFrom(type)) {
                instance = new TreeMap();

            } else {
                instance = new HashMap();
            }
        } else {
            instance = (Map) type.newInstance();
        }

        Class convertKeyType = String.class;
        Class convertValueType = String.class;
        if (genericType != null && genericType instanceof ParameterizedType) {
            ParameterizedType parameterizedType = (ParameterizedType) genericType;
            convertKeyType = (Class) parameterizedType.getActualTypeArguments()[0];
            convertValueType = (Class) parameterizedType.getActualTypeArguments()[1];
        }

        for (Map.Entry<String, ParameterTree> entry : parameterObject.entrySet()) {
            String mapKey = entry.getKey();
            ParameterTree mapValue = entry.getValue();

            Object convertedKey = converter.convert(mapKey, convertKeyType);
            Object convertedValue = convert(mapValue, convertValueType, null);

            instance.put(convertedKey, convertedValue);
        }

        result = instance;

        // Manage simple object
    } else if (type.isArray()) {
        Class<?> componentType = type.getComponentType();

        if (parameterObject != null) {
            Object[] tabConverted = (Object[]) Array.newInstance(componentType, parameterObject.size());
            result = tabConverted;

            int index = 0;
            for (Map.Entry<String, ParameterTree> entry : parameterObject.entrySet()) {
                ParameterTree object = entry.getValue();
                Object objectConverted = convert(object, componentType, null);
                tabConverted[index] = objectConverted;
                index++;
            }

        } else {
            Object[] tab = (Object[]) value;
            Object[] tabConverted = (Object[]) Array.newInstance(componentType, tab.length);
            result = tabConverted;

            for (int index = 0; index < tab.length; index++) {
                Object object = tab[index];
                Object objectConverted = converter.convert(object, componentType);
                tabConverted[index] = objectConverted;
            }
        }

    } else if (value instanceof UploadFile) {
        if (File.class.isAssignableFrom(type)) {
            UploadFile uploadFile = (UploadFile) value;
            result = uploadFile.getFile();
        } else {
            result = value;
        }

        // Manage simple object
    } else {
        Object instance = type.newInstance();
        boolean one = false;

        if (parameterObject != null) {
            for (Map.Entry<String, ParameterTree> attribut : parameterObject.entrySet()) {
                String attributeName = attribut.getKey();
                ParameterTree attributeValue = attribut.getValue();

                boolean writeable = propertyUtils.isWriteable(instance, attributeName);
                if (writeable) {
                    one = true;

                    Field field = FieldUtils.getField(type, attributeName, true);
                    Class<?> attributeType = field.getType();

                    genericType = field.getGenericType();
                    Object attributeConverted = convert(attributeValue, attributeType, genericType);
                    beanUtil.setProperty(instance, attributeName, attributeConverted);
                }
            }
        }

        if (parameterArray != null) {
            for (Map.Entry<String, List<ParameterTree>> entry : parameterArray.entrySet()) {
                String attributeName = entry.getKey();
                List<ParameterTree> attributeValues = entry.getValue();

                boolean writeable = propertyUtils.isWriteable(instance, attributeName);
                if (writeable) {
                    one = true;

                    Field field = FieldUtils.getField(type, attributeName, true);
                    Class<?> attributeType = field.getType();

                    genericType = field.getGenericType();
                    Object attributeConverted = convert(attributeValues, attributeType, genericType);
                    beanUtil.setProperty(instance, attributeName, attributeConverted);
                }
            }
        }

        if (one) {
            result = instance;

        } else {
            result = null;
        }
    }

    return result;
}

From source file:org.evosuite.setup.TestAccessField.java

@Test
public void testDefaultField() {
    Properties.CLASS_PREFIX = "some.package";
    Properties.TARGET_CLASS = "some.package.Foo";
    Field f = FieldUtils.getField(com.examples.with.different.packagename.AccessExamples.class, "defaultField",
            true);//w w  w.ja v  a 2s.co m
    boolean result = TestUsageChecker.canUse(f);
    Assert.assertFalse(result);
}