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.sentencebuilder.etl.importers.FrequencyListImporterImplTest.java

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

    Field rowUpdateCountField = ReflectionUtils.findField(FrequencyListImporterImpl.class, "rowUpdateCount");
    ReflectionUtils.makeAccessible(rowUpdateCountField);
    AtomicInteger rowUpdateCountFromObject = (AtomicInteger) ReflectionUtils.getField(rowUpdateCountField,
            frequencyListImporterImpl);//from   www . j a  v  a 2 s.  c  o m

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

    frequencyListImporterImpl.importWord(null, insertBatch, updateBatch);

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

    assertTrue(updateBatch.isEmpty());
    assertTrue(insertBatch.isEmpty());
    assertEquals(0, rowUpdateCountFromObject.intValue());
    assertEquals(0, rowInsertCountFromObject.intValue());
    verifyZeroInteractions(wordDaoMock);
}

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

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

    doThrow(new IllegalStateException()).when(geneticAlgorithm).evolveAutonomously();

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

    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.runAlgorithmAutonomously(genericCallbackMock);
    assertFalse(geneticCipherSolutionService.isRunning());

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

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

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

    /*/*from  w w w  . jav  a2  s.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);

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

From source file:org.hdiv.web.servlet.tags.UrlTagTests.java

private String invokeCreateUrl(UrlTagHDIV tag) {
    Method createUrl = ReflectionUtils.findMethod(tag.getClass(), "createUrl");
    ReflectionUtils.makeAccessible(createUrl);
    return (String) ReflectionUtils.invokeMethod(createUrl, tag);
}

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

@SuppressWarnings("unchecked")
@Test//from ww  w.j av a  2 s .c o  m
public void testImportWord_BatchSizeNotReached() {
    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(3);

    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, never()).updateBatch(anyListOf(Word.class));
    assertEquals(2, updateBatch.size());
    assertTrue(insertBatch.isEmpty());

    frequencyListImporterImpl.importWord(word3, insertBatch, updateBatch);

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

    frequencyListImporterImpl.importWord(word4, insertBatch, updateBatch);

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

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

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

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

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

    GeneticAlgorithmStrategy strategyToSet = new GeneticAlgorithmStrategy();
    strategyToSet.setGeneticStructure(new Object());
    strategyToSet.setPopulationSize(1);// w ww .ja v  a  2  s.  c  o m
    strategyToSet.setLifespan(0);
    strategyToSet.setSurvivalRate(0.1);
    strategyToSet.setMutationRate(0.0);
    strategyToSet.setMaxMutationsPerIndividual(0);
    strategyToSet.setCrossoverRate(0.0);
    strategyToSet.setMutateDuringCrossover(false);
    strategyToSet.setMaxGenerations(-1);
    strategyToSet.setCrossoverAlgorithm(mock(CrossoverAlgorithm.class));
    strategyToSet.setFitnessEvaluator(mock(FitnessEvaluator.class));
    strategyToSet.setMutationAlgorithm(mock(MutationAlgorithm.class));
    strategyToSet.setSelectionAlgorithm(mock(SelectionAlgorithm.class));
    strategyToSet.setSelector(mock(Selector.class));

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

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

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

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

    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.runAlgorithmStepwise();
    assertFalse(geneticCipherSolutionService.isRunning());

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

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

    /*//w ww .j av a  2s  . 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);
}

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

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

    GeneticAlgorithmStrategy strategyToSet = new GeneticAlgorithmStrategy();
    strategyToSet.setGeneticStructure(null);
    strategyToSet.setPopulationSize(0);/*from w  ww. j a v  a  2 s.  com*/
    strategyToSet.setLifespan(null);

    /*
     * This must be set via reflection because the setter method does its
     * own validation
     */
    Field survivalRateField = ReflectionUtils.findField(GeneticAlgorithmStrategy.class, "survivalRate");
    ReflectionUtils.makeAccessible(survivalRateField);
    ReflectionUtils.setField(survivalRateField, strategyToSet, -0.1);

    /*
     * This must be set via reflection because the setter method does its
     * own validation
     */
    Field mutationRateField = ReflectionUtils.findField(GeneticAlgorithmStrategy.class, "mutationRate");
    ReflectionUtils.makeAccessible(mutationRateField);
    ReflectionUtils.setField(mutationRateField, strategyToSet, -0.1);

    strategyToSet.setMaxMutationsPerIndividual(-1);

    /*
     * This must be set via reflection because the setter method does its
     * own validation
     */
    Field crossoverRateField = ReflectionUtils.findField(GeneticAlgorithmStrategy.class, "crossoverRate");
    ReflectionUtils.makeAccessible(crossoverRateField);
    ReflectionUtils.setField(crossoverRateField, strategyToSet, -0.1);

    strategyToSet.setMutateDuringCrossover(null);
    strategyToSet.setMaxGenerations(0);
    strategyToSet.setCrossoverAlgorithm(null);
    strategyToSet.setFitnessEvaluator(null);
    strategyToSet.setMutationAlgorithm(null);
    strategyToSet.setSelectionAlgorithm(null);
    strategyToSet.setSelector(null);

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

    boolean exceptionCaught = false;

    try {
        multigenerationalGeneticAlgorithm.validateParameters();
    } catch (IllegalStateException ise) {
        String expectedMessage = "Unable to execute genetic algorithm because one or more of the required parameters are missing.  The validation errors are:";
        expectedMessage += "\n\t-Parameter 'geneticStructure' cannot be null.";
        expectedMessage += "\n\t-Parameter 'populationSize' must be greater than zero.";
        expectedMessage += "\n\t-Parameter 'lifespan' cannot be null.";
        expectedMessage += "\n\t-Parameter 'survivalRate' must be greater than zero.";
        expectedMessage += "\n\t-Parameter 'mutationRate' must be greater than or equal to zero.";
        expectedMessage += "\n\t-Parameter 'maxMutationsPerIndividual' must be greater than or equal to zero.";
        expectedMessage += "\n\t-Parameter 'crossoverRate' must be greater than or equal to zero.";
        expectedMessage += "\n\t-Parameter 'mutateDuringCrossover' cannot be null.";
        expectedMessage += "\n\t-Parameter 'maxGenerations' cannot be null and must not equal zero.";
        expectedMessage += "\n\t-Parameter 'crossoverAlgorithm' cannot be null.";
        expectedMessage += "\n\t-Parameter 'fitnessEvaluator' cannot be null.";
        expectedMessage += "\n\t-Parameter 'mutationAlgorithm' cannot be null.";
        expectedMessage += "\n\t-Parameter 'selectionAlgorithm' cannot be null.";
        expectedMessage += "\n\t-Parameter 'selectorMethod' cannot be null.";

        assertEquals(expectedMessage, ise.getMessage());

        exceptionCaught = true;
    }

    assertTrue(exceptionCaught);
}

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

@Test
public void testEnd() 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.end();//ww  w .  ja va2s  . c om
    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:com.ciphertool.sentencebuilder.etl.importers.FrequencyListImporterImplTest.java

@Test
public void testBatchWordImportTask() {
    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("awesome", PartOfSpeechType.ADJECTIVE), 400);
    List<Word> threadBatch = new ArrayList<Word>();
    threadBatch.add(word1);/*from  w  ww  .ja  v a 2s. co m*/
    threadBatch.add(word2);
    threadBatch.add(word3);
    threadBatch.add(word4);

    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 = 2;

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

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

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

    assertEquals(2, rowUpdateCountFromObject.intValue());
    assertEquals(2, rowInsertCountFromObject.intValue());
    verify(wordDaoMock, times(1)).insertBatch(anyListOf(Word.class));
    verify(wordDaoMock, times(1)).updateBatch(anyListOf(Word.class));
    verify(wordDaoMock, times(4)).findByWordString(anyString());
}