List of usage examples for org.springframework.context.annotation AnnotationConfigApplicationContext getBean
@Override public Object getBean(String name) throws BeansException
From source file:nl.surfnet.coin.api.service.JanusClientDetailsServiceTest.java
/** * Test to see if the cache works. Especially the fact that we store items in * the same cache with the same key for different return Objects: * ClientDetails and ConsumerDetails// ww w . ja v a2s. c o m * */ @Test public void testCache() throws IOException { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(this.getClass()); ClientDetailsService clientDetailsService = (ClientDetailsService) ctx.getBean("janusClientDetailsService"); Janus janus = (Janus) ctx.getBean("janus"); when(janus.getEntityIdsByMetaData(Metadata.OAUTH_CONSUMERKEY, "consumerkey")) .thenReturn(Collections.singletonList("sp-entity-id")); when(janus.getMetadataByEntityId("sp-entity-id")).thenReturn(getMetadata()); ClientDetails clientDetails = clientDetailsService.loadClientByClientId("consumerkey"); assertEquals("secret", clientDetails.getClientSecret()); // when we do this a second time the cache should kick in when(janus.getEntityIdsByMetaData(Metadata.OAUTH_CONSUMERKEY, "consumerkey")) .thenThrow(new RuntimeException("Cache did not kick in")); clientDetailsService.loadClientByClientId("consumerkey"); /* * now do the same for the loading of ConsumerDetails (and yes, this lengthy * test including the reset is necessary) to make sure we don't hit the * cache for loading the ConsumerDetails as we store both in the same cache * with potentially the same key (e.g. the consumerkey) resulting in * java.lang.ClassCastException: * nl.surfnet.coin.api.oauth.ExtendedBaseClientDetails cannot be cast to * org.springframework.security.oauth.provider.ConsumerDetails without a * custom key generator */ reset(janus); when(janus.getEntityIdsByMetaData(Metadata.OAUTH_CONSUMERKEY, "consumerkey")) .thenReturn(Collections.singletonList("sp-entity-id")); when(janus.getMetadataByEntityId("sp-entity-id")).thenReturn(getMetadata()); ConsumerDetailsService consumerDetailsService = (ConsumerDetailsService) clientDetailsService; ConsumerDetails consumerDetails = consumerDetailsService.loadConsumerByConsumerKey("consumerkey"); assertEquals("secret", ((SharedConsumerSecret) consumerDetails.getSignatureSecret()).getConsumerSecret()); when(janus.getEntityIdsByMetaData(Metadata.OAUTH_CONSUMERKEY, "consumerkey")) .thenThrow(new RuntimeException("Cache did not kick in")); consumerDetailsService.loadConsumerByConsumerKey("consumerkey"); }
From source file:org.twinkql.template.AbstractTwinkqlTemplateFactory.java
/** * Gets the twinkql template./* w w w . j a va2 s . c o m*/ * * @return the twinkql template * @throws Exception the exception */ public TwinkqlTemplate getTwinkqlTemplate() { DefaultListableBeanFactory parentBeanFactory = new DefaultListableBeanFactory(); parentBeanFactory.registerSingleton("twinkqlContext", this.getTwinkqlContext()); GenericApplicationContext parentContext = new GenericApplicationContext(parentBeanFactory); parentContext.refresh(); AnnotationConfigApplicationContext annotationConfigApplicationContext = this .decorateContext(new AnnotationConfigApplicationContext()); annotationConfigApplicationContext.setParent(parentContext); annotationConfigApplicationContext.scan(PACKAGE_SCAN); annotationConfigApplicationContext.refresh(); TwinkqlTemplate template = annotationConfigApplicationContext.getBean(TwinkqlTemplate.class); return template; }
From source file:org.cellcore.code.exec.ExecConsolidate.java
@Override protected void execute(CommandLine commandLine) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ContextConfig.class); final File crawlResultDir = new File(commandLine.getOptionValue("input")); boolean global = commandLine.hasOption("global"); Collection<File> resultFiles = FileUtils.listFiles(crawlResultDir, new String[] { "data.json" }, true); CardPriceConsolidator conciliatePriceCrawlData = context.getBean(CardPriceConsolidator.class); Gson gson = GsonUtils.getSerializer(); for (File crawlResultFile : resultFiles) { logger.info("processing file " + crawlResultFile.getAbsolutePath()); try {/*from w w w . j av a 2 s . c om*/ String fetched = FileUtils.readFileToString(crawlResultFile); try { Card[] cards = gson.fromJson(fetched, Card[].class); for (Card card : cards) { if (card != null) { if (global) { conciliatePriceCrawlData.conciliateGlobal(card); } else { conciliatePriceCrawlData.conciliate(card); } } } } catch (Throwable t) { logger.error("ERROR PROCESSING FILE: " + crawlResultFile.getAbsolutePath(), t); } } catch (Throwable t) { logger.error("ERROR READING FILE: " + crawlResultFile.getAbsolutePath(), t); } } if (global) { for (Map.Entry<String, Card> entry : conciliatePriceCrawlData.getGlobalCards().entrySet()) { conciliatePriceCrawlData.conciliate(entry.getValue()); } } }
From source file:st.malike.service.storm.LNSBolt.java
@Override public void prepare(Map stormConf, TopologyContext context) { try {//w w w .j a va 2s. c o m this.config = stormConf; // reinitialize Spring IoC-- a hack AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.getEnvironment().getPropertySources() .addFirst(new ResourcePropertySource("classpath:application.properties")); ctx.scan("st.malike"); ctx.refresh(); demographicSummaryService = ctx.getBean(DemographicSummaryService.class); demographicService = ctx.getBean(DemographicService.class); summaryElasticSearchService = ctx.getBean(SummaryElasticSearchService.class); liveNotificationService = ctx.getBean(LiveNotificationService.class); summaryCalculatorService = ctx.getBean(SummaryCalculatorService.class); } catch (IOException ex) { Logger.getLogger(LNSBolt.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.doctor.spring4.blog.code.WireObjectDependenciesOutsideSpring.java
/** * ??spring??// ww w.jav a2 s .c o m * * @see http://www.javacodegeeks.com/2012/03/integrating-spring-into-legacy.html * */ @Test public void test_registerSingleton() { AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext( SpringConfig.class); Person person = new Person(); assertNull(person.getContext()); applicationContext.getBeanFactory().registerSingleton("person", person); assertNotNull(applicationContext.getBean(Person.class)); assertNull(person.getContext()); applicationContext.getAutowireCapableBeanFactory().autowireBean(person); assertNotNull(person.getContext()); Stream.of(applicationContext.getBeanDefinitionNames()).forEach(System.out::println); applicationContext.close(); }
From source file:org.springframework.hateoas.config.EnableHypermediaSupportIntegrationTest.java
/** * @see #134, #219//from w ww. j av a2 s. c o m */ @Test @SuppressWarnings("unchecked") public void halSetupIsAppliedToAllTransitiveComponentsInRequestMappingHandlerAdapter() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(HalConfig.class); Jackson2ModuleRegisteringBeanPostProcessor postProcessor = new HypermediaSupportBeanDefinitionRegistrar.Jackson2ModuleRegisteringBeanPostProcessor(); postProcessor.setBeanFactory(context); RequestMappingHandlerAdapter adapter = context.getBean(RequestMappingHandlerAdapter.class); assertThat(adapter.getMessageConverters().get(0).getSupportedMediaTypes(), hasItem(MediaTypes.HAL_JSON)); boolean found = false; for (HandlerMethodArgumentResolver resolver : adapter.getArgumentResolvers().getResolvers()) { if (resolver instanceof AbstractMessageConverterMethodArgumentResolver) { found = true; AbstractMessageConverterMethodArgumentResolver processor = (AbstractMessageConverterMethodArgumentResolver) resolver; List<HttpMessageConverter<?>> converters = (List<HttpMessageConverter<?>>) ReflectionTestUtils .getField(processor, "messageConverters"); // assertThat(converters.get(0), // is(instanceOf(TypeConstrainedMappingJackson2HttpMessageConverter.class))); assertThat(converters.get(0), is(instanceOf(MappingJackson2HttpMessageConverter.class))); assertThat(converters.get(0).getSupportedMediaTypes(), hasItem(MediaTypes.HAL_JSON)); } } assertThat(found, is(true)); }
From source file:com.ryantenney.metrics.spring.EnableMetricsTest.java
@Test public void metricsConfigTest() throws Throwable { // Initialize the context AnnotationConfigApplicationContext applicationContext = null; try {/*from ww w . j a va2s . co m*/ applicationContext = new AnnotationConfigApplicationContext(); applicationContext.register(MetricsConfig.class); applicationContext.refresh(); // Assert that the custom registries were used assertSame(metricRegistry, applicationContext.getBean(MetricRegistry.class)); assertSame(healthCheckRegistry, applicationContext.getBean(HealthCheckRegistry.class)); // Verify that the configureReporters method was invoked assertThat(MetricsConfig.isConfigureReportersInvoked, is(true)); // Assert that the bean has been proxied TestBean testBean = applicationContext.getBean(TestBean.class); assertNotNull(testBean); assertThat(AopUtils.isAopProxy(testBean), is(true)); // Verify that the Gauge field's value is returned Gauge<Integer> fieldGauge = (Gauge<Integer>) forGaugeField(metricRegistry, TestBean.class, "intGaugeField"); assertNotNull(fieldGauge); assertThat(fieldGauge.getValue(), is(5)); // Verify that the Gauge method's value is returned Gauge<Integer> methodGauge = (Gauge<Integer>) forGaugeMethod(metricRegistry, TestBean.class, "intGaugeMethod"); assertNotNull(methodGauge); assertThat(methodGauge.getValue(), is(6)); // Verify that the Timer's counter is incremented on method invocation Timer timedMethodTimer = forTimedMethod(metricRegistry, TestBean.class, "timedMethod"); assertNotNull(timedMethodTimer); assertThat(timedMethodTimer.getCount(), is(0L)); testBean.timedMethod(); assertThat(timedMethodTimer.getCount(), is(1L)); // Verify that the Meter's counter is incremented on method invocation Meter meteredMethodMeter = forMeteredMethod(metricRegistry, TestBean.class, "meteredMethod"); assertNotNull(meteredMethodMeter); assertThat(meteredMethodMeter.getCount(), is(0L)); testBean.meteredMethod(); assertThat(meteredMethodMeter.getCount(), is(1L)); // Verify that the Meter's counter is incremented on method invocation Meter exceptionMeteredMethodMeter = forExceptionMeteredMethod(metricRegistry, TestBean.class, "exceptionMeteredMethod"); assertNotNull(exceptionMeteredMethodMeter); assertThat(exceptionMeteredMethodMeter.getCount(), is(0L)); try { testBean.exceptionMeteredMethod(); } catch (Throwable t) { } assertThat(exceptionMeteredMethodMeter.getCount(), is(1L)); } finally { if (applicationContext != null) { applicationContext.close(); } } }
From source file:org.jasypt.spring31.annotation.EncryptablePropertySourcePostProcessorTest.java
@Test public void withUnresolvablePlaceholderAndDefault() { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(ConfigWithUnresolvablePlaceholderAndDefault.class); ctx.refresh();// w w w. j a v a 2 s.co m assertThat(ctx.getBean(TestBean.class).getName(), equalTo("p1TestBean")); ctx.close(); }
From source file:com.visural.domo.spring.TransactionImplTest.java
private AnnotationConfigApplicationContext springBootstrap(ConnectionSource source) throws BeansException, IllegalStateException { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); context.register(AnnotationAwareAspectJAutoProxyCreator.class); CustomScopeConfigurer conf = new CustomScopeConfigurer(); Map<String, Object> scopes = new HashMap<String, Object>(); TransactionScope scope = new TransactionScope(); scopes.put(TransactionScope.Name, scope); conf.setScopes(scopes);//ww w . j a va 2s . c o m context.getBeanFactory().registerSingleton("transactionScope", scope); context.addBeanFactoryPostProcessor(conf); context.scan("com.visural"); context.refresh(); context.getBean(TransactionConfig.class).getConnectionProvider().registerDefaultConnectionSource(source); return context; }
From source file:org.jasypt.spring31.annotation.EncryptablePropertySourcePostProcessorTest.java
@Test public void withResolvablePlaceholder() { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(ConfigWithResolvablePlaceholder.class); System.setProperty("path.to.properties", "org/jasypt/spring31/annotation"); ctx.refresh();/*from w ww .j a v a2 s . c om*/ assertThat(ctx.getBean(TestBean.class).getName(), equalTo("p1TestBean")); System.clearProperty("path.to.properties"); ctx.close(); }