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.anrisoftware.globalpom.reflection.beans.BeanAccessImpl.java

private <T> T getValueFromField(Field field, Object bean) {
    try {/* w w  w . j  a v a  2s .  c o  m*/
        return toType(FieldUtils.readField(field, bean, true));
    } catch (IllegalAccessException e) {
        throw log.illegalAccessError(e, fieldName, bean);
    }
}

From source file:com.github.lukaszbudnik.dqueue.jaxrs.service.QueueServiceTest.java

@Test
public void shouldConsumeWithFilters() throws IllegalAccessException, IOException {
    Response response = resources.getJerseyTest().client().target("/dqueue/v1/consume").request()
            .header(QueueService.X_DQUEUE_FILTERS, filtersHeader)
            .accept(MediaType.APPLICATION_OCTET_STREAM_TYPE).get();

    ClientResponse clientResponse = (ClientResponse) FieldUtils.readField(response, "context", true);

    ByteArrayInputStream bais = (ByteArrayInputStream) response.getEntity();
    byte[] contents = IOUtils.toByteArray(bais);
    String startTime = clientResponse.getHeaderString(QueueService.X_DQUEUE_START_TIME_HEADER);
    String filters = clientResponse.getHeaderString(QueueService.X_DQUEUE_FILTERS);
    String cacheControl = clientResponse.getHeaderString(HttpHeaders.CACHE_CONTROL);

    assertThat(response.getStatus(), equalTo(Response.Status.OK.getStatusCode()));
    assertThat(cacheControl, equalTo("no-cache"));
    assertThat(filters, equalTo(filtersHeader));
    assertThat(contents, equalTo(itemWithFilters.getContents().array()));
    assertThat(startTime, equalTo(itemWithFilters.getStartTime().toString()));

    verify(queueClient, times(1)).consume(eq(itemWithFilters.getFilters()));
}

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

public void willAttachInternalRetryHandlersToProvidedBuilder()
        throws IOException, ReflectiveOperationException {
    config.setRetries(1);//from   w  ww . ja v a2s  .  c om

    final MantaConnectionFactoryConfigurator conf = new MantaConnectionFactoryConfigurator(builder);
    connectionFactory = new MantaConnectionFactory(config, conf);

    final Object factoryInternalBuilder = FieldUtils.readField(connectionFactory, "httpClientBuilder", true);
    final Object retryHandler = FieldUtils.readField(factoryInternalBuilder, "retryHandler", true);
    final Object serviceUnavailStrategy = FieldUtils.readField(factoryInternalBuilder, "serviceUnavailStrategy",
            true);

    Assert.assertTrue(retryHandler instanceof MantaHttpRequestRetryHandler);
    Assert.assertTrue(serviceUnavailStrategy instanceof MantaServiceUnavailableRetryStrategy);
}

From source file:com.joyent.manta.client.multipart.AbstractMultipartManager.java

/**
 * <p>Uses reflection to read a private field from a {@link MantaClient}
 * instance.</p>//from   ww  w.j  a  v  a  2s . c  o m
 *
 * <p>We use reflection to read private fields from {@link MantaClient} as
 * part of a compromise between package level separation and private/default
 * scoping. Essentially, it makes sense to put multipart related classes
 * in their own package because the package in which {@link MantaClient} is
 * contained is already crowded. However, by making that decision there is
 * no scoping mechanism available in Java to allow us to share
 * methods/fields between packages without giving other packages access.
 * Thus, we scope the methods/fields that shouldn't be available to a user
 * of the SDK as private/protected/default and use reflection
 * <em>sparingly</em> to access the values from another package. Particular
 * care has been paid to making this reflection-based reads outside of
 * performance sensitive code paths.</p>
 *
 * @param fieldName field name to read
 * @param mantaClient Manta client instance to read fields from
 * @param returnType type of field
 * @param <T> field type
 * @return value of the field
 */
protected static <T> T readFieldFromMantaClient(final String fieldName, final MantaClient mantaClient,
        final Class<T> returnType) {
    final Field field = FieldUtils.getField(MantaClient.class, fieldName, true);

    try {
        Object object = FieldUtils.readField(field, mantaClient, true);
        return returnType.cast(object);
    } catch (IllegalAccessException e) {
        throw new MantaMultipartException("Unable to access httpHelper " + "field on MantaClient");
    }
}

