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:com.ciphertool.genetics.algorithms.ConcurrentMultigenerationalGeneticAlgorithmTest.java

@Test
public void testDoConcurrentCrossovers() {
    ConcurrentMultigenerationalGeneticAlgorithm concurrentMultigenerationalGeneticAlgorithm = new ConcurrentMultigenerationalGeneticAlgorithm();
    concurrentMultigenerationalGeneticAlgorithm.setTaskExecutor(taskExecutor);

    CrossoverAlgorithm crossoverAlgorithmMock = mock(CrossoverAlgorithm.class);

    Field crossoverAlgorithmField = ReflectionUtils.findField(ConcurrentMultigenerationalGeneticAlgorithm.class,
            "crossoverAlgorithm");
    ReflectionUtils.makeAccessible(crossoverAlgorithmField);
    ReflectionUtils.setField(crossoverAlgorithmField, concurrentMultigenerationalGeneticAlgorithm,
            crossoverAlgorithmMock);//ww w.ja  v  a  2  s  . co  m

    Chromosome chromosomeToReturn = new MockKeylessChromosome();
    when(crossoverAlgorithmMock.crossover(any(Chromosome.class), any(Chromosome.class)))
            .thenReturn(Arrays.asList(chromosomeToReturn));

    long pairsToCrossover = 5;
    List<Chromosome> moms = new ArrayList<Chromosome>();
    List<Chromosome> dads = new ArrayList<Chromosome>();

    for (int i = 0; i < 5; i++) {
        moms.add(new MockKeylessChromosome());
        dads.add(new MockKeylessChromosome());
    }

    List<Chromosome> childrenReturned = concurrentMultigenerationalGeneticAlgorithm
            .doConcurrentCrossovers(pairsToCrossover, moms, dads);

    assertEquals(5, childrenReturned.size());
    for (Chromosome child : childrenReturned) {
        assertSame(chromosomeToReturn, child);
    }

    verify(crossoverAlgorithmMock, times(5)).crossover(any(Chromosome.class), any(Chromosome.class));
}

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

