Example usage for org.springframework.context.support GenericApplicationContext registerShutdownHook

List of usage examples for org.springframework.context.support GenericApplicationContext registerShutdownHook

Introduction

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

Prototype

@Override
public void registerShutdownHook() 

Source Link

Document

Register a shutdown hook with the JVM runtime, closing this context on JVM shutdown unless it has already been closed at that time.

Usage

From source file:org.anarres.dblx.core.Main.java

public static void main(String[] args) throws Exception {
    Stopwatch stopwatch = Stopwatch.createStarted();
    Arguments arguments = new Arguments(args);
    GenericApplicationContext context = new GenericApplicationContext();
    AnnotatedBeanDefinitionReader reader = new AnnotatedBeanDefinitionReader(context);
    reader.register(AppConfiguration.class);
    for (AppConfiguration.Provider configurationProvider : ServiceLoader
            .load(AppConfiguration.Provider.class)) {
        for (Class<?> configurationClass : configurationProvider.getConfigurationClasses()) {
            LOG.debug("Registering additional ServerConfiguration class " + configurationClass.getName());
            reader.register(configurationClass);
        }//from  w w  w.  ja  va 2s . c  om
    }
    SpringUtils.addConfigurations(context, arguments);
    context.refresh();
    context.registerShutdownHook();
    context.start();

    LOG.info("Ready; startup took " + stopwatch);
}

From source file:co.paralleluniverse.common.spring.SpringContainerHelper.java

public static ConfigurableApplicationContext createContext(String defaultDomain, Resource xmlResource,
        Object properties, BeanFactoryPostProcessor beanFactoryPostProcessor) {
    LOG.info("JAVA: {} {}, {}", new Object[] { System.getProperty("java.runtime.name"),
            System.getProperty("java.runtime.version"), System.getProperty("java.vendor") });
    LOG.info("OS: {} {}, {}", new Object[] { System.getProperty("os.name"), System.getProperty("os.version"),
            System.getProperty("os.arch") });
    LOG.info("DIR: {}", System.getProperty("user.dir"));

    final DefaultListableBeanFactory beanFactory = createBeanFactory();
    final GenericApplicationContext context = new GenericApplicationContext(beanFactory);
    context.registerShutdownHook();

    final PropertyPlaceholderConfigurer propertyPlaceholderConfigurer = new PropertyPlaceholderConfigurer();
    propertyPlaceholderConfigurer//from  w ww.  ja v a  2 s.c  o  m
            .setSystemPropertiesMode(PropertyPlaceholderConfigurer.SYSTEM_PROPERTIES_MODE_OVERRIDE);

    if (properties != null) {
        if (properties instanceof Resource)
            propertyPlaceholderConfigurer.setLocation((Resource) properties);
        else if (properties instanceof Properties)
            propertyPlaceholderConfigurer.setProperties((Properties) properties);
        else
            throw new IllegalArgumentException(
                    "Properties argument - " + properties + " - is of an unhandled type");
    }
    context.addBeanFactoryPostProcessor(propertyPlaceholderConfigurer);

    // MBean exporter
    //final MBeanExporter mbeanExporter = new AnnotationMBeanExporter();
    //mbeanExporter.setServer(ManagementFactory.getPlatformMBeanServer());
    //beanFactory.registerSingleton("mbeanExporter", mbeanExporter);
    context.registerBeanDefinition("mbeanExporter", getMBeanExporterBeanDefinition(defaultDomain));

    // inject bean names into components
    context.addBeanFactoryPostProcessor(new BeanFactoryPostProcessor() {
        @Override
        public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
            for (String beanName : beanFactory.getBeanDefinitionNames()) {
                try {
                    final BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);
                    if (beanDefinition.getBeanClassName() != null) { // van be null for factory methods
                        final Class<?> beanClass = Class.forName(beanDefinition.getBeanClassName());
                        if (Component.class.isAssignableFrom(beanClass))
                            beanDefinition.getConstructorArgumentValues().addIndexedArgumentValue(0, beanName);
                    }
                } catch (Exception ex) {
                    LOG.error("Error loading bean " + beanName + " definition.", ex);
                    throw new Error(ex);
                }
            }
        }
    });

    if (beanFactoryPostProcessor != null)
        context.addBeanFactoryPostProcessor(beanFactoryPostProcessor);

    beanFactory.registerCustomEditor(org.w3c.dom.Element.class,
            co.paralleluniverse.common.util.DOMElementProprtyEditor.class);

    final Map<String, Object> beans = new HashMap<String, Object>();

    beanFactory.addBeanPostProcessor(new BeanPostProcessor() {
        @Override
        public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
            LOG.info("Loading bean {} [{}]", beanName, bean.getClass().getName());
            beans.put(beanName, bean);

            if (bean instanceof Service) {
                final BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);
                Collection<String> dependencies = getBeanDependencies(beanDefinition);

                for (String dependeeName : dependencies) {
                    Object dependee = beanFactory.getBean(dependeeName);
                    if (dependee instanceof Service) {
                        ((Service) dependee).addDependedBy((Service) bean);
                        ((Service) bean).addDependsOn((Service) dependee);
                    }
                }
            }
            return bean;
        }

        @Override
        public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
            LOG.info("Bean {} [{}] loaded", beanName, bean.getClass().getName());
            return bean;
        }
    });

    final XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader((BeanDefinitionRegistry) beanFactory);
    xmlReader.loadBeanDefinitions(xmlResource);

    // start container
    context.refresh();

    // Call .postInit() on all Components
    // There's probably a better way to do this
    try {
        for (Map.Entry<String, Object> entry : beans.entrySet()) {
            final String beanName = entry.getKey();
            final Object bean = entry.getValue();
            if (bean instanceof Component) {
                LOG.info("Performing post-initialization on bean {} [{}]", beanName, bean.getClass().getName());
                ((Component) bean).postInit();
            }
        }
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }

    return context;
}

