Example usage for org.springframework.context ApplicationContext getBeanNamesForType

List of usage examples for org.springframework.context ApplicationContext getBeanNamesForType

Introduction

In this page you can find the example usage for org.springframework.context ApplicationContext getBeanNamesForType.

Prototype

String[] getBeanNamesForType(ResolvableType type);

Source Link

Document

Return the names of beans matching the given type (including subclasses), judging from either bean definitions or the value of getObjectType in the case of FactoryBeans.

Usage

From source file:edu.internet2.middleware.psp.Psp.java

/**
 * {@inheritDoc}/*from  w  w  w.  j av  a  2 s.c  o  m*/
 * 
 * Initialize the "objects" map whose keys are target ids and values are {@link Pso}s. Initialize the "targets" map
 * whose keys are target ids and values are {@link SpmlTarget}s.
 */
protected void onNewContextCreated(ApplicationContext newServiceContext) throws ServiceException {

    Map<String, List<Pso>> oldPsoDefinitions = objects;
    Map<String, SpmlTarget> oldTargets = targets;

    try {
        String[] psoBeanNames = newServiceContext.getBeanNamesForType(Pso.class);
        LOG.debug("PSP '{}' - Loading {} PSO definitions", getId(), Arrays.asList(psoBeanNames));
        objects = new LinkedHashMap<String, List<Pso>>(psoBeanNames.length);
        for (String beanName : psoBeanNames) {
            Pso psoDefinition = (Pso) newServiceContext.getBean(beanName);
            String targetId = psoDefinition.getPsoIdentifier().getTargetId();
            if (!objects.containsKey(targetId)) {
                objects.put(targetId, new ArrayList<Pso>());
            }
            objects.get(targetId).add(psoDefinition);
        }
        targets = new LinkedHashMap<String, SpmlTarget>(objects.keySet().size());
        for (String targetId : objects.keySet()) {
            Object target = newServiceContext.getBean(targetId, SpmlTarget.class);
            ((SpmlTarget) target).setPSP(this);
            targets.put(targetId, (SpmlTarget) target);
        }
    } catch (Exception e) {
        objects = oldPsoDefinitions;
        targets = oldTargets;
        LOG.error("PSP '" + getId() + "' - Configuration is not valid, retaining old configuration", e);
        throw new ServiceException(
                "PSP '" + getId() + "' - Configuration is not valid, retaining old configuration", e);
    }
}

From source file:io.s4.MainApp.java

