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.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:org.eclipse.gemini.blueprint.test.AbstractOsgiTests.java

/**
 * Determines through reflection the methods used for invoking the TestRunnerService.
 * /*from w w  w  .ja  v a 2s .c om*/
 * @throws Exception
 */
private void initializeServiceRunnerInvocationMethods() throws Exception {
    // get JUnit test service reference
    // this is a loose reference - update it if the JUnitTestActivator
    // class is
    // changed.

    BundleContext ctx = getRuntimeBundleContext();

    ServiceReference reference = ctx.getServiceReference(ACTIVATOR_REFERENCE);
    Assert.notNull(reference, "no OSGi service reference found at " + ACTIVATOR_REFERENCE);

    service = ctx.getService(reference);
    Assert.notNull(service, "no service found for reference: " + reference);

    serviceTrigger = service.getClass().getDeclaredMethod("executeTest", null);
    ReflectionUtils.makeAccessible(serviceTrigger);
    Assert.notNull(serviceTrigger, "no executeTest() method found on: " + service.getClass());
}

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

    /*//from  w  w w.jav a 2  s  .com
     * 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.sentencebuilder.etl.importers.FrequencyListImporterImplTest.java

@SuppressWarnings("unchecked")
@Test//from   w w  w .jav a  2 s.  c o m
public void testImportWord() {
    FrequencyListImporterImpl frequencyListImporterImpl = new FrequencyListImporterImpl();

    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);
    when(wordDaoMock.updateBatch(anyListOf(Word.class))).thenReturn(true);

    frequencyListImporterImpl.setWordDao(wordDaoMock);
    frequencyListImporterImpl.setPersistenceBatchSize(2);

    List<Word> insertBatch = new ArrayList<Word>();
    List<Word> updateBatch = new ArrayList<Word>();

    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("awesome", PartOfSpeechType.ADJECTIVE), 400);
    Word wordFromDatabase1 = new Word(new WordId("george", PartOfSpeechType.NOUN));
    Word wordFromDatabase2 = new Word(new WordId("belden", PartOfSpeechType.NOUN));

    when(wordDaoMock.findByWordString(anyString())).thenReturn(Arrays.asList(wordFromDatabase1),
            Arrays.asList(wordFromDatabase2), null, null);

    frequencyListImporterImpl.importWord(word1, insertBatch, updateBatch);

    verify(wordDaoMock, never()).insertBatch(anyListOf(Word.class));
    verify(wordDaoMock, never()).updateBatch(anyListOf(Word.class));
    assertEquals(1, updateBatch.size());
    assertTrue(insertBatch.isEmpty());

    frequencyListImporterImpl.importWord(word2, insertBatch, updateBatch);

    verify(wordDaoMock, never()).insertBatch(anyListOf(Word.class));
    verify(wordDaoMock, times(1)).updateBatch(anyListOf(Word.class));
    assertTrue(updateBatch.isEmpty());
    assertTrue(insertBatch.isEmpty());

    frequencyListImporterImpl.importWord(word3, insertBatch, updateBatch);

    verify(wordDaoMock, never()).insertBatch(anyListOf(Word.class));
    verify(wordDaoMock, times(1)).updateBatch(anyListOf(Word.class));
    assertTrue(updateBatch.isEmpty());
    assertEquals(1, insertBatch.size());

    frequencyListImporterImpl.importWord(word4, insertBatch, updateBatch);

    verify(wordDaoMock, times(1)).insertBatch(anyListOf(Word.class));
    verify(wordDaoMock, times(1)).updateBatch(anyListOf(Word.class));
    assertTrue(updateBatch.isEmpty());
    assertTrue(insertBatch.isEmpty());

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

    assertEquals(100, wordFromDatabase1.getFrequencyWeight());
    assertEquals(200, wordFromDatabase2.getFrequencyWeight());
    assertEquals(2, rowUpdateCountFromObject.intValue());
    assertEquals(2, rowInsertCountFromObject.intValue());
    verify(wordDaoMock, times(4)).findByWordString(anyString());
}

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

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

    Word word1 = new Word(new WordId("george", PartOfSpeechType.NOUN));
    Word word2 = new Word(new WordId("elmer", PartOfSpeechType.NOUN));
    Word word3 = new Word(new WordId("belden", PartOfSpeechType.NOUN));
    List<Word> threadBatch = new ArrayList<Word>();
    threadBatch.add(word1);/*from  w  w  w . j  a  v  a2  s  .c  o  m*/
    threadBatch.add(word2);
    threadBatch.add(word3);

    WordListImporterImpl.BatchWordImportTask batchWordImportTask = wordListImporterImpl.new BatchWordImportTask(
            threadBatch);

    Field rowCountField = ReflectionUtils.findField(WordListImporterImpl.class, "rowCount");
    ReflectionUtils.makeAccessible(rowCountField);
    AtomicInteger rowCountFromObject = (AtomicInteger) ReflectionUtils.getField(rowCountField,
            wordListImporterImpl);

    assertEquals(0, rowCountFromObject.intValue());

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

    int persistenceBatchSizeToSet = 3;
    int concurrencyBatchSizeToSet = 3;

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

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

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

    assertEquals(3, rowCountFromObject.intValue());
    verify(wordDaoMock, times(1)).insertBatch(anyListOf(Word.class));
}

