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:org.ktc.soapui.maven.extension.impl.runner.SoapUIProExtensionMockServiceRunner.java

private CoverageBuilder getCoverageBuilder() {
    try {//w  w w . j a va2  s .  co  m
        return (CoverageBuilder) FieldUtils.readField(this, COVERAGE_BUILDER_FIELD_NAME, true);
    } catch (IllegalAccessException e) {
        throw new RuntimeException("Unable to read field " + COVERAGE_BUILDER_FIELD_NAME, e);
    }
}

From source file:org.lesscss.LessCompilerTest.java

@Test
public void testNewLessCompiler() throws Exception {
    assertEquals(LessCompiler.class.getClassLoader().getResource("META-INF/env.rhino.js"),
            FieldUtils.readField(lessCompiler, "envJs", true));
    assertEquals(LessCompiler.class.getClassLoader().getResource("META-INF/less.js"),
            FieldUtils.readField(lessCompiler, "lessJs", true));
    assertEquals(Collections.EMPTY_LIST, FieldUtils.readField(lessCompiler, "customJs", true));
}

From source file:org.meveo.admin.action.BaseBean.java

private void loadPartOfModules() {
    if ((entity instanceof BusinessEntity) && isPartOfModules()) {
        BusinessEntity businessEntity = (BusinessEntity) entity;
        String appliesTo = null;/*from ww w.  j  a va2s . c  o m*/
        if (ReflectionUtils.hasField(entity, "appliesTo")) {
            try {
                appliesTo = (String) FieldUtils.readField(entity, "appliesTo", true);
            } catch (IllegalAccessException e) {
                log.error("Failed to access 'appliesTo' field value", e);
            }
        }

        partOfModules = meveoModuleService.getRelatedModulesAsString(businessEntity.getCode(), clazz.getName(),
                appliesTo, businessEntity.getProvider());
    }
}

From source file:org.openmrs.EncounterTest.java

/**
 * @see Encounter#addProvider(EncounterRole,Provider)
 * @verifies not add same provider twice for role
 *//*  ww w .  j  a v a 2  s  .  co m*/
@Test
public void addProvider_shouldNotAddSameProviderTwiceForRole() throws Exception {
    //given
    Encounter encounter = new Encounter();
    EncounterRole role = new EncounterRole();
    Provider provider1 = new Provider();

    //when
    encounter.addProvider(role, provider1);
    encounter.addProvider(role, provider1);

    //then
    // we need to cheat and use reflection to look at the private encounterProviders property; we don't want the getProvidersByRole method hiding duplicates from us
    Collection<EncounterProvider> providers = (Collection<EncounterProvider>) FieldUtils.readField(encounter,
            "encounterProviders", true);
    Assert.assertEquals(1, providers.size());
    Assert.assertTrue(encounter.getProvidersByRole(role).contains(provider1));
}

From source file:org.openmrs.ProviderTest.java

/**
 * @see {@link Provider#setPerson(Person)}
 *//*from w  ww .  j  a  va2s. c  om*/
@Test
@Verifies(value = "should blank out name if set to non null person", method = "setPerson(Person)")
public void setPerson_shouldBlankOutNameIfSetToNonNullPerson() throws Exception {
    final String providerName = "Provider Name";
    final String nameField = "name";

    Provider provider = new Provider();
    provider.setName(providerName);
    Assert.assertEquals(providerName, FieldUtils.readField(provider, nameField, true));

    Person person = new Person(1);
    person.addName(new PersonName("givenName", "middleName", "familyName"));
    provider.setPerson(person);
    Assert.assertNull(FieldUtils.readField(provider, nameField, true));
}

From source file:org.pepstock.jem.ant.tasks.StepListener.java

/**
 * If a task locking scope is set, load resources definition and asks for locking
 * // www. j av a2  s  .c  o m
 * @param event ANT event
 */
