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

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

Introduction

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

Prototype

@Override
    public void addBeanFactoryPostProcessor(BeanFactoryPostProcessor postProcessor) 

Source Link

Usage

From source file:se.trillian.goodies.spring.HostNameBasedPropertyPlaceHolderConfigurerTest.java

@SuppressWarnings("unchecked")
public void testConfigurer() throws Exception {
    HostNameBasedPropertyPlaceHolderConfigurer configurer = new HostNameBasedPropertyPlaceHolderConfigurer() {
        @Override// w ww .  j  a  v a 2 s. c  om
        protected String getHostName() {
            return "foobar-10";
        }
    };
    configurer.setLocation(new ClassPathResource("/se/trillian/goodies/spring/spring.properties"));
    List<String> hostNameFilters = new ArrayList<String>();
    hostNameFilters.add("nonmatchingfilter=>$1");
    hostNameFilters.add("([a-z]+)-\\d+=>$1");
    configurer.setHostNameFilters(hostNameFilters);
    configurer.setIgnoreUnresolvablePlaceholders(true);
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("context.xml", this.getClass());
    context.addBeanFactoryPostProcessor(configurer);
    context.refresh();
    Map<String, String> fruits = (Map<String, String>) context.getBean("fruits");

    assertEquals("boquila", fruits.get("fruit1"));
    assertEquals("currant", fruits.get("fruit2"));
    assertEquals("blueberry", fruits.get("fruit3"));
    assertEquals("raspberry", fruits.get("fruit4"));
    assertEquals("peach", fruits.get("fruit5"));
    assertEquals("pear", fruits.get("fruit6"));

    Map<String, String> hostname = (Map<String, String>) context.getBean("hostname");
    assertEquals("foobar-10", hostname.get("hostname1"));
    assertEquals("foobar-10", hostname.get("hostname2"));
}

From source file:org.apache.servicemix.nmr.spring.BundleExtTest.java

public void test() {
    final long bundleId = 32;
    BundleExtUrlPostProcessor processor = new BundleExtUrlPostProcessor();
    processor.setBundleContext((BundleContext) Proxy.newProxyInstance(getClass().getClassLoader(),
            new Class[] { BundleContext.class }, new InvocationHandler() {
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    if ("getBundle".equals(method.getName())) {
                        return (Bundle) Proxy.newProxyInstance(getClass().getClassLoader(),
                                new Class[] { Bundle.class }, new InvocationHandler() {
                                    public Object invoke(Object proxy, Method method, Object[] args)
                                            throws Throwable {
                                        if ("getBundleId".equals(method.getName())) {
                                            return bundleId;
                                        }
                                        return null;
                                    }/*  ww w.  ja  va  2  s . com*/
                                });
                    }
                    return null; //To change body of implemented methods use File | Settings | File Templates.
                }
            }));
    ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(new String[] { "bundle.xml" },
            false);
    ctx.addBeanFactoryPostProcessor(processor);
    ctx.refresh();
    Object str = ctx.getBean("string");
    System.err.println(str);
    assertNotNull(str);
    assertEquals("bundle://" + bundleId + "///schema.xsd", str);
}

From source file:net.dfs.remote.main.ClientServicesStarter.java

public final void loadNode() {

    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext();

    PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer();
    configurer.setProperties(props);//from   www. j  a  v  a 2s.c o  m

    context.addBeanFactoryPostProcessor(configurer);
    context.setConfigLocation("net\\dfs\\remote\\filestorage\\spring-client.xml");
    context.refresh();
    context.start();

    /*      FileLocationTrackerImpl hash = new FileLocationTrackerImpl();
          hash.removeAll();
    */
    log.info("Client Started");

    FileReceiverSupport receiveFile = (FileReceiverSupport) context.getBean("receiveFile");

    receiveFile.connectJavaSpace();
    receiveFile.retrieveFile();
}

From source file:org.activiti.crystalball.simulator.impl.simulationexecutor.SimulationRunExecuteJobHandler.java

