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

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

Introduction

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

Prototype

@Override
    public void refresh() throws BeansException, IllegalStateException 

Source Link

Usage

From source file:net.frontlinesms.FrontlineSMS.java

/** Initialise {@link #applicationContext}. */
public void initApplicationContext() throws DataAccessResourceFailureException {
    // Load the data mode from the app.properties file
    AppProperties appProperties = AppProperties.getInstance();

    LOG.info("Load Spring/Hibernate application context to initialise DAOs");

    // Create a base ApplicationContext defining the hibernate config file we need to import
    StaticApplicationContext baseApplicationContext = new StaticApplicationContext();
    baseApplicationContext.registerBeanDefinition("hibernateConfigLocations",
            createHibernateConfigLocationsBeanDefinition());

    // Get the spring config locations
    String databaseExternalConfigPath = ResourceUtils.getConfigDirectoryPath()
            + ResourceUtils.PROPERTIES_DIRECTORY_NAME + File.separatorChar
            + appProperties.getDatabaseConfigPath();
    String[] configLocations = getSpringConfigLocations(databaseExternalConfigPath);
    baseApplicationContext.refresh();

    FileSystemXmlApplicationContext applicationContext = new FileSystemXmlApplicationContext(configLocations,
            false, baseApplicationContext);
    this.applicationContext = applicationContext;

    // Add post-processor to handle substituted database properties
    PropertyPlaceholderConfigurer propertyPlaceholderConfigurer = new PropertyPlaceholderConfigurer();
    String databasePropertiesPath = ResourceUtils.getConfigDirectoryPath()
            + ResourceUtils.PROPERTIES_DIRECTORY_NAME + File.separatorChar
            + appProperties.getDatabaseConfigPath() + ".properties";
    propertyPlaceholderConfigurer.setLocation(new FileSystemResource(new File(databasePropertiesPath)));
    propertyPlaceholderConfigurer.setIgnoreResourceNotFound(true);
    applicationContext.addBeanFactoryPostProcessor(propertyPlaceholderConfigurer);
    applicationContext.refresh();//from  www.  j  ava  2  s .co  m

    LOG.info("Context loaded successfully.");

    this.pluginManager = new PluginManager(this, applicationContext);

    LOG.info("Getting DAOs from application context...");
    groupDao = (GroupDao) applicationContext.getBean("groupDao");
    groupMembershipDao = (GroupMembershipDao) applicationContext.getBean("groupMembershipDao");
    contactDao = (ContactDao) applicationContext.getBean("contactDao");
    keywordDao = (KeywordDao) applicationContext.getBean("keywordDao");
    keywordActionDao = (KeywordActionDao) applicationContext.getBean("keywordActionDao");
    messageDao = (MessageDao) applicationContext.getBean("messageDao");
    emailDao = (EmailDao) applicationContext.getBean("emailDao");
    emailAccountDao = (EmailAccountDao) applicationContext.getBean("emailAccountDao");
    smsInternetServiceSettingsDao = (SmsInternetServiceSettingsDao) applicationContext
            .getBean("smsInternetServiceSettingsDao");
    smsModemSettingsDao = (SmsModemSettingsDao) applicationContext.getBean("smsModemSettingsDao");
    eventBus = (EventBus) applicationContext.getBean("eventBus");
}

From source file:ome.client.utests.Preferences3Test.java

@Test
public void test_makeOurOwnDefault() throws Exception {
    // Others:/*from  w ww. j a va  2  s.  c om*/
    // new ManagedMap();
    // BeanWrapper bw = new BeanWrapperImpl( defaultMap );

    Map defaultMap = new HashMap();
    defaultMap.put("omero.user", "foo");
    ConstructorArgumentValues cav = new ConstructorArgumentValues();
    cav.addGenericArgumentValue(defaultMap);
    BeanDefinition def = new RootBeanDefinition(HashMap.class, cav, null);
    StaticApplicationContext ac = new StaticApplicationContext();
    ac.registerBeanDefinition("map", def);
    ac.refresh();

    ConstructorArgumentValues testCav = new ConstructorArgumentValues();
    testCav.addGenericArgumentValue(new RuntimeBeanReference("map"));
    BeanDefinition testDef = new RootBeanDefinition(HashMap.class, testCav, null);
    StaticApplicationContext defaultTest = new StaticApplicationContext(ac);
    defaultTest.registerBeanDefinition("test", testDef);
    defaultTest.refresh();
    assertTrue("foo".equals(((Map) defaultTest.getBean("test")).get("omero.user")));

}

