List of usage examples for org.springframework.util ReflectionUtils findField
@Nullable public static Field findField(Class<?> clazz, String name)
From source file:com.glaf.core.util.ReflectUtils.java
public static Object getFieldValue(Object object, String fieldName) { try {/*w w w . j a v a 2 s .c o m*/ Field field = ReflectionUtils.findField(object.getClass(), fieldName); if (!Modifier.isPublic(field.getModifiers())) { field.setAccessible(true); } return ReflectionUtils.getField(field, object); } catch (Exception ex) { try { return BeanUtils.getProperty(object, fieldName); } catch (Exception e) { } } return null; }
From source file:com.ciphertool.sentencebuilder.etl.importers.FrequencyListImporterImplTest.java
@SuppressWarnings("unchecked") @Test/*www.j a v a 2 s. co 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 w w . j a 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)); /*/*from www . j av a 2 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); }
From source file:py.una.pol.karaku.reports.DynamicUtils.java
/** * Metodo que obtiene el tipo de dato de cada columna que debe ser generada * de forma dinamica y finalmente agrega las columnas correctamente * definidas al reporte./*from www . j a va2s . c o m*/ * * @param structReport * Estructura del reporte * @param columns * Lista de columnas que deben ser generadas * @param clazz * Clase de la entidad sobre la cual se desea realizar el reporte * @return Reporte con las correspondientes columnas generadas * @throws ReportException */ public <T> FastReportBuilder addColumn(FastReportBuilder structReport, List<Column> columns, Class<T> clazz) throws ReportException { for (Column column : columns) { try { if (column.getField().contains(".")) { structReport.addColumn(column.getTitle(), column.getField(), Object.class.getName(), column.getWidth(), getStyleColumn(column)); } else { Field field = ReflectionUtils.findField(clazz, column.getNameField()); structReport.addColumn(column.getTitle(), column.getField(), field.getType().getName(), getWidthColumn(column, field), this.getStyleColumn(column, field)); } } catch (ClassNotFoundException e) { throw new ReportException(e); } catch (SecurityException e) { throw new ReportException(e); } } return structReport; }
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 w w .j av a2s. c om 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();/*from ww w . ja va2 s .c o m*/ 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);/* w w w .jav a2 s. 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()); }
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 w w . j av a 2 s. c om 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 2 s . c o m 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)); }