Example usage for org.springframework.util ReflectionUtils makeAccessible

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

Introduction

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

Prototype

@SuppressWarnings("deprecation") 
public static void makeAccessible(Field field) 

Source Link

Document

Make the given field accessible, explicitly setting it accessible if necessary.

Usage

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

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

    GeneticAlgorithm geneticAlgorithm = mock(GeneticAlgorithm.class);
    when(geneticAlgorithm.getPopulation()).thenThrow(new IllegalStateException());
    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.end();/*from   w  ww .j ava 2  s  .  c  o m*/
    assertFalse(geneticCipherSolutionService.isRunning());

    verifyZeroInteractions(solutionDaoMock);

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

    /*
     * 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);
}

From source file:com.ciphertool.genetics.PopulationTest.java

@SuppressWarnings("unchecked")
@Test//from   w w  w. jav  a  2s.com
public void testAddIndividualAsIneligible() {
    Population population = new Population();

    Field ineligibleForReproductionField = ReflectionUtils.findField(Population.class,
            "ineligibleForReproduction");
    ReflectionUtils.makeAccessible(ineligibleForReproductionField);

    FitnessEvaluator fitnessEvaluatorMock = mock(FitnessEvaluator.class);
    when(fitnessEvaluatorMock.evaluate(any(Chromosome.class))).thenReturn(DEFAULT_FITNESS_VALUE);
    population.setFitnessEvaluator(fitnessEvaluatorMock);

    Double fitnessSum = 0.0;
    assertEquals(fitnessSum, population.getTotalFitness());
    assertEquals(0, population.size());

    // Add a chromosome that needs evaluation
    MockKeylessChromosome chromosomeEvaluationNeeded = new MockKeylessChromosome();
    chromosomeEvaluationNeeded.setFitness(5.0);
    chromosomeEvaluationNeeded.setEvaluationNeeded(true);
    population.addIndividualAsIneligible(chromosomeEvaluationNeeded);

    // Validate - this shouldn't affect the individuals List
    assertEquals(new Double(0.0), population.getTotalFitness());
    verifyZeroInteractions(fitnessEvaluatorMock);
    assertEquals(0, population.size());

    List<Chromosome> ineligibleForReproductionFromObject = (List<Chromosome>) ReflectionUtils
            .getField(ineligibleForReproductionField, population);
    assertEquals(1, ineligibleForReproductionFromObject.size());
    assertSame(chromosomeEvaluationNeeded, ineligibleForReproductionFromObject.get(0));

    // Add a chromosome that doesn't need evaluation
    MockKeylessChromosome chromosomeEvaluationNotNeeded = new MockKeylessChromosome();
    chromosomeEvaluationNotNeeded.setFitness(5.0);
    population.addIndividualAsIneligible(chromosomeEvaluationNotNeeded);

    // Validate - this shouldn't affect the individuals List
    assertEquals(new Double(0.0), population.getTotalFitness());
    verifyZeroInteractions(fitnessEvaluatorMock);
    assertEquals(0, population.size());

    ineligibleForReproductionFromObject = (List<Chromosome>) ReflectionUtils
            .getField(ineligibleForReproductionField, population);
    assertEquals(2, ineligibleForReproductionFromObject.size());
    assertSame(chromosomeEvaluationNotNeeded, ineligibleForReproductionFromObject.get(1));
}

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

@Test
public void testSelect() {
    MultigenerationalGeneticAlgorithm multigenerationalGeneticAlgorithm = new MultigenerationalGeneticAlgorithm();

    int populationSize = 100;
    double survivalRate = 0.9;

    Population population = new Population();
    multigenerationalGeneticAlgorithm.setPopulation(population);

    GeneticAlgorithmStrategy strategyToSet = new GeneticAlgorithmStrategy();
    strategyToSet.setPopulationSize(populationSize);
    strategyToSet.setSurvivalRate(survivalRate);

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

    SelectionAlgorithm selectionAlgorithmMock = mock(SelectionAlgorithm.class);

    Field selectionAlgorithmField = ReflectionUtils.findField(MultigenerationalGeneticAlgorithm.class,
            "selectionAlgorithm");
    ReflectionUtils.makeAccessible(selectionAlgorithmField);
    ReflectionUtils.setField(selectionAlgorithmField, multigenerationalGeneticAlgorithm,
            selectionAlgorithmMock);/*ww w  .ja va  2  s  .  co m*/

    multigenerationalGeneticAlgorithm.select();

    verify(selectionAlgorithmMock, times(1)).select(same(population), eq(populationSize), eq(survivalRate));
    verifyNoMoreInteractions(selectionAlgorithmMock);
}