public static void main(String args[]) throws Exception {
    Options options = new Options();

    options.addOption(OptionBuilder.withArgName("corehome").hasArg().withDescription("core home").create("c"));

    options.addOption(/*from   w  ww  .jav a2s.  c o m*/
            OptionBuilder.withArgName("appshome").hasArg().withDescription("applications home").create("a"));

    options.addOption(OptionBuilder.withArgName("s4clock").hasArg().withDescription("s4 clock").create("d"));

    options.addOption(OptionBuilder.withArgName("seedtime").hasArg()
            .withDescription("event clock initialization time").create("s"));

    options.addOption(
            OptionBuilder.withArgName("extshome").hasArg().withDescription("extensions home").create("e"));

    options.addOption(
            OptionBuilder.withArgName("instanceid").hasArg().withDescription("instance id").create("i"));

    options.addOption(
            OptionBuilder.withArgName("configtype").hasArg().withDescription("configuration type").create("t"));

    CommandLineParser parser = new GnuParser();
    CommandLine commandLine = null;
    String clockType = "wall";

    try {
        commandLine = parser.parse(options, args);
    } catch (ParseException pe) {
        System.err.println(pe.getLocalizedMessage());
        System.exit(1);
    }

    int instanceId = -1;
    if (commandLine.hasOption("i")) {
        String instanceIdStr = commandLine.getOptionValue("i");
        try {
            instanceId = Integer.parseInt(instanceIdStr);
        } catch (NumberFormatException nfe) {
            System.err.println("Bad instance id: %s" + instanceIdStr);
            System.exit(1);
        }
    }

    if (commandLine.hasOption("c")) {
        coreHome = commandLine.getOptionValue("c");
    }

    if (commandLine.hasOption("a")) {
        appsHome = commandLine.getOptionValue("a");
    }

    if (commandLine.hasOption("d")) {
        clockType = commandLine.getOptionValue("d");
    }

    if (commandLine.hasOption("e")) {
        extsHome = commandLine.getOptionValue("e");
    }

    String configType = "typical";
    if (commandLine.hasOption("t")) {
        configType = commandLine.getOptionValue("t");
    }

    long seedTime = 0;
    if (commandLine.hasOption("s")) {
        seedTime = Long.parseLong(commandLine.getOptionValue("s"));
    }

    File coreHomeFile = new File(coreHome);
    if (!coreHomeFile.isDirectory()) {
        System.err.println("Bad core home: " + coreHome);
        System.exit(1);
    }

    File appsHomeFile = new File(appsHome);
    if (!appsHomeFile.isDirectory()) {
        System.err.println("Bad applications home: " + appsHome);
        System.exit(1);
    }

    if (instanceId > -1) {
        System.setProperty("instanceId", "" + instanceId);
    } else {
        System.setProperty("instanceId", "" + S4Util.getPID());
    }

    List loArgs = commandLine.getArgList();

    if (loArgs.size() < 1) {
        // System.err.println("No bean configuration file specified");
        // System.exit(1);
    }

    // String s4ConfigXml = (String) loArgs.get(0);
    // System.out.println("s4ConfigXml is " + s4ConfigXml);

    ClassPathResource propResource = new ClassPathResource("s4-core.properties");
    Properties prop = new Properties();
    if (propResource.exists()) {
        prop.load(propResource.getInputStream());
    } else {
        System.err.println("Unable to find s4-core.properties. It must be available in classpath");
        System.exit(1);
    }

    ApplicationContext coreContext = null;
    String configBase = coreHome + File.separatorChar + "conf" + File.separatorChar + configType;
    String configPath = "";
    List<String> coreConfigUrls = new ArrayList<String>();
    File configFile = null;

    // load clock configuration
    configPath = configBase + File.separatorChar + clockType + "-clock.xml";
    coreConfigUrls.add(configPath);

    // load core config xml
    configPath = configBase + File.separatorChar + "s4-core-conf.xml";
    configFile = new File(configPath);
    if (!configFile.exists()) {
        System.err.printf("S4 core config file %s does not exist\n", configPath);
        System.exit(1);
    }

    coreConfigUrls.add(configPath);
    String[] coreConfigFiles = new String[coreConfigUrls.size()];
    coreConfigUrls.toArray(coreConfigFiles);

    String[] coreConfigFileUrls = new String[coreConfigFiles.length];
    for (int i = 0; i < coreConfigFiles.length; i++) {
        coreConfigFileUrls[i] = "file:" + coreConfigFiles[i];
    }

    coreContext = new FileSystemXmlApplicationContext(coreConfigFileUrls, coreContext);
    ApplicationContext context = coreContext;

    Clock s4Clock = (Clock) context.getBean("clock");
    if (s4Clock instanceof EventClock && seedTime > 0) {
        EventClock s4EventClock = (EventClock) s4Clock;
        s4EventClock.updateTime(seedTime);
        System.out.println("Intializing event clock time with seed time " + s4EventClock.getCurrentTime());
    }

    PEContainer peContainer = (PEContainer) context.getBean("peContainer");

    Watcher w = (Watcher) context.getBean("watcher");
    w.setConfigFilename(configPath);

    // load extension modules
    String[] configFileNames = getModuleConfigFiles(extsHome, prop);
    if (configFileNames.length > 0) {
        String[] configFileUrls = new String[configFileNames.length];
        for (int i = 0; i < configFileNames.length; i++) {
            configFileUrls[i] = "file:" + configFileNames[i];
        }
        context = new FileSystemXmlApplicationContext(configFileUrls, context);
    }

    // load application modules
    configFileNames = getModuleConfigFiles(appsHome, prop);
    if (configFileNames.length > 0) {
        String[] configFileUrls = new String[configFileNames.length];
        for (int i = 0; i < configFileNames.length; i++) {
            configFileUrls[i] = "file:" + configFileNames[i];
        }
        context = new FileSystemXmlApplicationContext(configFileUrls, context);
        // attach any beans that implement ProcessingElement to the PE
        // Container
        String[] processingElementBeanNames = context.getBeanNamesForType(ProcessingElement.class);
        for (String processingElementBeanName : processingElementBeanNames) {
            Object bean = context.getBean(processingElementBeanName);
            try {
                Method getS4ClockMethod = bean.getClass().getMethod("getS4Clock");

                if (getS4ClockMethod.getReturnType().equals(Clock.class)) {
                    if (getS4ClockMethod.invoke(bean) == null) {
                        Method setS4ClockMethod = bean.getClass().getMethod("setS4Clock", Clock.class);
                        setS4ClockMethod.invoke(bean, coreContext.getBean("clock"));
                    }
                }
            } catch (NoSuchMethodException mnfe) {
                // acceptable
            }
            System.out.println("Adding processing element with bean name " + processingElementBeanName + ", id "
                    + ((ProcessingElement) bean).getId());
            peContainer.addProcessor((ProcessingElement) bean, processingElementBeanName);
        }
    }
}

From source file:org.agnitas.web.EmmActionAction.java

/**
 * Gets action operations.//  ww w .  j  av a  2s. co m
 */