@Test
public void testInitialize() {
    Date beforeInitialize = new Date();

    GeneticAlgorithmStrategy strategyToSet = new GeneticAlgorithmStrategy();
    int populationSize = 100;
    int lifeSpan = 0;
    double survivalRate = 0.1;
    double mutationRate = 0.0;
    double crossoverRate = 0.0;
    CrossoverAlgorithm crossoverAlgorithmMock = mock(CrossoverAlgorithm.class);
    FitnessEvaluator fitnessEvaluatorMock = mock(FitnessEvaluator.class);
    MutationAlgorithm mutationAlgorithmMock = mock(MutationAlgorithm.class);
    strategyToSet.setGeneticStructure(new Object());
    strategyToSet.setPopulationSize(populationSize);
    strategyToSet.setLifespan(lifeSpan);
    strategyToSet.setSurvivalRate(survivalRate);
    strategyToSet.setMutationRate(mutationRate);
    strategyToSet.setMaxMutationsPerIndividual(0);
    strategyToSet.setCrossoverRate(crossoverRate);
    strategyToSet.setMutateDuringCrossover(false);
    strategyToSet.setMaxGenerations(-1);
    strategyToSet.setCrossoverAlgorithm(crossoverAlgorithmMock);
    strategyToSet.setFitnessEvaluator(fitnessEvaluatorMock);
    strategyToSet.setMutationAlgorithm(mutationAlgorithmMock);
    strategyToSet.setSelectionAlgorithm(mock(SelectionAlgorithm.class));
    strategyToSet.setSelector(mock(Selector.class));

    Population populationMock = mock(Population.class);

    MultigenerationalGeneticAlgorithm multigenerationalGeneticAlgorithm = new MultigenerationalGeneticAlgorithm();
    multigenerationalGeneticAlgorithm.setPopulation(populationMock);

    Field strategyField = ReflectionUtils.findField(MultigenerationalGeneticAlgorithm.class, "strategy");
    ReflectionUtils.makeAccessible(strategyField);
    ReflectionUtils.setField(strategyField, multigenerationalGeneticAlgorithm, strategyToSet);

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

    Field stopRequestedField = ReflectionUtils.findField(MultigenerationalGeneticAlgorithm.class,
            "stopRequested");
    ReflectionUtils.makeAccessible(stopRequestedField);
    ReflectionUtils.setField(stopRequestedField, multigenerationalGeneticAlgorithm, true);

    Field executionStatisticsField = ReflectionUtils.findField(MultigenerationalGeneticAlgorithm.class,
            "executionStatistics");
    ReflectionUtils.makeAccessible(executionStatisticsField);
    ExecutionStatistics executionStatisticsFromObject = (ExecutionStatistics) ReflectionUtils
            .getField(executionStatisticsField, multigenerationalGeneticAlgorithm);
    assertNull(executionStatisticsFromObject);

    multigenerationalGeneticAlgorithm.initialize();

    int generationCountFromObject = (int) ReflectionUtils.getField(generationCountField,
            multigenerationalGeneticAlgorithm);
    boolean stopRequestedFromObject = (boolean) ReflectionUtils.getField(stopRequestedField,
            multigenerationalGeneticAlgorithm);
    executionStatisticsFromObject = (ExecutionStatistics) ReflectionUtils.getField(executionStatisticsField,
            multigenerationalGeneticAlgorithm);

    assertEquals(0, generationCountFromObject);
    assertFalse(stopRequestedFromObject);
    assertNotNull(executionStatisticsFromObject);
    assertTrue(executionStatisticsFromObject.getStartDateTime().getTime() >= beforeInitialize.getTime());
    assertEquals(populationSize, executionStatisticsFromObject.getPopulationSize().intValue());
    assertEquals(lifeSpan, executionStatisticsFromObject.getLifespan().intValue());
    assertEquals(new Double(survivalRate), executionStatisticsFromObject.getSurvivalRate());
    assertEquals(new Double(mutationRate), executionStatisticsFromObject.getMutationRate());
    assertEquals(new Double(crossoverRate), executionStatisticsFromObject.getCrossoverRate());
    assertEquals(crossoverAlgorithmMock.getClass().getSimpleName(),
            executionStatisticsFromObject.getCrossoverAlgorithm());
    assertEquals(fitnessEvaluatorMock.getClass().getSimpleName(),
            executionStatisticsFromObject.getFitnessEvaluator());
    assertEquals(mutationAlgorithmMock.getClass().getSimpleName(),
            executionStatisticsFromObject.getMutationAlgorithm());

    verify(populationMock, times(1)).clearIndividuals();
    verify(populationMock, times(1)).breed(eq(populationSize));
    verify(populationMock, times(1)).evaluateFitness(null);
    verify(populationMock, times(1)).size();
    verifyNoMoreInteractions(populationMock);
}

From source file:com.frank.search.solr.server.support.SolrClientUtils.java

@SuppressWarnings("unchecked")
private static <T> T readField(SolrClient solrServer, String fieldName) {
    Field field = ReflectionUtils.findField(solrServer.getClass(), fieldName);
    if (field == null) {
        return null;
    }/* w w w .  j  a  v  a 2 s . c o  m*/
    ReflectionUtils.makeAccessible(field);
    return (T) ReflectionUtils.getField(field, solrServer);
}

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

