Example usage for org.springframework.beans.factory.support DefaultListableBeanFactory getBean

List of usage examples for org.springframework.beans.factory.support DefaultListableBeanFactory getBean

Introduction

In this page you can find the example usage for org.springframework.beans.factory.support DefaultListableBeanFactory getBean.

Prototype

@Override
    public <T> T getBean(Class<T> requiredType) throws BeansException 

Source Link

Usage

From source file:com.gwtplatform.dispatch.rpc.server.spring.utils.SpringUtils.java

public static <B> B getInstance(ApplicationContext applicationContext, Class<B> clazz) throws BeansException {
    DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(applicationContext);
    return beanFactory.getBean(clazz);
}

From source file:org.bambooframework.dao.impl.cfg.BeansConfigurationHelper.java

public static DaoEngineConfigurationImpl parseDaoEngineConfiguration(Resource springResource, String beanName) {
    DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
    XmlBeanDefinitionReader xmlBeanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
    xmlBeanDefinitionReader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_XSD);
    xmlBeanDefinitionReader.loadBeanDefinitions(springResource);
    DaoEngineConfigurationImpl processEngineConfiguration = (DaoEngineConfigurationImpl) beanFactory
            .getBean(beanName);/*from ww w .j a v  a 2  s .co  m*/
    processEngineConfiguration.setBeans(new SpringBeanFactoryProxyMap(beanFactory));
    return processEngineConfiguration;
}

From source file:org.activiti.crystalball.simulator.impl.cfg.BeansConfigurationHelper.java

public static SimulationEngineConfiguration parseSimulationEngineConfiguration(Resource springResource,
        String beanName) {//from   ww  w.j a va 2 s . c o m
    DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
    XmlBeanDefinitionReader xmlBeanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
    xmlBeanDefinitionReader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_XSD);
    xmlBeanDefinitionReader.loadBeanDefinitions(springResource);
    SimulationEngineConfigurationImpl simulationEngineConfiguration = (SimulationEngineConfigurationImpl) beanFactory
            .getBean(beanName);
    simulationEngineConfiguration.setBeans(new SpringBeanFactoryProxyMap(beanFactory));
    return simulationEngineConfiguration;
}

From source file:com.sharksharding.resources.register.bean.RegisterDataSource.java

/**
 * bean//from   ww  w  .  j  a  v  a2 s .  co  m
 * 
 * @author gaoxianglong
 * 
 * @param nodePathValue
 *            zookeepervalue
 * 
 * @param resourceType
 *            
 * 
 * @return void
 */
public static void register(String nodePathValue, String resourceType) {
    if (null == aContext)
        return;
    final String tmpdir = TmpManager.createTmp();
    logger.debug("tmpdir-->" + tmpdir);
    try (BufferedWriter out = new BufferedWriter(new FileWriter(tmpdir))) {
        if (null != nodePathValue) {
            out.write(nodePathValue);
            out.flush();
            FileSystemResource resource = new FileSystemResource(tmpdir);
            ConfigurableApplicationContext cfgContext = (ConfigurableApplicationContext) aContext;
            DefaultListableBeanFactory beanfactory = (DefaultListableBeanFactory) cfgContext.getBeanFactory();
            /*
             * ?????ioc?,???bean,
             * loadBeanDefinitions()
             */
            new XmlBeanDefinitionReader(beanfactory).loadBeanDefinitions(resource);
            final String defaultBeanName = "jdbcTemplate";
            String[] beanNames = beanfactory.getBeanDefinitionNames();
            for (String beanName : beanNames) {
                /* ??beanNamejdbcTemplateJdbcTemplate */
                if (defaultBeanName.equals(beanName)) {
                    GetJdbcTemplate.setJdbcTemplate((JdbcTemplate) beanfactory.getBean(defaultBeanName));
                } else {
                    /* bean */
                    beanfactory.getBean(beanName);
                }
            }
        }
    } catch (Exception e) {
        throw new RegisterBeanException(e.toString());
    } finally {
        TmpManager.deleteTmp(tmpdir);
    }
}

