Example usage for org.springframework.context ApplicationContext getBeansOfType

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

Introduction

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

Prototype

<T> Map<String, T> getBeansOfType(@Nullable Class<T> type) throws BeansException;

Source Link

Document

Return the bean instances that match the given object type (including subclasses), judging from either bean definitions or the value of getObjectType in the case of FactoryBeans.

Usage

From source file:org.apache.ignite.internal.util.spring.IgniteSpringHelperImpl.java

/** {@inheritDoc} */
@Override/*w  ww  . j a  v  a  2s .c  om*/
public <T> IgniteBiTuple<Collection<T>, ? extends GridSpringResourceContext> loadConfigurations(URL cfgUrl,
        Class<T> cls, String... excludedProps) throws IgniteCheckedException {
    ApplicationContext springCtx = applicationContext(cfgUrl, excludedProps);
    Map<String, T> cfgMap;

    try {
        cfgMap = springCtx.getBeansOfType(cls);
    } catch (BeansException e) {
        throw new IgniteCheckedException(
                "Failed to instantiate bean [type=" + cls + ", err=" + e.getMessage() + ']', e);
    }

    if (cfgMap == null || cfgMap.isEmpty())
        throw new IgniteCheckedException("Failed to find configuration in: " + cfgUrl);

    return F.t(cfgMap.values(), new GridSpringResourceContextImpl(springCtx));
}

From source file:org.apache.ignite.internal.util.spring.IgniteSpringHelperImpl.java

/** {@inheritDoc} */
@Override/*from w ww .  ja  va  2s.  c om*/
public <T> IgniteBiTuple<Collection<T>, ? extends GridSpringResourceContext> loadConfigurations(
        InputStream cfgStream, Class<T> cls, String... excludedProps) throws IgniteCheckedException {
    ApplicationContext springCtx = applicationContext(cfgStream, excludedProps);
    Map<String, T> cfgMap;

    try {
        cfgMap = springCtx.getBeansOfType(cls);
    } catch (BeansException e) {
        throw new IgniteCheckedException(
                "Failed to instantiate bean [type=" + cls + ", err=" + e.getMessage() + ']', e);
    }

    if (cfgMap == null || cfgMap.isEmpty())
        throw new IgniteCheckedException("Failed to find configuration in: " + cfgStream);

    return F.t(cfgMap.values(), new GridSpringResourceContextImpl(springCtx));
}

From source file:org.apache.ignite.startup.GridRandomCommandLineLoader.java

/**
 * Initializes configurations./*from w  ww.  ja  v a 2s .c  o  m*/
 *
 * @param springCfgPath Configuration file path.
 * @param logCfgPath Log file name.
 * @return List of configurations.
 * @throws IgniteCheckedException If an error occurs.
 */
@SuppressWarnings("unchecked")
private static IgniteConfiguration getConfiguration(String springCfgPath, @Nullable String logCfgPath)
        throws IgniteCheckedException {
    assert springCfgPath != null;

    File path = GridTestUtils.resolveIgnitePath(springCfgPath);

    if (path == null)
        throw new IgniteCheckedException("Spring XML configuration file path is invalid: "
                + new File(springCfgPath)
                + ". Note that this path should be either absolute path or a relative path to IGNITE_HOME.");

    if (!path.isFile())
        throw new IgniteCheckedException("Provided file path is not a file: " + path);

    // Add no-op logger to remove no-appender warning.
    Appender app = new NullAppender();

    Logger.getRootLogger().addAppender(app);

    ApplicationContext springCtx;

    try {
        springCtx = new FileSystemXmlApplicationContext(path.toURI().toURL().toString());
    } catch (BeansException | MalformedURLException e) {
        throw new IgniteCheckedException(
                "Failed to instantiate Spring XML application context: " + e.getMessage(), e);
    }

    Map cfgMap;

    try {
        // Note: Spring is not generics-friendly.
        cfgMap = springCtx.getBeansOfType(IgniteConfiguration.class);
    } catch (BeansException e) {
        throw new IgniteCheckedException("Failed to instantiate bean [type=" + IgniteConfiguration.class
                + ", err=" + e.getMessage() + ']', e);
    }

    if (cfgMap == null)
        throw new IgniteCheckedException("Failed to find a single grid factory configuration in: " + path);

    // Remove previously added no-op logger.
    Logger.getRootLogger().removeAppender(app);

    if (cfgMap.size() != 1)
        throw new IgniteCheckedException(
                "Spring configuration file should contain exactly 1 grid configuration: " + path);

    IgniteConfiguration cfg = (IgniteConfiguration) F.first(cfgMap.values());

    assert cfg != null;

    if (logCfgPath != null)
        cfg.setGridLogger(new GridTestLog4jLogger(U.resolveIgniteUrl(logCfgPath)));

    return cfg;
}