From source file:bootstrap.JsonInitialData.java

private List<DiffRecord> diffObjects(Object newObject, Object oldObject, final Set<String> ignoreFields) {
    List<DiffRecord> result = new LinkedList<DiffRecord>();
    Set<Field> allFields = ReflectionUtils.getAllFields(newObject.getClass(), new Predicate<Field>() {
        @Override//  w w  w.  j av  a2 s . co m
        public boolean apply(Field field) {
            return !ignoreFields.contains(field.getName());
        }
    });
    for (Field field : allFields) {
        try {
            Object oldValue = FieldUtils.readField(field, oldObject, true);
            Object newValue = FieldUtils.readField(field, oldObject, true);
            if (!ObjectUtils.equals(oldValue, newValue)) {
                result.add(new DiffRecord(field.getName(), oldValue, newValue));
            }
        } catch (Exception e) {
            logger.error("unable to get field values [{}]", e);
        }
    }
    return result;
}

From source file:com.feilong.core.lang.reflect.FieldUtil.java

/**
 * ? <code>owner</code>  <code>fieldName</code> .
 *
 * @param <T>//w  w  w .j ava  2 s .  c  o  m
 *            the generic type
 * @param obj
 *            the owner
 * @param fieldName
 *            the field name
 * @return  <code>owner</code> null, {@link NullPointerException}<br>
 *          <code>fieldName</code> null, {@link NullPointerException}<br>
 *          <code>fieldName</code> blank, {@link IllegalArgumentException}<br>
 * @see org.apache.commons.lang3.reflect.FieldUtils#readField(Object, String, boolean)
 * @since 1.4.0
 */
@SuppressWarnings("unchecked")
public static <T> T getFieldValue(Object obj, String fieldName) {
    try {
        return (T) FieldUtils.readField(obj, fieldName, true);
    } catch (IllegalAccessException e) {
        String message = Slf4jUtil.format("ownerClass:[{}],fieldName:[{}],ownerObj:[{}]",
                obj.getClass().getName(), fieldName, obj);
        LOGGER.error(message, e);
        throw new ReflectException(message, e);
    }
}

From source file:com.offbynull.coroutines.instrumenter.InstrumenterTest.java

@Test
public void mustProperlySuspendWithSerialization() throws Exception {
    try (URLClassLoader classLoader = loadClassesInZipResourceAndInstrument(
            SERIALIZABLE_INVOKE_TEST + ".zip")) {
        Class<Coroutine> cls = (Class<Coroutine>) classLoader.loadClass(SERIALIZABLE_INVOKE_TEST);
        Coroutine coroutine = ConstructorUtils.invokeConstructor(cls, new StringBuilder());

        // Create and run original for a few cycles
        CoroutineRunner originalRunner = new CoroutineRunner(coroutine);

        Assert.assertTrue(originalRunner.execute());
        Assert.assertTrue(originalRunner.execute());
        Assert.assertTrue(originalRunner.execute());
        Assert.assertTrue(originalRunner.execute());
        Assert.assertTrue(originalRunner.execute());
        Assert.assertTrue(originalRunner.execute());

        // Serialize
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(originalRunner);
        oos.close();// www  . j a v  a2 s .c  o m
        baos.close();
        byte[] serializedCoroutine = baos.toByteArray();

        // Deserialize
        ByteArrayInputStream bais = new ByteArrayInputStream(serializedCoroutine);
        ObjectInputStream ois = new ObjectInputStream(bais) {

            @Override
            protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException {
                try {
                    return super.resolveClass(desc);
                } catch (ClassNotFoundException cnfe) {
                    return classLoader.loadClass(desc.getName());
                }
            }

        };
        CoroutineRunner deserializedRunner = (CoroutineRunner) ois.readObject();

        // Continue running deserialized
        Assert.assertTrue(deserializedRunner.execute());
        Assert.assertTrue(deserializedRunner.execute());
        Assert.assertTrue(deserializedRunner.execute());
        Assert.assertTrue(deserializedRunner.execute());
        Assert.assertFalse(deserializedRunner.execute()); // coroutine finished executing here
        Assert.assertTrue(deserializedRunner.execute());
        Assert.assertTrue(deserializedRunner.execute());
        Assert.assertTrue(deserializedRunner.execute());

        // Assert everything continued fine with deserialized version
        Object deserializedCoroutine = FieldUtils.readField(deserializedRunner, "coroutine", true);
        StringBuilder deserializedBuilder = (StringBuilder) FieldUtils.readField(deserializedCoroutine,
                "builder", true);

        Assert.assertEquals("started\n" + "0\n" + "1\n" + "2\n" + "3\n" + "4\n" + "5\n" + "6\n" + "7\n" + "8\n"
                + "9\n" + "started\n" + "0\n" + "1\n" + "2\n", deserializedBuilder.toString());
    }
}

