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

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

Introduction

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

Prototype

public void setClassLoader(@Nullable ClassLoader classLoader) 

Source Link

Document

Specify the ClassLoader to load class path resources with, or null for using the thread context class loader at the time of actual resource access.

Usage

From source file:com.hivemq.plugin.springexample.ExamplePluginModule.java

private ClassPathXmlApplicationContext getApplicationContext() {

    //We need to use ClassPathXmlApplicationContext here and pass a ClassLoader because
    //every plugin has his own classloader and Spring won't be able to find the xml file in
    //the default system classloader

    ClassLoader classLoader = this.getClass().getClassLoader();
    ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext();
    ctx.setClassLoader(classLoader);
    ctx.setConfigLocation("spring-context.xml");
    ctx.refresh();//  w  w  w  . j  a va  2s  .co  m
    return ctx;
}

From source file:org.apache.axis2.sample.spring.service.SpringContextLoader.java

public void startUp(ConfigurationContext configctx, AxisService service) {
    ClassLoader classLoader = service.getClassLoader();
    ClassPathXmlApplicationContext appCtx = new ClassPathXmlApplicationContext(
            new String[] { "applicationContext.xml" }, false);
    appCtx.setClassLoader(classLoader);
    appCtx.refresh();//  ww w. j av  a  2s.  c  om
}

From source file:org.hexlogic.CooptoPluginAdaptor.java

@Override
protected ApplicationContext createApplicationContext(ApplicationContext defaultParent) {
    ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(
            new String[] { DEFAULT_CONFIG }, false, defaultParent);
    applicationContext.setClassLoader(getClass().getClassLoader());
    applicationContext.refresh();/*from w  ww. j  a v a  2  s.  c o m*/

    return applicationContext;
}

From source file:sample.spring.service.SpringInit.java

/**
* this will be called during the deployement time of the service. irrespective
* of the service scope this method will be called
*///from   w w  w .  ja  v a 2s .c om
public void startUp(ConfigurationContext ignore, AxisService service) {
    ClassLoader classLoader = service.getClassLoader();
    ClassPathXmlApplicationContext appCtx = new ClassPathXmlApplicationContext(
            new String[] { "applicationContext.xml" }, false);
    appCtx.setClassLoader(classLoader);
    appCtx.refresh();
    if (logger.isDebugEnabled()) {
        logger.debug("\n\nstartUp() set spring classloader via axisService.getClassLoader() ... ");
    }
}

From source file:org.atomserver.core.dbstore.utils.SeederDBSTest.java

public void testSeedDB() throws Exception {

    if (hasRun) {
        return;//from  w  w  w.j a  v  a 2  s .c o m
    }

    String[] configs = { "/org/atomserver/spring/propertyConfigurerBeans.xml",
            "/org/atomserver/spring/logBeans.xml", "/org/atomserver/spring/storageBeans.xml",
            "/org/atomserver/spring/databaseBeans.xml" };
    ClassPathXmlApplicationContext springFactory = new ClassPathXmlApplicationContext(configs, false);
    springFactory.setClassLoader(new ConfigurationAwareClassLoader(springFactory.getClassLoader()));
    springFactory.refresh();

    try {
        DBSeeder.getInstance(springFactory).seedEntriesClearingFirst();
    } catch (Exception ee) {
        ee.printStackTrace();
    }
    hasRun = true;

    // We should now get an ordered List back
    // SORTED -- From the beginning of time

    EntriesDAO widgetsDAOiBatis = (EntriesDAO) springFactory.getBean("org.atomserver-entriesDAO");

    List sortedList = widgetsDAOiBatis
            .selectEntriesByLastModifiedSeqNum(new BaseFeedDescriptor("widgets", null), ZERO_DATE);
    log.debug("List= " + sortedList);

    Date lastVal = ZERO_DATE;
    long seqNum = 0;
    for (Object obj : sortedList) {
        EntryMetaData widget = (EntryMetaData) obj;

        assertTrue(lastVal.compareTo(widget.getUpdatedDate()) <= 0);
        lastVal = widget.getUpdatedDate();

        assertTrue("expected " + seqNum + " < " + widget.getUpdateTimestamp() + " for " + widget,
                seqNum < widget.getUpdateTimestamp());

        seqNum = widget.getUpdateTimestamp();
    }
}

From source file:com.vmware.o11n.plugin.PowerShellPluginAdaptor.java

