List of usage examples for org.springframework.util ReflectionUtils getField
@Nullable public static Object getField(Field field, @Nullable Object target)
From source file:com.ciphertool.sentencebuilder.etl.importers.WordListImporterImplTest.java
@Test public void testImportWordList() { ThreadPoolTaskExecutor taskExecutorSpy = spy(new ThreadPoolTaskExecutor()); taskExecutorSpy.setCorePoolSize(4);//from w w w . j a v a 2 s . c om taskExecutorSpy.setMaxPoolSize(4); taskExecutorSpy.setQueueCapacity(100); taskExecutorSpy.setKeepAliveSeconds(1); taskExecutorSpy.setAllowCoreThreadTimeOut(true); taskExecutorSpy.initialize(); WordListImporterImpl wordListImporterImpl = new WordListImporterImpl(); wordListImporterImpl.setTaskExecutor(taskExecutorSpy); 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); 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> wordsToReturn = new ArrayList<Word>(); wordsToReturn.add(word1); wordsToReturn.add(word2); wordsToReturn.add(word3); PartOfSpeechFileParser fileParserMock = mock(PartOfSpeechFileParser.class); when(fileParserMock.parseFile()).thenReturn(wordsToReturn); wordListImporterImpl.setFileParser(fileParserMock); wordListImporterImpl.importWordList(); rowCountFromObject = (AtomicInteger) ReflectionUtils.getField(rowCountField, wordListImporterImpl); assertEquals(3, rowCountFromObject.intValue()); verify(wordDaoMock, times(1)).insertBatch(anyListOf(Word.class)); verify(taskExecutorSpy, times(1)).execute(any(Runnable.class)); }
From source file:com.agapple.asyncload.impl.pool.AsyncLoadThreadPool.java
private void initThreadLocal(Field field, Thread caller, Thread runner) { if (caller == null || runner == null) { return;/* www . jav a 2 s . c om*/ } // ? // 1. callerThreadLocalrunnerThreadLocal??caller // 2. ?caller,runnerThreadLocal?,set?ThreadLocal,???? // ??Runnable??ThreadLocalMaprunner???caller?????? // threadlocal?,?? Object callerThreadLocalMap = ReflectionUtils.getField(field, caller); if (callerThreadLocalMap != null) { ReflectionUtils.setField(field, runner, callerThreadLocalMap);// ?caller?runner } else { // ?,execute??? } }
From source file:com.ciphertool.genetics.PopulationTest.java
@Test public void testSetTaskExecutor() { Population population = new Population(); TaskExecutor taskExecutor = mock(TaskExecutor.class); population.setTaskExecutor(taskExecutor); Field taskExecutorField = ReflectionUtils.findField(Population.class, "taskExecutor"); ReflectionUtils.makeAccessible(taskExecutorField); TaskExecutor taskExecutorFromObject = (TaskExecutor) ReflectionUtils.getField(taskExecutorField, population);/*from ww w. j a v a 2 s . c o m*/ assertSame(taskExecutor, taskExecutorFromObject); }
From source file:com.github.marsbits.restfbmessenger.spring.boot.autoconfigure.MessengerAutoConfigurationTests.java
private Object getFieldValue(Object object, String name) { Field field = ReflectionUtils.findField(object.getClass(), name); ReflectionUtils.makeAccessible(field); return ReflectionUtils.getField(field, object); }
From source file:com.ciphertool.genetics.algorithms.MultigenerationalGeneticAlgorithmTest.java
@Test public void testSetStrategy() { GeneticAlgorithmStrategy strategyToSet = new GeneticAlgorithmStrategy(); Population populationMock = mock(Population.class); CrossoverAlgorithm crossoverAlgorithmMock = mock(CrossoverAlgorithm.class); NonUniformMutationAlgorithm mutationAlgorithmMock = mock(NonUniformMutationAlgorithm.class); SelectionAlgorithm selectionAlgorithmMock = mock(SelectionAlgorithm.class); FitnessEvaluator fitnessEvaluatorMock = mock(FitnessEvaluator.class); FitnessEvaluator knownSolutionFitnessEvaluatorMock = mock(FitnessEvaluator.class); Object geneticStructure = new Object(); int lifeSpan = 10; boolean compareToKnownSolution = true; boolean mutateDuringCrossover = true; int maxMutationsPerIndividual = 5; strategyToSet.setGeneticStructure(geneticStructure); strategyToSet.setFitnessEvaluator(fitnessEvaluatorMock); strategyToSet.setLifespan(lifeSpan); strategyToSet.setKnownSolutionFitnessEvaluator(knownSolutionFitnessEvaluatorMock); strategyToSet.setCompareToKnownSolution(compareToKnownSolution); strategyToSet.setCrossoverAlgorithm(crossoverAlgorithmMock); strategyToSet.setMutationAlgorithm(mutationAlgorithmMock); strategyToSet.setMutateDuringCrossover(mutateDuringCrossover); strategyToSet.setMaxMutationsPerIndividual(maxMutationsPerIndividual); strategyToSet.setSelectionAlgorithm(selectionAlgorithmMock); MultigenerationalGeneticAlgorithm multigenerationalGeneticAlgorithm = new MultigenerationalGeneticAlgorithm(); multigenerationalGeneticAlgorithm.setPopulation(populationMock); multigenerationalGeneticAlgorithm.setStrategy(strategyToSet); Field strategyField = ReflectionUtils.findField(MultigenerationalGeneticAlgorithm.class, "strategy"); ReflectionUtils.makeAccessible(strategyField); GeneticAlgorithmStrategy strategyFromObject = (GeneticAlgorithmStrategy) ReflectionUtils .getField(strategyField, multigenerationalGeneticAlgorithm); assertSame(strategyToSet, strategyFromObject); verify(populationMock, times(1)).setGeneticStructure(same(geneticStructure)); verify(populationMock, times(1)).setFitnessEvaluator(same(fitnessEvaluatorMock)); verify(populationMock, times(1)).setLifespan(eq(lifeSpan)); verify(populationMock, times(1)).setKnownSolutionFitnessEvaluator(same(knownSolutionFitnessEvaluatorMock)); verify(populationMock, times(1)).setCompareToKnownSolution(eq(compareToKnownSolution)); verifyNoMoreInteractions(populationMock); verify(crossoverAlgorithmMock, times(1)).setMutationAlgorithm(same(mutationAlgorithmMock)); verify(crossoverAlgorithmMock, times(1)).setMutateDuringCrossover(eq(mutateDuringCrossover)); verifyNoMoreInteractions(crossoverAlgorithmMock); verify(mutationAlgorithmMock, times(1)).setMaxMutationsPerChromosome(eq(maxMutationsPerIndividual)); verifyNoMoreInteractions(mutationAlgorithmMock); Field crossoverAlgorithmField = ReflectionUtils.findField(MultigenerationalGeneticAlgorithm.class, "crossoverAlgorithm"); ReflectionUtils.makeAccessible(crossoverAlgorithmField); CrossoverAlgorithm crossoverAlgorithmFromObject = (CrossoverAlgorithm) ReflectionUtils .getField(crossoverAlgorithmField, multigenerationalGeneticAlgorithm); assertSame(crossoverAlgorithmMock, crossoverAlgorithmFromObject); Field mutationAlgorithmField = ReflectionUtils.findField(MultigenerationalGeneticAlgorithm.class, "mutationAlgorithm"); ReflectionUtils.makeAccessible(mutationAlgorithmField); MutationAlgorithm mutationAlgorithmFromObject = (MutationAlgorithm) ReflectionUtils .getField(mutationAlgorithmField, multigenerationalGeneticAlgorithm); assertSame(mutationAlgorithmMock, mutationAlgorithmFromObject); Field selectionAlgorithmField = ReflectionUtils.findField(MultigenerationalGeneticAlgorithm.class, "selectionAlgorithm"); ReflectionUtils.makeAccessible(selectionAlgorithmField); SelectionAlgorithm selectionAlgorithmFromObject = (SelectionAlgorithm) ReflectionUtils .getField(selectionAlgorithmField, multigenerationalGeneticAlgorithm); assertSame(selectionAlgorithmMock, selectionAlgorithmFromObject); }
From source file:com.ciphertool.sentencebuilder.etl.importers.FrequencyListImporterImplTest.java
@Test public void testImportFrequencyList() { ThreadPoolTaskExecutor taskExecutorSpy = spy(new ThreadPoolTaskExecutor()); taskExecutorSpy.setCorePoolSize(4);/*www . j a v a 2s . c o m*/ taskExecutorSpy.setMaxPoolSize(4); taskExecutorSpy.setQueueCapacity(100); taskExecutorSpy.setKeepAliveSeconds(1); taskExecutorSpy.setAllowCoreThreadTimeOut(true); taskExecutorSpy.initialize(); FrequencyListImporterImpl frequencyListImporterImpl = new FrequencyListImporterImpl(); frequencyListImporterImpl.setTaskExecutor(taskExecutorSpy); 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 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> wordsToReturn = new ArrayList<Word>(); wordsToReturn.add(word1); wordsToReturn.add(word2); wordsToReturn.add(word3); wordsToReturn.add(word4); FrequencyFileParser fileParserMock = mock(FrequencyFileParser.class); when(fileParserMock.parseFile()).thenReturn(wordsToReturn); frequencyListImporterImpl.setFileParser(fileParserMock); 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); frequencyListImporterImpl.importFrequencyList(); 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()); verify(taskExecutorSpy, times(2)).execute(any(Runnable.class)); }
From source file:localdomain.localhost.CasInitializer.java
@Override public void afterPropertiesSet() throws Exception { System.err.println(/* w w w .j a va 2 s . co m*/ "##############################################################################################"); System.err.println( "##############################################################################################"); System.err.println( "# #"); System.err.println( "# CLOUDBEES JASIG CAS SSO SERVER CLICKSTART #"); System.err.println( "# #"); System.err.println( "# See documentation at https://github.com/CloudBees-community/jasig-cas-clickstart/wiki #"); System.err.println( "# #"); System.err.println( "##############################################################################################"); System.err.println( "##############################################################################################"); try { authenticationHandler = applicationContext.getBean(SearchModeSearchDatabaseAuthenticationHandler.class); } catch (NoSuchBeanDefinitionException e) { String msg = "No Spring bean of type " + SearchModeSearchDatabaseAuthenticationHandler.class + " found, initializer can not run"; logger.warn(msg); throw new IllegalStateException(msg, e); } dataSource = (DataSource) ReflectionUtils.getField(dataSourceField, authenticationHandler); fieldUser = (String) ReflectionUtils.getField(fieldUserField, authenticationHandler); fieldPassword = (String) ReflectionUtils.getField(fieldPasswordField, authenticationHandler); tableUsers = (String) ReflectionUtils.getField(tableUsersField, authenticationHandler); passwordEncoder = (PasswordEncoder) ReflectionUtils.getField(passwordEncoderField, authenticationHandler); final Connection cnn = dataSource.getConnection(); Statement stmt = null; ResultSet rst = null; try { logger.info("Create table " + tableUsers + " if not exist"); stmt = cnn.createStatement(); String createTableDdl = "CREATE TABLE IF NOT EXISTS `" + tableUsers + "` (" + " `" + fieldUser + "` varchar(255) DEFAULT NULL,\n" + " `" + fieldPassword + "` varchar(255) DEFAULT NULL,\n" + " PRIMARY KEY (`" + fieldUser + "`)\n" + ")"; stmt.execute(createTableDdl); closeQuietly(stmt); logger.info("Validate table columns"); stmt = cnn.createStatement(); String sqlCheckDatabaseTable = "select `" + fieldUser + "`,`" + fieldPassword + "`" + " from `" + tableUsers + "` where 0=1"; try { stmt.execute(sqlCheckDatabaseTable); } catch (SQLException e) { throw new IllegalStateException("Invalid table structure:" + sqlCheckDatabaseTable, e); } closeQuietly(stmt); stmt = cnn.createStatement(); String sqlCountUsers = "select count(*) from `" + tableUsers + "`"; rst = stmt.executeQuery(sqlCountUsers); rst.next(); int usersCount = rst.getInt(1); closeQuietly(stmt, rst); if (usersCount == 0) { insertUser("demo", "mode", cnn); } if (!cnn.getAutoCommit()) { cnn.commit(); } logger.info("CAS CLICKSTART INITIALIZED"); } finally { closeQuietly(cnn, stmt, rst); } }
From source file:com.ciphertool.genetics.PopulationTest.java
@Test public void testSetSelector() { Population population = new Population(); Selector selector = mock(Selector.class); population.setSelector(selector);/*from w w w . ja v a 2 s.c om*/ Field selectorField = ReflectionUtils.findField(Population.class, "selector"); ReflectionUtils.makeAccessible(selectorField); Selector selectorFromObject = (Selector) ReflectionUtils.getField(selectorField, population); assertSame(selector, selectorFromObject); }
From source file:com.ciphertool.genetics.algorithms.ConcurrentMultigenerationalGeneticAlgorithmTest.java
@SuppressWarnings("unchecked") @Test// w ww .ja va 2 s . c om public void testCrossover() { ConcurrentMultigenerationalGeneticAlgorithm concurrentMultigenerationalGeneticAlgorithm = new ConcurrentMultigenerationalGeneticAlgorithm(); concurrentMultigenerationalGeneticAlgorithm.setTaskExecutor(taskExecutor); 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()); } concurrentMultigenerationalGeneticAlgorithm.setPopulation(population); CrossoverAlgorithm crossoverAlgorithmMock = mock(CrossoverAlgorithm.class); Field crossoverAlgorithmField = ReflectionUtils.findField(ConcurrentMultigenerationalGeneticAlgorithm.class, "crossoverAlgorithm"); ReflectionUtils.makeAccessible(crossoverAlgorithmField); ReflectionUtils.setField(crossoverAlgorithmField, concurrentMultigenerationalGeneticAlgorithm, 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(ConcurrentMultigenerationalGeneticAlgorithm.class, "strategy"); ReflectionUtils.makeAccessible(strategyField); ReflectionUtils.setField(strategyField, concurrentMultigenerationalGeneticAlgorithm, 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 = concurrentMultigenerationalGeneticAlgorithm.crossover(initialPopulationSize); ineligibleForReproductionFromObject = (List<Chromosome>) ReflectionUtils .getField(ineligibleForReproductionField, population); /* * The population size should be reduced by the number of parents used * during crossover. */ assertEquals(40, population.size()); assertEquals(5, childrenProduced); // 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:net.community.chest.gitcloud.facade.backend.git.BackendUploadPackFactory.java
@Override public UploadPack create(final C request, Repository db) throws ServiceNotEnabledException, ServiceNotAuthorizedException { final File dir = db.getDirectory(); final String logPrefix; if (request instanceof HttpServletRequest) { HttpServletRequest req = (HttpServletRequest) request; logPrefix = "create(" + req.getMethod() + ")[" + req.getRequestURI() + "][" + req.getQueryString() + "]"; } else {//w ww. j a v a 2 s .c o m logPrefix = "create(" + dir.getAbsolutePath() + ")"; } if (logger.isDebugEnabled()) { logger.debug(logPrefix + ": " + dir.getAbsolutePath()); } UploadPack up = new UploadPack(db) { @Override @SuppressWarnings("synthetic-access") public void upload(InputStream input, OutputStream output, OutputStream messages) throws IOException { InputStream effIn = input; OutputStream effOut = output, effMessages = messages; if (logger.isTraceEnabled()) { LineLevelAppender inputAppender = new LineLevelAppender() { @Override public void writeLineData(CharSequence lineData) throws IOException { logger.trace(logPrefix + " upload(C): " + lineData); } @Override public boolean isWriteEnabled() { return true; } }; effIn = new TeeInputStream(effIn, new HexDumpOutputStream(inputAppender), true); LineLevelAppender outputAppender = new LineLevelAppender() { @Override public void writeLineData(CharSequence lineData) throws IOException { logger.trace(logPrefix + " upload(S): " + lineData); } @Override public boolean isWriteEnabled() { return true; } }; effOut = new TeeOutputStream(effOut, new HexDumpOutputStream(outputAppender)); if (effMessages != null) { LineLevelAppender messagesAppender = new LineLevelAppender() { @Override public void writeLineData(CharSequence lineData) throws IOException { logger.trace(logPrefix + " upload(M): " + lineData); } @Override public boolean isWriteEnabled() { return true; } }; // TODO review the decision to use an AsciiLineOutputStream here effMessages = new TeeOutputStream(effMessages, new AsciiLineOutputStream(messagesAppender)); } } super.upload(effIn, effOut, effMessages); } @Override @SuppressWarnings("synthetic-access") public void sendAdvertisedRefs(RefAdvertiser adv) throws IOException, ServiceMayNotContinueException { RefAdvertiser effAdv = adv; if (logger.isTraceEnabled() && (adv instanceof PacketLineOutRefAdvertiser)) { PacketLineOut pckOut = (PacketLineOut) ReflectionUtils.getField(pckOutField, adv); effAdv = new PacketLineOutRefAdvertiser(pckOut) { private final PacketLineOut pckLog = new PacketLineOut( // TODO review the decision to use an AsciiLineOutputStream here new AsciiLineOutputStream(new LineLevelAppender() { @Override public void writeLineData(CharSequence lineData) throws IOException { logger.trace(logPrefix + " S: " + lineData); } @Override public boolean isWriteEnabled() { return true; } })); @Override protected void writeOne(CharSequence line) throws IOException { String s = line.toString(); super.writeOne(s); pckLog.writeString(s); } @Override protected void end() throws IOException { super.end(); pckLog.end(); } }; } super.sendAdvertisedRefs(effAdv); } }; up.setTimeout(uploadTimeoutValue); return up; }