From source file:io.gravitee.gateway.services.apikeyscache.ApiKeysCacheService.java

@Override
protected void doStart() throws Exception {
    if (enabled) {
        super.doStart();

        LOGGER.info("Overriding API key repository implementation with cached API Key repository");
        DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) ((ConfigurableApplicationContext) applicationContext
                .getParent()).getBeanFactory();

        this.apiKeyRepository = beanFactory.getBean(ApiKeyRepository.class);
        LOGGER.debug("Current API key repository implementation is {}", apiKeyRepository.getClass().getName());

        String[] beanNames = beanFactory.getBeanNamesForType(ApiKeyRepository.class);
        String oldBeanName = beanNames[0];

        beanFactory.destroySingleton(oldBeanName);

        LOGGER.debug("Register API key repository implementation {}", ApiKeyRepositoryWrapper.class.getName());
        beanFactory.registerSingleton(ApiKeyRepository.class.getName(),
                new ApiKeyRepositoryWrapper(this.apiKeyRepository, cache));

        eventManager.subscribeForEvents(this, ReactorEvent.class);

        executorService = Executors.newScheduledThreadPool(threads, new ThreadFactory() {
            private int counter = 0;
            private String prefix = "apikeys-refresher";

            @Override//  ww  w  .  j a v a 2s . c o  m
            public Thread newThread(Runnable r) {
                return new Thread(r, prefix + '-' + counter++);
            }
        });
    }
}

From source file:org.mybatis.caches.ignite.IgniteCacheAdapter.java

/**
 * Constructor.//from ww  w.ja v  a  2s. c  o m
 *
 * @param id
 *          Cache id.
 */
@SuppressWarnings("unchecked")
public IgniteCacheAdapter(String id) {
    if (id == null) {
        throw new IllegalArgumentException("Cache instances require an ID");
    }

    CacheConfiguration<Object, Object> cacheCfg = null;

    try {
        DefaultListableBeanFactory factory = new DefaultListableBeanFactory();

        new XmlBeanDefinitionReader(factory).loadBeanDefinitions(new FileSystemResource(new File(CFG_PATH)));

        cacheCfg = (CacheConfiguration<Object, Object>) factory.getBean("templateCacheCfg");

        cacheCfg.setEvictionPolicy(null);
        cacheCfg.setCacheLoaderFactory(null);
        cacheCfg.setCacheWriterFactory(null);

        // overrides template cache name with the specified id.
        cacheCfg.setName(id);
    } catch (NoSuchBeanDefinitionException | BeanDefinitionStoreException e) {
        // initializes the default cache.
        log.warn("Initializing the default cache. Consider properly configuring '" + CFG_PATH + "' instead.");
        log.trace("" + e);

        cacheCfg = new CacheConfiguration<>(id);
    }

    cache = ignite.getOrCreateCache(cacheCfg);

    this.id = id;
}

From source file:org.carewebframework.shell.BaseXmlParser.java

/**
 * Parses an xml extension from an xml string.
 * /* w w  w . j  av  a  2  s . c o  m*/
 * @param xml XML containing the extension.
 * @param tagName The top level tag name.
 * @return Result of the parsed extension.
 * @throws Exception Unspecified exception.
 */
protected Object fromXml(String xml, String tagName) throws Exception {
    Document document = XMLUtil.parseXMLFromString(xml);
    NodeList nodeList = document.getElementsByTagName(tagName);

    if (nodeList == null || nodeList.getLength() != 1) {
        throw new DOMException(DOMException.NOT_FOUND_ERR, "Top level tag '" + tagName + "' was not found.");
    }

    Element element = (Element) nodeList.item(0);
    Class<?> beanClass = getBeanClass(element);
    BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(beanClass);
    doParse(element, builder);
    DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
    factory.setParentBeanFactory(SpringUtil.getAppContext());
    AbstractBeanDefinition beanDefinition = builder.getBeanDefinition();
    factory.registerBeanDefinition(tagName, beanDefinition);
    return factory.getBean(tagName);
}