@Override
protected ApplicationContext createApplicationContext(ApplicationContext defaultParent) {
    ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(
            new String[] { DEFAULT_CONFIG }, false, defaultParent);

    pluginClassLoader = getClass().getClassLoader();//we expect spring
    applicationContext.setClassLoader(pluginClassLoader);
    applicationContext.refresh();/*w w  w.j  a va 2s. c o m*/

    return applicationContext;
}

From source file:org.atomserver.core.EntryURIHelperTest.java

protected void setUp() throws Exception {
    String[] configs = { "/org/atomserver/spring/propertyConfigurerBeans.xml",
            "/org/atomserver/spring/databaseBeans.xml", "/org/atomserver/spring/storageBeans.xml",
            "/org/atomserver/spring/logBeans.xml", "/org/atomserver/spring/abderaBeans.xml" };

    ClassPathXmlApplicationContext springFactory = new ClassPathXmlApplicationContext(configs, false);
    springFactory.setClassLoader(new ConfigurationAwareClassLoader(springFactory.getClassLoader()));
    springFactory.refresh();//  w w  w . ja va 2s.c o m

    handler = ((AbstractAtomService) springFactory.getBean("org.atomserver-atomService")).getURIHandler();
    serviceContext = (ServiceContext) springFactory.getBean(CONTEXT_NAME);
    if (serviceContext.getAbdera() == null) {
        serviceContext.init(new Abdera(), null);
    }
    baseURI = handler.getServiceBaseUri();
}

From source file:org.brutusin.jsonsrv.SpringJsonServlet.java

@Override
protected Map<String, JsonAction> loadActions() throws Exception {
    String springConfigFile = getServletConfig().getInitParameter(INIT_PARAM_SPRING_CFG_FILE);
    ClassPathXmlApplicationContext applicationContext;
    if (springConfigFile == null) {
        applicationContext = new ClassPathXmlApplicationContext(DEFAULT_CFG_FILE);
    } else {//w w  w.j av  a 2  s . c o m
        applicationContext = new ClassPathXmlApplicationContext(springConfigFile, DEFAULT_CFG_FILE);
    }
    applicationContext.setClassLoader(getClassLoader());
    return applicationContext.getBeansOfType(JsonAction.class);
}

From source file:org.pentaho.pat.plugin.PatLifeCycleListener.java

