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.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 w w . j a  v  a 2 s . c o  m

    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.gridgain.grid.kernal.processors.spring.GridSpringProcessorImpl.java

/** {@inheritDoc} */
@Override//from   ww  w  .j a  v a 2 s  .c  om
public GridBiTuple<Collection<GridConfiguration>, ? extends GridSpringResourceContext> loadConfigurations(
        URL cfgUrl, String... excludedProps) throws GridException {
    ApplicationContext springCtx;

    try {
        springCtx = applicationContext(cfgUrl, excludedProps);
    } catch (BeansException e) {
        if (X.hasCause(e, ClassNotFoundException.class))
            throw new GridException("Failed to instantiate Spring XML application context "
                    + "(make sure all classes used in Spring configuration are present at CLASSPATH) "
                    + "[springUrl=" + cfgUrl + ']', e);
        else
            throw new GridException("Failed to instantiate Spring XML application context [springUrl=" + cfgUrl
                    + ", err=" + e.getMessage() + ']', e);
    }

    Map<String, GridConfiguration> cfgMap;

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

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

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

From source file:org.gridgain.grid.loaders.servlet.GridServletLoader.java

/**
 * {@inheritDoc}//from   w ww  . ja v a2s  .c  o  m
 */
@SuppressWarnings({ "unchecked" })
@Override
public void init() throws ServletException {
    // Avoid multiple servlet instances. GridGain should be loaded once.
    if (loaded == true) {
        return;
    }

    log = new GridJclLogger(LogFactory.getLog("GridGain"));

    logo();

    cfgFile = getServletConfig().getInitParameter(cfgFilePathParam);

    File path = GridUtils.resolveGridGainPath(cfgFile);

    if (path == null) {
        throw new ServletException("Spring XML configuration file path is invalid: " + new File(cfgFile)
                + ". Note that this path should be either absolute path or a relative path to GRIDGAIN_HOME.");
    }

    if (path.isFile() == false) {
        throw new ServletException("Provided file path is not a file: " + path);
    }

    ApplicationContext springCtx = null;

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

    Map cfgMap = null;

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

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

    if (cfgMap.size() == 0) {
        throw new ServletException("Can't find grid factory configuration in: " + path);
    }

    try {
        for (GridConfiguration cfg : (Collection<GridConfiguration>) cfgMap.values()) {
            assert cfg != null : "ASSERTION [line=221, file=src/java/org/gridgain/grid/loaders/servlet/GridServletLoader.java]";

            GridConfigurationAdapter adapter = new GridConfigurationAdapter(cfg);

            // Set Glassfish logger.
            if (cfg.getGridLogger() == null) {
                adapter.setGridLogger(log);
            }

            Grid grid = GridFactory.start(adapter, springCtx);

            // Test if grid is not null - started properly.
            if (grid != null) {
                gridNames.add(grid.getName());
            }
        }
    } catch (GridException e) {
        // Stop started grids only.
        for (String name : gridNames) {
            GridFactory.stop(name, true);
        }

        throw new ServletException("Failed to start GridGain.", e);
    }

    loaded = true;
}

From source file:org.gridgain.startup.GridRandomCommandLineLoader.java

/**
 * Initializes configurations.//  w w  w  . j a va  2 s . c  om
 *
 * @param springCfgPath Configuration file path.
 * @param logCfgPath Log file name.
 * @return List of configurations.
 * @throws GridException If an error occurs.
 */
@SuppressWarnings("unchecked")
private static GridConfiguration getConfiguration(String springCfgPath, @Nullable String logCfgPath)
        throws GridException {
    assert springCfgPath != null;

    File path = GridTestUtils.resolveGridGainPath(springCfgPath);

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

    if (!path.isFile())
        throw new GridException("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 GridException("Failed to instantiate Spring XML application context: " + e.getMessage(), e);
    }

    Map cfgMap;

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

    if (cfgMap == null)
        throw new GridException("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 GridException(
                "Spring configuration file should contain exactly 1 grid configuration: " + path);

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

    assert cfg != null;

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

    return cfg;
}

From source file:org.gridgain.startup.GridVmNodesStarter.java

/**
 * Initializes configurations./*from   w w  w.  j  av a  2s  . c o  m*/
 *
 *
 * @param springCfgPath Configuration file path.
 * @return List of configurations.
 * @throws GridException If an error occurs.
 */
@SuppressWarnings("unchecked")
private static Iterable<GridConfiguration> getConfigurations(String springCfgPath) throws GridException {
    File path = GridTestUtils.resolveGridGainPath(springCfgPath);

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

    if (!path.isFile())
        throw new GridException("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 GridException("Failed to instantiate Spring XML application context: " + e.getMessage(), e);
    }

    Map cfgMap;

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

    if (cfgMap == null)
        throw new GridException("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 GridException("Can't find grid factory configuration in: " + path);

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

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

        cfg.setGridName(GRID_NAME_PREF + gridCnt.incrementAndGet());
    }

    return res;
}

From source file:org.jahia.services.seo.urlrewrite.UrlRewriteService.java

protected List<HandlerMapping> getRenderMapping() {
    if (renderMapping == null) {
        LinkedList<HandlerMapping> mapping = new LinkedList<HandlerMapping>();
        ApplicationContext ctx = (ApplicationContext) servletContext.getAttribute(
                "org.springframework.web.servlet.FrameworkServlet.CONTEXT.RendererDispatcherServlet");
        if (ctx != null) {
            mapping.addAll(ctx.getBeansOfType(HandlerMapping.class).values());
            mapping.addAll(ctx.getParent().getBeansOfType(HandlerMapping.class).values());
            renderMapping = mapping;//from  www.j  a  v a 2s  .  c  om
        }
    }
    if (renderMapping != null) {
        List<HandlerMapping> l = new LinkedList<HandlerMapping>(renderMapping);
        l.addAll(ServicesRegistry.getInstance().getJahiaTemplateManagerService().getTemplatePackageRegistry()
                .getSpringHandlerMappings());
        return l;
    }
    return null;
}

From source file:org.jsecurity.spring.SpringIniWebConfiguration.java

@SuppressWarnings("unchecked")
protected SecurityManager createDefaultSecurityManagerFromRealms(ApplicationContext appCtx,
        Map<String, Map<String, String>> sections) {
    SecurityManager securityManager = null;

    Map<String, Realm> realmMap = appCtx.getBeansOfType(Realm.class);
    if (realmMap == null || realmMap.isEmpty()) {
        return null;
    }//  w w w. j a v  a2 s  .co m

    Collection<Realm> realms = realmMap.values();
    if (realms == null || realms.isEmpty()) {
        return null;
    }

    if (!realms.isEmpty()) {

        // Create security manager according to superclass and set realms on it from Spring.
        securityManager = super.createSecurityManager(sections);

        if (securityManager instanceof RealmSecurityManager) {
            RealmSecurityManager realmSM = (RealmSecurityManager) securityManager;
            realmSM.setRealms(realms);
        } else {
            log.warn("Attempted to set realms declared in Spring on SecurityManager, but was not of "
                    + "type RealmSecurityManager - instead was of type: "
                    + securityManager.getClass().getName());
        }
    }

    return securityManager;
}

From source file:org.jsecurity.spring.SpringIniWebConfiguration.java

@SuppressWarnings("unchecked")
protected SecurityManager getSecurityManagerByType(ApplicationContext appCtx) {

    SecurityManager securityManager = null;

    Map<String, SecurityManager> securityManagers = appCtx.getBeansOfType(SecurityManager.class);
    if (securityManagers == null || securityManagers.isEmpty()) {
        return null;
    }/*w  w w  . jav a  2  s .  co m*/

    if (securityManagers.size() > 1) {

        // If more than one are declared, see if one is named "securityManager"
        securityManager = securityManagers.get(DEFAULT_SECURITY_MANAGER_BEAN_ID);

        if (securityManager == null) {
            String msg = "There is more than one bean of type " + SecurityManager.class.getName()
                    + " available in the "
                    + "Spring WebApplicationContext.  Please specify which bean should be used by "
                    + "setting this filter's 'securityManagerBeanName' init-param or by naming one of the "
                    + "security managers '" + DEFAULT_SECURITY_MANAGER_BEAN_ID + "'.";
            throw new ApplicationContextException(msg);
        }

    } else if (securityManagers.size() == 1) {

        securityManager = securityManagers.values().iterator().next();
    }

    return securityManager;
}

From source file:org.jspresso.framework.tools.entitygenerator.EntityGenerator.java

/**
 * Generates the component java source files.
 *//* w w  w . j ava 2 s. c  o m*/
@SuppressWarnings({ "rawtypes", "ConstantConditions" })
public void generateComponents() {
    LOG.debug("Loading Spring context {}.", applicationContextKey);
    BeanFactoryReference bfr = getBeanFactoryReference();
    try {
        ApplicationContext appContext = (ApplicationContext) bfr.getFactory();
        LOG.debug("Spring context {} loaded.", applicationContextKey);
        Collection<IComponentDescriptor<?>> componentDescriptors = new LinkedHashSet<>();
        if (componentIds == null) {
            LOG.debug("Retrieving components from Spring context.");
            Map<String, IComponentDescriptor> allComponents = appContext
                    .getBeansOfType(IComponentDescriptor.class);
            LOG.debug("{} components retrieved.", allComponents.size());
            LOG.debug("Filtering components to generate.");
            for (Map.Entry<String, IComponentDescriptor> componentEntry : allComponents.entrySet()) {
                String className = componentEntry.getValue().getName();
                if (className != null) {
                    boolean include = false;
                    if (includePackages != null) {
                        for (String pkg : includePackages) {
                            if (className.startsWith(pkg)) {
                                include = true;
                            }
                        }
                    } else {
                        include = true;
                    }
                    if (include) {
                        if (excludePatterns != null) {
                            for (String excludePattern : excludePatterns) {
                                if (include && Pattern.matches(excludePattern,
                                        componentEntry.getValue().getName())) {
                                    include = false;
                                }
                            }
                        }
                        if (include) {
                            componentDescriptors.add(componentEntry.getValue());
                        }
                    }
                }
            }
        } else {
            for (String componentId : componentIds) {
                componentDescriptors.add((IComponentDescriptor<?>) appContext.getBean(componentId));
            }
        }
        LOG.debug("{} components filtered.", componentDescriptors.size());
        LOG.debug("Initializing Freemarker template");
        Version version = new Version(2, 3, 23);
        Configuration cfg = new Configuration(version);
        cfg.setClassForTemplateLoading(getClass(), templateResourcePath);
        BeansWrapper wrapper = new DefaultObjectWrapper(version);
        cfg.setObjectWrapper(new DefaultObjectWrapper(version));
        Template template;
        try {
            template = cfg.getTemplate(templateName);
        } catch (IOException ex) {
            LOG.error("Error while loading the template", ex);
            return;
        }
        Map<String, Object> rootContext = new HashMap<>();

        rootContext.put("generateSQLName", new GenerateSqlName());
        rootContext.put("dedupSQLName", new DedupSqlName(false));
        rootContext.put("reduceSQLName", new ReduceSqlName(maxSqlNameSize, new DedupSqlName(true)));
        rootContext.put("instanceof", new InstanceOf(wrapper));
        rootContext.put("compareStrings", new CompareStrings(wrapper));
        rootContext.put("compactString", new CompactString());
        rootContext.put("componentTranslationsDescriptor",
                appContext.getBean("componentTranslationsDescriptor"));
        rootContext.put("generateAnnotations", generateAnnotations);
        rootContext.put("hibernateTypeRegistry", new BasicTypeRegistry());
        if (classnamePrefix == null) {
            classnamePrefix = "";
        }
        if (classnameSuffix == null) {
            classnameSuffix = "";
        }
        LOG.debug("Freemarker template initialized");
        for (IComponentDescriptor<?> componentDescriptor : componentDescriptors) {
            OutputStream out = null;
            if (outputDir != null) {
                String cDescName = componentDescriptor.getName();
                int lastDotIndex = cDescName.lastIndexOf('.');
                if (lastDotIndex >= 0) {
                    cDescName = cDescName.substring(0, lastDotIndex + 1) + classnamePrefix
                            + cDescName.substring(lastDotIndex + 1);
                } else {
                    cDescName = classnamePrefix + cDescName;
                }
                cDescName = cDescName + classnameSuffix;
                try {
                    File outFile = new File(
                            outputDir + "/" + cDescName.replace('.', '/') + "." + fileExtension);
                    if (!outFile.exists()) {
                        LOG.debug("Creating " + outFile.getName());
                        if (!outFile.getParentFile().exists()) {
                            //noinspection ResultOfMethodCallIgnored
                            outFile.getParentFile().mkdirs();
                        }
                        //noinspection ResultOfMethodCallIgnored
                        outFile.createNewFile();
                        out = new FileOutputStream(outFile);
                    } else if (componentDescriptor.getLastUpdated() > outFile.lastModified()) {
                        out = new FileOutputStream(outFile);
                    } else {
                        LOG.debug("No change detected for {} : {} <= {}", componentDescriptor.getName(),
                                new Date(componentDescriptor.getLastUpdated()),
                                new Date(outFile.lastModified()));
                    }
                } catch (IOException ex) {
                    LOG.error("Error while writing output", ex);
                    return;
                }
            } else {
                out = System.out;
            }
            if (out != null) {
                LOG.info("Generating source code for {}", componentDescriptor.getName());
                rootContext.put("componentDescriptor", componentDescriptor);
                try {
                    template.process(rootContext, new OutputStreamWriter(out));
                    out.flush();
                    if (out != System.out) {
                        out.close();
                    }
                } catch (TemplateException ex) {
                    LOG.error("Error while processing the template", ex);
                    return;
                } catch (IOException ex) {
                    LOG.error("Error while writing output", ex);
                    return;
                }
            } else {
                LOG.debug("Source code for {} is up to date. Skipping generation.",
                        componentDescriptor.getName());
            }
            LOG.debug("Finished generating Source code for {}.", componentDescriptor.getName());
        }
    } finally {
        bfr.release();
    }
}

From source file:org.openehealth.ipf.platform.camel.ihe.xds.iti17.Iti17Servlet.java

private CamelContext getCamelContext() {
    ServletContext servletContext = getServletContext();
    ApplicationContext appContext = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
    Map<?, ?> camelContextBeans = appContext.getBeansOfType(CamelContext.class);
    Validate.isTrue(camelContextBeans.size() == 1,
            "A single camelContext bean is required in the application context");
    CamelContext camelContext = (CamelContext) camelContextBeans.values().iterator().next();
    Validate.notNull(camelContext, "A single camelContext bean is required in the application context");
    return camelContext;
}