@Override
public void taskStarted(BuildEvent event) {
    // checks if you are using a JAVA ANT task with FORK
    // this option is not allowed because with the fork
    // the application is out of secured environment,
    // that means without security manager

    // checks if is cast-able
    if (event.getTask() != null) {
        Task task = null;
        // checks if is an Unknown element
        if (event.getTask() instanceof UnknownElement) {
            // gets ANT task
            UnknownElement ue = (UnknownElement) event.getTask();
            ue.maybeConfigure();
            task = (Task) ue.getTask();
        } else if (event.getTask() instanceof Task) {
            // gets the task
            // here if the ANT task is already configured
            // mainly on sequential, parallel and JEM procedure
            task = (Task) event.getTask();
        }
        // if is a ANT JAVA TASK
        if (task instanceof Java && !(task instanceof StepJava)) {
            // gets AJAV task
            Java java = (Java) task;
            boolean isFork = true;
            try {
                // reflection to understand if the attribute fork is set to true
                // unfortunately ANT java task don't have any get method to have fork value
                Field f = java.getClass().getDeclaredField(ANT_JAVA_TASK_FORK_ATTRIBUTE_NAME);
                isFork = (Boolean) FieldUtils.readField(f, java, true);
            } catch (SecurityException e) {
                LogAppl.getInstance().ignore(e.getMessage(), e);
            } catch (NoSuchFieldException e) {
                LogAppl.getInstance().ignore(e.getMessage(), e);
            } catch (IllegalAccessException e) {
                LogAppl.getInstance().ignore(e.getMessage(), e);
            }
            // and force FORK to false
            java.setFork(false);
            if (isFork) {
                // shows the message of the force of fork.
                event.getProject().log(
                        AntMessage.JEMA077W.toMessage().getFormattedMessage(event.getTask().getTaskName()));
            }
        }

    }

    // if task locking scope is set, locks resources
    if (isTaskLockingScope()) {
        loadForLock(event.getTask());
        checkProcedure();
        try {
            locker.lock();
        } catch (AntException e) {
            throw new BuildException(e);
        }
    }

}

From source file:org.pepstock.jem.junit.test.antutils.java.TrySecurity.java

/**
 * //from  w ww . ja  v a 2 s. c  o  m
 * @param args
 * @throws Exception
 */
public static void main(String[] args) throws Exception {

    String what = null;
    try {
        what = "CHANGE SECURITY MANAGER!";
        // gry to change security manager
        System.setSecurityManager(null);
    } catch (Exception e) {
        e.printStackTrace();
        try {
            what = "CHANGE FIELD OF SECURITY MANAGER!";
            SecurityManager sm = System.getSecurityManager();
            Field f = sm.getClass().getField("isAdministrator");
            System.err.println(FieldUtils.readField(f, sm, true));
        } catch (Exception e1) {
            e1.printStackTrace();
            return;
        }
    }
    throw new SecurityException("Securitymanager is not secure: " + what);
}

From source file:org.pepstock.jem.junit.test.springbatch.java.TrySecurityRunnable.java

@Override
public void run() {

    String what = null;/*ww w.j av  a2  s  . com*/
    try {
        what = "CHANGE SECURITY MANAGER!";
        // gry to change security manager
        System.setSecurityManager(null);
    } catch (Exception e) {
        e.printStackTrace();
        try {
            what = "CHANGE FIELD OF SECURITY MANAGER!";
            SecurityManager sm = System.getSecurityManager();
            Field f = sm.getClass().getField("isAdministrator");
            System.err.println(FieldUtils.readField(f, sm, true));
        } catch (Exception e1) {
            e1.printStackTrace();
            return;
        }
    }
    throw new SecurityException("Securitymanager is not secure: " + what);
}

From source file:org.silverpeas.core.viewer.service.ViewServiceConcurrencyDemonstrationIT.java

