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

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

Introduction

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

Prototype

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

Source Link

Document

Read the named field.

Usage

From source file:org.jodconverter.office.SimpleOfficeManagerTest.java

@Test
public void build_WithValuesAsString_ShouldInitializedOfficeManagerWithCustomValues() throws Exception {

    final OfficeManager manager = SimpleOfficeManager.builder()
            .workingDir(new File(System.getProperty("java.io.tmpdir")).getPath()).build();

    assertThat(manager).isInstanceOf(AbstractOfficeManagerPool.class);
    final SimpleOfficeManagerPoolConfig config = (SimpleOfficeManagerPoolConfig) FieldUtils.readField(manager,
            "config", true);
    assertThat(config.getWorkingDir().getPath())
            .isEqualTo(new File(System.getProperty("java.io.tmpdir")).getPath());
}

From source file:org.jodconverter.office.SimpleOfficeManagerTest.java

@Test
public void build_WithEmptyValuesAsString_ShouldInitializedOfficeManagerWithDefaultValues() throws Exception {

    final OfficeManager manager = SimpleOfficeManager.builder().workingDir("   ").build();

    assertThat(manager).isInstanceOf(AbstractOfficeManagerPool.class);
    final SimpleOfficeManagerPoolConfig config = (SimpleOfficeManagerPoolConfig) FieldUtils.readField(manager,
            "config", true);
    assertThat(config.getWorkingDir().getPath())
            .isEqualTo(new File(System.getProperty("java.io.tmpdir")).getPath());
}

From source file:org.nebula.service.dao.PaginationInterceptor.java

public Object intercept(Invocation inv) throws Throwable {

    StatementHandler target = (StatementHandler) inv.getTarget();
    BoundSql boundSql = target.getBoundSql();
    String sql = boundSql.getSql();
    if (StringUtils.isBlank(sql)) {
        return inv.proceed();
    }// ww  w .  ja  v a  2  s  .  c om
    logger.debug("origin sql>>>>>" + sql.replaceAll("\n", ""));
    // ?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", newSql(sql, rowBounds), true);
            logger.debug("new sql>>>>>" + boundSql.getSql().replaceAll("\n", ""));
            // ???(?)
            FieldUtils.writeField(rowBounds, "offset", RowBounds.NO_ROW_OFFSET, true);
            FieldUtils.writeField(rowBounds, "limit", RowBounds.NO_ROW_LIMIT, true);
        }
    }
    return inv.proceed();
}

From source file:org.openengsb.core.ekb.common.EDBConverterUtils.java

/**
 * Adds to the EDBObject special entries which mark that a model is referring to other models through
 * OpenEngSBForeignKey annotations/*from www .  ja  v  a  2  s  .  co m*/
 */
public static void fillEDBObjectWithEngineeringObjectInformation(EDBObject object, OpenEngSBModel model)
        throws IllegalAccessException {
    if (!new SimpleModelWrapper(model).isEngineeringObject()) {
        return;
    }
    for (Field field : model.getClass().getDeclaredFields()) {
        OpenEngSBForeignKey annotation = field.getAnnotation(OpenEngSBForeignKey.class);
        if (annotation == null) {
            continue;
        }
        String value = (String) FieldUtils.readField(field, model, true);
        if (value == null) {
            continue;
        }
        value = String.format("%s/%s", ContextHolder.get().getCurrentContextId(), value);
        String key = getEOReferenceStringFromAnnotation(annotation);
        object.put(key, new EDBObjectEntry(key, value, String.class));
    }
}

From source file:org.openengsb.core.ekb.common.EngineeringObjectModelWrapper.java

/**
 * Loads the model referenced by the given field for the given model instance. Returns null if the field has no
 * value set./*from ww  w.  ja v  a 2 s .  c  o m*/
 */
public SimpleModelWrapper loadReferencedModel(Field field, ModelRegistry modelRegistry,
        EngineeringDatabaseService edbService, EDBConverter edbConverter) {
    try {
        ModelDescription description = getModelDescriptionFromField(field);
        String modelKey = (String) FieldUtils.readField(field, model, true);
        if (modelKey == null) {
            return null;
        }
        modelKey = appendContextId(modelKey);
        Class<?> sourceClass = modelRegistry.loadModel(description);
        return new SimpleModelWrapper(
                edbConverter.convertEDBObjectToModel(sourceClass, edbService.getObject(modelKey)));
    } catch (SecurityException e) {
        throw new EKBException(generateErrorMessage(field), e);
    } catch (IllegalArgumentException e) {
        throw new EKBException(generateErrorMessage(field), e);
    } catch (IllegalAccessException e) {
        throw new EKBException(generateErrorMessage(field), e);
    } catch (ClassNotFoundException e) {
        throw new EKBException(generateErrorMessage(field), e);
    }
}