From source file:ome.client.utests.Preferences3Test.java

@Test
public void test_makeOurOwnRuntime() throws Exception {

    // use properties
    // if no Properties given, then is static (global)

    Map runtimeMap = new HashMap();
    runtimeMap.put("omero.user", "bar");
    ConstructorArgumentValues cav2 = new ConstructorArgumentValues();
    cav2.addGenericArgumentValue(runtimeMap);
    BeanDefinition def2 = new RootBeanDefinition(HashMap.class, cav2, null);
    StaticApplicationContext ac2 = new StaticApplicationContext();
    ac2.registerBeanDefinition("map", def2);
    ac2.refresh();

    ConstructorArgumentValues testCav2 = new ConstructorArgumentValues();
    testCav2.addGenericArgumentValue(new RuntimeBeanReference("map"));
    BeanDefinition testDef2 = new RootBeanDefinition(HashMap.class, testCav2, null);
    StaticApplicationContext defaultTest2 = new StaticApplicationContext(ac2);
    defaultTest2.registerBeanDefinition("test", testDef2);
    defaultTest2.refresh();//from   w  w w. ja v a2s . co m
    assertTrue("bar".equals(((Map) defaultTest2.getBean("test")).get("omero.user")));

}

From source file:ome.client.utests.Preferences3Test.java

@Test(groups = "ticket:62")
@ExpectedExceptions(BeanInitializationException.class)
public void test_missingLoadProperties() {
    StaticApplicationContext ac = new StaticApplicationContext();
    PreferencesPlaceholderConfigurer ppc = new PreferencesPlaceholderConfigurer();
    ppc.setLocation(new ClassPathResource("DOES--NOT--EXIST"));

    ac.addBeanFactoryPostProcessor(ppc);
    ac.refresh();
}

From source file:ome.client.utests.Preferences3Test.java

@Test(groups = "ticket:62")
public void test_missingLoadPropertiesIgnore() {
    StaticApplicationContext ac = new StaticApplicationContext();
    PreferencesPlaceholderConfigurer ppc = new PreferencesPlaceholderConfigurer();
    ppc.setLocation(new ClassPathResource("DOES--NOT--EXIST"));
    ppc.setIgnoreResourceNotFound(true);

    ac.addBeanFactoryPostProcessor(ppc);
    ac.refresh();

}

From source file:ome.client.utests.Preferences3Test.java

@Test(groups = "ticket:1058")
public void testOmeroUserIsProperlySetWithSpring2_5_5Manual() {

    Server s = new Server("localhost", 1099);
    Login l = new Login("me", "password");
    Properties p = s.asProperties();
    p.putAll(l.asProperties());/*w  w w .  j a  va 2 s .c o m*/

    // This is copied from OmeroContext. This is the parent context which
    // should contain the properties;
    Properties copy = new Properties(p);
    ConstructorArgumentValues ctorArg1 = new ConstructorArgumentValues();
    ctorArg1.addGenericArgumentValue(copy);
    BeanDefinition definition1 = new RootBeanDefinition(Properties.class, ctorArg1, null);
    StaticApplicationContext staticContext = new StaticApplicationContext();
    staticContext.registerBeanDefinition("properties", definition1);
    staticContext.refresh();

    // This is the child context and contains a definition of a
    // PlaceHolderConfigurer
    // as well as a user of
    StaticApplicationContext childContext = new StaticApplicationContext();

    MutablePropertyValues mpv2 = new MutablePropertyValues();
    mpv2.addPropertyValue("properties", new RuntimeBeanReference("properties"));
    mpv2.addPropertyValue("systemPropertiesModeName", "SYSTEM_PROPERTIES_MODE_FALLBACK");
    mpv2.addPropertyValue("localOverride", "true");
    BeanDefinition definitionConfigurer = new RootBeanDefinition(PreferencesPlaceholderConfigurer.class, null,
            mpv2);
    childContext.registerBeanDefinition("propertiesPlaceholderConfigurer", definitionConfigurer);

    ConstructorArgumentValues cav2 = new ConstructorArgumentValues();
    cav2.addGenericArgumentValue("${omero.user}");
    BeanDefinition definitionTest = new RootBeanDefinition(String.class, cav2, null);
    childContext.registerBeanDefinition("test", definitionTest);

    childContext.setParent(staticContext);
    childContext.refresh();

    String test = (String) childContext.getBean("test");
    assertEquals(test, "me");

}

