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

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

Introduction

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

Prototype

public FileSystemXmlApplicationContext(String[] configLocations, boolean refresh) throws BeansException 

Source Link

Document

Create a new FileSystemXmlApplicationContext, loading the definitions from the given XML files.

Usage

From source file:org.trpr.platform.batch.impl.spring.BatchConfigInfo.java

/**
 * Loads and returns an AbstractApplicationContext using data contained in this class
 * @return the job's AbstractApplicationContext
 *///from   w ww.j  a v a  2s .c o  m
protected AbstractApplicationContext loadJobContext(ClassLoader classLoader) {
    ClassLoader existingTCCL = Thread.currentThread().getContextClassLoader();
    // set the custom classloader as the tccl for loading the job
    Thread.currentThread().setContextClassLoader(classLoader);
    // add the "file:" prefix to file names to get around strange behavior of FileSystemXmlApplicationContext that converts absolute path 
    // to relative path
    this.jobContext = new FileSystemXmlApplicationContext(
            new String[] { FILE_PREFIX + jobConfigXML.getAbsolutePath() },
            SpringBatchComponentContainer.getCommonBatchBeansContext());
    // now reset the thread's TCCL to the one that existed prior to loading the job
    Thread.currentThread().setContextClassLoader(existingTCCL);
    return this.jobContext;
}

From source file:it.cilea.osd.jdyna.utils.ImportUtils.java

/**
 * Effettua l'import di una specifica tipologia di oggetti a partire dalla
 * loro definizione xml (Spring)//w ww.j av a2  s. c  om
 * 
 * @param <T>
 *            la classe di oggetti da importare
 * @param importFilePath
 *            il path al file (sul server) contenente la definizione xml
 *            degli oggetti
 * @param clazz
 *            la classe di oggetti da importare
 * @return il risultato dell'importazione (num. successi, num. fallimenti,
 *         eccezioni occorse)
 */
public <T extends Identifiable> ImportResult importSingolaClasseOggetti(String importFilePath, Class<T> clazz) {

    ImportResult importResult = new ImportResult();

    ApplicationContext context = new FileSystemXmlApplicationContext(new String[] { "file:" + importFilePath },
            appContext);

    String[] definitions = context.getBeanNamesForType(clazz);

    for (String definition : definitions) {
        try {
            T oggettoDaImportare = (T) context.getBean(definition);

            if (clazz.isAssignableFrom(AnagraficaSupport.class)) {
                AnagraficaObject oggetto = (AnagraficaObject) oggettoDaImportare;
                applicationService.fitAnagrafica(oggetto);
                //formulaManager.ricalcolaFormule(oggetto);
                oggetto.pulisciAnagrafica();
            }
            applicationService.saveOrUpdate(clazz, oggettoDaImportare);
            importResult.addSuccess();
        } catch (Exception ecc) {
            logger.warn("Errore nel salvataggio della definizione di " + clazz.getSimpleName() + " - bean id: "
                    + definition, ecc);

            importResult.addFail(ecc);
        }
    }
    return importResult;
}

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