public void loaded() throws PluginLifecycleException {
    ClassLoader origContextClassloader = Thread.currentThread().getContextClassLoader();
    IServiceManager serviceManager = (IServiceManager) PentahoSystem.get(IServiceManager.class,
            PentahoSessionHolder.getSession());
    try {// w ww  . j a v a  2s  .c o  m
        sessionBean = (SessionServlet) serviceManager.getServiceBean("gwt", "session.rpc"); //$NON-NLS-1$
        queryBean = (QueryServlet) serviceManager.getServiceBean("gwt", "query.rpc"); //$NON-NLS-1$
        discoveryBean = (DiscoveryServlet) serviceManager.getServiceBean("gwt", "discovery.rpc"); //$NON-NLS-1$
        platformBean = (PlatformServlet) serviceManager.getServiceBean("gwt", "platform.rpc"); //$NON-NLS-1$

        final IPluginManager pluginManager = (IPluginManager) PentahoSystem.get(IPluginManager.class,
                PentahoSessionHolder.getSession());
        final PluginClassLoader pluginClassloader = (PluginClassLoader) pluginManager
                .getClassLoader(PAT_PLUGIN_NAME);
        final String hibernateConfigurationFile = PentahoSystem
                .getSystemSetting("hibernate/hibernate-settings.xml", "settings/config-file", null); //$NON-NLS-1$
        final String pentahoHibConfigPath = PentahoSystem.getApplicationContext()
                .getSolutionPath(hibernateConfigurationFile);

        if (pluginClassloader == null)
            throw new ServiceException(Messages.getString("LifeCycleListener.NoPluginClassloader")); //$NON-NLS-1$

        Thread.currentThread().setContextClassLoader(pluginClassloader);
        final URL contextUrl = pluginClassloader.getResource(PAT_APP_CONTEXT);
        final URL patHibConfigUrl = pluginClassloader.getResource(PAT_HIBERNATE_CONFIG);
        final URL patPluginPropertiesUrl = pluginClassloader.getResource(PAT_PLUGIN_PROPERTIES);
        if (patHibConfigUrl == null)
            throw new ServiceException("File not found: PAT Hibernate Config : " + PAT_HIBERNATE_CONFIG);
        else
            LOG.debug(PAT_PLUGIN_NAME + ": PAT Hibernate Config:" + patHibConfigUrl.toString());

        if (patPluginPropertiesUrl == null)
            throw new ServiceException("File not found: PAT Plugin properties : " + PAT_PLUGIN_PROPERTIES);
        else
            LOG.debug(PAT_PLUGIN_NAME + ": PAT Plugin Properties:" + patPluginPropertiesUrl.toString());

        if (contextUrl != null) {
            String appContextUrl = contextUrl.toString();
            final ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(
                    new String[] { appContextUrl }, false);
            applicationContext.setClassLoader(pluginClassloader);
            applicationContext.setConfigLocation(appContextUrl);
            applicationContext.setAllowBeanDefinitionOverriding(true);

            final Configuration pentahoHibConfig = new Configuration();
            pentahoHibConfig.configure(new File(pentahoHibConfigPath));

            final AnnotationConfiguration patHibConfig = new AnnotationConfiguration();
            patHibConfig.configure(patHibConfigUrl);

            Properties properties = new Properties();
            properties.load(pluginClassloader.getResourceAsStream(PAT_PLUGIN_PROPERTIES));
            String hibernateDialectCfg = (String) properties.get("pat.plugin.datasource.hibernate.dialect");
            String hibernateDialect = null;
            if (StringUtils.isNotBlank(hibernateDialectCfg)) {
                if (hibernateDialectCfg.equals("auto")) {
                    hibernateDialect = pentahoHibConfig.getProperty("dialect");
                } else {
                    hibernateDialect = hibernateDialectCfg;
                }
            }

            if (StringUtils.isNotBlank(hibernateDialect)) {
                patHibConfig.setProperty("hibernate.dialect", hibernateDialect);
                LOG.info(PAT_PLUGIN_NAME + " : using hibernate dialect: " + hibernateDialect);
            }

            String dataSourceType = (String) properties.get("pat.plugin.datasource.type");
            String datasourceResource = null;
            if (StringUtils.isNotEmpty(dataSourceType) && dataSourceType.equals("jdbc")) {
                datasourceResource = PAT_DATASOURCE_JDBC;
                LOG.info(PAT_PLUGIN_NAME + " : using JDBC connection");

            }
            if (StringUtils.isNotEmpty(dataSourceType) && dataSourceType.equals("jndi")) {
                datasourceResource = PAT_DATASOURCE_JNDI;
                LOG.info(PAT_PLUGIN_NAME + " : using JNDI : " + (String) properties.get("jndi.name"));
            }

            XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource(datasourceResource));
            PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer();
            cfg.setLocation(new ClassPathResource(PAT_PLUGIN_PROPERTIES));
            cfg.postProcessBeanFactory(factory);

            XmlBeanFactory bfSession = new XmlBeanFactory(new ClassPathResource(PAT_SESSIONFACTORY), factory);

            PropertyPlaceholderConfigurer cfgSession = new PropertyPlaceholderConfigurer();
            cfgSession.setProperties(patHibConfig.getProperties());
            cfgSession.postProcessBeanFactory(bfSession);

            ClassPathXmlApplicationContext tmpCtxt = new ClassPathXmlApplicationContext();
            tmpCtxt.refresh();
            DefaultListableBeanFactory tmpBf = (DefaultListableBeanFactory) tmpCtxt.getBeanFactory();

            tmpBf.setParentBeanFactory(bfSession);

            applicationContext.setClassLoader(pluginClassloader);
            applicationContext.setParent(tmpCtxt);
            applicationContext.refresh();

            sessionBean.setStandalone(true);
            SessionServlet.setApplicationContext(applicationContext);
            sessionBean.init();

            queryBean.setStandalone(true);
            QueryServlet.setApplicationContext(applicationContext);
            queryBean.init();

            discoveryBean.setStandalone(true);
            DiscoveryServlet.setApplicationContext(applicationContext);
            discoveryBean.init();

            platformBean.setStandalone(true);
            PlatformServlet.setApplicationContext(applicationContext);
            platformBean.init();

            injectPentahoXmlaUrl();
        } else {
            throw new Exception(Messages.getString("LifeCycleListener.AppContextNotFound"));
        }

    } catch (ServiceException e1) {
        LOG.error(e1.getMessage(), e1);
    } catch (ServletException e) {
        LOG.error(e.getMessage(), e);
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
    } finally {
        // reset the classloader of the current thread
        if (origContextClassloader != null) {
            Thread.currentThread().setContextClassLoader(origContextClassloader);
        }
    }
}

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 w w  .  j a  va  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");
    }
}