From source file:org.openengsb.core.ekb.persistence.persist.edb.internal.ModelDiff.java

/**
 * Calculates the real differences between the two models of the given ModelDiff and saves them to the differences
 * field of the ModelDiff class./*from  ww w. j  av a 2 s .  c om*/
 */
private static void calculateDifferences(ModelDiff diff) {
    Class<?> modelClass = diff.getBefore().getClass();
    for (Field field : modelClass.getDeclaredFields()) {
        if (field.getName().equals(ModelUtils.MODEL_TAIL_FIELD_NAME)) {
            continue;
        }
        try {
            Object before = FieldUtils.readField(field, diff.getBefore(), true);
            Object after = FieldUtils.readField(field, diff.getAfter(), true);
            if (!Objects.equal(before, after)) {
                diff.addDifference(field, before, after);
            }
        } catch (IllegalAccessException e) {
            LOGGER.warn("Skipped field '{}' because of illegal access to it", field.getName(), e);
        }
    }
}

From source file:org.openhab.binding.weather.internal.utils.PropertyUtils.java

/**
 * Returns the object of the (nested) property.
 *///w  ww  .  j  a v  a2 s . c  o  m
public static Object getNestedObject(Object instance, String propertyName) throws IllegalAccessException {
    if (PropertyUtils.isWeatherProperty(propertyName)) {
        return instance;
    }

    while (PropertyResolver.hasNested(propertyName)) {
        instance = FieldUtils.readField(instance, PropertyResolver.first(propertyName), true);
        propertyName = PropertyResolver.removeFirst(propertyName);
    }
    return instance;
}

From source file:org.ops4j.ramler.generator.EnumsTest.java

@SuppressWarnings("unchecked")
@Test/*w  w w .j  a va 2s. c  o  m*/
public void shouldFindEnumValues() throws IllegalAccessException {
    klass = modelPackage._getClass("Colour");
    assertThat(klass.getClassType()).isEqualTo(ClassType.ENUM);
    Map<String, JEnumConstant> enums = (Map<String, JEnumConstant>) FieldUtils.readField(klass,
            "enumConstantsByName", true);
    assertThat(enums.keySet()).contains("LIGHT_BLUE", "RED");

    JEnumConstant lightBlue = enums.get("LIGHT_BLUE");
    assertThat(lightBlue.javadoc().get(0)).isEqualTo("Colour of the sky");

    List<JExpression> args = (List<JExpression>) FieldUtils.readField(lightBlue, "args", true);
    assertThat(args).hasSize(1);

    assertThat(args.get(0)).isInstanceOf(JStringLiteral.class);

    String literal = (String) FieldUtils.readField(args.get(0), "str", true);
    assertThat(literal).isEqualTo("lightBlue");
}

From source file:org.ops4j.ramler.generator.SimpleObjectTest.java

@SuppressWarnings("unchecked")
@Test// w  w w .  j a v  a  2s  .co m
public void shouldFindEnumValues() throws IllegalAccessException {
    klass = modelPackage._getClass("Colour");
    assertThat(klass.getClassType()).isEqualTo(ClassType.ENUM);
    Map<String, JEnumConstant> enums = (Map<String, JEnumConstant>) FieldUtils.readField(klass,
            "enumConstantsByName", true);
    assertThat(enums.keySet()).containsExactly("LIGHT_BLUE", "RED", "YELLOW", "GREEN");
}

From source file:org.sonar.process.logging.LogbackHelperTest.java

@Test
public void createRollingPolicy_size() throws Exception {
    props.set("sonar.log.rollingPolicy", "size:1MB");
    props.set("sonar.log.maxFiles", "20");
    LoggerContext ctx = underTest.getRootContext();
    LogbackHelper.RollingPolicy policy = underTest.createRollingPolicy(ctx, props, "sonar");

    Appender appender = policy.createAppender("SONAR_FILE");
    assertThat(appender).isInstanceOf(RollingFileAppender.class);

    // max 20 files of 1Mb
    RollingFileAppender fileAppender = (RollingFileAppender) appender;
    FixedWindowRollingPolicy rollingPolicy = (FixedWindowRollingPolicy) fileAppender.getRollingPolicy();
    assertThat(rollingPolicy.getMaxIndex()).isEqualTo(20);
    assertThat(rollingPolicy.getFileNamePattern()).endsWith("sonar.%i.log");
    SizeBasedTriggeringPolicy triggeringPolicy = (SizeBasedTriggeringPolicy) fileAppender.getTriggeringPolicy();
    FileSize maxFileSize = (FileSize) FieldUtils.readField(triggeringPolicy, "maxFileSize", true);
    assertThat(maxFileSize.getSize()).isEqualTo(1024L * 1024);
}