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

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

Introduction

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

Prototype

@Override
@Nullable
public ClassLoader getClassLoader() 

Source Link

Document

Return the ClassLoader to load class path resources with.

Usage

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

public void testSeedDB() throws Exception {

    if (hasRun) {
        return;/*from  www  .j av a 2  s  .  co 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: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();/*from   ww w  .j av  a 2 s .  c om*/

    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.easyrec.plugin.container.PluginRegistry.java

@SuppressWarnings({ "unchecked" })
public PluginVO checkPlugin(byte[] file) throws Exception {
    PluginVO plugin;/*from w  w  w. ja  v  a2 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.plugins.jpcomponentinstaller.aps.system.services.installer.DefaultComponentInstaller.java

private void installPlugin(AvailableArtifact availableArtifact, String version, InputStream is)
        throws Exception {
    ServletContext servletContext = ((ConfigurableWebApplicationContext) this._applicationContext)
            .getServletContext();/*from w  ww .j av a2  s  .  c o  m*/
    String filename = availableArtifact.getGroupId() + "_" + availableArtifact.getArtifactId() + "_" + version
            + ".war";
    String artifactName = availableArtifact.getArtifactId();
    String appRootPath = servletContext.getRealPath("/");
    File destDir = new File(appRootPath);
    String tempDirPath = appRootPath + "componentinstaller" + File.separator + artifactName;
    File artifactFile = new File(appRootPath + "componentinstaller" + File.separator + filename);

    FileUtils.copyInputStreamToFile(is, artifactFile);
    this.extractArchiveFile(artifactFile, tempDirPath);
    File artifactFileRootDir = new File(
            artifactFile.getParentFile().getAbsolutePath() + File.separator + artifactName);

    List<File> tilesFiles = (List<File>) FileUtils.listFiles(artifactFileRootDir,
            FileFilterUtils.suffixFileFilter("-tiles.xml"), FileFilterUtils.trueFileFilter());
    if (tilesFiles == null) {
        tilesFiles = new ArrayList<File>();
    }

    File tempArtifactRootDir = this.extractAllJars(destDir, artifactName);
    List<File> pluginSqlFiles = (List<File>) FileUtils.listFiles(tempArtifactRootDir, new String[] { "sql" },
            true);
    List<File> pluginXmlFiles = (List<File>) FileUtils.listFiles(tempArtifactRootDir, new String[] { "xml" },
            true);

    List<File> mainAppJarLibraries = (List<File>) FileUtils.listFiles(
            new File(destDir.getAbsolutePath() + File.separator + "WEB-INF" + File.separator + "lib"),
            new String[] { "jar" }, true);
    List<File> pluginJarLibraries = (List<File>) FileUtils.listFiles(artifactFileRootDir,
            new String[] { "jar" }, true);
    pluginJarLibraries = filterOutDuplicateLibraries(mainAppJarLibraries, pluginJarLibraries);

    FileUtils.copyDirectory(artifactFileRootDir, destDir);

    List<File> allFiles = new ArrayList<File>();
    File systemParamsFile = FileUtils.getFile(destDir + File.separator + "WEB-INF" + File.separator + "conf",
            "systemParams.properties");
    allFiles.add(systemParamsFile);
    allFiles.addAll(pluginJarLibraries);
    allFiles.addAll(pluginSqlFiles);
    allFiles.addAll(pluginXmlFiles);
    //The classloader's content is stored in servlet context and 
    //updated every time so the classloader will eventually contain 
    //the classes and resources of all the installed plugins
    List<URL> urlList = (List<URL>) servletContext.getAttribute("pluginInstallerURLList");
    if (urlList == null) {
        urlList = new ArrayList<URL>();
        servletContext.setAttribute("pluginInstallerURLList", urlList);
    }
    Set<File> jarSet = (Set<File>) servletContext.getAttribute("pluginInstallerJarSet");
    if (jarSet == null) {
        jarSet = new HashSet<File>();
        servletContext.setAttribute("pluginInstallerJarSet", jarSet);
    }
    jarSet.addAll(pluginJarLibraries);
    URLClassLoader cl = getURLClassLoader(urlList, allFiles.toArray(new File[0]), servletContext);
    loadClasses(jarSet.toArray(new File[0]), cl);
    servletContext.setAttribute("componentInstallerClassLoader", cl);
    ComponentManager.setComponentInstallerClassLoader(cl);

    //load plugin and dependencies contexts 
    File componentFile = this.getFileFromArtifactJar(tempArtifactRootDir, "component.xml");
    String componentToInstallName = this.getComponentName(componentFile);

    InitializerManager initializerManager = (InitializerManager) this._applicationContext
            .getBean("InitializerManager");
    initializerManager.reloadCurrentReport();
    SystemInstallationReport currentReport = initializerManager.getCurrentReport();
    if (null != currentReport.getComponentReport(componentToInstallName, false)) {
        currentReport.removeComponentReport(componentToInstallName);
        this.saveReport(currentReport);
        initializerManager.reloadCurrentReport();
    }

    List<String> components = this.getAllComponents(artifactFileRootDir);

    Properties properties = new Properties();
    properties.load(new FileInputStream(systemParamsFile));

    for (String componentName : components) {
        List<String> configLocs = new ArrayList<String>();
        InitializerManager currenInitializerManager = (InitializerManager) _applicationContext
                .getBean("InitializerManager");
        currentReport = currenInitializerManager.getCurrentReport();
        ComponentInstallationReport cir = currentReport.getComponentReport(componentName, false);
        if (null != cir && cir.getStatus().equals(SystemInstallationReport.Status.UNINSTALLED)) {
            currentReport.removeComponentReport(componentName);
            this.saveReport(currentReport);
            currenInitializerManager.reloadCurrentReport();
        }

        configLocs = this.getConfigPaths(artifactFileRootDir, componentName);
        if (configLocs.isEmpty()) {
            continue;
        }

        ClassPathXmlApplicationContext newContext = (ClassPathXmlApplicationContext) loadContext(
                (String[]) configLocs.toArray(new String[0]), cl, componentName, properties);

        this.reloadActionsDefinitions(newContext);
        this.reloadResourcsBundles(newContext, servletContext);
        TilesContainer container = TilesAccess.getContainer(servletContext);
        this.reloadTilesDefinitions(tilesFiles, container);

        currenInitializerManager.reloadCurrentReport();
        ComponentManager componentManager = (ComponentManager) _applicationContext.getBean("ComponentManager");
        ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();
        try {
            Thread.currentThread().setContextClassLoader(newContext.getClassLoader());
            componentManager.refresh();
        } catch (Exception e) {
            throw e;
        } finally {
            Thread.currentThread().setContextClassLoader(currentClassLoader);
        }
    }
}

From source file:org.entando.entando.plugins.jpcomponentinstaller.aps.system.services.installer.DefaultComponentInstaller.java

private void reloadActionsDefinitions(ClassPathXmlApplicationContext context) throws Exception {
    ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();
    try {//from w w w.  j  a  va2  s .  c o m
        Thread.currentThread().setContextClassLoader(context.getClassLoader());
        Dispatcher.getInstance().getConfigurationManager().reload();
    } catch (Exception e) {
        throw e;
    } finally {
        Thread.currentThread().setContextClassLoader(currentClassLoader);
    }
}

From source file:org.entando.entando.plugins.jpcomponentinstaller.aps.system.services.installer.DefaultComponentInstaller.java

private void reloadResourcsBundles(ClassPathXmlApplicationContext context, ServletContext servletContext)
        throws Exception {
    TextProviderSupport.servletContext = servletContext;
    ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();
    try {//from  ww w  .j a v a  2s  .  c  o  m
        Thread.currentThread().setContextClassLoader(context.getClassLoader());
        LocalizedTextUtil.setDelegatedClassLoader(context.getClassLoader());
        addPluginRecourceBundle(servletContext);
    } catch (Exception e) {
        throw e;
    } finally {
        Thread.currentThread().setContextClassLoader(currentClassLoader);
    }
}