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:cn.wanghaomiao.seimi.utils.StructValidator.java

public static boolean validateAnno(Object object) {
    for (Field field : object.getClass().getDeclaredFields()) {
        NotNull notNullCheck = field.getAnnotation(NotNull.class);
        if (notNullCheck != null) {
            try {
                Object val = FieldUtils.readField(field, object, true);
                if (StringUtils.isBlank(String.valueOf(val))) {
                    logger.error("Field={}.{} can not be null!", object.getClass().getSimpleName(),
                            field.getName());
                    return false;
                }/*  w ww . ja  va2s  .  co  m*/
            } catch (IllegalAccessException e) {
                logger.error(e.getMessage(), e);
            }
        }
    }
    return true;
}

From source file:com.github.srgg.yads.JsonUnitInitializer.java

public static ObjectMapper initialize() {
    // making JsonAssert to be more tolerant to JSON format
    final Object converter;
    try {//from   w w  w  . ja v a  2  s .co  m
        converter = FieldUtils.readStaticField(JsonUtils.class, "converter", true);
        final List<NodeFactory> factories = (List<NodeFactory>) FieldUtils.readField(converter, "factories",
                true);

        ObjectMapper mapper;
        for (NodeFactory nf : factories) {
            if (nf.getClass().getSimpleName().equals("Jackson2NodeFactory")) {
                mapper = (ObjectMapper) FieldUtils.readField(nf, "mapper", true);
                mapper.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, true)
                        .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true)
                        .configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true)
                        .configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true)
                        .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);

                return mapper;
            }
        }
    } catch (IllegalAccessException e) {
        throw new IllegalStateException("Can't initialize Jackson2 ObjectMapper because of UE", e);
    }

    throw new IllegalStateException("Can't initialize Jackson2 ObjectMapper, Jackson2NodeFactory is not found");
}

From source file:atg.tools.dynunit.DynUnit.java

public static void stop(final Object testInstance) {
    logger.entry(testInstance);//  w w w .  j a  va2s. c  om
    boolean foundNucleus = false;
    final Field[] fields = testInstance.getClass().getDeclaredFields();
    for (final Field field : fields) {
        if (field.isAnnotationPresent(Nuke.class)) {
            foundNucleus = true;
            try {
                final Nucleus nucleus = (Nucleus) FieldUtils.readField(field, testInstance, true);
                logger.info("Found Nucleus: {}.", nucleus.getAbsoluteName());
                if (nucleus.isRunning()) {
                    logger.info("Stopping Nucleus.");
                    nucleus.stopService();
                }
            } catch (IllegalAccessException e) {
                logger.catching(e);
                logger.error("Can't access test instance's Nucleus. Strange.");
            } catch (ServiceException e) {
                logger.catching(e);
                logger.warn("Problem stopping Nucleus.");
            }
        }
    }
    if (!foundNucleus) {
        logger.error("Couldn't find nucleus field to stop!");
    }
    logger.exit();
}

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

public static void serializeToMap(Map<String, Object> map, Object sourceObject) {
    if (sourceObject == null) {
        return;//w  w  w .  j av a2  s  . com
    }
    FieldUtils.getAllFieldsList(sourceObject.getClass()).stream().filter(IntrospectionUtil::isSimple)
            .forEach(f -> {
                try {
                    Object value = FieldUtils.readField(f, sourceObject, true);
                    if (value != null) {
                        map.put(f.getName(), value);
                    }
                } catch (IllegalAccessException ex) {
                    java.util.logging.Logger.getLogger(ValueMapSerializer.class.getName()).log(Level.SEVERE,
                            null, ex);
                }
            });
}

From source file:io.rhiot.utils.Reflections.java