From source file:com.mylife.hbase.mapper.HBaseEntityMapper.java

private Object fieldValue(final Field field, final Object hbasePersistableObject,
        final ImmutableMap<Class<?>, ImmutableMap<Field, Method>> map) {
    final Method getter = map.get(hbasePersistableObject.getClass()).get(field);
    ReflectionUtils.makeAccessible(getter);
    return ReflectionUtils.invokeMethod(getter, hbasePersistableObject);
}

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

@Test
public void testTearDown() throws IOException {
    GeneticCipherSolutionService geneticCipherSolutionService = new GeneticCipherSolutionService();

    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);

    geneticCipherSolutionService.tearDown();

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

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

@SuppressWarnings("unchecked")
@Test/*  w  w  w.j  av  a 2 s .co m*/
public void testCrossover() {
    MultigenerationalGeneticAlgorithm multigenerationalGeneticAlgorithm = new MultigenerationalGeneticAlgorithm();

    Population population = new Population();
    FitnessEvaluator fitnessEvaluatorMock = mock(FitnessEvaluator.class);
    when(fitnessEvaluatorMock.evaluate(any(Chromosome.class))).thenReturn(DEFAULT_FITNESS_VALUE);
    population.setFitnessEvaluator(fitnessEvaluatorMock);

    Selector selectorMock = mock(Selector.class);
    population.setSelector(selectorMock);
    when(selectorMock.getNextIndex(anyListOf(Chromosome.class), any(Double.class))).thenReturn(0, 1, 2, 3, 4);

    int initialPopulationSize = 50;

    for (int i = 0; i < initialPopulationSize; i++) {
        population.addIndividual(new MockKeylessChromosome());
    }

    multigenerationalGeneticAlgorithm.setPopulation(population);

    CrossoverAlgorithm crossoverAlgorithmMock = mock(CrossoverAlgorithm.class);

    Field crossoverAlgorithmField = ReflectionUtils.findField(MultigenerationalGeneticAlgorithm.class,
            "crossoverAlgorithm");
    ReflectionUtils.makeAccessible(crossoverAlgorithmField);
    ReflectionUtils.setField(crossoverAlgorithmField, multigenerationalGeneticAlgorithm,
            crossoverAlgorithmMock);

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

    GeneticAlgorithmStrategy strategy = new GeneticAlgorithmStrategy();
    strategy.setCrossoverRate(0.1);

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

    Field ineligibleForReproductionField = ReflectionUtils.findField(Population.class,
            "ineligibleForReproduction");
    ReflectionUtils.makeAccessible(ineligibleForReproductionField);
    List<Chromosome> ineligibleForReproductionFromObject = (List<Chromosome>) ReflectionUtils
            .getField(ineligibleForReproductionField, population);

    assertEquals(0, ineligibleForReproductionFromObject.size());

    int childrenProduced = multigenerationalGeneticAlgorithm.crossover(initialPopulationSize);

    ineligibleForReproductionFromObject = (List<Chromosome>) ReflectionUtils
            .getField(ineligibleForReproductionField, population);

    assertEquals(5, childrenProduced);

    /*
     * The population size should be reduced by the number of parents used
     * during crossover.
     */
    assertEquals(40, population.size());

    // There should be 10 ineligible parents, along with the 5 children
    assertEquals(15, ineligibleForReproductionFromObject.size());

    verify(selectorMock, times(10)).getNextIndex(anyListOf(Chromosome.class), any(Double.class));

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

From source file:com.ciphertool.genetics.PopulationTest.java

@SuppressWarnings("unchecked")
@Test//  w  w w .ja v a 2  s .  co m
public void testMakeIneligibleForReproduction() {
    Population population = new Population();

    Field ineligibleForReproductionField = ReflectionUtils.findField(Population.class,
            "ineligibleForReproduction");
    ReflectionUtils.makeAccessible(ineligibleForReproductionField);

    MockKeylessChromosome chromosome1 = new MockKeylessChromosome();
    chromosome1.setFitness(5.0);
    population.addIndividual(chromosome1);
    chromosome1.setEvaluationNeeded(true);

    MockKeylessChromosome chromosome2 = new MockKeylessChromosome();
    chromosome2.setFitness(5.0);
    population.addIndividual(chromosome2);

    Double fitnessSum = new Double(10.0);
    assertEquals(fitnessSum, population.getTotalFitness());
    assertEquals(2, population.size());

    fitnessSum -= chromosome1.getFitness();
    population.makeIneligibleForReproduction(0);

    // Validate individuals List
    assertEquals(fitnessSum, population.getTotalFitness());
    assertEquals(1, population.size());
    assertSame(chromosome2, population.getIndividuals().get(0));

    // Validate ineligible List
    List<Chromosome> ineligibleForReproductionFromObject = (List<Chromosome>) ReflectionUtils
            .getField(ineligibleForReproductionField, population);
    assertEquals(1, ineligibleForReproductionFromObject.size());
    assertSame(chromosome1, ineligibleForReproductionFromObject.get(0));

    fitnessSum -= chromosome2.getFitness();
    population.makeIneligibleForReproduction(0);

    // Validate individuals List
    assertEquals(fitnessSum, population.getTotalFitness());
    assertEquals(0, population.size());

    // Validate ineligible List
    ineligibleForReproductionFromObject = (List<Chromosome>) ReflectionUtils
            .getField(ineligibleForReproductionField, population);
    assertEquals(2, ineligibleForReproductionFromObject.size());
    assertSame(chromosome2, ineligibleForReproductionFromObject.get(1));

    // Try to remove an individual that doesn't exist
    assertNull(population.removeIndividual(0));
}

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

@Test
public void testBatchWordImportTask_LeftoversFromBatch() {
    FrequencyListImporterImpl frequencyListImporterImpl = new FrequencyListImporterImpl();

    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("seriously", PartOfSpeechType.ADJECTIVE), 500);
    Word word6 = new Word(new WordId("awesome", PartOfSpeechType.ADJECTIVE), 600);
    List<Word> threadBatch = new ArrayList<Word>();
    threadBatch.add(word1);/*from  w w w.j a  v a 2 s . c om*/
    threadBatch.add(word2);
    threadBatch.add(word3);
    threadBatch.add(word4);
    threadBatch.add(word5);
    threadBatch.add(word6);

    FrequencyListImporterImpl.BatchWordImportTask batchWordImportTask = frequencyListImporterImpl.new BatchWordImportTask(
            threadBatch);

    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 = 2;
    int concurrencyBatchSizeToSet = 3;

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

    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);

    try {
        batchWordImportTask.call();
    } catch (Exception e) {
        fail(e.getMessage());
    }

    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(3, rowInsertCountFromObject.intValue());
    verify(wordDaoMock, times(2)).insertBatch(anyListOf(Word.class));
    verify(wordDaoMock, times(2)).updateBatch(anyListOf(Word.class));
    verify(wordDaoMock, times(6)).findByWordString(anyString());
}

