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

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

Introduction

In this page you can find the example usage for org.springframework.context.support FileSystemXmlApplicationContext 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.browseengine.bobo.api.BoboIndexReader.java

private static Collection<FacetHandler<?>> loadFromIndex(File file, WorkArea workArea) throws IOException {
    // File springFile = new File(file, SPRING_CONFIG);
    // FileSystemXmlApplicationContext appCtx =
    //   new FileSystemXmlApplicationContext("file:" + springFile.getAbsolutePath());
    //return (Collection<FacetHandler<?>>) appCtx.getBean("handlers");

    Set<Entry<Class<?>, Object>> entries = workArea.map.entrySet();
    FileSystemXmlApplicationContext appCtx = new FileSystemXmlApplicationContext();
    for (Entry<Class<?>, Object> entry : entries) {
        Object obj = entry.getValue();
        if (obj instanceof ClassLoader) {
            appCtx.setClassLoader((ClassLoader) obj);
            break;
        }/*  w  ww  .j  a  va  2  s. c o m*/
    }

    String absolutePath = file.getAbsolutePath();
    String partOne = absolutePath.substring(0, absolutePath.lastIndexOf(File.separator));
    String partTwo = URLEncoder.encode(absolutePath.substring(absolutePath.lastIndexOf(File.separator) + 1),
            "UTF-8");
    absolutePath = partOne + File.separator + partTwo;

    File springFile = new File(new File(absolutePath), SPRING_CONFIG);
    appCtx.setConfigLocation("file:" + springFile.getAbsolutePath());
    appCtx.refresh();

    return (Collection<FacetHandler<?>>) appCtx.getBean("handlers");

}

From source file:org.pentaho.agilebi.spoon.visualizations.VisualizationManager.java

protected void loadVisualizationFile(File file) {
    try {/*from  w  ww  .j  a  v a  2 s  .  co m*/
        FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext(
                new String[] { file.getPath() }, false);
        context.setClassLoader(getClass().getClassLoader());
        context.refresh();
        Map beans = context.getBeansOfType(IVisualization.class);
        for (Object key : beans.keySet()) {
            IVisualization vis = (IVisualization) beans.get(key);
            if (vis.getOrder() >= 0) {
                visualizations.add(vis);
            }
        }
    } catch (XmlBeanDefinitionStoreException e) {
        // TODO: introduce logging
        e.printStackTrace();
    }
}

From source file:org.red5.server.Bootstrap.java

/**
 * Launch Red5 under it's own classloader
 *  //from   w w  w.ja  va 2s .  com
 */