protected Map getActionOperations(HttpServletRequest req) {
    String name = null;
    String key = null;
    TreeMap ops = new TreeMap();
    ApplicationContext con = getWebApplicationContext();
    String[] names = con.getBeanNamesForType(org.agnitas.actions.ActionOperation.class);

    for (int i = 0; i < names.length; i++) {
        name = names[i];
        if (allowed(new String("action.op." + name), req)) {
            key = this.getMessage(new String("action.op." + name), req);
            ops.put(key, name);
        }
    }
    return ops;
}

From source file:org.apache.camel.spring.SpringCamelContext.java

public static SpringCamelContext springCamelContext(ApplicationContext applicationContext) throws Exception {
    // lets try and look up a configured camel context in the context
    String[] names = applicationContext.getBeanNamesForType(SpringCamelContext.class);
    if (names.length == 1) {
        return (SpringCamelContext) applicationContext.getBean(names[0], SpringCamelContext.class);
    }// ww  w .ja  v a  2 s . co  m
    SpringCamelContext answer = new SpringCamelContext();
    answer.setApplicationContext(applicationContext);
    answer.afterPropertiesSet();
    return answer;
}

From source file:org.codehaus.groovy.grails.web.util.WebUtils.java

public static ViewResolver lookupViewResolver(ApplicationContext wac) {
    if (wac.containsBean("jspViewResolver")) {
        return wac.getBean("jspViewResolver", ViewResolver.class);
    }/*from www.j  av a  2 s. c o  m*/
    String[] beanNames = wac.getBeanNamesForType(ViewResolver.class);
    if (beanNames.length > 0) {
        String beanName = beanNames[0];
        return wac.getBean(beanName, ViewResolver.class);
    }
    return null;
}

From source file:org.geoserver.gwc.GWCTest.java

@Before
public void setUp() throws Exception {

    System.setProperty("ALLOW_ENV_PARAMETRIZATION", "true");
    System.setProperty("TEST_ENV_PROPERTY", "H2");

    catalog = mock(Catalog.class);
    layer = mockLayer("testLayer", new String[] { "style1", "style2" }, PublishedType.RASTER);
    layerGroup = mockGroup("testGroup", layer);
    mockCatalog();//from   w ww .j  a v a 2 s .  com

    defaults = GWCConfig.getOldDefaults();

    gwcConfigPersister = mock(GWCConfigPersister.class);
    when(gwcConfigPersister.getConfig()).thenReturn(defaults);

    storageBroker = mock(StorageBroker.class);
    gridSetBroker = new GridSetBroker(true, true);

    tileLayerInfo = TileLayerInfoUtil.loadOrCreate(layer, defaults);
    tileLayerGroupInfo = TileLayerInfoUtil.loadOrCreate(layerGroup, defaults);

    tileLayer = new GeoServerTileLayer(layer, gridSetBroker, tileLayerInfo);
    tileLayerGroup = new GeoServerTileLayer(layerGroup, gridSetBroker, tileLayerGroupInfo);

    tld = mock(TileLayerDispatcher.class);
    mockTileLayerDispatcher();

    config = mock(Configuration.class);
    tileBreeder = mock(TileBreeder.class);
    quotaStore = mock(QuotaStore.class);
    diskQuotaMonitor = mock(DiskQuotaMonitor.class);
    when(diskQuotaMonitor.getQuotaStore()).thenReturn(quotaStore);
    owsDispatcher = mock(Dispatcher.class);
    diskQuotaStoreProvider = mock(ConfigurableQuotaStoreProvider.class);
    when(diskQuotaMonitor.getQuotaStoreProvider()).thenReturn(diskQuotaStoreProvider);

    storageFinder = mock(DefaultStorageFinder.class);
    jdbcStorage = createMock(JDBCConfigurationStorage.class);
    xmlConfig = mock(XMLConfiguration.class);

    GeoWebCacheEnvironment genv = createMockBuilder(GeoWebCacheEnvironment.class).withConstructor()
            .createMock();

    ApplicationContext appContext = createMock(ApplicationContext.class);

    expect(appContext.getBeanNamesForType(GeoWebCacheEnvironment.class))
            .andReturn(new String[] { "geoWebCacheEnvironment" }).anyTimes();
    Map<String, GeoWebCacheEnvironment> genvMap = new HashMap<>();
    genvMap.put("geoWebCacheEnvironment", genv);
    expect(appContext.getBeansOfType(GeoWebCacheEnvironment.class)).andReturn(genvMap).anyTimes();
    expect(appContext.getBean("geoWebCacheEnvironment")).andReturn(genv).anyTimes();

    expect(appContext.getBeanNamesForType(XMLConfiguration.class))
            .andReturn(new String[] { "geoWebCacheXMLConfiguration" }).anyTimes();
    Map<String, XMLConfiguration> xmlConfMap = new HashMap();
    xmlConfMap.put("geoWebCacheXMLConfiguration", xmlConfig);
    expect(appContext.getBeansOfType(XMLConfiguration.class)).andReturn(xmlConfMap).anyTimes();
    expect(appContext.getBean("geoWebCacheXMLConfiguration")).andReturn(xmlConfig).anyTimes();

    replay(appContext);

    GeoWebCacheExtensions gse = createMockBuilder(GeoWebCacheExtensions.class).createMock();
    gse.setApplicationContext(appContext);

    replay(gse);

    List<GeoWebCacheEnvironment> extensions = GeoWebCacheExtensions.extensions(GeoWebCacheEnvironment.class);
    assertNotNull(extensions);
    assertEquals(1, extensions.size());
    assertTrue(extensions.contains(genv));

    JDBCConfiguration jdbcConfiguration = new JDBCConfiguration();
    if (GeoWebCacheEnvironment.ALLOW_ENV_PARAMETRIZATION) {
        jdbcConfiguration.setDialect("${TEST_ENV_PROPERTY}");
    } else {
        jdbcConfiguration.setDialect("H2");
    }
    File jdbcConfigurationFile = File.createTempFile("jdbcConfigurationFile", ".tmp", tmpDir().dir());
    jdbcConfiguration.store(jdbcConfiguration, jdbcConfigurationFile);

    JDBCConfiguration loadedConf = jdbcConfiguration.load(jdbcConfigurationFile);
    jdbcStorage.setApplicationContext(appContext);

    expect(jdbcStorage.getJDBCDiskQuotaConfig()).andReturn(loadedConf).anyTimes();

    replay(jdbcStorage);

    mediator = new GWC(gwcConfigPersister, storageBroker, tld, gridSetBroker, tileBreeder, diskQuotaMonitor,
            owsDispatcher, catalog, catalog, storageFinder, jdbcStorage);
    mediator.setApplicationContext(appContext);

    mediator = spy(mediator);
    when(mediator.getXmlConfiguration()).thenReturn(xmlConfig);

    GWC.set(mediator);
}