From source file:com.ciphertool.genetics.PopulationTest.java

@SuppressWarnings("unchecked")
@Test/*from   w  w  w  .  j  ava  2 s.  c om*/
public void testResetEligibility() {
    Population population = new Population();

    Field ineligibleForReproductionField = ReflectionUtils.findField(Population.class,
            "ineligibleForReproduction");
    ReflectionUtils.makeAccessible(ineligibleForReproductionField);

    FitnessEvaluator fitnessEvaluatorMock = mock(FitnessEvaluator.class);
    when(fitnessEvaluatorMock.evaluate(any(Chromosome.class))).thenReturn(DEFAULT_FITNESS_VALUE);
    population.setFitnessEvaluator(fitnessEvaluatorMock);

    Double fitnessSum = 0.0;
    assertEquals(fitnessSum, population.getTotalFitness());
    assertEquals(0, population.size());

    // Add a chromosome that needs evaluation
    MockKeylessChromosome chromosomeEvaluationNeeded = new MockKeylessChromosome();
    chromosomeEvaluationNeeded.setFitness(5.0);
    chromosomeEvaluationNeeded.setEvaluationNeeded(true);
    population.addIndividualAsIneligible(chromosomeEvaluationNeeded);

    // Add a chromosome that doesn't need evaluation
    MockKeylessChromosome chromosomeEvaluationNotNeeded = new MockKeylessChromosome();
    chromosomeEvaluationNotNeeded.setFitness(5.0);
    population.addIndividualAsIneligible(chromosomeEvaluationNotNeeded);

    List<Chromosome> ineligibleForReproductionFromObject = (List<Chromosome>) ReflectionUtils
            .getField(ineligibleForReproductionField, population);

    // Validate - this shouldn't affect the individuals List
    assertEquals(new Double(0.0), population.getTotalFitness());
    verifyZeroInteractions(fitnessEvaluatorMock);
    assertEquals(0, population.size());

    ineligibleForReproductionFromObject = (List<Chromosome>) ReflectionUtils
            .getField(ineligibleForReproductionField, population);
    assertEquals(2, ineligibleForReproductionFromObject.size());
    assertSame(chromosomeEvaluationNeeded, ineligibleForReproductionFromObject.get(0));
    assertSame(chromosomeEvaluationNotNeeded, ineligibleForReproductionFromObject.get(1));

    population.resetEligibility();

    assertEquals(0, ineligibleForReproductionFromObject.size());

    fitnessSum = chromosomeEvaluationNeeded.getFitness() + chromosomeEvaluationNotNeeded.getFitness();
    assertEquals(fitnessSum, population.getTotalFitness());
    verify(fitnessEvaluatorMock, times(1)).evaluate(same(chromosomeEvaluationNeeded));
    assertEquals(2, population.size());
    assertSame(chromosomeEvaluationNeeded, population.getIndividuals().get(0));
    assertSame(chromosomeEvaluationNotNeeded, population.getIndividuals().get(1));
}

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