public void launch() {
    try {
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        //System.out.printf("Launch - Thread classloader: %s\n", loader);

        //create red5 app context
        FileSystemXmlApplicationContext ctx = new FileSystemXmlApplicationContext(
                new String[] { "classpath:/red5.xml" }, false);
        ctx.setClassLoader(loader);

        //install the slf4j bridge (mostly for JUL logging)
        SLF4JBridgeHandler.install();
        //we create the logger here so that it is instanced inside the expected 
        //classloader
        Logger log = Red5LoggerFactory.getLogger(Bootstrap.class);
        //version info banner
        log.info("{} (http://www.osflash.org/red5)", Red5.getVersion());
        //see which logger binder has been instanced
        log.trace("Logger binder: {}", StaticLoggerBinder.getSingleton().getClass().getName());

        //refresh must be called before accessing the bean factory
        ctx.refresh();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.red5.server.Launcher.java

/**
 * Launch Red5 under it's own classloader
 *//*from w  w w  . ja va2s.c  o m*/
public void launch() {
    System.out.printf("Root: %s\nDeploy type: %s\nLogback selector: %s\n", System.getProperty("red5.root"),
            System.getProperty("red5.deployment.type"), System.getProperty("logback.ContextSelector"));
    try {
        // install the slf4j bridge (mostly for JUL logging)
        SLF4JBridgeHandler.install();
        // we create the logger here so that it is instanced inside the expected classloader
        // check for the logback disable flag
        boolean useLogback = Boolean.valueOf(System.getProperty("useLogback", "true"));
        Red5LoggerFactory.setUseLogback(useLogback);
        // get the first logger
        Logger log = Red5LoggerFactory.getLogger(Launcher.class);
        // version info banner
        log.info("{} (http://code.google.com/p/red5/)", Red5.getVersion());
        // pimp red5
        System.out.printf("%s (http://code.google.com/p/red5/)\n", Red5.getVersion());
        // create red5 app context
        FileSystemXmlApplicationContext ctx = new FileSystemXmlApplicationContext(
                new String[] { "classpath:/red5.xml" }, false);
        // set the current threads classloader as the loader for the factory/appctx
        ctx.setClassLoader(Thread.currentThread().getContextClassLoader());
        // refresh must be called before accessing the bean factory
        ctx.refresh();
        /*
        if (log.isTraceEnabled()) {
           String[] names = ctx.getBeanDefinitionNames();
           for (String name : names) {
              log.trace("Bean name: {}", name);
           }
        }
        */
    } catch (Throwable t) {
        System.out.printf("Exception %s\n", t);
        System.exit(9999);
    }
}

From source file:org.apache.oodt.cas.catalog.cli.action.LoadCatalogRepositoryCliAction.java

@Override
public void execute(ActionMessagePrinter printer) throws CmdLineActionException {
    try {//from w w w. j a  v  a 2  s. c o  m
        Validate.notNull(catalogRepositoryId, "Must specify catalogRepositoryId");
        Validate.notNull(beanRepo, "Must specify beanRepo");

        FileSystemXmlApplicationContext appContext = new FileSystemXmlApplicationContext(
                new String[] { this.beanRepo }, false);
        appContext.setClassLoader(new Serializer().getClassLoader());
        appContext.refresh();
        CatalogRepositoryFactory factory = (CatalogRepositoryFactory) appContext
                .getBean(this.catalogRepositoryId, CatalogRepositoryFactory.class);
        CatalogRepository catalogRepository = factory.createRepository();
        Set<Catalog> catalogs = catalogRepository.deserializeAllCatalogs();
        printer.println("Deserialized Catalogs: " + catalogs.toString());
        for (Catalog catalog : catalogs) {
            printer.println("Adding Catalog: " + catalog);
            getClient().addCatalog(catalog);
        }
    } catch (Exception e) {
        throw new CmdLineActionException("Failed to load catalogs from bean repo : " + e.getMessage(), e);
    }
}

From source file:org.apache.oodt.cas.catalog.cli.action.LoadCatalogsCliAction.java

@Override
public void execute(ActionMessagePrinter printer) throws CmdLineActionException {
    try {//  w  w w .j  av  a 2 s  .  c  om
        Validate.notNull(beanRepo, "Must specify beanRepo");

        FileSystemXmlApplicationContext repoAppContext = new FileSystemXmlApplicationContext(
                new String[] { this.beanRepo }, false);
        repoAppContext.setClassLoader(new Serializer().getClassLoader());
        repoAppContext.refresh();
        @SuppressWarnings("unchecked")
        Map<String, Catalog> catalogs = repoAppContext.getBeansOfType(Catalog.class);
        for (Catalog catalog : catalogs.values()) {
            printer.println("Adding catalog: " + catalog.getId());
            getClient().addCatalog(catalog);
        }
    } catch (Exception e) {
        throw new CmdLineActionException("Failed to load catalogs : " + e.getMessage(), e);
    }
}

From source file:org.springframework.data.hadoop.admin.util.HadoopWorkflowUtils.java

/**
 * create and register Spring Batch job//from   w  w  w  .j a  v  a 2s.  co m
 * 
 * @param context root application context
 * @param artifacts workflow artifacts which include workflow descriptor and class loader information.
 * @throws Exception
 */
public static void createAndRegisterSpringBatchJob(ApplicationContext context,
        final WorkflowArtifacts artifacts) throws SpringHadoopAdminWorkflowException {
    if (context == null) {
        logger.warn("root applicaton context is null");
        throw new SpringHadoopAdminWorkflowException("root applicaton context is null");
    }
    String workflowDescriptor = getWorkflowDescriptor(artifacts);
    logger.info("create spring batch job:" + workflowDescriptor + ", classloader:"
            + artifacts.getWorkflowClassLoader());

    final FileSystemXmlApplicationContext ctx = new FileSystemXmlApplicationContext();
    ctx.setClassLoader(artifacts.getWorkflowClassLoader());
    ctx.setConfigLocation(HadoopWorkflowUtils.fileURLPrefix + workflowDescriptor);

    try {
        SimpleJob job = new SimpleJob(generateSpringBatchJobName(artifacts));
        TaskletStep step = new TaskletStep(springHadoopTaskName);
        SimpleSpringHadoopTasklet tasklet = new SimpleSpringHadoopTasklet();
        tasklet.setContext(ctx);
        step.setTasklet(tasklet);
        JobRepository jobRepository = context.getBean(JobRepository.class);
        DataSourceTransactionManager transactionManager = context.getBean("transactionManager",
                DataSourceTransactionManager.class);
        step.setTransactionManager(transactionManager);
        step.setJobRepository(jobRepository);
        step.afterPropertiesSet();
        job.addStep(step);
        JobRegistry jobRegistry = context.getBean("jobRegistry", JobRegistry.class);
        job.setJobRepository(jobRepository);
        job.afterPropertiesSet();
        JobFactory jobFactory = new ReferenceJobFactory(job);
        jobRegistry.register(jobFactory);
    } catch (Exception e) {
        logger.warn("create and register Spring Batch Job failed");
        throw new SpringHadoopAdminWorkflowException("create and register Spring Batch Job failed", e);
    }
}

From source file:org.springframework.data.hadoop.admin.workflow.support.FileSystemApplicationContextFactory.java

/**
 * Creates an {@link ApplicationContext} from the provided path.
 * // w  w  w  .  j a va 2s  .c o m
 * @see ApplicationContextFactory#createApplicationContext()
 */
public ConfigurableApplicationContext createApplicationContext() {
    logger.info("resource is:" + resource);
    if (resource == null) {
        return parent;
    }
    try {
        logger.info("create application context, resource:" + resource.getFile().getAbsolutePath()
                + ", classloader:" + this.beanClassLoader + ". Parent is:" + parent);
        FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext();
        context.setClassLoader(this.beanClassLoader);
        context.setParent(parent);
        context.setConfigLocation(HadoopWorkflowUtils.fileURLPrefix + resource.getFile().getAbsolutePath());
        context.refresh();
        return context;
    } catch (Exception e) {
        try {
            logger.error(
                    "create application context fail. with resource:" + resource.getFile().getAbsolutePath(),
                    e);
        } catch (IOException e1) {
            logger.error("log error", e1);
        }
    }
    return parent;
}