From source file:io.gravitee.gateway.service.ratelimit.AsyncRateLimitService.java

@Override
protected void doStart() throws Exception {
    super.doStart();

    DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) ((ConfigurableApplicationContext) applicationContext)
            .getBeanFactory();/*w w w . j a  va2 s  .  c o  m*/
    DefaultListableBeanFactory parentBeanFactory = (DefaultListableBeanFactory) ((ConfigurableApplicationContext) applicationContext
            .getParent()).getBeanFactory();

    // Retrieve the current rate-limit repository implementation
    RateLimitRepository rateLimitRepository = parentBeanFactory.getBean(RateLimitRepository.class);
    LOGGER.debug("Rate-limit repository implementation is {}", rateLimitRepository.getClass().getName());

    if (enabled) {
        // Prepare caches
        RateLimitRepository aggregateCacheRateLimitRepository = new CachedRateLimitRepository(aggregateCache);
        RateLimitRepository localCacheRateLimitRepository = new CachedRateLimitRepository(localCache);

        // Prepare queue to flush data into the final repository implementation
        BlockingQueue<RateLimit> rateLimitsQueue = new BlockingArrayQueue<>(queueCapacity);

        LOGGER.debug("Register rate-limit repository asynchronous implementation {}",
                AsyncRateLimitRepository.class.getName());
        AsyncRateLimitRepository asyncRateLimitRepository = new AsyncRateLimitRepository();
        beanFactory.autowireBean(asyncRateLimitRepository);
        asyncRateLimitRepository.setLocalCacheRateLimitRepository(localCacheRateLimitRepository);
        asyncRateLimitRepository.setAggregateCacheRateLimitRepository(aggregateCacheRateLimitRepository);
        asyncRateLimitRepository.setRateLimitsQueue(rateLimitsQueue);

        LOGGER.info("Register the rate-limit service bridge for synchronous and asynchronous mode");
        DefaultRateLimitService rateLimitService = new DefaultRateLimitService();
        rateLimitService.setRateLimitRepository(rateLimitRepository);
        rateLimitService.setAsyncRateLimitRepository(asyncRateLimitRepository);
        parentBeanFactory.registerSingleton(RateLimitService.class.getName(), rateLimitService);

        // Prepare and start rate-limit poller
        rateLimitPollerExecutor = Executors
                .newSingleThreadScheduledExecutor(r -> new Thread(r, "rate-limit-poller"));
        RateLimitPoller rateLimitPoller = new RateLimitPoller();
        beanFactory.autowireBean(rateLimitPoller);
        rateLimitPoller.setRateLimitRepository(rateLimitRepository);
        rateLimitPoller.setAggregateCacheRateLimitRepository(aggregateCacheRateLimitRepository);

        LOGGER.info("Schedule rate-limit poller at fixed rate: {} {}", polling, TimeUnit.MILLISECONDS);
        rateLimitPollerExecutor.scheduleAtFixedRate(rateLimitPoller, 0L, polling, TimeUnit.MILLISECONDS);

        // Prepare and start rate-limit updater
        rateLimitUpdaterExecutor = Executors.newSingleThreadExecutor(r -> new Thread(r, "rate-limit-updater"));
        RateLimitUpdater rateLimitUpdater = new RateLimitUpdater(rateLimitsQueue);
        beanFactory.autowireBean(rateLimitUpdater);
        rateLimitUpdater.setRateLimitRepository(rateLimitRepository);

        LOGGER.info("Start rate-limit updater");
        rateLimitUpdaterExecutor.submit(rateLimitUpdater);
    } else {
        // By disabling async and cached rate limiting, only the strict mode is allowed
        LOGGER.info("Register the rate-limit service bridge for strict mode only");
        DefaultRateLimitService rateLimitService = new DefaultRateLimitService();
        rateLimitService.setRateLimitRepository(rateLimitRepository);
        rateLimitService.setAsyncRateLimitRepository(rateLimitRepository);
        parentBeanFactory.registerSingleton(RateLimitService.class.getName(), rateLimitService);
    }
}