From source file:org.grails.orm.hibernate.SessionFactoryProxy.java

private void updateCurrentSessionContext(SessionFactory sessionFactory) {
    // patch the currentSessionContext variable of SessionFactoryImpl to use this proxy as the key
    CurrentSessionContext ssc = createCurrentSessionContext();
    if (ssc instanceof GrailsSessionContext) {
        ((GrailsSessionContext) ssc).initJta();
    }//from  w w w .  jav a 2  s .  c o  m

    try {
        Class<? extends SessionFactory> sessionFactoryClass = sessionFactory.getClass();
        Field currentSessionContextField = sessionFactoryClass.getDeclaredField("currentSessionContext");
        if (currentSessionContextField != null) {
            ReflectionUtils.makeAccessible(currentSessionContextField);
            currentSessionContextField.set(sessionFactory, ssc);
        }
    } catch (NoSuchFieldException e) {
        // ignore
    } catch (SecurityException e) {
        // ignore
    } catch (IllegalArgumentException e) {
        // ignore
    } catch (IllegalAccessException e) {
        // ignore
    }
}

From source file:com.music.Generator.java

@SuppressWarnings("unused")
private static void initJMusicSynthesizer() {
    try {//from w w w . jav a  2s. com
        Field fld = ReflectionUtils.findField(Play.class, "ms");
        ReflectionUtils.makeAccessible(fld);
        MidiSynth synth = (MidiSynth) fld.get(null);
        // playing for the first time initializes the synthesizer
        try {
            synth.play(null);
        } catch (Exception ex) {
        }
        ;
        Field synthField = ReflectionUtils.findField(MidiSynth.class, "m_synth");
        ReflectionUtils.makeAccessible(synthField);
        Synthesizer synthsizer = (Synthesizer) synthField.get(synth);
        loadSoundbankInstruments(synthsizer);
    } catch (Exception ex) {
        throw new IllegalStateException(ex);
    }

}

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

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

    int initialPopulationSize = 100;
    int populationSize = 100;
    int index = 0;
    double survivalRate = 0.9;
    double mutationRate = 0.1;
    double crossoverRate = 0.1;

    Population populationMock = mock(Population.class);

    List<Chromosome> individuals = new ArrayList<Chromosome>();
    for (int i = 0; i < initialPopulationSize; i++) {
        individuals.add(new MockKeylessChromosome());
    }//w  ww .j a  v a  2  s . co m

    when(populationMock.selectIndex()).thenReturn(index);
    when(populationMock.getIndividuals()).thenReturn(individuals);
    when(populationMock.size()).thenReturn(initialPopulationSize);
    when(populationMock.selectIndex()).thenReturn(0);
    multigenerationalGeneticAlgorithm.setPopulation(populationMock);

    GeneticAlgorithmStrategy strategyToSet = new GeneticAlgorithmStrategy();
    strategyToSet.setPopulationSize(populationSize);
    strategyToSet.setSurvivalRate(survivalRate);
    strategyToSet.setMutationRate(mutationRate);
    strategyToSet.setCrossoverRate(crossoverRate);

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

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

    MutationAlgorithm mutationAlgorithmMock = mock(MutationAlgorithm.class);
    Field mutationAlgorithmField = ReflectionUtils.findField(MultigenerationalGeneticAlgorithm.class,
            "mutationAlgorithm");
    ReflectionUtils.makeAccessible(mutationAlgorithmField);
    ReflectionUtils.setField(mutationAlgorithmField, multigenerationalGeneticAlgorithm, mutationAlgorithmMock);

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

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

    assertEquals(0, executionStatistics.getGenerationStatisticsList().size());

    multigenerationalGeneticAlgorithm.proceedWithNextGeneration();

    assertEquals(1, executionStatistics.getGenerationStatisticsList().size());

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

    int generationCountFromObject = (int) ReflectionUtils.getField(generationCountField,
            multigenerationalGeneticAlgorithm);
    assertEquals(1, generationCountFromObject);

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

    verify(populationMock, times(30)).selectIndex();
    verify(populationMock, times(30)).getIndividuals();
    verify(populationMock, times(30)).makeIneligibleForReproduction(index);
    verify(populationMock, times(20)).addIndividualAsIneligible(any(Chromosome.class));
    verify(populationMock, times(5)).size();
    verify(populationMock, times(1)).increaseAge();
    verify(populationMock, times(1)).resetEligibility();
    verify(populationMock, times(1)).breed(populationSize);
    verify(populationMock, times(1)).evaluateFitness(any(GenerationStatistics.class));
    verifyNoMoreInteractions(populationMock);

    verify(mutationAlgorithmMock, times(10)).mutateChromosome(any(Chromosome.class));
    verifyNoMoreInteractions(mutationAlgorithmMock);

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

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

