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

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

Introduction

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

Prototype

@Override
    public void refresh() throws BeansException, IllegalStateException 

Source Link

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);//from   w  w  w.  j a  va2 s  . c o  m
    ctx.setConfigLocation("spring-context.xml");
    ctx.refresh();
    return ctx;
}

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

@SuppressWarnings("unchecked")
public void testConfigurer() throws Exception {
    HostNameBasedPropertyPlaceHolderConfigurer configurer = new HostNameBasedPropertyPlaceHolderConfigurer() {
        @Override/*  w  w  w.ja v a2 s . c  o m*/
        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:lcn.module.batch.core.launch.support.SchedulerRunner.java

/**
 * Scheduler ./*from  w  w w  .  j av  a2  s .com*/
 * 
 * Thread.sleep()? ?, Scheduler schedulerJob?   
 * ApplicationContext  ?? delayTime ? .
 * ApplicationContext ?  ? Scheduler   Batch Job? .
 * :  10 Batch Job (Cron ?: 0/10 * * * * ?)
 * ?? xml? : /framework/batch/batch-scheduler-runner-context.xml
 */
public void start() {
    List<String> paths = new ArrayList<String>();

    paths.add(contextPath);
    paths.add(schedulerJobPath);

    //  XML ?? ContextPath? ?.
    for (int index = 0; index < jobPaths.size(); index++) {
        paths.add(jobPaths.get(index));
    }

    String[] locations = paths.toArray(new String[paths.size()]);

    // ApplicationContext ?.
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(locations, false);
    context.refresh();

    logger.warn("ApplicationContext Running Time: " + delayTime / 1000 + " seconds");
    logger.warn("CronTrigger is loaded on Spring ApplicationContext");

    try {
        //  ? ,  ?? Scheduler ?.
        Thread.sleep(delayTime);
    } catch (InterruptedException e) {
        /* interrupted by other thread */
    }

    context.close();
}

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;
                                    }/* w  w  w  .j a  v  a  2 s.c  o  m*/
                                });
                    }
                    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: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.  j a v a 2  s. 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.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();

    return applicationContext;
}

From source file:egovframework.rte.bat.core.launch.support.EgovSchedulerRunner.java

/**
 * Scheduler ./*from ww  w. j a  v  a2  s. c  o m*/
 * <br>
 * Thread.sleep()? ?, Scheduler schedulerJob?   
 * ApplicationContext  ?? delayTime ? .
 * ApplicationContext ?  ? Scheduler   Batch Job? .
 * :  10 Batch Job (Cron ?: 0/10 * * * * ?)
 * ?? xml? : /egovframework/batch/batch-scheduler-runner-context.xml
 */
public void start() {
    List<String> paths = new ArrayList<String>();

    paths.add(contextPath);
    paths.add(schedulerJobPath);

    //  XML ?? ContextPath? ?.
    for (int index = 0; index < jobPaths.size(); index++) {
        paths.add(jobPaths.get(index));
    }

    String[] locations = paths.toArray(new String[paths.size()]);

    // ApplicationContext ?.
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(locations, false);
    context.refresh();

    logger.warn("ApplicationContext Running Time: " + delayTime / 1000 + " seconds");

    boolean mustContinue = false;
    long realDelayTIme = delayTime;

    if (delayTime < 0) {
        mustContinue = true;
        realDelayTIme = -1 * delayTime;
    }

    if (mustContinue) {
        logger.info("Continue...");
        while (!Thread.currentThread().isInterrupted()) {
            try {
                Thread.sleep(realDelayTIme);
            } catch (InterruptedException ie) {
                break;
            }
        }
        logger.info("Sleeping ends...");
        context.close();
    } else {
        try {
            //  ? ,  ?? Scheduler ?.
            logger.info("Sleeping Time: " + realDelayTIme / 1000 + " seconds");
            Thread.sleep(realDelayTIme);
            logger.info("Sleeping ends...");
        } catch (InterruptedException ie) {
            /* interrupted by other thread */
        }
        context.close();
    }
}

From source file:org.datalift.sdmxdatacube.SDMXDataCubeModel.java

/**
 * Creates a new SDMXDataCubeModel instance.
 * // w w  w  .ja v a2 s  .c  om
 * @param name
 *            Name of the module.
 */
public SDMXDataCubeModel(String name) {
    super(name);

    // Initialize the sdmxDataCubeTransformer, which is a Spring bean.
    // It is also referenced in spring-beans.xml.
    Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
    ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext();
    ctx.setConfigLocation("spring/spring-beans.xml");
    ctx.refresh();

    sdmxDataCubeTransformer = ctx.getBean(SDMXDataCubeTransformer.class);
}

From source file:ws.antonov.config.consumer.ConfigClientTest.java

public void testSpring() throws Exception {
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
    context.refresh();

    FlatConfigService service = context.getBean(FlatConfigService.class);

    FlatConfigObject config = service.getConfig("build/classes", "test/config.properties");

    assertEquals(config.getTimeout(), 10);
    assertEquals(config.getValidate(), false);
    assertEquals(config.getSystemCode(), "101");
}

From source file:gemlite.shell.admin.Admin.java

public void printMenu(String[] args) throws IOException, CmdLineException {
    String resource = ("ds-client.xml");
    ClassPathXmlApplicationContext mainContext = new ClassPathXmlApplicationContext(new String[] { resource },
            false);//from w w w.  j  av  a2 s .  c  o m
    mainContext.setValidating(true);
    mainContext.refresh();
    //Set<String> keys= mainContext.getBeansOfType(Region.class).keySet();

    ClientCache clientCache = ClientCacheFactory.getAnyInstance();
    dao = new AdminDao();
    Map<String, Pool> pools = PoolManager.getAll();
    dao.setClientPool(pools.entrySet().iterator().next().getValue());
    CmdLineParser parser = new CmdLineParser(this);
    do {
        System.out
                .println("*************************************************************\n Administrator args:");
        parser.printExample(ExampleMode.ALL);
        parser.printUsage(System.out);
        System.out.println("Press \"X\" to exit. Any other key to continue.");
        System.out.println("Input your option: ");
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        String line = bufferedReader.readLine();
        if (line.equalsIgnoreCase("X"))
            break;
        resetParam();
        String[] inputArgs = line.split(" ");
        if (inputArgs.length > 0 && inputArgs.length <= 2) {
            try {
                parser.parseArgument(inputArgs);
            } catch (Exception e) {
                System.err.println("Option error!");
            }
            try {
                doCommand(dao, clientCache);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (inputArgs.length > 2) {
            System.out.println("Please choose only one option each time.");
        }
    } while (true);
    mainContext.close();
}