Example usage for org.springframework.util ReflectionUtils findField

List of usage examples for org.springframework.util ReflectionUtils findField

Introduction

In this page you can find the example usage for org.springframework.util ReflectionUtils findField.

Prototype

@Nullable
public static Field findField(Class<?> clazz, String name) 

Source Link

Document

Attempt to find a Field field on the supplied Class with the supplied name .

Usage

From source file:org.terasoluna.gfw.web.token.transaction.TransactionTokenContextImplTest.java

@Test
public void TestCancelReservation04() throws IllegalArgumentException, IllegalAccessException {

    // setup parameters
    TransactionTokenInfo inTransactionToken = new TransactionTokenInfo("testTokenAttribute2",
            TransactionTokenType.IN);/*from  w w w  .  j  a v a 2 s.  c  om*/
    TransactionToken receivedToken = new TransactionToken("bbb", "key", "value");

    // setup up expected result
    ReserveCommand expectedCommand = ReserveCommand.UPDATE_TOKEN;

    // run
    TransactionTokenContextImpl contextImpl = new TransactionTokenContextImpl(inTransactionToken,
            receivedToken);
    contextImpl.cancelReservation();

    // test
    Field field = ReflectionUtils.findField(TransactionTokenContextImpl.class, "defaultCommand");
    ReflectionUtils.makeAccessible(field);
    ReserveCommand resultCommand = (ReserveCommand) field.get(contextImpl);
    assertThat(resultCommand, is(expectedCommand));

}

From source file:org.powertac.logtool.common.DomainObjectReader.java

private Object restoreInstance(Class<?> clazz, String[] args) throws MissingDomainObject {
    Domain domain = clazz.getAnnotation(Domain.class);
    if (domain instanceof Domain) {
        // only do this for @Domain classes
        Object thing = null;/*from  w w  w .  jav a2  s  . c o m*/
        try {
            Constructor<?> cons = clazz.getDeclaredConstructor();
            cons.setAccessible(true);
            thing = cons.newInstance();
        } catch (Exception e) {
            log.warn("No default constructor for " + clazz.getName() + ": " + e.toString());
            return null;
        }
        String[] fieldNames = domain.fields();
        Field[] fields = new Field[fieldNames.length];
        Class<?>[] types = new Class<?>[fieldNames.length];
        for (int i = 0; i < fieldNames.length; i++) {
            fields[i] = ReflectionUtils.findField(clazz, resolveDoubleCaps(fieldNames[i]));
            if (null == fields[i]) {
                log.warn("No field in " + clazz.getName() + " named " + fieldNames[i]);
                types[i] = null;
            } else {
                types[i] = fields[i].getType();
            }
        }
        Object[] data = resolveArgs(types, args);
        if (null == data) {
            log.error("Could not resolve args for " + clazz.getName());
            return null;
        } else {
            for (int i = 0; i < fields.length; i++) {
                if (null == fields[i])
                    continue;
                fields[i].setAccessible(true);
                try {
                    fields[i].set(thing, data[i]);
                } catch (Exception e) {
                    log.error("Exception setting field: " + e.toString());
                    return null;
                }
            }
        }
        return thing;
    }
    return null;
}

From source file:com.ciphertool.sentencebuilder.etl.importers.WordListImporterImplTest.java

@Test
public void testImportWord_BatchSizeNotReached() {
    WordListImporterImpl wordListImporterImpl = new WordListImporterImpl();

    Field rowCountField = ReflectionUtils.findField(WordListImporterImpl.class, "rowCount");
    ReflectionUtils.makeAccessible(rowCountField);
    AtomicInteger rowCountFromObject = (AtomicInteger) ReflectionUtils.getField(rowCountField,
            wordListImporterImpl);/* ww w  .  j  a  v a 2 s.c  om*/

    assertEquals(0, rowCountFromObject.intValue());

    WordDao wordDaoMock = mock(WordDao.class);
    when(wordDaoMock.insertBatch(anyListOf(Word.class))).thenReturn(true);

    wordListImporterImpl.setWordDao(wordDaoMock);
    wordListImporterImpl.setPersistenceBatchSize(4);

    List<Word> wordBatch = new ArrayList<Word>();

    Word word1 = new Word(new WordId("george", PartOfSpeechType.NOUN));
    wordListImporterImpl.importWord(word1, wordBatch);

    verify(wordDaoMock, never()).insertBatch(anyListOf(Word.class));
    assertEquals(1, wordBatch.size());

    Word word2 = new Word(new WordId("elmer", PartOfSpeechType.NOUN));
    wordListImporterImpl.importWord(word2, wordBatch);

    verify(wordDaoMock, never()).insertBatch(anyListOf(Word.class));
    assertEquals(2, wordBatch.size());

    Word word3 = new Word(new WordId("belden", PartOfSpeechType.NOUN));
    wordListImporterImpl.importWord(word3, wordBatch);

    rowCountFromObject = (AtomicInteger) ReflectionUtils.getField(rowCountField, wordListImporterImpl);

    assertEquals(0, rowCountFromObject.intValue());
    verify(wordDaoMock, never()).insertBatch(anyListOf(Word.class));
    assertEquals(3, wordBatch.size());
    assertSame(word1, wordBatch.get(0));
    assertSame(word2, wordBatch.get(1));
    assertSame(word3, wordBatch.get(2));
}