From source file:org.marketcetera.client.ClientImpl.java

private void connect() throws ConnectionException {
    if (mParameters.getURL() == null || mParameters.getURL().trim().isEmpty()) {
        throw new ConnectionException(Messages.CONNECT_ERROR_NO_URL);
    }/* w  ww. ja v a2  s . c o m*/
    if (mParameters.getUsername() == null || mParameters.getUsername().trim().isEmpty()) {
        throw new ConnectionException(Messages.CONNECT_ERROR_NO_USERNAME);
    }
    if (mParameters.getHostname() == null || mParameters.getHostname().trim().isEmpty()) {
        throw new ConnectionException(Messages.CONNECT_ERROR_NO_HOSTNAME);
    }
    if (mParameters.getPort() < 1 || mParameters.getPort() > 0xFFFF) {
        throw new ConnectionException(
                new I18NBoundMessage1P(Messages.CONNECT_ERROR_INVALID_PORT, mParameters.getPort()));
    }
    try {
        StaticApplicationContext parentCtx = new StaticApplicationContext();
        SpringUtils.addStringBean(parentCtx, "brokerURL", //$NON-NLS-1$
                mParameters.getURL());
        SpringUtils.addStringBean(parentCtx, "runtimeUsername", mParameters.getUsername()); //$NON-NLS-1$
        SpringUtils.addStringBean(parentCtx, "runtimePassword", mParameters == null //$NON-NLS-1$
                ? null
                : String.valueOf(mParameters.getPassword()));
        parentCtx.refresh();
        AbstractApplicationContext ctx;
        try {
            ctx = new FileSystemXmlApplicationContext(
                    new String[] { "file:" + ApplicationBase.CONF_DIR + "client.xml" }, //$NON-NLS-1$
                    parentCtx);
        } catch (BeansException e) {
            ctx = new ClassPathXmlApplicationContext(new String[] { "client.xml" }, //$NON-NLS-1$
                    parentCtx);
        }
        ctx.registerShutdownHook();
        ctx.start();
        setContext(ctx);
        SpringConfig cfg = SpringConfig.getSingleton();
        if (cfg == null) {
            throw new ConnectionException(Messages.CONNECT_ERROR_NO_CONFIGURATION);
        }

        mServiceClient = new org.marketcetera.util.ws.stateful.Client(mParameters.getHostname(),
                mParameters.getPort(), ClientVersion.APP_ID);
        mServiceClient.login(mParameters.getUsername(), mParameters.getPassword());
        mService = mServiceClient.getService(Service.class);

        mJmsMgr = new JmsManager(cfg.getIncomingConnectionFactory(), cfg.getOutgoingConnectionFactory(), this);
        startJms();
        mServerAlive = true;
        notifyServerStatus(true);

        mHeart = new Heart();
        mHeart.start();

        ClientIDFactory idFactory = new ClientIDFactory(mParameters.getIDPrefix(), this);
        idFactory.init();
        Factory.getInstance().setOrderIDFactory(idFactory);
    } catch (Throwable t) {
        internalClose();
        ExceptUtils.interrupt(t);
        if (t.getCause() instanceof RemoteProxyException) {
            RemoteProxyException ex = (RemoteProxyException) t.getCause();
            if (IncompatibleComponentsException.class.getName().equals(ex.getServerName())) {
                throw new ConnectionException(t,
                        new I18NBoundMessage1P(Messages.ERROR_CONNECT_INCOMPATIBLE_DEDUCED, ex.getMessage()));
            }
        } else if (t.getCause() instanceof IncompatibleComponentsException) {
            IncompatibleComponentsException ex = (IncompatibleComponentsException) t.getCause();
            throw new ConnectionException(t, new I18NBoundMessage2P(Messages.ERROR_CONNECT_INCOMPATIBLE_DIRECT,
                    ClientVersion.APP_ID, ex.getServerVersion()));
        }
        throw new ConnectionException(t,
                new I18NBoundMessage4P(Messages.ERROR_CONNECT_TO_SERVER, mParameters.getURL(),
                        mParameters.getUsername(), mParameters.getHostname(), mParameters.getPort()));
    }
    mLastConnectTime = new Date();
}

From source file:org.marketcetera.strategyagent.StrategyAgent.java