public void execute(JobEntity job, String configuration, SimulationInstanceEntity simulationInstance,
        CommandContext commandContext) {
    log.log(Level.INFO, "Starting simulation experiment [" + simulationInstance + "] configuration ["
            + configuration + "]");

    SimulationRunEntity simulationRun = commandContext.getSimulationRunManager()
            .findSimulationRunWithReferencesById(configuration);
    SimulationContext.setSimulationRun(simulationRun);

    //initializeSimulationRun
    ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext(
            simulationRun.getSimulation().getSimulationConfigUrl());
    PropertyPlaceholderConfigurer propConfig = new PropertyPlaceholderConfigurer();
    Properties properties = new Properties();
    properties.put("simulationRunId", configuration);
    propConfig.setProperties(properties);
    appContext.addBeanFactoryPostProcessor(propConfig);
    appContext.refresh();/* w  ww. j  a  v  a  2s .com*/

    SimulationRunHelper runHelper = new NoopSimulationRunHelper();
    if (appContext.containsBean("simulationRunHelper"))
        runHelper = (SimulationRunHelper) appContext.getBean("simulationRunHelper");

    try {
        runHelper.before(configuration);

        SimulationRun simRun = (SimulationRun) appContext.getBean("simulationRun");
        simRun.execute(simulationRun);
    } catch (Exception e) {
        log.log(Level.SEVERE, "SimulationRun handling error" + simulationRun, e);
    } finally {

        runHelper.after(configuration);
        appContext.close();
    }
    job.delete();

    SimulationContext.removeSimulationRun();

    // check whether all jobs for given simulationInstance were already executed.
    simulationInstance.checkActivity();

    log.log(Level.INFO, "finished simulation experiment [" + simulationInstance + "] configuration ["
            + configuration + "]");
}

From source file:org.activiti.crystalball.simulator.TwoEnginesWithoutProcessTest.java

@Test
public void test() throws Exception {
    String tempDir = "target";
    FileUtils.copyFile(/*from  ww  w. ja  v a 2s .  c o m*/
            FileUtils.getFile(
                    new String[] { (new StringBuilder()).append(LIVE_DB).append(".h2.db").toString() }),
            FileUtils.getFile(
                    new String[] { (new StringBuilder()).append(tempDir).append("/simulationRunDB-aaa-")
                            .append(Thread.currentThread().getId()).append(".h2.db").toString() }));
    System.setProperty("_SIM_DB_PATH", (new StringBuilder()).append(tempDir).append("/simulationRunDB-aaa-")
            .append(Thread.currentThread().getId()).toString());
    ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext(
            "/org/activiti/crystalball/simulator/SimRun-h2-context.xml");
    PropertyPlaceholderConfigurer propConfig = new PropertyPlaceholderConfigurer();
    Properties properties = new Properties();
    properties.put("simulationRunId", "simulationRunDB-aaa-" + Thread.currentThread().getId());
    propConfig.setProperties(properties);
    appContext.addBeanFactoryPostProcessor(propConfig);
    appContext.refresh();

    SimulationRun simRun = (SimulationRun) appContext.getBean(SimulationRun.class);
    String userId = "user1";
    TaskService taskService = (TaskService) appContext.getBean("taskService");
    TaskService simTaskService = (TaskService) appContext.getBean("simTaskService");
    List<Task> liveTaskList = ((TaskQuery) taskService.createTaskQuery().taskCandidateUser(userId)
            .orderByTaskPriority().desc()).listPage(0, 1);
    List<Task> execTaskList = ((TaskQuery) simTaskService.createTaskQuery().taskCandidateUser(userId)
            .orderByTaskPriority().desc()).listPage(0, 1);
    Assert.assertTrue(liveTaskList.size() == execTaskList.size());
    IdentityService identityService = (IdentityService) appContext.getBean("identityService");
    IdentityService simIdentityService = (IdentityService) appContext.getBean("simIdentityService");
    List<User> users = identityService.createUserQuery().list();
    List<User> simUsers = simIdentityService.createUserQuery().list();
    Assert.assertTrue(users.size() == simUsers.size());
    simRun.execute(new Date(), null);
    appContext.close();
}

From source file:org.openspaces.itest.persistency.cassandra.archive.CassandaraArchiveOperationHandlerTest.java

