Example usage for org.springframework.context.support ClassPathXmlApplicationContext getBeansOfType

List of usage examples for org.springframework.context.support ClassPathXmlApplicationContext getBeansOfType

Introduction

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

Prototype

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

Source Link

Usage

From source file:org.cleverbus.core.common.extension.AbstractExtensionConfigurationLoader.java

private void loadExtension(String extConfigLocation, int extNumber) throws Exception {
    Log.debug("new extension context for '" + extConfigLocation + "' started ...");

    ClassPathXmlApplicationContext extContext = new ClassPathXmlApplicationContext(parentContext);
    extContext.setId("CleverBus extension nr. " + extNumber);
    extContext.setDisplayName("CleverBus extension context for '" + extConfigLocation + '"');
    extContext.setConfigLocation(extConfigLocation);

    extContext.refresh();//from  ww w  .java2s .  c o m

    // 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");
}

From source file:com.ponysdk.spring.servlet.SpringHttpServlet.java

protected EntryPoint newPonySession(final UIContext ponySession) {
    if (clientConfigurations.isEmpty())
        clientConfigurations.addAll(Arrays.asList("conf/client_application.inc.xml", "client_application.xml"));

    final ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(
            clientConfigurations.toArray(new String[0]));

    final EventBus rootEventBus = applicationContext.getBean(EventBus.class);
    final EntryPoint entryPoint = applicationContext.getBean(EntryPoint.class);
    final PHistory history = applicationContext.getBean(PHistory.class);

    ponySession.setRootEventBus(rootEventBus);
    ponySession.setHistory(history);// w  w w  .j  a v a2  s .  c o  m

    final Map<String, InitializingActivity> initializingPages = applicationContext
            .getBeansOfType(InitializingActivity.class);
    if (initializingPages != null && !initializingPages.isEmpty()) {
        for (final InitializingActivity p : initializingPages.values()) {
            p.afterContextInitialized();
        }
    }

    return entryPoint;
}

From source file:fr.gael.dhus.DHuS.java