From source file:edu.internet2.middleware.psp.util.PSPUtil.java

public static GenericApplicationContext createSpringContext(List<Resource> resources) throws ResourceException {

    GenericApplicationContext gContext = new GenericApplicationContext();
    SpringConfigurationUtils.populateRegistry(gContext, resources);
    gContext.refresh();//  www  . ja  v  a 2  s. co m
    gContext.registerShutdownHook();

    return gContext;
}

From source file:edu.berkeley.compbio.ncbitaxonomy.NcbiTaxonomyDbContextFactory.java

public static ApplicationContext makeNcbiTaxonomyDbContext() //String dbName)
        throws IOException

{
    /*/*from  w  w  w.j av  a2s  .  c o m*/
    File propsFile = PropertiesUtils
    .findPropertiesFile("NCBI_TAXONOMY_PROPERTIES", ".ncbitaxonomy", "ncbi_taxonomy.properties");
    EnvironmentUtils.init(propsFile);
            
    logger.debug("Using properties file: " + propsFile);
    Properties p = new Properties();
    FileInputStream is = null;
    try
       {
       is = new FileInputStream(propsFile);
       p.load(is);
       }
    finally
       {
       is.close();
       }
    //String dbName = (String) p.get("default");
            
    Map<String, Properties> databases = PropertiesUtils.splitPeriodDelimitedProperties(p);
            
    */
    GenericApplicationContext ctx = new GenericApplicationContext();
    XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(ctx);
    //         xmlReader.loadBeanDefinitions(new ClassPathResource("springjpautils.xml"));
    xmlReader.loadBeanDefinitions(new ClassPathResource("ncbitaxonomy.xml"));

    //PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer();
    //cfg.setProperties(databases.get(dbName));
    //ctx.addBeanFactoryPostProcessor(cfg);

    ctx.refresh();

    // add a shutdown hook for the above context...
    ctx.registerShutdownHook();

    return ctx;
}

From source file:edu.berkeley.compbio.ncbitaxonomy.service.NcbiTaxonomyServicesContextFactory.java

public static ApplicationContext makeNcbiTaxonomyServicesContext() throws IOException {

    File propsFile = PropertiesUtils.findPropertiesFile("NCBI_TAXONOMY_SERVICE_PROPERTIES", ".ncbitaxonomy",
            "service.properties");

    logger.debug("Using properties file: " + propsFile);
    Properties p = new Properties();
    FileInputStream is = null;/* www . ja va2  s .  com*/
    try {
        is = new FileInputStream(propsFile);
        p.load(is);
    } finally {
        is.close();
    }
    String dbName = (String) p.get("default");

    Map<String, Properties> databases = PropertiesUtils.splitPeriodDelimitedProperties(p);

    GenericApplicationContext ctx = new GenericApplicationContext();
    XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(ctx);
    xmlReader.loadBeanDefinitions(new ClassPathResource("ncbitaxonomyclient.xml"));

    PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer();
    Properties properties = databases.get(dbName);

    if (properties == null) {
        logger.error("Service definition not found: " + dbName);
        logger.error("Valid names: " + StringUtils.join(databases.keySet().iterator(), ", "));
        throw new NcbiTaxonomyRuntimeException("Database definition not found: " + dbName);
    }

    cfg.setProperties(properties);
    ctx.addBeanFactoryPostProcessor(cfg);

    ctx.refresh();

    // add a shutdown hook for the above context...
    ctx.registerShutdownHook();

    return ctx;
}

From source file:com.graphaware.server.foundation.context.FoundationRootContextCreator.java