public static <T> T readField(Object object, String field, Class<T> type) {
    try {/*from ww  w . j a v  a 2  s.co m*/
        Field actualField = getField(object.getClass(), field, true);
        if (!isInstanceOfOrWrappable(actualField.getType(), type)) {
            String message = format("Field %s is a type of %s instead of %s.", field, actualField.getType(),
                    type);
            throw new IllegalStateException(message);
        }
        return (T) FieldUtils.readField(actualField, object, true);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.norconex.importer.handler.splitter.impl.FixedGoogleTranslator.java

public String getApiKey() {
    try {//from  ww w  . ja  va2 s  .  co  m
        return (String) FieldUtils.readField(this, "apiKey", true);
    } catch (IllegalAccessException e) {
        throw new ImporterRuntimeException("Cannot set api key.", e);
    }
}

From source file:com.norconex.importer.handler.splitter.impl.FixedLingo24Translator.java

public String getUserKey() {
    try {//from   w w w .  j a  va 2  s  . c  o  m
        return (String) FieldUtils.readField(this, "userKey", true);
    } catch (IllegalAccessException e) {
        throw new ImporterRuntimeException("Cannot set user key.", e);
    }
}

From source file:com.astamuse.asta4d.web.form.flow.base.StepAwaredValidationFormHelper.java

static final Object getValidationTargetByAnnotation(Object form, String step) {
    String cacheKey = step + "@" + form.getClass().getName();
    Optional<Field> oField = ValidationTargetFieldCache.get(cacheKey);

    if (oField == null) {
        List<Field> list = new ArrayList<>(ClassUtil.retrieveAllFieldsIncludeAllSuperClasses(form.getClass()));
        Iterator<Field> it = list.iterator();
        while (it.hasNext()) {
            Field f = it.next();//  ww  w . jav  a  2  s. co m
            StepAwaredValidationTarget vtAnno = f.getAnnotation(StepAwaredValidationTarget.class);
            if (vtAnno == null) {
                continue;
            }
            String representingStep = vtAnno.value();
            if (step.equals(representingStep)) {
                oField = Optional.of(f);
                break;
            }
        }
        if (oField == null) {
            oField = Optional.empty();
        }
        if (Configuration.getConfiguration().isCacheEnable()) {
            Map<String, Optional<Field>> newCache = new HashMap<>(ValidationTargetFieldCache);
            newCache.put(cacheKey, oField);
            ValidationTargetFieldCache = newCache;
        }
    }

    if (oField.isPresent()) {
        try {
            return FieldUtils.readField(oField.get(), form, true);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    } else {
        return form;
    }
}

From source file:com.castlemock.core.basis.model.validation.validator.NotNullValidator.java

/**
 * The method is responsible for validating a provided message and enforce the rule that the
 * validator is responsible for// w  w w  . java 2s.  c  o  m
 * @param message The message that will be validated
 * @param field The specific field that will be validated
 */
@Override
protected void validateMessage(final Message message, final String field) {
    try {
        final Object object = FieldUtils.readField(message, field, true);
        if (object == null) {
            throw new NullPointerException("The following value cannot be null in the message "
                    + message.getClass().getSimpleName() + ": " + field);
        }
    } catch (IllegalAccessException e) {
        LOGGER.error("Unable to read the following value in the message " + message.getClass().getSimpleName()
                + ": " + field, e);
    }
}

From source file:de.tudarmstadt.ukp.dkpro.core.ixa.internal.IxaLemmatizerTagsetDescriptionProvider.java

@Override
public Set<String> listTags(String aLayer, String aTagsetName) {
    try {/*  ww  w  .java  2 s . c  om*/
        AbstractModel innerModel = (AbstractModel) FieldUtils.readField(model, "model", true);
        HashMap<String, Integer> pmap = (HashMap<String, Integer>) FieldUtils.readField(innerModel, "pmap",
                true);

        Set<String> tagSet = new TreeSet<String>();
        String prefix = feature + separator;
        for (Object key : pmap.keySet()) {
            if (key instanceof String && ((String) key).startsWith(prefix)) {
                tagSet.add(StringUtils.substringAfter(((String) key), separator));
            }
        }

        return tagSet;
    } catch (IllegalAccessException e) {
        throw new IllegalStateException(e);
    }
}