From source file:org.sipfoundry.sipxconfig.common.SpringHibernateInstantiatorTestIntegration.java

protected void init() throws Exception {
    ApplicationContext m_applicationContext = getApplicationContext();
    m_instantiator = new SpringHibernateInstantiator();
    m_instantiator.setBeanFactory(m_applicationContext);
    // to make sure that test are valid
    assertTrue(m_applicationContext.getBeanNamesForType(Gateway.class).length > 1);
}

From source file:org.springframework.cloud.gateway.filter.ratelimit.RedisRateLimiter.java

@Override
@SuppressWarnings("unchecked")
public void setApplicationContext(ApplicationContext context) throws BeansException {
    if (initialized.compareAndSet(false, true)) {
        this.redisTemplate = context.getBean("stringReactiveRedisTemplate", ReactiveRedisTemplate.class);
        this.script = context.getBean(REDIS_SCRIPT_NAME, RedisScript.class);
        if (context.getBeanNamesForType(Validator.class).length > 0) {
            this.setValidator(context.getBean(Validator.class));
        }/*from ww  w .  j av a  2  s  .  c  o  m*/
    }
}

From source file:org.springframework.data.mongodb.core.MongoTemplate.java

public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    String[] beans = applicationContext.getBeanNamesForType(MongoPersistentEntityIndexCreator.class);
    if ((null == beans || beans.length == 0) && applicationContext instanceof ConfigurableApplicationContext) {
        ((ConfigurableApplicationContext) applicationContext).addApplicationListener(indexCreator);
    }//from   w  ww . j a  va  2 s. c o m
    eventPublisher = applicationContext;
    if (mappingContext instanceof ApplicationEventPublisherAware) {
        ((ApplicationEventPublisherAware) mappingContext).setApplicationEventPublisher(eventPublisher);
    }
    resourceLoader = applicationContext;
}

From source file:org.springframework.integration.config.IdGeneratorConfigurer.java

public synchronized void onApplicationEvent(ApplicationContextEvent event) {
    ApplicationContext context = event.getApplicationContext();
    if (event instanceof ContextRefreshedEvent) {
        boolean contextHasIdGenerator = context.getBeanNamesForType(IdGenerator.class).length > 0;
        if (contextHasIdGenerator) {
            if (this.setIdGenerator(context)) {
                IdGeneratorConfigurer.generatorContextId.add(context.getId());
            }// ww  w .  j  av  a 2s .  com
        }
    } else if (event instanceof ContextClosedEvent) {
        if (IdGeneratorConfigurer.generatorContextId.contains(context.getId())) {
            if (IdGeneratorConfigurer.generatorContextId.size() == 1) {
                this.unsetIdGenerator();
            }
            IdGeneratorConfigurer.generatorContextId.remove(context.getId());
        }
    }
}