protected void loadVisualizationFile(File file) {
    try {//  ww  w .  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:com.flipkart.phantom.task.spi.registry.HandlerConfigInfo.java

/**
 * Loads and returns an AbstractApplicationContext using data contained in this class
 * @return the proxy handler's AbstractApplicationContext
 *//*from  w w w. ja  v a  2  s  . com*/
public AbstractApplicationContext loadProxyHandlerContext(ClassLoader classLoader,
        AbstractApplicationContext applicationContext) {
    ClassLoader existingTCCL = Thread.currentThread().getContextClassLoader();
    // set the custom classloader as the tccl for loading the proxy handler
    Thread.currentThread().setContextClassLoader(classLoader);
    // add the "file:" prefix to file names to get around strange behavior of FileSystemXmlApplicationContext that converts absolute path 
    // to relative path
    this.proxyHandlerContext = new FileSystemXmlApplicationContext(
            new String[] { FILE_PREFIX + this.xmlConfigFile.getAbsolutePath() }, applicationContext);
    // now reset the thread's TCCL to the one that existed prior to loading the proxy handler
    Thread.currentThread().setContextClassLoader(existingTCCL);
    return this.proxyHandlerContext;
}

From source file:com.flipkart.aesop.runtime.spring.registry.ServerContainerConfigInfo.java

/**
 * Loads and returns an AbstractApplicationContext using data contained in this class
 * @return the runtime's AbstractApplicationContext
 *///from ww w .  j  a v a2 s. com
public AbstractApplicationContext loadRuntimeContext(ClassLoader classLoader,
        AbstractApplicationContext applicationContext) {
    ClassLoader existingTCCL = Thread.currentThread().getContextClassLoader();
    // set the custom classloader as the tccl for loading the runtime
    Thread.currentThread().setContextClassLoader(classLoader);
    // add the "file:" prefix to file names to get around strange behavior of FileSystemXmlApplicationContext that converts absolute path 
    // to relative path
    this.runtimeContext = new FileSystemXmlApplicationContext(
            new String[] { FILE_PREFIX + this.xmlConfigFile.getAbsolutePath() }, applicationContext);
    // now reset the thread's TCCL to the one that existed prior to loading the runtime
    Thread.currentThread().setContextClassLoader(existingTCCL);
    return this.runtimeContext;
}

From source file:org.trpr.platform.runtime.impl.bootstrapext.spring.ApplicationContextFactory.java

/**
 * Interface method implementation. Creates and loads a Spring ApplicationContext for each property specified in {@link #getAllProperties()}
 * @see org.trpr.platform.runtime.spi.bootstrapext.BootstrapExtension#init()
 *//*  ww  w.jav a2s .  c om*/
public void init() {
    // Iterate through the properties to get ApplicationContext name and the corresponding file name
    for (String key : this.getAllProperties().keySet()) {
        String fileName = this.getAllProperties().get(key);
        try {
            File springBeansFile = FileLocator.findUniqueFile(fileName);
            // add the "file:" prefix to file names to get around strange behavior of FileSystemXmlApplicationContext that converts 
            // absolute path to relative path

            // Set the commons beans context as the parent of all application contexts created through this ApplicationContextFactory
            AbstractApplicationContext appContext = new FileSystemXmlApplicationContext(
                    new String[] { FILE_PREFIX + springBeansFile.getAbsolutePath() }, getCommonBeansContext());
            ApplicationContextFactory.appContextMap.put(key.toLowerCase(), appContext);

        } catch (Exception e) { // blanket catch for all checked and unchecked exceptions
            LOGGER.error("Error loading ApplicationContext. [Name][Path] : [" + key + "][" + fileName
                    + "].Error is : " + e.getMessage(), e);
            this.bootstrapOutcome = BootstrapExtension.VETO_BOOTSTRAP;
            return;
        }
    }
}

From source file:cross.applicationContext.DefaultApplicationContextFactory.java

/**
 * Creates a new application context from the current list of
 * <code>applicationContextPaths</code>, interpreted as file system
 * resources, and the current/*from  w w  w .  java2 s . c o m*/
 * <code>configuration</code>.
 *
 * @return the application context
 * @throws BeansException if any beans are not configured correctly
 */
public ApplicationContext createApplicationContext() throws BeansException {
    AbstractRefreshableApplicationContext context = null;
    try {
        final ConfiguringBeanPostProcessor cbp = new ConfiguringBeanPostProcessor();
        cbp.setConfiguration(configuration);
        context = new FileSystemXmlApplicationContext(
                applicationContextPaths.toArray(new String[applicationContextPaths.size()]), context);
        context.addBeanFactoryPostProcessor(new BeanFactoryPostProcessor() {
            @Override
            public void postProcessBeanFactory(ConfigurableListableBeanFactory clbf) throws BeansException {
                clbf.addBeanPostProcessor(cbp);
            }
        });
        context.refresh();
    } catch (BeansException e2) {
        throw e2;
    }
    return context;
}

From source file:it.cilea.osd.jdyna.web.controller.ImportConfigurazione.java

/** Performa l'import da file xml di configurazioni di oggetti;
 *  Sull'upload del file la configurazione dell'oggetto viene caricato come contesto di spring
 *  e salvate su db./*www  .  j  a  v  a 2s .  c  o  m*/
 */
@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object object,
        BindException errors) throws RuntimeException, IOException {

    FileUploadConfiguration bean = (FileUploadConfiguration) object;
    MultipartFile file = (CommonsMultipartFile) bean.getFile();
    File a = null;

    //creo il file temporaneo che sara' caricato come contesto di spring per caricare la configurazione degli oggetti
    a = File.createTempFile("jdyna", ".xml", new File(path));
    file.transferTo(a);

    ApplicationContext context = null;
    try {
        context = new FileSystemXmlApplicationContext(new String[] { "file:" + a.getAbsolutePath() },
                getApplicationContext());

    } catch (XmlBeanDefinitionStoreException exc) {
        //cancello il file dalla directory temporanea
        logger.warn("Errore nell'importazione della configurazione dal file: " + file.getOriginalFilename(),
                exc);
        a.delete();
        saveMessage(request, getText("action.file.nosuccess.upload", new Object[] { exc.getMessage() },
                request.getLocale()));
        return new ModelAndView(getErrorView());
    }
    //cancello il file dalla directory temporanea
    a.delete();
    String[] tpDefinitions = context.getBeanNamesForType(tpClass);
    //la variabile i conta le tipologie caricate con successo
    int i = 0;
    //la variabile j conta le tipologie non caricate
    int j = 0;
    for (String tpNameDefinition : tpDefinitions) {
        try {
            TP tipologiaDaImportare = (TP) context.getBean(tpNameDefinition);
            applicationService.saveOrUpdate(tpClass, tipologiaDaImportare);
        } catch (Exception ecc) {
            saveMessage(request, getText("action.file.nosuccess.metadato.upload",
                    new Object[] { ecc.getMessage() }, request.getLocale()));
            j++;
            i--;
        }
        i++;
    }

    String[] areeDefinitions = context.getBeanNamesForType(areaClass);
    int w = 0;
    int v = 0;
    for (String areaNameDefinition : areeDefinitions) {
        try {
            A areaDaImportare = (A) context.getBean(areaNameDefinition);
            applicationService.saveOrUpdate(areaClass, areaDaImportare);
        } catch (Exception ecc) {
            saveMessage(request, getText("action.file.nosuccess.metadato.upload",
                    new Object[] { ecc.getMessage() }, request.getLocale()));
            v++;
            w--;
        }
        w++;
    }
    // check sulla tipologia poiche' ci sono oggetti che non hanno la tipologia tipo Opera e Parte
    if (typeClass != null) {
        String[] typeDefinitions = context.getBeanNamesForType(typeClass);
        int r = 0;
        int t = 0;
        for (String typeDefinition : typeDefinitions) {
            try {
                TY tipologiaDaImportare = (TY) context.getBean(typeDefinition);
                applicationService.saveOrUpdate(typeClass, tipologiaDaImportare);
            } catch (Exception ecc) {
                saveMessage(request, getText("action.file.nosuccess.metadato.upload",
                        new Object[] { ecc.getMessage() }, request.getLocale()));
                t++;
                r--;
            }
            r++;
        }

        saveMessage(request,
                getText("action.file.success.upload.tipologie",
                        new Object[] { new String("Totale Tipologie:" + (t + r) + " [" + r
                                + "caricate con successo/" + t + " fallito caricamento]") },
                        request.getLocale()));

    }

    saveMessage(request,
            getText("action.file.success.upload",
                    new Object[] {
                            new String("Totale TP:" + (i + j) + "" + "[" + i + " caricate con successo/" + j
                                    + " fallito caricamento]"),
                            new String("Totale Aree:" + (w + v) + " [" + w + "caricate con successo/" + v
                                    + " fallito caricamento]") },
                    request.getLocale()));

    return new ModelAndView(getDetailsView());
}

From source file:org.red5.server.plugin.icy.ICYPlugin.java

public void doStart() throws Exception {
    log.debug("Start");
    //create app context
    try {//from   ww  w. ja  va2s  .com
        nsvContext = new FileSystemXmlApplicationContext(new String[] { "${red5.root}/plugins/icy.xml" }, true);
    } catch (Exception e) {
        nsvContext = new FileSystemXmlApplicationContext(new String[] { "classpath:/icy.xml" }, true);
    }
}

From source file:org.trpr.platform.batch.impl.spring.SpringBatchComponentContainer.java

/**
 * Interface method implementation. Locates and loads all configured jobs.
 * @see ComponentContainer#init()// w ww.  j a  v a 2  s  . c o m
 */
public void init() throws PlatformException {

    // add the "file:" prefix to file name to get around strange behavior of FileSystemXmlApplicationContext that converts absolute path 
    // to relative path
    // The common batch beans context is loaded first using the Platform common beans context as parent
    String commonContextFile = FILE_PREFIX
            + FileLocator.findUniqueFile(BatchFrameworkConstants.COMMON_BATCH_CONFIG).getAbsolutePath();
    this.commonBatchBeansContext = new FileSystemXmlApplicationContext(new String[] { commonContextFile },
            ApplicationContextFactory.getCommonBeansContext());
    // add the common batch beans to the contexts list
    this.jobsContextList.add(this.commonBatchBeansContext);

    // locate and load the individual job bean XML files using the common batch beans context as parent
    File[] jobBeansFiles = FileLocator.findFiles(BatchFrameworkConstants.SPRING_BATCH_CONFIG);
    for (File jobBeansFile : jobBeansFiles) {
        // add the "file:" prefix to file names to get around strange behavior of FileSystemXmlApplicationContext that converts absolute path 
        // to relative path
        this.jobsContextList.add(new FileSystemXmlApplicationContext(
                new String[] { FILE_PREFIX + jobBeansFile.getAbsolutePath() }, this.commonBatchBeansContext));
    }

}