@Test
public void testImportFrequencyList_LeftoversFromBatch() {
    ThreadPoolTaskExecutor taskExecutorSpy = spy(new ThreadPoolTaskExecutor());
    taskExecutorSpy.setCorePoolSize(4);/*from   w  w w.  jav a 2  s  .c o  m*/
    taskExecutorSpy.setMaxPoolSize(4);
    taskExecutorSpy.setQueueCapacity(100);
    taskExecutorSpy.setKeepAliveSeconds(1);
    taskExecutorSpy.setAllowCoreThreadTimeOut(true);
    taskExecutorSpy.initialize();

    FrequencyListImporterImpl frequencyListImporterImpl = new FrequencyListImporterImpl();
    frequencyListImporterImpl.setTaskExecutor(taskExecutorSpy);

    Field rowUpdateCountField = ReflectionUtils.findField(FrequencyListImporterImpl.class, "rowUpdateCount");
    ReflectionUtils.makeAccessible(rowUpdateCountField);
    AtomicInteger rowUpdateCountFromObject = (AtomicInteger) ReflectionUtils.getField(rowUpdateCountField,
            frequencyListImporterImpl);

    assertEquals(0, rowUpdateCountFromObject.intValue());

    Field rowInsertCountField = ReflectionUtils.findField(FrequencyListImporterImpl.class, "rowInsertCount");
    ReflectionUtils.makeAccessible(rowInsertCountField);
    AtomicInteger rowInsertCountFromObject = (AtomicInteger) ReflectionUtils.getField(rowInsertCountField,
            frequencyListImporterImpl);

    assertEquals(0, rowInsertCountFromObject.intValue());

    WordDao wordDaoMock = mock(WordDao.class);
    when(wordDaoMock.insertBatch(anyListOf(Word.class))).thenReturn(true);
    int persistenceBatchSizeToSet = 3;
    int concurrencyBatchSizeToSet = 2;

    frequencyListImporterImpl.setWordDao(wordDaoMock);
    frequencyListImporterImpl.setPersistenceBatchSize(persistenceBatchSizeToSet);
    frequencyListImporterImpl.setConcurrencyBatchSize(concurrencyBatchSizeToSet);

    Word word1 = new Word(new WordId("george", PartOfSpeechType.NOUN), 100);
    Word word2 = new Word(new WordId("belden", PartOfSpeechType.NOUN), 200);
    Word word3 = new Word(new WordId("is", PartOfSpeechType.VERB_PARTICIPLE), 300);
    Word word4 = new Word(new WordId("super", PartOfSpeechType.ADJECTIVE), 400);
    Word word5 = new Word(new WordId("awesome", PartOfSpeechType.ADJECTIVE), 500);
    List<Word> wordsToReturn = new ArrayList<Word>();
    wordsToReturn.add(word1);
    wordsToReturn.add(word2);
    wordsToReturn.add(word3);
    wordsToReturn.add(word4);
    wordsToReturn.add(word5);
    FrequencyFileParser fileParserMock = mock(FrequencyFileParser.class);
    when(fileParserMock.parseFile()).thenReturn(wordsToReturn);

    frequencyListImporterImpl.setFileParser(fileParserMock);

    Word wordFromDatabase1 = new Word(new WordId("george", PartOfSpeechType.NOUN));
    Word wordFromDatabase2 = new Word(new WordId("belden", PartOfSpeechType.NOUN));
    Word wordFromDatabase3 = new Word(new WordId("is", PartOfSpeechType.ADJECTIVE));

    when(wordDaoMock.insertBatch(anyListOf(Word.class))).thenReturn(true);
    when(wordDaoMock.updateBatch(anyListOf(Word.class))).thenReturn(true);
    when(wordDaoMock.findByWordString(eq("george"))).thenReturn(Arrays.asList(wordFromDatabase1));
    when(wordDaoMock.findByWordString(eq("belden"))).thenReturn(Arrays.asList(wordFromDatabase2));
    when(wordDaoMock.findByWordString(eq("is"))).thenReturn(

            Arrays.asList(wordFromDatabase3));
    when(wordDaoMock.findByWordString(eq("super"))).thenReturn(null);
    when(wordDaoMock.findByWordString(eq("seriously"))).thenReturn(null);
    when(wordDaoMock.findByWordString(eq("awesome"))).thenReturn(null);

    frequencyListImporterImpl.importFrequencyList();

    assertEquals(100, wordFromDatabase1.getFrequencyWeight());
    assertEquals(200, wordFromDatabase2.getFrequencyWeight());
    assertEquals(300, wordFromDatabase3.getFrequencyWeight());

    rowUpdateCountFromObject = (AtomicInteger) ReflectionUtils.getField(rowUpdateCountField,
            frequencyListImporterImpl);
    rowInsertCountFromObject = (AtomicInteger) ReflectionUtils.getField(rowInsertCountField,
            frequencyListImporterImpl);

    assertEquals(3, rowUpdateCountFromObject.intValue());
    assertEquals(2, rowInsertCountFromObject.intValue());
    verify(wordDaoMock, times(2)).insertBatch(anyListOf(Word.class));
    verify(wordDaoMock, times(2)).updateBatch(anyListOf(Word.class));
    verify(wordDaoMock, times(5)).findByWordString(anyString());
    verify(taskExecutorSpy, times(3)).execute(any(Runnable.class));
}

