@Test public void testFactoryBeanAndApplicationListener() { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(CONTEXT_WILDCARD); ctx.getBeanFactory().registerSingleton("manualFBAAL", new FactoryBeanAndApplicationListener()); assertEquals(2, ctx.getBeansOfType(ApplicationListener.class).size()); ctx.close(); }
@Test public void staticScriptImplementingInterface() { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("bshContext.xml", getClass()); assertTrue(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("messengerImpl")); Messenger messenger = (Messenger) ctx.getBean("messengerImpl"); String desiredMessage = "Hello World!"; assertEquals("Message is incorrect", desiredMessage, messenger.getMessage()); assertTrue(ctx.getBeansOfType(Messenger.class).values().contains(messenger)); ctx.close(); assertNull(messenger.getMessage()); }
@Test public void staticWithScriptReturningInstance() { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("bshContext.xml", getClass()); assertTrue(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("messengerInstance")); Messenger messenger = (Messenger) ctx.getBean("messengerInstance"); String desiredMessage = "Hello World!"; assertEquals("Message is incorrect", desiredMessage, messenger.getMessage()); assertTrue(ctx.getBeansOfType(Messenger.class).values().contains(messenger)); ctx.close(); assertNull(messenger.getMessage()); }
@Test public void staticScriptWithTwoInterfacesSpecified() { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("bshContext.xml", getClass()); assertTrue(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("messengerWithConfigExtra")); ConfigurableMessenger messenger = (ConfigurableMessenger) ctx.getBean("messengerWithConfigExtra"); messenger.setMessage(null); assertNull(messenger.getMessage()); assertTrue(ctx.getBeansOfType(Messenger.class).values().contains(messenger)); ctx.close(); assertNull(messenger.getMessage()); }
private void assertOneMessageSourceOnly(ClassPathXmlApplicationContext ctx, Object myMessageSource) { String[] beanNamesForType = ctx.getBeanNamesForType(StaticMessageSource.class); assertEquals(1, beanNamesForType.length); assertEquals("myMessageSource", beanNamesForType[0]); beanNamesForType = ctx.getBeanNamesForType(StaticMessageSource.class, true, true); assertEquals(1, beanNamesForType.length); assertEquals("myMessageSource", beanNamesForType[0]); beanNamesForType = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(ctx, StaticMessageSource.class); assertEquals(1, beanNamesForType.length); assertEquals("myMessageSource", beanNamesForType[0]); beanNamesForType = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(ctx, StaticMessageSource.class, true, true); assertEquals(1, beanNamesForType.length); assertEquals("myMessageSource", beanNamesForType[0]); Map<?, StaticMessageSource> beansOfType = ctx.getBeansOfType(StaticMessageSource.class); assertEquals(1, beansOfType.size()); assertSame(myMessageSource, beansOfType.values().iterator().next()); beansOfType = ctx.getBeansOfType(StaticMessageSource.class, true, true); assertEquals(1, beansOfType.size()); assertSame(myMessageSource, beansOfType.values().iterator().next()); beansOfType = BeanFactoryUtils.beansOfTypeIncludingAncestors(ctx, StaticMessageSource.class); assertEquals(1, beansOfType.size()); assertSame(myMessageSource, beansOfType.values().iterator().next()); beansOfType = BeanFactoryUtils.beansOfTypeIncludingAncestors(ctx, StaticMessageSource.class, true, true); assertEquals(1, beansOfType.size()); assertSame(myMessageSource, beansOfType.values().iterator().next()); }
@Test public void resourceScriptFromTag() { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("bsh-with-xsd.xml", getClass()); TestBean testBean = (TestBean) ctx.getBean("testBean"); Collection<String> beanNames = Arrays.asList(ctx.getBeanNamesForType(Messenger.class)); assertTrue(beanNames.contains("messenger")); assertTrue(beanNames.contains("messengerImpl")); assertTrue(beanNames.contains("messengerInstance")); Messenger messenger = (Messenger) ctx.getBean("messenger"); assertEquals("Hello World!", messenger.getMessage()); assertFalse(messenger instanceof Refreshable); Messenger messengerImpl = (Messenger) ctx.getBean("messengerImpl"); assertEquals("Hello World!", messengerImpl.getMessage()); Messenger messengerInstance = (Messenger) ctx.getBean("messengerInstance"); assertEquals("Hello World!", messengerInstance.getMessage()); TestBeanAwareMessenger messengerByType = (TestBeanAwareMessenger) ctx.getBean("messengerByType"); assertEquals(testBean, messengerByType.getTestBean()); TestBeanAwareMessenger messengerByName = (TestBeanAwareMessenger) ctx.getBean("messengerByName"); assertEquals(testBean, messengerByName.getTestBean()); Collection<Messenger> beans = ctx.getBeansOfType(Messenger.class).values(); assertTrue(beans.contains(messenger)); assertTrue(beans.contains(messengerImpl)); assertTrue(beans.contains(messengerInstance)); assertTrue(beans.contains(messengerByType)); assertTrue(beans.contains(messengerByName)); ctx.close(); assertNull(messenger.getMessage()); assertNull(messengerImpl.getMessage()); assertNull(messengerInstance.getMessage()); }
@Override public void run() { System.out.println("Tools supported by this build of bakemono:"); System.out.println(); for(Map.Entry<String,Tool> i:context.getBeansOfType(Tool.class).entrySet()) { System.out.println(" "+i.getKey()); } }
@SuppressWarnings( "unchecked" ) private Map<String, KnownRepositoryContentConsumer> getConsumers() { Map<String, KnownRepositoryContentConsumer> beans = applicationContext.getBeansOfType( KnownRepositoryContentConsumer.class ); // we use a naming conventions knownRepositoryContentConsumer#hint // with plexus we used only hint so remove before# Map<String, KnownRepositoryContentConsumer> smallNames = new HashMap<>( beans.size() ); for ( Map.Entry<String, KnownRepositoryContentConsumer> entry : beans.entrySet() ) { smallNames.put( StringUtils.substringAfterLast( entry.getKey(), "#" ), entry.getValue() ); } return smallNames; }
@SuppressWarnings("unchecked") public <T> List<T> getServicesByType(Class<T> type) { ArrayList<T> l = new ArrayList<T>(); Map<String, T> beans; try { beans = applicationContext.getBeansOfType(type, true, true); l.addAll( (Collection<? extends T>) beans.values() ); } catch (BeansException e) { throw new RuntimeException("Failed to get beans of type ("+type+"): " + e.getMessage(), e); } return l; }
@SuppressWarnings("unchecked") @Override public <T> List<T> getServicesByType(Class<T> type) { ArrayList<T> l = new ArrayList<T>(); Map<String, T> beans; try { beans = applicationContext.getBeansOfType(type, true, true); l.addAll((Collection<? extends T>) beans.values()); } catch (BeansException e) { throw new RuntimeException("Failed to get beans of type (" + type + "): " + e.getMessage(), e); } return l; }
@SuppressWarnings("unchecked") @Override public <T> List<T> getServicesByType(Class<T> type) { ArrayList<T> l = new ArrayList<T>(); Map<String, T> beans; try { beans = applicationContext.getBeansOfType(type, true, true); l.addAll( (Collection<? extends T>) beans.values() ); } catch (BeansException e) { throw new RuntimeException("Failed to get beans of type ("+type+"): " + e.getMessage(), e); } return l; }
@Override public <T> Map<String, T> getObjectsByType(Class<T> type) { if (isSpringInternalType(type)) { return emptyMap(); } Map<String, T> beans = applicationContext.getBeansOfType(type); return beans.entrySet().stream().filter(entry -> applicationContext.getBeanFactory().containsBeanDefinition(entry.getKey())) .collect(toMap(Map.Entry::getKey, Map.Entry::getValue)); }
public static <A extends RpcAction> Map<String, RpcService<A>> loadServices(ClassPathXmlApplicationContext ctx, Class<A> actionClass) { Map<String, RpcService<A>> services = new LinkedHashMap<String, RpcService<A>>(); Map<String, A> actions = ctx.getBeansOfType(actionClass); for (Map.Entry<String, A> entry : actions.entrySet()) { String id = entry.getKey(); A action = entry.getValue(); if (action.getDescription() == null) { LOGGER.warning("Service '" + id + "' is not documented. For maintainability reasons, document action class with @Description or set 'description' property in 'brutusin-rpc.xml'"); } RpcService<A> service = new RpcService<A>(id, action); services.put(id, service); } return services; }
@Override protected Map<String, JsonAction> loadActions() throws Exception { String springConfigFile = getServletConfig().getInitParameter(INIT_PARAM_SPRING_CFG_FILE); if (springConfigFile == null) { applicationContext = new ClassPathXmlApplicationContext(DEFAULT_CFG_FILE); } else { applicationContext = new ClassPathXmlApplicationContext(springConfigFile, DEFAULT_CFG_FILE); } applicationContext.setClassLoader(getClassLoader()); return applicationContext.getBeansOfType(JsonAction.class); }
@Override public void start() { if (SoaSystemEnvProperties.SOA_TRANSACTIONAL_ENABLE) { String configPath = System.getProperty(SpringContainer.SPRING_CONFIG); if (configPath == null || configPath.length() <= 0) { configPath = SpringContainer.DEFAULT_SPRING_CONFIG; } try { List<String> xmlPaths = new ArrayList<>(); Enumeration<URL> resources = TransactionContainer.class.getClassLoader().getResources(configPath); while (resources.hasMoreElements()) { URL nextElement = resources.nextElement(); if(nextElement.toString().matches(".*isuwang-soa-transaction.*")) xmlPaths.add(nextElement.toString()); } context = new ClassPathXmlApplicationContext(xmlPaths.toArray(new String[0])); context.start(); GlobalTransactionFactory.setGlobalTransactionService(context.getBeansOfType(GlobalTransactionService.class).values().iterator().next()); GlobalTransactionFactory.setGlobalTransactionProcessService(context.getBeansOfType(GlobalTransactionProcessService.class).values().iterator().next()); } catch (Exception e) { LOGGER.error(e.getMessage(), e); } } }
@SuppressWarnings("unchecked") private void init(String metadataContext, DictionaryService...dictionaryServices){ if (metadataContext != null){ String[] locations = StringUtils.tokenizeToStringArray(metadataContext, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS); ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(locations); Map<String, DataObjectStructure> beansOfType = (Map<String, DataObjectStructure>) context.getBeansOfType(DataObjectStructure.class); metadataRepository = new HashMap<String, Object>(); for (DataObjectStructure dataObjStr : beansOfType.values()){ metadataRepository.put(dataObjStr.getName(), getProperties(dataObjStr, new RecursionCounter())); } } if (dictionaryServices != null){ this.dictionaryServiceMap = new HashMap<String, DictionaryService>(); for (DictionaryService d:dictionaryServices){ List<String> objectTypes = d.getObjectTypes(); for(String objectType:objectTypes){ dictionaryServiceMap.put(objectType, d); } } } }
private RpcContext() { if (testMode) { this.applicationContext = new ClassPathXmlApplicationContext(SpringNames.CFG_CORE_FILE); } else { this.applicationContext = new ClassPathXmlApplicationContext(SpringNames.CFG_CORE_FILE, SpringNames.CFG_FILE); } this.applicationContext.setClassLoader(Thread.currentThread().getContextClassLoader()); loadBuiltServices(applicationContext); this.httpServices = ServiceLoader.loadServices(this.applicationContext, HttpAction.class); this.webSocketServices = ServiceLoader.loadServices(this.applicationContext, WebsocketAction.class); this.webSocketTopics = applicationContext.getBeansOfType(Topic.class); validateTopics(webSocketTopics); }
/** * Parse Spring context. */ @SuppressWarnings("unchecked") public void parseSpringContext(String fileName) { try { logInfo("Loading configurations from classpath file [" + fileName + "]"); ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(fileName); this.envs = ctx.getBeansOfType(FF4j.class); if (ctx.containsBean("AUTHORIZED_USERS")) { this.users = (Map<String, String>) ctx.getBean("AUTHORIZED_USERS"); } ctx.close(); } catch (RuntimeException fne) { error(fne, "Cannot parse Spring context"); } }
private void loadExtension(String extConfigLocation, int extNumber) throws Exception { LOG.debug("new extension context for '" + extConfigLocation + "' started ..."); ClassPathXmlApplicationContext extContext = new ClassPathXmlApplicationContext(parentContext); extContext.setId("OpenHub extension nr. " + extNumber); extContext.setDisplayName("OpenHub extension context for '" + extConfigLocation + '"'); extContext.setConfigLocation(extConfigLocation); extContext.refresh(); // add routes into Camel context if (isAutoRouteAdding()) { Map<String, AbstractExtRoute> beansOfType = extContext.getBeansOfType(AbstractExtRoute.class); for (Map.Entry<String, AbstractExtRoute> entry : beansOfType.entrySet()) { AbstractExtRoute route = entry.getValue(); // note: route with existing route ID will override the previous one // it's not possible automatically change route ID before adding to Camel context camelContext.addRoutes(route); } } LOG.debug("new extension context for '" + extConfigLocation + "' was successfully created"); }
@Test public void testMetricCollector() throws Exception { Map<String, SystemInfoCollector> collectors = context.getBeansOfType(SystemInfoCollector.class); assertEquals(1, collectors.size()); SystemInfoCollector systemInfoCollector = collectors.values().iterator().next(); // SystemInfoCollector systemInfoCollector = context.getBean(SystemInfoCollector.class); Metrics collected = systemInfoCollector.retrieveAllSystemInfo(); List<MetricValue> metrics = collected.getMetrics(); for (MetricValue m : metrics) { if (m.getAvailable()) { System.out.println( m.getName() + " IS available -> " + m.getValue() + " " + m.getUnit()); } else { System.err.println(m.getName() + " IS NOT available"); } collector.checkThat( "Metric for " + m.getName() + " available but value is not retrived", (m.getAvailable() && !m.getValue().equals(BaseSystemInfoCollector.DEFAULT_VALUE) || (!m.getAvailable() && m.getValue().equals(BaseSystemInfoCollector.DEFAULT_VALUE))), equalTo(true)); } } }