private void xmlTest(String relativeXmlName) {

    final boolean refreshNow = false;
    final ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
            new String[] { relativeXmlName }, refreshNow);

    PropertyPlaceholderConfigurer propertyConfigurer = new PropertyPlaceholderConfigurer();
    Properties properties = new Properties();
    properties.put("cassandra.keyspace", server.getKeySpaceName());
    properties.put("cassandra.hosts", server.getHost());
    properties.put("cassandra.port", "" + server.getPort());
    properties.put("cassandra.write-consistency", "ALL");
    propertyConfigurer.setProperties(properties);
    context.addBeanFactoryPostProcessor(propertyConfigurer);
    context.refresh();//  w  w w  .java  2  s  .  c o  m

    try {
        final CassandraArchiveOperationHandler archiveHandler = context
                .getBean(CassandraArchiveOperationHandler.class);
        Assert.assertEquals(CassandraConsistencyLevel.ALL, archiveHandler.getWriteConsistency());
        final GigaSpace gigaSpace = context.getBean(org.openspaces.core.GigaSpace.class);
        test(archiveHandler, gigaSpace);
    } finally {
        context.close();
    }
}

From source file:org.openspaces.itest.persistency.cassandra.spring.CassandaraFactoryBeansTest.java

@Test
public void test() {

    final boolean refreshNow = false;
    final ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
            new String[] { TEST_FACTORY_XML }, refreshNow);

    PropertyPlaceholderConfigurer propertyConfigurer = new PropertyPlaceholderConfigurer();
    Properties properties = new Properties();
    properties.setProperty("cassandra.hosts", server.getHost());
    properties.setProperty("cassandra.port", String.valueOf(server.getPort()));
    properties.setProperty("cassandra.keyspace", server.getKeySpaceName());
    properties.setProperty("cassandra.user", "default");
    properties.setProperty("cassandra.password", "default");
    properties.setProperty("cassandra.ds.cluster", "ds_cluster");
    properties.setProperty("cassandra.sync.cluster", "sync_cluster");
    properties.setProperty("cassandra.ds.minconnections", String.valueOf(1));
    properties.setProperty("cassandra.ds.maxconnections", String.valueOf(5));
    properties.setProperty("cassandra.ds.batchlimit", String.valueOf(100));
    properties.setProperty("cassandra.hector.gcgrace", String.valueOf(60 * 60 * 24 * 10));
    properties.setProperty("cassandra.hector.read.consistency.level", CassandraConsistencyLevel.QUORUM.name());
    properties.setProperty("cassandra.hector.write.consistency.level", CassandraConsistencyLevel.ONE.name());
    propertyConfigurer.setProperties(properties);
    context.addBeanFactoryPostProcessor(propertyConfigurer);
    context.refresh();/*w ww.  j a  v a 2 s .c  o  m*/

    try {
        syncEndpoint = context.getBean(CassandraSpaceSynchronizationEndpoint.class);
        dataSource = context.getBean(CassandraSpaceDataSource.class);
        doWork();
    } finally {
        context.close();
    }
}

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

private ApplicationContext loadContext(String[] configLocations, URLClassLoader cl, String contextDisplayName,
        Properties properties) throws Exception {
    ServletContext servletContext = ((ConfigurableWebApplicationContext) this._applicationContext)
            .getServletContext();/*from   w ww.  java  2  s  .c  o  m*/
    //if plugin's classes have been loaded we can go on
    List<ClassPathXmlApplicationContext> ctxList = (List<ClassPathXmlApplicationContext>) servletContext
            .getAttribute("pluginsContextsList");
    if (ctxList == null) {
        ctxList = new ArrayList<ClassPathXmlApplicationContext>();
        servletContext.setAttribute("pluginsContextsList", ctxList);
    }
    ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();
    ClassPathXmlApplicationContext newContext = null;
    try {
        //create a new spring context with the classloader and the paths defined as parameter in pluginsInstallerContext.xml.
        //The new context is given the default webapplication context as its parent  
        Thread.currentThread().setContextClassLoader(cl);
        newContext = new ClassPathXmlApplicationContext();
        //ClassPathXmlApplicationContext newContext = new ClassPathXmlApplicationContext(configLocations, applicationContext);    
        PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer();
        configurer.setProperties(properties);
        newContext.addBeanFactoryPostProcessor(configurer);
        newContext.setClassLoader(cl);
        newContext.setParent(this._applicationContext);
        String[] configLocs = new String[] { "classpath:spring/restServerConfig.xml",
                "classpath:spring/baseSystemConfig.xml" };
        newContext.setConfigLocations(configLocs);
        newContext.refresh();
        BaseConfigManager baseConfigManager = (BaseConfigManager) ((ConfigurableWebApplicationContext) this._applicationContext)
                .getBean("BaseConfigManager");
        baseConfigManager.init();
        newContext.setConfigLocations(configLocations);
        newContext.refresh();
        newContext.setDisplayName(contextDisplayName);
        ClassPathXmlApplicationContext currentCtx = (ClassPathXmlApplicationContext) this
                .getStoredContext(contextDisplayName);
        if (currentCtx != null) {
            currentCtx.close();
            ctxList.remove(currentCtx);
        }
        ctxList.add(newContext);

    } catch (Exception e) {
        _logger.error("Unexpected error loading application context: " + e.getMessage());
        e.printStackTrace();
        throw e;
    } finally {
        Thread.currentThread().setContextClassLoader(currentClassLoader);
    }
    return newContext;
}