@Test
public void demonstrateConcurrencyManagement() throws Exception {
    if (canPerformViewConversionTest()) {
        final List<Throwable> throwables = new ArrayList<>();

        final ConcurrentMap serviceCache = (ConcurrentMap) FieldUtils.readField(viewService, "cache", true);
        assertThat(serviceCache.size(), is(0));

        final long startTime = System.currentTimeMillis();
        final int NB_VIEW_CALLS = 100;
        final int LAST_REQUEST_INDEX = NB_VIEW_CALLS - 1;
        final long durationToIncreaseChancesToPerformThreadBefore = 50;

        final long[] durationTimes = new long[NB_VIEW_CALLS];
        final long[] endTimes = new long[NB_VIEW_CALLS];
        final DocumentView[] results = new DocumentView[NB_VIEW_CALLS];

        for (int i = 0; i < LAST_REQUEST_INDEX; i++) {
            final int index = i;
            SubThreadManager.addAndStart(new Thread(() -> {
                try {
                    final long startThreadTime = System.currentTimeMillis();
                    final DocumentView viewFirstRequest = viewService
                            .getDocumentView(ViewerContext.from(getSimpleDocumentNamed("file.ppt")));
                    final long endThreadTime = System.currentTimeMillis();
                    durationTimes[index] = endThreadTime - startThreadTime;
                    endTimes[index] = endThreadTime;
                    results[index] = viewFirstRequest;
                } catch (Exception e) {
                    throwables.add(e);//from w  ww .j  a  v  a 2  s.c om
                    SubThreadManager.killAll();
                }
            }));
        }

        SubThreadManager.addAndStart(new Thread(() -> {
            try {
                Thread.sleep(500);

                // Technical verification
                assertThat("At this level, the cache has 2 elements", serviceCache.size(), is(2));
                assertThat(getTemporaryPath().listFiles(), arrayWithSize(2));

            } catch (Throwable e) {
                throwables.add(e);
                SubThreadManager.killAll();
            }
        }));

        Thread.sleep(durationToIncreaseChancesToPerformThreadBefore);

        final long startLastRequestTime = System.currentTimeMillis();
        final DocumentView viewLastRequest = viewService
                .getDocumentView(ViewerContext.from(getSimpleDocumentNamed("file.ppt")));
        final long endLastRequestTime = System.currentTimeMillis();
        durationTimes[LAST_REQUEST_INDEX] = endLastRequestTime - startLastRequestTime;
        endTimes[LAST_REQUEST_INDEX] = endLastRequestTime;
        results[LAST_REQUEST_INDEX] = viewLastRequest;

        // Waiting for all thread ends
        SubThreadManager.joinAll(60000);

        for (Throwable throwable : throwables) {
            throw new RuntimeException(throwable);
        }

        for (long endTime : endTimes) {
            assertThat(endTime, greaterThan(startTime));
        }

        long minEndTime = Long.MAX_VALUE;
        long maxEndTime = 0;
        for (long endTime : endTimes) {
            assertThat(endTime, greaterThan(startTime));
            minEndTime = Math.min(minEndTime, endTime);
            maxEndTime = Math.max(maxEndTime, endTime);
        }
        assertThat((maxEndTime - minEndTime), lessThan(250l));
        for (DocumentView documentView : results) {
            assertThat(documentView, notNullValue());
        }

        for (int i = 0; i < LAST_REQUEST_INDEX; i++) {
            assertThat(results[i].getPhysicalFile(), is(viewLastRequest.getPhysicalFile()));
            assertThat(results[i].getNbPages(), is(viewLastRequest.getNbPages()));
            assertThat(results[i].getWidth(), is(viewLastRequest.getWidth()));
            assertThat(results[i].getHeight(), is(viewLastRequest.getHeight()));
            assertThat(results[i].getDisplayLicenseKey(), is(viewLastRequest.getDisplayLicenseKey()));
            assertThat(results[i].getOriginalFileName(), is(viewLastRequest.getOriginalFileName()));
            assertThat(results[i].getURLAsString(), is(viewLastRequest.getURLAsString()));
            assertThat(results[i].isDocumentSplit(), is(viewLastRequest.isDocumentSplit()));
            assertThat(results[i].areSearchDataComputed(), is(viewLastRequest.areSearchDataComputed()));
        }

        assertThat(serviceCache.size(), is(0));
        assertThat(getTemporaryPath().listFiles(), arrayWithSize(2));
    }
}

From source file:org.silverpeas.core.viewer.service.ViewServiceConcurrencyDemonstrationIT.java

@Test
public void demonstrateConcurrencyManagementWithTwoDifferentConversionsAtSameTime() throws Exception {
    if (canPerformViewConversionTest()) {
        final List<Throwable> throwables = new ArrayList<>();

        final ConcurrentMap serviceCache = (ConcurrentMap) FieldUtils.readField(viewService, "cache", true);
        assertThat(serviceCache.size(), is(0));

        final int NB_VIEW_CALLS = 100;

        for (int i = 0; i < NB_VIEW_CALLS; i++) {
            SubThreadManager.addAndStart(new Thread(() -> {
                try {
                    viewService.getDocumentView(ViewerContext.from(getSimpleDocumentNamed("file.odp")));
                } catch (Exception ignore) {
                }/* w ww  .  j  a va2 s  .  c  om*/
            }));
            SubThreadManager.addAndStart(new Thread(() -> {
                try {
                    viewService.getDocumentView(ViewerContext.from(getSimpleDocumentNamed("file.pdf")));
                } catch (Exception ignore) {
                }
            }));
        }

        SubThreadManager.addAndStart(new Thread(() -> {
            try {
                Thread.sleep(500);

                // Technical verification
                assertThat(getTemporaryPath().listFiles(), arrayWithSize(4));

            } catch (Throwable e) {
                throwables.add(e);
                SubThreadManager.killAll();
            }
        }));

        // Waiting for all thread ends
        SubThreadManager.joinAll(60000);

        for (Throwable throwable : throwables) {
            throw new RuntimeException(throwable);
        }

        assertThat(serviceCache.size(), is(0));
        assertThat(getTemporaryPath().listFiles(), arrayWithSize(4));
    }
}