/** Starts the DHuS (starts Tomcat, creates the Spring application context. */
public static void start() {
    // Transfer System.err in logger
    System.setErr(new PrintStream(new LoggingOutputStream(LOGGER), true));

    String version = DHuS.class.getPackage().getImplementationVersion();

    // Force ehcache not to call home
    System.setProperty("net.sf.ehcache.skipUpdateCheck", "true");
    System.setProperty("org.terracotta.quartz.skipUpdateCheck", "true");
    System.setProperty("user.timezone", "UTC");
    TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
    System.setProperty("fr.gael.dhus.version", version == null ? "dev" : version);

    if (!SystemService.restore()) {
        LOGGER.error("Cannot run system restoration.");
        LOGGER.error("Check the restoration file \"" + SystemService.RESTORATION_PROPERTIES
                + "\" from the current directory.");
        System.exit(1);/*from  w  ww  . ja  va  2s . co  m*/
    }

    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        @Override
        public void run() {
            if ((server != null) && server.isRunning()) {
                try {
                    server.stop();
                } catch (TomcatException e) {
                    e.printStackTrace();
                }
            }
        }
    }));

    // Always add JMSAppender
    //Logger rootLogger = LogManager.getRootLogger ();
    //org.apache.logging.log4j.core.Logger coreLogger =
    //(org.apache.logging.log4j.core.Logger)rootLogger;
    //JMSAppender jmsAppender = JMSAppender.createAppender ();
    //coreLogger.addAppender (jmsAppender);
    try {
        // Activates the resolver for Drb
        DrbFactoryResolver.setMetadataResolver(new DrbCortexMetadataResolver(DrbCortexModel.getDefaultModel()));
    } catch (IOException e) {
        LOGGER.error("Resolver cannot be handled.");
        //logger.error (new Message(MessageType.SYSTEM,
        //"Resolver cannot be handled."));
    }

    LOGGER.info("Launching Data Hub Service...");
    //logger.info (new Message(MessageType.SYSTEM,
    //"Loading Data Hub Service..."));

    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
            "classpath:fr/gael/dhus/spring/dhus-core-context.xml");
    context.registerShutdownHook();

    // Registers ContextClosedEvent listeners to properly save states before
    // the Spring context is destroyed.
    ApplicationListener sync_sv = context.getBean(ISynchronizerService.class);
    context.addApplicationListener(sync_sv);

    // Initialize Database Incoming folder
    IncomingManager incoming_manager = (IncomingManager) context.getBean("incomingManager");
    incoming_manager.initIncoming();

    // Initialize DHuS loggers
    //jmsAppender.cleanWaitingLogs ();
    //logger.info (new Message(MessageType.SYSTEM, "DHuS Started"));
    try {
        //ftp = xml.getBean (FtpServer.class);
        //ftp.start ();

        server = ApplicationContextProvider.getBean(TomcatServer.class);
        server.init();

        LOGGER.info("Starting server " + server.getClass() + "...");
        //logger.info (new Message(MessageType.SYSTEM, "Starting server..."));
        server.start();
        //logger.info (new Message(MessageType.SYSTEM, "Server started."));

        LOGGER.info("Server started.");

        // Initialises SolrDAO
        SolrDao solr_dao = (SolrDao) context.getBean("solrDao");
        solr_dao.initServerStarted();

        Map<String, WebApplication> webapps = context.getBeansOfType(WebApplication.class);
        for (String beanName : webapps.keySet()) {
            server.install(webapps.get(beanName));
        }

        fr.gael.dhus.server.http.web.WebApplication.installAll(server);
        WebServlet.installAll(server);
        WebPostProcess.launchAll();

        LOGGER.info("Server is ready...");
        started = true;

        //InitializableComponent.initializeAll ();
        //logger.info (new Message(MessageType.SYSTEM, "Server is ready..."));
        server.await();
    } catch (Exception e) {
        LOGGER.error("Cannot start system.", e);
        //logger.error (new Message(MessageType.SYSTEM, "Cannot start DHuS."), e);
        //ftp.stop ();
        System.exit(1);
    }
}

From source file:com.temenos.interaction.loader.detector.SpringBasedLoaderAction.java