/**
 * Configures the agent. Initializes the spring configuration to get
 * a properly configured module manager instance.
 *///from www . j av  a 2  s  . co  m
private void configure() {
    File modulesDir = new File(APP_DIR, "modules"); //$NON-NLS-1$
    StaticApplicationContext parentCtx = new StaticApplicationContext();
    //Provide the module jar directory path to the spring context.
    SpringUtils.addStringBean(parentCtx, "modulesDir", //$NON-NLS-1$
            modulesDir.getAbsolutePath());
    parentCtx.refresh();
    mContext = new ClassPathXmlApplicationContext(new String[] { "modules.xml" }, parentCtx); //$NON-NLS-1$
    mContext.registerShutdownHook();
    mManager = (ModuleManager) mContext.getBean("moduleManager", //$NON-NLS-1$
            ModuleManager.class);
    //Set the context classloader to the jar classloader so that
    //all modules have the thread context classloader set to the same
    //value as the classloader that loaded them.
    ClassLoader loader = (ClassLoader) mContext.getBean("moduleLoader", //$NON-NLS-1$
            ClassLoader.class);
    Thread.currentThread().setContextClassLoader(loader);

    //Setup the WS services after setting up the context class loader.
    String hostname = (String) mContext.getBean("wsServerHost"); //$NON-NLS-1$
    if (hostname != null && !hostname.trim().isEmpty()) {
        int port = (Integer) mContext.getBean("wsServerPort"); //$NON-NLS-1$
        SessionManager<ClientSession> sessionManager = new SessionManager<ClientSession>(
                new ClientSessionFactory(), SessionManager.INFINITE_SESSION_LIFESPAN);
        mServer = new Server<ClientSession>(hostname, port, new Authenticator() {
            @Override
            public boolean shouldAllow(StatelessClientContext context, String user, char[] password)
                    throws I18NException {
                return authenticate(context, user, password);
            }
        }, sessionManager, contextClasses);
        mRemoteService = mServer.publish(new SAServiceImpl(sessionManager, mManager, dataPublisher),
                SAService.class);
        //Register a shutdown task to shutdown the remote service.
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                stopRemoteService();
            }
        });
        Messages.LOG_REMOTE_WS_CONFIGURED.info(this, hostname, String.valueOf(port));
    }
}

From source file:org.springframework.integration.jms.SubscribableJmsChannelTests.java

@Test
public void contextManagesLifecycle() {
    BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(JmsChannelFactoryBean.class);
    builder.addConstructorArgValue(true);
    builder.addPropertyValue("connectionFactory", this.connectionFactory);
    builder.addPropertyValue("destinationName", "dynamicQueue");
    builder.addPropertyValue("pubSubDomain", false);
    StaticApplicationContext context = new StaticApplicationContext();
    context.registerBeanDefinition("channel", builder.getBeanDefinition());
    SubscribableJmsChannel channel = context.getBean("channel", SubscribableJmsChannel.class);
    assertFalse(channel.isRunning());// w  w  w .jav a  2  s. co m
    context.refresh();
    assertTrue(channel.isRunning());
    context.stop();
    assertFalse(channel.isRunning());
    context.close();
}

From source file:org.springframework.ws.transport.http.CommonsHttpMessageSenderIntegrationTest.java

@Test
public void testContextClose() throws Exception {
    MessageFactory messageFactory = MessageFactory.newInstance();
    int port = FreePortScanner.getFreePort();
    Server jettyServer = new Server(port);
    Context jettyContext = new Context(jettyServer, "/");
    jettyContext.addServlet(new ServletHolder(new EchoServlet()), "/");
    jettyServer.start();//from   w ww  .ja  v a  2 s . com
    WebServiceConnection connection = null;
    try {

        StaticApplicationContext appContext = new StaticApplicationContext();
        appContext.registerSingleton("messageSender", CommonsHttpMessageSender.class);
        appContext.refresh();

        CommonsHttpMessageSender messageSender = appContext.getBean("messageSender",
                CommonsHttpMessageSender.class);
        connection = messageSender.createConnection(new URI("http://localhost:" + port));

        appContext.close();

        connection.send(new SaajSoapMessage(messageFactory.createMessage()));
        connection.receive(new SaajSoapMessageFactory(messageFactory));
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (IOException ex) {
                // ignore
            }
        }
        if (jettyServer.isRunning()) {
            jettyServer.stop();
        }
    }

}