@Override
public AbstractApplicationContext createContext(NeoServer neoServer, StatsCollector statsCollector) {
    GenericApplicationContext parent = new GenericApplicationContext();
    parent.registerShutdownHook();
    parent.getBeanFactory().registerSingleton("database", neoServer.getDatabase().getGraph());
    parent.getBeanFactory().registerSingleton("procedures",
            neoServer.getDatabase().getGraph().getDependencyResolver().resolveDependency(Procedures.class));

    parent.getBeanFactory().registerSingleton("getStatsCollector", statsCollector);

    GraphAwareRuntime runtime = RuntimeRegistry.getRuntime(neoServer.getDatabase().getGraph());
    if (runtime != null) {
        runtime.waitUntilStarted();//from ww w .ja v  a2s  . com
        parent.getBeanFactory().registerSingleton("databaseWriter", runtime.getDatabaseWriter());
    }

    parent.refresh();

    return parent;
}

From source file:com.textocat.textokit.eval.EvaluationLauncher.java

public static void runUsingProperties(Properties configProperties) throws Exception {
    GenericApplicationContext appCtx = new GenericApplicationContext();

    appCtx.getEnvironment().getPropertySources()
            .addLast(new PropertiesPropertySource("configFile", configProperties));

    XmlBeanDefinitionReader xmlBDReader = new XmlBeanDefinitionReader(appCtx);
    xmlBDReader.loadBeanDefinitions(APP_CONTEXT_LOCATION);

    // register listeners
    Map<String, String> listenerImpls = getPrefixedKeyPairs(configProperties, PREFIX_LISTENER_ID);
    for (String listenerId : listenerImpls.keySet()) {
        String listenerClass = listenerImpls.get(listenerId);
        BeanDefinitionBuilder bb = genericBeanDefinition(listenerClass);
        Map<String, String> listenerProperties = getPrefixedKeyPairs(configProperties,
                PREFIX_LISTENER_PROPERTY + listenerId + ".");
        for (String propName : listenerProperties.keySet()) {
            bb.addPropertyValue(propName, listenerProperties.get(propName));
        }/*from w  w w  . j av a 2  s.  c  o m*/
        appCtx.registerBeanDefinition(listenerId, bb.getBeanDefinition());
    }

    appCtx.refresh();

    appCtx.registerShutdownHook();

    GoldStandardBasedEvaluation eval = appCtx.getBean(GoldStandardBasedEvaluation.class);
    eval.run();
}

From source file:com.taobao.itest.spring.context.GenericXmlContextLoader.java

public ApplicationContext loadContext(String... locations) throws Exception {
    GenericApplicationContext context = new GenericApplicationContext();
    new XmlBeanDefinitionReader(context).loadBeanDefinitions(locations);
    context.refresh();/* w  w  w .j  a  v a 2s  . com*/
    context.registerShutdownHook();
    return context;
}

From source file:org.alfresco.cacheserver.dropwizard.Application.java

public void start() {
    if (springContextFileLocation != null) {
        // parent spring context with the normal DropWizard configuration defined
        GenericApplicationContext parent = new GenericApplicationContext();
        parent.refresh();/*  w  w w .j  ava2s  .  c o m*/
        parent.getBeanFactory().registerSingleton("configuration", this);
        parent.registerShutdownHook();
        parent.start();

        try {
            PropertyPlaceholderConfigurer configurer = loadSpringConfigurer(yamlConfigFileLocation);

            // child spring context from xml
            context = new ClassPathXmlApplicationContext(parent);
            if (configurer != null) {
                context.addBeanFactoryPostProcessor(configurer);
            }
            context.setConfigLocations(new String[] { springContextFileLocation });
            context.registerShutdownHook();
            context.refresh();
        } catch (IOException e) {
            throw new IllegalStateException("Could not create Spring context", e);
        }
    } else {
        throw new IllegalArgumentException("Spring context file location not set");
    }
}

From source file:ch.nydi.spring.context.support.TestGenericXmlContextLoader.java

/**
 * {@inheritDoc}//  w  w  w . ja  v a2  s .  c  o  m
 */
@Override
public final ConfigurableApplicationContext loadContext(final String... locations) throws Exception {

    final DefaultListableBeanFactory beanFactory = new PrimaryResolverListableBeanFactory();
    beanFactory.setParameterNameDiscoverer(new LocalVariableTableParameterNameDiscoverer());
    beanFactory.setAutowireCandidateResolver(new QualifierAnnotationAutowireCandidateResolver());

    final GenericApplicationContext context = new GenericApplicationContext(beanFactory);
    createBeanDefinitionReader(context).loadBeanDefinitions(locations);
    AnnotationConfigUtils.registerAnnotationConfigProcessors(context);
    context.refresh();
    context.registerShutdownHook();
    return context;
}