From source file:org.apache.ignite.startup.GridVmNodesStarter.java

/**
 * Initializes configurations./* w w  w  .  ja v  a2 s. co  m*/
 *
 *
 * @param springCfgPath Configuration file path.
 * @return List of configurations.
 * @throws IgniteCheckedException If an error occurs.
 */
@SuppressWarnings("unchecked")
private static Iterable<IgniteConfiguration> getConfigurations(String springCfgPath)
        throws IgniteCheckedException {
    File path = GridTestUtils.resolveIgnitePath(springCfgPath);

    if (path == null)
        throw new IgniteCheckedException("Spring XML configuration file path is invalid: "
                + new File(springCfgPath)
                + ". Note that this path should be either absolute path or a relative path to IGNITE_HOME.");

    if (!path.isFile())
        throw new IgniteCheckedException("Provided file path is not a file: " + path);

    // Add no-op logger to remove no-appender warning.
    Appender app = new NullAppender();

    Logger.getRootLogger().addAppender(app);

    ApplicationContext springCtx;

    try {
        springCtx = new FileSystemXmlApplicationContext(path.toURI().toURL().toString());
    } catch (BeansException | MalformedURLException e) {
        throw new IgniteCheckedException(
                "Failed to instantiate Spring XML application context: " + e.getMessage(), e);
    }

    Map cfgMap;

    try {
        // Note: Spring is not generics-friendly.
        cfgMap = springCtx.getBeansOfType(IgniteConfiguration.class);
    } catch (BeansException e) {
        throw new IgniteCheckedException("Failed to instantiate bean [type=" + IgniteConfiguration.class
                + ", err=" + e.getMessage() + ']', e);
    }

    if (cfgMap == null)
        throw new IgniteCheckedException("Failed to find a single grid factory configuration in: " + path);

    // Remove previously added no-op logger.
    Logger.getRootLogger().removeAppender(app);

    if (cfgMap.isEmpty())
        throw new IgniteCheckedException("Can't find grid factory configuration in: " + path);

    Collection<IgniteConfiguration> res = new ArrayList<>();

    for (IgniteConfiguration cfg : (Collection<IgniteConfiguration>) cfgMap.values()) {
        res.add(cfg);

        cfg.setIgniteInstanceName(IGNITE_INSTANCE_NAME_PREF + gridCnt.incrementAndGet());
    }

    return res;
}

From source file:org.apache.oodt.config.distributed.DistributedConfigurationPublisherTest.java

