List of usage examples for org.springframework.util ReflectionUtils findField
@Nullable public static Field findField(Class<?> clazz, String name)
From source file:com.gdcn.modules.db.jdbc.processor.CamelBeanProcessor.java
/** * Returns a PropertyDescriptor[] for the given Class. * * @param c The Class to retrieve PropertyDescriptors for. * @return A PropertyDescriptor[] describing the Class. * @throws SQLException if introspection failed. *//*from w w w .java 2s. com*/ private PropertyDescriptor[] propertyDescriptors(Class<?> c) throws SQLException { // Introspector caches BeanInfo classes for better performance BeanInfo beanInfo = null; try { beanInfo = Introspector.getBeanInfo(c); } catch (IntrospectionException e) { throw new SQLException("Bean introspection failed: " + e.getMessage()); } List<PropertyDescriptor> propList = Lists.newArrayList(); PropertyDescriptor[] props = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor prop : props) { String propName = prop.getName(); try { Field field = ReflectionUtils.findField(c, propName); if (field != null && !field.isAnnotationPresent(Transient.class)) {//1.field=null 2.Transient?? propList.add(prop); } } catch (SecurityException e) { throw new SQLException("Bean Get Field failed: " + e.getMessage()); } } return propList.toArray(new PropertyDescriptor[propList.size()]); }
From source file:com.ciphertool.sentencebuilder.etl.importers.FrequencyListImporterImplTest.java
@SuppressWarnings("unchecked") @Test// w ww . j a v a 2s . 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.gmail.sretof.db.jdbc.processor.CamelBeanProcessor.java
/** * Returns a PropertyDescriptor[] for the given Class. * /*w ww . ja va 2s. com*/ * @param c * The Class to retrieve PropertyDescriptors for. * @return A PropertyDescriptor[] describing the Class. * @throws SQLException * if introspection failed. */ private PropertyDescriptor[] propertyDescriptors(Class<?> c) throws SQLException { // Introspector caches BeanInfo classes for better performance BeanInfo beanInfo = null; try { beanInfo = Introspector.getBeanInfo(c); } catch (IntrospectionException e) { throw new SQLException("Bean introspection failed: " + e.getMessage()); } List<PropertyDescriptor> propList = Lists.newArrayList(); PropertyDescriptor[] props = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor prop : props) { String propName = prop.getName(); try { Field field = ReflectionUtils.findField(c, propName); if (field != null && !field.isAnnotationPresent(Transient.class)) {// 1.field=null // 2.Transient?? propList.add(prop); } } catch (SecurityException e) { throw new SQLException("Bean Get Field failed: " + e.getMessage()); } } return propList.toArray(new PropertyDescriptor[propList.size()]); }
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);/* w w w .j a v a 2 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:com.music.Generator.java
@SuppressWarnings("unused") private static void initJMusicSynthesizer() { try {/* w ww . j av a 2 s. c o m*/ 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()); }//from ww w .ja v a 2 s. c o 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(); /*/*from w w w .ja 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);/*from w ww. java 2s. co 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)); }
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);// w ww . j a v a2 s .co 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)); /*// w w w .ja va 2s . c om * 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(); }