@Test
public void testRunAlgorithmAutonomously() 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);

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

    GenericCallback genericCallbackMock = mock(GenericCallback.class);

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

    assertTrue(geneticCipherSolutionService.isRunning());
    geneticCipherSolutionService.runAlgorithmAutonomously(genericCallbackMock);
    assertFalse(geneticCipherSolutionService.isRunning());

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

    verify(genericCallbackMock, times(1)).doCallback();

    /*//  w  ww  .  j a va 2 s. c  o 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);

    verify(geneticAlgorithm, times(1)).evolveAutonomously();
}

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

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

    Word word1 = new Word(new WordId("george", PartOfSpeechType.NOUN));
    Word word2 = new Word(new WordId("elmer", PartOfSpeechType.NOUN));
    Word word3 = new Word(new WordId("belden", PartOfSpeechType.NOUN));
    List<Word> threadBatch = new ArrayList<Word>();
    threadBatch.add(word1);//ww  w .j ava2s .c o  m
    threadBatch.add(word2);
    threadBatch.add(word3);

    WordListImporterImpl.BatchWordImportTask batchWordImportTask = wordListImporterImpl.new BatchWordImportTask(
            threadBatch);

    Field rowCountField = ReflectionUtils.findField(WordListImporterImpl.class, "rowCount");
    ReflectionUtils.makeAccessible(rowCountField);
    AtomicInteger rowCountFromObject = (AtomicInteger) ReflectionUtils.getField(rowCountField,
            wordListImporterImpl);

    assertEquals(0, rowCountFromObject.intValue());

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

    int persistenceBatchSizeToSet = 2;
    int concurrencyBatchSizeToSet = 3;

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

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

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

    assertEquals(3, rowCountFromObject.intValue());
    verify(wordDaoMock, times(2)).insertBatch(anyListOf(Word.class));
}