From source file:fragment.web.TasksControllerTest.java

@Test
public void testActOnPendingActionRejectWithMemo() {
    Tenant tenant = tenantService.get("dfc84388-d44d-4d8e-9d6a-a62c1c16b7e4");
    BusinessTransaction bt = new TenantStateChangeTransaction();
    bt.setUuid(UUID.randomUUID().toString());
    bt.setWorkflowId("1e42822b-cad6-4dc0-bb77-99abb9395f1a");

    Field field = ReflectionUtils.findField(BusinessTransaction.class, "id");
    field.setAccessible(true);/*from   ww w  . ja  va  2  s  . c o m*/
    ReflectionUtils.setField(field, bt, 1l);

    Task task = new Task();
    task.setActorRole(authorityService.findByAuthority("ROLE_FINANCE_CRUD"));
    task.setCreatedAt(new Date());
    task.setState(com.citrix.cpbm.core.workflow.model.Task.State.PENDING);
    task.setTenant(tenant);
    task.setUser(tenant.getOwner());
    task.setUpdatedBy(getRootUser());
    task.setBusinessTransaction(bt);
    task.setType("FINANCE_APPROVAL");
    task.setDisplayMode(DisplayMode.POPUP);
    task = taskService.save(task);
    String memo = "Rejected";
    String actedAction = tasksController.actOnApprovalTask(task.getUuid(), Task.State.FAILURE.toString(), memo,
            request);
    Assert.assertEquals("ui.task.state.FAILURE", actedAction);
}

From source file:org.terasoluna.gfw.web.token.transaction.TransactionTokenContextImplTest.java

@Test
public void TestCancelReservation05() throws IllegalArgumentException, IllegalAccessException {

    // setup parameters
    TransactionTokenInfo endTransactionToken = new TransactionTokenInfo("testTokenAttribute3",
            TransactionTokenType.END);/*ww w . j  av a  2 s  . c o  m*/
    TransactionToken receivedToken = new TransactionToken("ccc");

    // setup up expected result
    ReserveCommand expectedCommand = ReserveCommand.NONE;

    // run
    TransactionTokenContextImpl contextImpl = new TransactionTokenContextImpl(endTransactionToken,
            receivedToken);

    contextImpl.cancelReservation();

    // test
    Field field = ReflectionUtils.findField(TransactionTokenContextImpl.class, "defaultCommand");
    ReflectionUtils.makeAccessible(field);
    ReserveCommand resultCommand = (ReserveCommand) field.get(contextImpl);
    assertThat(resultCommand, is(expectedCommand));
}

From source file:org.terasoluna.gfw.web.token.transaction.TransactionTokenContextImplTest.java

@Test
public void TestCancelReservation06() throws IllegalArgumentException, IllegalAccessException {

    // setup parameters
    TransactionTokenInfo endTransactionToken = new TransactionTokenInfo("testTokenAttribute3",
            TransactionTokenType.END);/*from  ww  w.  j av a  2  s .com*/
    TransactionToken receivedToken = new TransactionToken("ccc", "key", "value");

    // setup up expected result
    ReserveCommand expectedCommand = ReserveCommand.REMOVE_TOKEN;

    // run
    TransactionTokenContextImpl contextImpl = new TransactionTokenContextImpl(endTransactionToken,
            receivedToken);

    contextImpl.cancelReservation();

    // test
    Field field = ReflectionUtils.findField(TransactionTokenContextImpl.class, "defaultCommand");
    ReflectionUtils.makeAccessible(field);
    ReserveCommand resultCommand = (ReserveCommand) field.get(contextImpl);
    assertThat(resultCommand, is(expectedCommand));
}

From source file:com.ciphertool.genetics.algorithms.MultigenerationalGeneticAlgorithmTest.java