From source file:com.longio.spring.LioBootstrap.java

private void bootEndpoints(DefaultListableBeanFactory bf, String name) {
    RootBeanDefinition bd = (RootBeanDefinition) bf.getBeanDefinition(name);
    String fbMethod = bd.getFactoryMethodName();
    String fbName = bd.getFactoryBeanName();
    Object fb = bf.getBean(fbName);

    if (!bf.containsBeanDefinition("longio.connector")) {
        GenericBeanDefinition bdd = new GenericBeanDefinition();
        bdd.setBeanClass(NettyConnector.class);
        bf.registerBeanDefinition("longio.connector", bdd);
    }//from w  w w.j  a va2 s. co m

    Connector connector = bf.getBean("longio.connector", Connector.class);

    Class<?> fbCls = fb.getClass().getSuperclass();
    Method m;
    try {
        m = fbCls.getDeclaredMethod(fbMethod);
        Boots boots = m.getAnnotation(Boots.class);
        if (boots == null) {
            MethodDispatcher dispatcher = new MethodDispatcher();
            Boot b = m.getAnnotation(Boot.class);
            connector.start(b.port(), dispatcher, b.tt(), b.pt(), b.pkg());
            logger.info("connector start at port [" + b.port() + "] with tt = " + b.tt() + " and pt = " + b.pt()
                    + " for pkg = " + b.pkg());
        } else {
            for (Boot b : boots.value()) {
                MethodDispatcher dispatcher = new MethodDispatcher();
                connector.start(b.port(), dispatcher, b.tt(), b.pt(), b.pkg());
                logger.info("connector start at port [" + b.port() + "] with tt = " + b.tt() + " and pt = "
                        + b.pt() + " for pkg = " + b.pkg());
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.google.enterprise.connector.db.MockDBConnectorFactory.java

/**
 * Creates a database connector.//from   w ww .  j  a v a 2  s.  c o  m
 *
 * @param config map of configuration values.
 */
/* TODO(jlacey): Extract the Spring instantiation code in CM. */
@Override
public Connector makeConnector(Map<String, String> config) throws RepositoryException {
    // TODO(jlacey): The placeholder values are in the EPPC bean in
    // connectorDefaults.xml, but we're not loading that, and doing so
    // would unravel a ball of string: using setLocation instead of
    // setProperties (since the EPPC bean already has properties),
    // which in turn requires the ByteArrayResource machinery in
    // InstanceInfo or writing the properties to a file.
    Properties props = new Properties();
    for (String configKey : DBConnectorType.CONFIG_KEYS) {
        props.put(configKey, "");
    }
    // Escape MyBatis syntax that looks like a Spring placeholder.
    // See https://jira.springsource.org/browse/SPR-4953
    props.put("docIds", "#{'$'}{docIds}");
    props.putAll(config);

    Resource prototype = new ClassPathResource("config/connectorInstance.xml", MockDBConnectorFactory.class);
    Resource defaults = new ClassPathResource("config/connectorDefaults.xml", MockDBConnectorFactory.class);

    DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
    XmlBeanDefinitionReader beanReader = new XmlBeanDefinitionReader(factory);
    try {
        beanReader.loadBeanDefinitions(prototype);
        beanReader.loadBeanDefinitions(defaults);
    } catch (BeansException e) {
        throw new RepositoryException(e);
    }

    PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer();
    cfg.setProperties(props);
    cfg.postProcessBeanFactory(factory);

    String[] beanList = factory.getBeanNamesForType(DiffingConnector.class);
    Assert.assertEquals(Arrays.asList(beanList).toString(), 1, beanList.length);
    return (Connector) factory.getBean(beanList[0]);
}