@Test
public void publishConfigurationTest() throws Exception {
    // Publishing configuration through CLI and verifying whether they were stored correctly
    ConfigPublisher.main(new String[] { "-connectString", zookeeper.getConnectString(), "-config",
            CONFIG_PUBLISHER_XML, "-a", "publish" });

    ApplicationContext applicationContext = new ClassPathXmlApplicationContext(CONFIG_PUBLISHER_XML);
    Map distributedConfigurationPublishers = applicationContext
            .getBeansOfType(DistributedConfigurationPublisher.class);

    List<DistributedConfigurationPublisher> publishers = new ArrayList<>(
            distributedConfigurationPublishers.values().size());
    for (Object bean : distributedConfigurationPublishers.values()) {
        publishers.add((DistributedConfigurationPublisher) bean);
    }//from  w ww.  ja  v a 2  s.c o  m

    for (DistributedConfigurationPublisher publisher : publishers) {
        Assert.assertTrue(publisher.verifyPublishedConfiguration());

        ZNodePaths zNodePaths = publisher.getZNodePaths();

        // Checking for configuration files
        for (Map.Entry<String, String> entry : publisher.getPropertiesFiles().entrySet()) {
            String zNodePath = zNodePaths.getPropertiesZNodePath(entry.getValue());
            Assert.assertNotNull(client.checkExists().forPath(zNodePath));

            String storedContent = new String(client.getData().forPath(zNodePath));
            String fileContent = FileUtils.readFileToString(new File(entry.getKey()));
            Assert.assertEquals(fileContent, storedContent);
        }

        // Checking for configuration files
        for (Map.Entry<String, String> entry : publisher.getConfigFiles().entrySet()) {
            String zNodePath = zNodePaths.getConfigurationZNodePath(entry.getValue());
            Assert.assertNotNull(client.checkExists().forPath(zNodePath));

            String storedContent = new String(client.getData().forPath(zNodePath));
            String fileContent = FileUtils.readFileToString(new File(entry.getKey()));
            Assert.assertEquals(fileContent, storedContent);
        }
    }

    // Clearing configuration through CLI and checking whether the configuration has actually been gone
    ConfigPublisher.main(new String[] { "-connectString", zookeeper.getConnectString(), "-config",
            CONFIG_PUBLISHER_XML, "-a", "clear" });

    for (DistributedConfigurationPublisher publisher : publishers) {
        Assert.assertFalse(publisher.verifyPublishedConfiguration());

        ZNodePaths zNodePaths = publisher.getZNodePaths();

        // Checking for configuration files
        for (Map.Entry<String, String> entry : publisher.getPropertiesFiles().entrySet()) {
            String zNodePath = zNodePaths.getPropertiesZNodePath(entry.getValue());
            Assert.assertNull(client.checkExists().forPath(zNodePath));
        }

        // Checking for configuration files
        for (Map.Entry<String, String> entry : publisher.getConfigFiles().entrySet()) {
            String zNodePath = zNodePaths.getConfigurationZNodePath(entry.getValue());
            Assert.assertNull(client.checkExists().forPath(zNodePath));
        }
    }

    for (DistributedConfigurationPublisher publisher : publishers) {
        publisher.destroy();
    }
}

From source file:org.apereo.portal.ldap.LdapServices.java

/**
 * Get a {@link Map} of {@link ILdapServer} instances from the spring configuration.
 * //  ww w  .  j a  va2s  .c o  m
 * @return A {@link Map} of {@link ILdapServer} instances.
 */
@SuppressWarnings("unchecked")
public static Map<String, ILdapServer> getLdapServerMap() {
    final ApplicationContext applicationContext = PortalApplicationContextLocator.getApplicationContext();
    final Map<String, ILdapServer> ldapServers = applicationContext.getBeansOfType(ILdapServer.class);

    if (LOG.isDebugEnabled()) {
        LOG.debug("Found Map of ILdapServers=" + ldapServers + "'");
    }

    return Collections.unmodifiableMap(ldapServers);
}

From source file:org.atricore.idbus.kernel.main.mediation.camel.AbstractCamelMediator.java