From source file:es.fcs.batch.integration.chunk.MyRemoteChunkHandlerFactoryBean.java

private static void setField(Object target, String name, Object value) {
    Assert.notNull(target, "Target object must not be null");
    Field field = ReflectionUtils.findField(target.getClass(), name);
    if (field == null) {
        throw new IllegalStateException("Could not find field [" + name + "] on target [" + target + "]");
    }//  ww  w.  j a v  a2 s .co  m

    if (logger.isDebugEnabled()) {
        logger.debug("Getting field [" + name + "] from target [" + target + "]");
    }
    ReflectionUtils.makeAccessible(field);
    ReflectionUtils.setField(field, target, value);
}

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

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

    // setup parameters
    TransactionTokenInfo inTransactionToken = new TransactionTokenInfo("testTokenAttribute2",
            TransactionTokenType.IN);/*from  w w w .j a  v a2s  .  c o  m*/
    TransactionToken receivedToken = new TransactionToken("bbb");

    // setup up expected result
    ReserveCommand expectedCommand = ReserveCommand.CREATE_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:com.frank.search.solr.server.support.SolrClientUtils.java

/**
 * Solr property names do not match the getters/setters used for them. Check
 * on any write method, try to find the according property and set the value
 * for it. Will ignore all other, and nested properties
 * /*  w ww .  j a  v a 2  s.com*/
 * @param source
 * @param target
 */
private static void copyProperties(SolrClient source, SolrClient target) {
    BeanWrapperImpl wrapperImpl = new BeanWrapperImpl(source);
    for (PropertyDescriptor pd : wrapperImpl.getPropertyDescriptors()) {
        Method writer = pd.getWriteMethod();
        if (writer != null) {
            try {
                Field property = ReflectionUtils.findField(source.getClass(), pd.getName());
                if (property != null) {
                    ReflectionUtils.makeAccessible(property);
                    Object o = ReflectionUtils.getField(property, source);
                    if (o != null) {
                        writer.invoke(target, o);
                    }
                }
            } catch (Exception e) {
                logger.warn("Could not copy property value for: " + pd.getName(), e);
            }
        }
    }
}

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

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

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

    assertEquals(0, rowCountFromObject.intValue());

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

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

    List<Word> wordBatch = new ArrayList<Word>();
    wordListImporterImpl.importWord(null, wordBatch);

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

    assertEquals(0, rowCountFromObject.intValue());
    verifyZeroInteractions(wordDaoMock);
    assertTrue(wordBatch.isEmpty());
}

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

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

    GeneticAlgorithm geneticAlgorithm = mock(GeneticAlgorithm.class);
    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);

    assertTrue(geneticCipherSolutionService.isRunning());
    geneticCipherSolutionService.endImmediately(true);
    assertFalse(geneticCipherSolutionService.isRunning());

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

    verify(runtimeMock, times(1)).exec(eq("command1"));
    verify(runtimeMock, times(1)).exec(eq("command2"));
    verifyNoMoreInteractions(runtimeMock);
}

From source file:es.fcs.batch.integration.chunk.MyChunkMessageChannelItemWriter.java

private static Object getField(Object target, String name) {
    Assert.notNull(target, "Target object must not be null");
    Field field = ReflectionUtils.findField(target.getClass(), name);
    if (field == null) {
        logger.debug("Could not find field [" + name + "] on target [" + target + "]");
        return null;
    }/* w w  w. ja  v a2 s . com*/

    if (logger.isDebugEnabled()) {
        logger.debug("Getting field [" + name + "] from target [" + target + "]");
    }
    ReflectionUtils.makeAccessible(field);
    return ReflectionUtils.getField(field, target);
}