From source file:org.jumpmind.symmetric.ClientSymmetricEngine.java

@Override
protected void init() {
    try {/*w  w  w  .j  a  v  a  2  s  .com*/
        LogSummaryAppenderUtils.registerLogSummaryAppender();

        super.init();

        this.dataSource = platform.getDataSource();

        PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer();
        configurer.setProperties(parameterService.getAllParameters());

        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(springContext);
        ctx.addBeanFactoryPostProcessor(configurer);

        List<String> extensionLocations = new ArrayList<String>();
        extensionLocations.add("classpath:/symmetric-ext-points.xml");
        if (registerEngine) {
            extensionLocations.add("classpath:/symmetric-jmx.xml");
        }

        String xml = parameterService.getString(ParameterConstants.EXTENSIONS_XML);
        File file = new File(parameterService.getTempDirectory(), "extension.xml");
        FileUtils.deleteQuietly(file);
        if (isNotBlank(xml)) {
            try {
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                factory.setValidating(false);
                factory.setNamespaceAware(true);
                DocumentBuilder builder = factory.newDocumentBuilder();
                // the "parse" method also validates XML, will throw an exception if misformatted
                builder.parse(new InputSource(new StringReader(xml)));
                FileUtils.write(file, xml, false);
                extensionLocations.add("file:" + file.getAbsolutePath());
            } catch (Exception e) {
                log.error("Invalid " + ParameterConstants.EXTENSIONS_XML + " parameter.");
            }
        }

        try {
            ctx.setConfigLocations(extensionLocations.toArray(new String[extensionLocations.size()]));
            ctx.refresh();

            this.springContext = ctx;

            ((ClientExtensionService) this.extensionService).setSpringContext(springContext);
            this.extensionService.refresh();
        } catch (Exception ex) {
            log.error(
                    "Failed to initialize the extension points.  Please fix the problem and restart the server.",
                    ex);
        }
    } catch (RuntimeException ex) {
        destroy();
        throw ex;
    }
}

From source file:org.springframework.richclient.application.ApplicationLauncher.java

/**
 * Returns an {@code ApplicationContext}, loaded from the bean definition
 * files at the classpath-relative locations specified by
 * {@code configLocations}./*from   ww w .java2s . c o  m*/
 *
 * <p>
 * If a splash screen has been created, the application context will be
 * loaded with a bean post processor that will notify the splash screen's
 * progress monitor as each bean is initialized.
 * </p>
 *
 * @param configLocations The classpath-relative locations of the files from
 * which the application context will be loaded.
 *
 * @return The main application context, never null.
 */
private ApplicationContext loadRootApplicationContext(String[] configLocations, MessageSource messageSource) {
    final ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(
            configLocations, false);

    if (splashScreen instanceof MonitoringSplashScreen) {
        final ProgressMonitor tracker = ((MonitoringSplashScreen) splashScreen).getProgressMonitor();

        applicationContext.addBeanFactoryPostProcessor(
                new ProgressMonitoringBeanFactoryPostProcessor(tracker, messageSource));

    }

    applicationContext.refresh();

    return applicationContext;
}