public void init(IdentityMediationUnitContainer unitContainer) throws IdentityMediationException {

    CamelIdentityMediationUnitContainer container = (CamelIdentityMediationUnitContainer) unitContainer;

    logger.info("Initializing Camel Mediator " + this.getClass().getName() + " with unitContainer "
            + (unitContainer != null ? unitContainer.getClass().getName() : "null"));

    context = container.getContext();//from   ww w  .j  av a 2 s.co  m
    registry = (JndiRegistry) context.getRegistry();

    // Get the application context for this mediator
    ApplicationContext applicationContext = registry.lookup("applicationContext", ApplicationContext.class);

    // Get Kernel configuration
    Map<String, ConfigurationContext> kernelCfgCtxs = applicationContext
            .getBeansOfType(ConfigurationContext.class);
    assert !kernelCfgCtxs.isEmpty() : "No Kernel Configuration context found";
    assert kernelCfgCtxs.values().size() == 1 : "Too many Kernel Context configurations found "
            + kernelCfgCtxs.values().size();
    kernelConfigCtx = kernelCfgCtxs.values().iterator().next();

    // Get Monitoring server
    if (mServer == null) {
        logger.warn("Auto-configuring Monitoring server");
        Map<String, MonitoringServer> mServers = applicationContext.getBeansOfType(MonitoringServer.class);
        if (!mServers.isEmpty()) {
            // We found a monitoring server, but it should be only one
            assert mServers.values().size() == 1 : "Too many Monitoring Servers found "
                    + kernelCfgCtxs.values().size();
            mServer = mServers.values().iterator().next();
        }
    }

    // Get Auditing server
    if (aServer == null) {
        logger.warn("Auto-configuring Auditing server");
        Map<String, AuditingServer> aServers = applicationContext.getBeansOfType(AuditingServer.class);
        if (!aServers.isEmpty()) {
            // We found an auditing server, but it should be only one
            assert aServers.values().size() == 1 : "Too many Auditing Servers found "
                    + kernelCfgCtxs.values().size();
            aServer = aServers.values().iterator().next();
        }
    }

    logger.info("Initialized Camel Mediator " + this.getClass().getName() + " with unitContainer "
            + (unitContainer != null ? unitContainer.getClass().getName() : "null") + " for IDBus Node : "
            + getIdBusNode());

    initialized = true;

}

From source file:org.codehaus.groovy.grails.web.binding.GrailsDataBinder.java

private void bindWithRequestAndPropertyValues(ServletRequest request, MutablePropertyValues mpvs) {
    GrailsWebRequest webRequest = GrailsWebRequest.lookup((HttpServletRequest) request);
    if (webRequest != null) {
        final ApplicationContext applicationContext = webRequest.getApplicationContext();
        if (applicationContext != null) {
            ServletContext servletContext = webRequest.getServletContext();
            @SuppressWarnings("unchecked")
            Map<String, BindEventListener> bindEventListenerMap = (Map<String, BindEventListener>) servletContext
                    .getAttribute(BIND_EVENT_LISTENERS);
            if (bindEventListenerMap == null) {
                bindEventListenerMap = applicationContext.getBeansOfType(BindEventListener.class);
                if (!Environment.isDevelopmentMode()) {
                    servletContext.setAttribute(BIND_EVENT_LISTENERS, bindEventListenerMap);
                }//from   w  w  w . j  a  v  a  2  s . c  o m
            }
            for (BindEventListener bindEventListener : bindEventListenerMap.values()) {
                bindEventListener.doBind(getTarget(), mpvs, getTypeConverter());
            }
        }
    }
    preProcessMutablePropertyValues(mpvs);

    if (request instanceof MultipartHttpServletRequest) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        bindMultipart(multipartRequest.getMultiFileMap(), mpvs);
    }
    doBind(mpvs);
}

From source file:org.codehaus.groovy.grails.web.metaclass.RenderDynamicMethod.java

protected Collection<ActionResultTransformer> getActionResultTransformers(GrailsWebRequest webRequest) {
    if (actionResultTransformers == null) {

        ApplicationContext applicationContext = webRequest.getApplicationContext();
        if (applicationContext != null) {
            actionResultTransformers = applicationContext.getBeansOfType(ActionResultTransformer.class)
                    .values();/* w w  w .  j a  va  2 s.  c o m*/
        }
        if (actionResultTransformers == null) {
            actionResultTransformers = Collections.emptyList();
        }
    }

    return actionResultTransformers;
}

From source file:org.codehaus.groovy.grails.web.servlet.mvc.AbstractGrailsControllerHelper.java

public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    this.applicationContext = applicationContext;
    this.actionResultTransformers = applicationContext.getBeansOfType(ActionResultTransformer.class).values();
}