@Test
public void testFinish() {
    Date beforeFinish = new Date();

    ExecutionStatisticsDao executionStatisticsDaoToSet = mock(ExecutionStatisticsDao.class);

    MultigenerationalGeneticAlgorithm multigenerationalGeneticAlgorithm = new MultigenerationalGeneticAlgorithm();
    multigenerationalGeneticAlgorithm.setExecutionStatisticsDao(executionStatisticsDaoToSet);

    ExecutionStatistics executionStatistics = new ExecutionStatistics();
    Field executionStatisticsField = ReflectionUtils.findField(MultigenerationalGeneticAlgorithm.class,
            "executionStatistics");
    ReflectionUtils.makeAccessible(executionStatisticsField);
    ReflectionUtils.setField(executionStatisticsField, multigenerationalGeneticAlgorithm, executionStatistics);

    Field generationCountField = ReflectionUtils.findField(MultigenerationalGeneticAlgorithm.class,
            "generationCount");
    ReflectionUtils.makeAccessible(generationCountField);
    ReflectionUtils.setField(generationCountField, multigenerationalGeneticAlgorithm, 1);

    multigenerationalGeneticAlgorithm.finish();

    assertTrue(executionStatistics.getEndDateTime().getTime() >= beforeFinish.getTime());

    verify(executionStatisticsDaoToSet, times(1)).insert(same(executionStatistics));

    ExecutionStatistics executionStatisticsFromObject = (ExecutionStatistics) ReflectionUtils
            .getField(executionStatisticsField, multigenerationalGeneticAlgorithm);
    assertNull(executionStatisticsFromObject);
}

From source file:fragment.web.TasksControllerTest.java

@Test
public void testActOnPendingActionRejectWithoutMemo() {
    try {/*from w  ww . j  av a 2 s  .  c  o  m*/
        Tenant tenant = tenantService.get("dfc84388-d44d-4d8e-9d6a-a62c1c16b7e4");
        BusinessTransaction bt = new TenantStateChangeTransaction();
        bt.setUuid(UUID.randomUUID().toString());
        bt.setWorkflowId("1e42822b-cad6-4dc0-bb77-99abb9395f1a");

        Field field = ReflectionUtils.findField(BusinessTransaction.class, "id");
        field.setAccessible(true);
        ReflectionUtils.setField(field, bt, 1l);

        Task task = new Task();
        task.setActorRole(authorityService.findByAuthority("ROLE_FINANCE_CRUD"));
        task.setCreatedAt(new Date());
        task.setState(com.citrix.cpbm.core.workflow.model.Task.State.PENDING);
        task.setTenant(tenant);
        task.setUser(tenant.getOwner());
        task.setUpdatedBy(getRootUser());
        task.setBusinessTransaction(bt);
        task.setType("FINANCE_APPROVAL");
        task.setDisplayMode(DisplayMode.POPUP);
        task = taskService.save(task);
        String memo = "";
        tasksController.actOnApprovalTask(task.getUuid(), Task.State.FAILURE.toString(), memo, request);
    } catch (Exception e) {

        Assert.assertEquals("Memo is required in case of Rejection", e.getMessage());
    }
}

From source file:com.ciphertool.zodiacengine.service.GeneticCipherSolutionServiceTest.java

@Test
public void testResume_ExceptionThrown() throws IOException {
    GeneticCipherSolutionService geneticCipherSolutionService = new GeneticCipherSolutionService();
    geneticCipherSolutionService.toggleRunning();

    GeneticAlgorithm geneticAlgorithm = mock(GeneticAlgorithm.class);
    doThrow(IllegalStateException.class).when(geneticAlgorithm).proceedWithNextGeneration();

    Population population = new Population();
    SolutionChromosome solutionChromosome = new SolutionChromosome();
    solutionChromosome.setEvaluationNeeded(false);
    population.addIndividual(solutionChromosome);
    when(geneticAlgorithm.getPopulation()).thenReturn(population);

    geneticCipherSolutionService.setGeneticAlgorithm(geneticAlgorithm);

    Runtime runtimeMock = mock(Runtime.class);

    Field runtimeField = ReflectionUtils.findField(GeneticCipherSolutionService.class, "runtime");
    ReflectionUtils.makeAccessible(runtimeField);
    ReflectionUtils.setField(runtimeField, geneticCipherSolutionService, runtimeMock);

    String[] commandsAfter = { "command1", "command2" };
    geneticCipherSolutionService.setCommandsAfter(commandsAfter);

    SolutionDao solutionDaoMock = mock(SolutionDao.class);
    geneticCipherSolutionService.setSolutionDao(solutionDaoMock);

    Field logField = ReflectionUtils.findField(GeneticCipherSolutionService.class, "log");
    Logger mockLogger = mock(Logger.class);
    ReflectionUtils.makeAccessible(logField);
    ReflectionUtils.setField(logField, geneticCipherSolutionService, mockLogger);

    doNothing().when(mockLogger).error(anyString(), any(Throwable.class));

    assertTrue(geneticCipherSolutionService.isRunning());
    geneticCipherSolutionService.resume();
    assertFalse(geneticCipherSolutionService.isRunning());

    verify(solutionDaoMock, times(1)).insert(same(solutionChromosome));

    verify(mockLogger, times(1)).error(anyString(), any(Throwable.class));

    /*//  www  .j a  v  a  2s. co  m
     * These commands should still get called even though an exception was
     * caught
     */
    verify(runtimeMock, times(1)).exec(eq("command1"));
    verify(runtimeMock, times(1)).exec(eq("command2"));
    verifyNoMoreInteractions(runtimeMock);
}