@SuppressWarnings("unchecked")
@Test/*from   www .  j  a  v  a2  s  .  com*/
public void testCrossover_SmallPopulation() {
    MultigenerationalGeneticAlgorithm multigenerationalGeneticAlgorithm = new MultigenerationalGeneticAlgorithm();

    Population population = new Population();

    Chromosome chromosome = new MockKeylessChromosome();
    population.addIndividual(chromosome);
    multigenerationalGeneticAlgorithm.setPopulation(population);

    CrossoverAlgorithm crossoverAlgorithmMock = mock(CrossoverAlgorithm.class);

    Field crossoverAlgorithmField = ReflectionUtils.findField(MultigenerationalGeneticAlgorithm.class,
            "crossoverAlgorithm");
    ReflectionUtils.makeAccessible(crossoverAlgorithmField);
    ReflectionUtils.setField(crossoverAlgorithmField, multigenerationalGeneticAlgorithm,
            crossoverAlgorithmMock);

    Field ineligibleForReproductionField = ReflectionUtils.findField(Population.class,
            "ineligibleForReproduction");
    ReflectionUtils.makeAccessible(ineligibleForReproductionField);
    List<Chromosome> ineligibleForReproductionFromObject = (List<Chromosome>) ReflectionUtils
            .getField(ineligibleForReproductionField, population);

    assertEquals(0, ineligibleForReproductionFromObject.size());

    int childrenProduced = multigenerationalGeneticAlgorithm.crossover(10);

    ineligibleForReproductionFromObject = (List<Chromosome>) ReflectionUtils
            .getField(ineligibleForReproductionField, population);

    assertEquals(1, population.size());

    assertEquals(0, childrenProduced);

    assertEquals(0, ineligibleForReproductionFromObject.size());

    verifyZeroInteractions(crossoverAlgorithmMock);
}