From source file:com.garethahealy.camel.dynamic.loadbalancer.statistics.mbeans.MBeanRouteStatisticsCollector.java

/**
 * Get the uri from the processor (NOTE: Current impl uses reflection, so could fail easily)
 *
 * @param current//from ww  w  . j  a v  a 2  s  . co m
 * @return
 */
private String getUriFromProcessor(Processor current) {
    String uri = "";

    //NOTE: What if camel uses different 'Channels', this wont work.
    // How can i get the URI from the processor in a nice way?

    if (current instanceof DefaultChannel) {
        DefaultChannel currentChannel = (DefaultChannel) current;

        Object outputValue = null;
        try {
            //NOTE: Shouldnt really be using reflection...but dont know what class i can use
            Field outputField = FieldUtils.getField(DefaultChannel.class, "childDefinition", true);
            outputValue = FieldUtils.readField(outputField, currentChannel, true);
        } catch (IllegalAccessException ex) {
            LOG.error("Cannot access 'childDefinition' on {} because: {}", current,
                    ExceptionUtils.getStackTrace(ex));
        }

        //NOTE: What if the definition isnt a To, its another type...
        if (outputValue != null && outputValue instanceof ToDefinition) {
            ToDefinition to = (ToDefinition) outputValue;

            uri = normalizeUri(to.getUri());
        }
    }

    if (uri.isEmpty()) {
        throw new IllegalStateException("Could not get URI from processor '" + current + "'");
    }

    return uri;
}

From source file:com.frank.search.solr.core.ResultHelper.java

private static Object getMappedId(Object o) {
    if (ClassUtils.hasProperty(o.getClass(), "id")) {
        try {/*ww  w. ja  va2 s.c  o  m*/
            return FieldUtils.readDeclaredField(o, "id", true);
        } catch (IllegalAccessException e) {
            throw new MappingException("Id property could not be accessed!", e);
        }
    }

    for (java.lang.reflect.Field field : o.getClass().getDeclaredFields()) {
        Annotation annotation = AnnotationUtils.getAnnotation(field, Id.class);
        if (annotation != null) {
            try {
                return FieldUtils.readField(field, o, true);
            } catch (IllegalArgumentException e) {
                throw new MappingException("Id property could not be accessed!", e);
            } catch (IllegalAccessException e) {
                throw new MappingException("Id property could not be accessed!", e);
            }
        }
    }
    throw new MappingException("Id property could not be found!");
}

From source file:com.mh.commons.utils.Reflections.java

/**
 * ?? trim() /*from   ww w . j  av  a  2s . com*/
 * ?? trim();  ??
 * @param obj
 * @param escapeList ??trim()
 * @return
 */
public static Object trim(Object obj, List<String> escapeList) {
    if (obj == null)
        return null;
    try {
        Field[] fields = obj.getClass().getDeclaredFields();
        if (fields != null && fields.length > 0) {
            for (Field field : fields) {
                if (field.getModifiers() < 15 && field.getType().toString().equals("class java.lang.String")) {
                    Object val = FieldUtils.readField(field, obj, true);
                    if (val != null) {
                        if (escapeList != null && escapeList.indexOf(field.getName()) != -1)
                            continue;
                        FieldUtils.writeField(field, obj, val.toString().trim(), true);
                    }
                }
            }
        }
    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
    return obj;
}