@Override
public void execute(FileEvent<File> dirEvent) {
    LOGGER.debug("Creation of new Spring ApplicationContext based CommandController triggerred by change in",
            dirEvent.getResource().getAbsolutePath());

    Collection<File> jars = FileUtils.listFiles(dirEvent.getResource(), new String[] { "jar" }, true);
    Set<URL> urls = new HashSet();
    for (File f : jars) {
        try {/*from w ww  .jav  a  2  s . c o  m*/
            LOGGER.trace("Adding {} to list of URLs to create ApplicationContext from", f.toURI().toURL());
            urls.add(f.toURI().toURL());
        } catch (MalformedURLException ex) {
            // kindly ignore and log
        }
    }
    Reflections reflectionHelper = new Reflections(
            new ConfigurationBuilder().addClassLoader(classloaderFactory.getForObject(dirEvent))
                    .addScanners(new ResourcesScanner()).addUrls(urls));

    Set<String> resources = new HashSet();

    for (String locationPattern : configLocationsPatterns) {
        String regex = convertWildcardToRegex(locationPattern);
        resources.addAll(reflectionHelper.getResources(Pattern.compile(regex)));
    }

    if (!resources.isEmpty()) {
        // if resources are empty just clean up the previous ApplicationContext and leave!
        LOGGER.debug("Detected potential Spring config files to load");
        ClassPathXmlApplicationContext context;
        if (parentContext != null) {
            context = new ClassPathXmlApplicationContext(parentContext);
        } else {
            context = new ClassPathXmlApplicationContext();
        }

        context.setConfigLocations(configLocationsPatterns.toArray(new String[] {}));

        ClassLoader childClassLoader = classloaderFactory.getForObject(dirEvent);
        context.setClassLoader(childClassLoader);
        context.refresh();

        CommandController cc = null;

        try {
            cc = context.getBean(commandControllerBeanName, CommandController.class);
            LOGGER.debug("Detected pre-configured CommandController in added config files");
        } catch (BeansException ex) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("No detected pre-configured CommandController in added config files.", ex);
            }
            Map<String, InteractionCommand> commands = context.getBeansOfType(InteractionCommand.class);
            if (!commands.isEmpty()) {
                LOGGER.debug("Adding new commands");
                SpringContextBasedInteractionCommandController scbcc = new SpringContextBasedInteractionCommandController();
                scbcc.setApplicationContext(context);
                cc = scbcc;
            } else {
                LOGGER.debug("No commands detected to be added");
            }
        }

        if (parentChainingCommandController != null) {
            List<CommandController> newCommandControllers = new ArrayList<CommandController>(
                    parentChainingCommandController.getCommandControllers());

            // "unload" the previously loaded CommandController
            if (previouslyAddedCommandController != null) {
                LOGGER.debug("Removing previously added instance of CommandController");
                newCommandControllers.remove(previouslyAddedCommandController);
            }

            // if there is a new CommandController on the Spring file, add it on top of the chain
            if (cc != null) {
                LOGGER.debug("Adding newly created CommandController to ChainingCommandController");
                newCommandControllers.add(0, cc);
                parentChainingCommandController.setCommandControllers(newCommandControllers);
                previouslyAddedCommandController = cc;
            } else {
                previouslyAddedCommandController = null;
            }
        } else {
            LOGGER.debug(
                    "No ChainingCommandController set to add newly created CommandController to - skipping action");
        }

        if (previousAppCtx != null) {
            if (previousAppCtx instanceof Closeable) {
                try {
                    ((Closeable) previousAppCtx).close();
                } catch (Exception ex) {
                    LOGGER.error("Error closing the ApplicationContext.", ex);
                }
            }
            previousAppCtx = context;
        }
    } else {
        LOGGER.debug("No Spring config files detected in the JARs scanned");
    }
}

From source file:org.easyrec.plugin.container.PluginRegistry.java

@SuppressWarnings({ "unchecked" })
public void installPlugin(URI pluginId, Version version) {
    FileOutputStream fos = null;/*  www .j  a  v a  2 s.c  o  m*/
    File tmpFile = null;

    try {
        PluginVO plugin = pluginDAO.loadPlugin(pluginId, version);
        if (plugin == null)
            throw new Exception("Plugin not found in DB!");
        // write file to plugin folder
        tmpFile = new File(pluginFolder.getFile(),
                plugin.getId().toString() + "_" + plugin.getDisplayName() + ".jar");
        fos = new FileOutputStream(tmpFile);
        fos.write(plugin.getFile());
        fos.close();

        // install the plugin

        PluginClassLoader ucl = new PluginClassLoader(new URL[] { tmpFile.toURI().toURL() },
                this.getClass().getClassLoader());

        if (ucl.findResource(DEFAULT_PLUGIN_CONFIG_FILE) == null) {
            logger.warn("no " + DEFAULT_PLUGIN_CONFIG_FILE + " found in plugin jar ");
            return;
        }

        ClassPathXmlApplicationContext cax = new ClassPathXmlApplicationContext(
                new String[] { DEFAULT_PLUGIN_CONFIG_FILE }, false, appContext);
        cax.setClassLoader(ucl);
        cax.refresh();
        //            cax.stop();
        //            cax.start();

        // currently only GeneratorPluginSupport is used
        Map<String, GeneratorPluginSupport> beans = cax.getBeansOfType(GeneratorPluginSupport.class);

        if (beans.isEmpty()) {
            logger.warn("no GeneratorPluginSupport subclasses found in plugin jar");
            return;
        }

        Generator<GeneratorConfiguration, GeneratorStatistics> generator = beans.values().iterator().next();

        installGenerator(pluginId, version, plugin, cax, generator);
    } catch (Exception e) {
        logger.error("An Exception occurred while installing the plugin!", e);

        pluginDAO.updatePluginState(pluginId, version, LifecyclePhase.INSTALL_FAILED.toString());
    } finally {
        if (fos != null)
            try {
                fos.close();
            } catch (Exception ignored) {
                logger.warn("could not close file output stream", ignored);
            }

        /*
        if (tmpFile != null)
        try {
            tmpFile.delete();
        } catch (Exception ignored) {
            logger.warn("could not delete temporary plugin file", ignored);
        }
        */
    }
}

From source file:org.easyrec.plugin.container.PluginRegistry.java

@SuppressWarnings({ "unchecked" })
public PluginVO checkPlugin(byte[] file) throws Exception {
    PluginVO plugin;/*from   w w w . ja  va  2  s. c  o m*/
    FileOutputStream fos = null;
    URLClassLoader ucl;
    ClassPathXmlApplicationContext cax = null;
    File tmpFile = null;

    try {
        if (file == null)
            throw new IllegalArgumentException("Passed file must not be null!");

        tmpFile = File.createTempFile("plugin", null);
        tmpFile.deleteOnExit();

        fos = new FileOutputStream(tmpFile);
        fos.write(file);
        fos.close();

        // check if plugin is valid
        ucl = new URLClassLoader(new URL[] { tmpFile.toURI().toURL() }, this.getClass().getClassLoader());

        if (ucl.getResourceAsStream(DEFAULT_PLUGIN_CONFIG_FILE) != null) {
            cax = new ClassPathXmlApplicationContext(new String[] { DEFAULT_PLUGIN_CONFIG_FILE }, false,
                    appContext);
            cax.setClassLoader(ucl);
            logger.info("Classloader: " + cax.getClassLoader());
            cax.refresh();

            Map<String, GeneratorPluginSupport> beans = cax.getBeansOfType(GeneratorPluginSupport.class);

            if (beans.isEmpty()) {
                logger.debug("No class implementing a generator could be found. Plugin rejected!");
                throw new Exception("No class implementing a generator could be found. Plugin rejected!");
            }

            Generator<GeneratorConfiguration, GeneratorStatistics> generator = beans.values().iterator().next();

            logger.info(String.format("Plugin successfully validated! class: %s name: %s, id: %s",
                    generator.getClass(), generator.getDisplayName(), generator.getId()));

            cax.getAutowireCapableBeanFactory().autowireBeanProperties(generator,
                    AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false);

            plugin = new PluginVO(generator.getDisplayName(), generator.getId().getUri(),
                    generator.getId().getVersion(), LifecyclePhase.NOT_INSTALLED.toString(), file, null);

            if (tmpFile.delete())
                logger.info("tmpFile deleted successfully");

            return plugin;
        } else { // config file not found
            logger.debug("No valid config file found in the supplied .jar file. Plugin rejected!");
            throw new Exception("No valid config file found in the supplied .jar file. Plugin rejected!");
        }
    } catch (Exception e) {
        logger.error("An Exception occurred while checking the plugin!", e);

        throw e;
    } finally {
        if (fos != null)
            fos.close();

        if ((cax != null) && (!cax.isActive()))
            cax.close();

        if (tmpFile != null)
            try {
                if (!tmpFile.delete())
                    logger.warn("could not delete tmpFile");
            } catch (SecurityException se) {
                logger.error("Could not delete temporary file! Please check permissions!", se);
            }
    }
}

From source file:org.entando.entando.aps.system.XmlWebApplicationContext.java

@Override
public <T> Map<String, T> getBeansOfType(Class<T> type) throws BeansException {
    Map<String, T> map = super.getBeansOfType(type);
    List<ClassPathXmlApplicationContext> contexts = (List<ClassPathXmlApplicationContext>) this
            .getServletContext().getAttribute("pluginsContextsList");
    if (contexts != null) {
        for (ClassPathXmlApplicationContext classPathXmlApplicationContext : contexts) {
            try {
                Map<String, T> tempmap = classPathXmlApplicationContext.getBeansOfType(type);
                map.putAll(tempmap);//from  ww  w .j a  v a2  s .c  om
            } catch (Exception ex) {
            }
        }
    }
    return map;
}