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

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

Introduction

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

Prototype

@Override
    public void refresh() throws BeansException, IllegalStateException 

Source Link

Usage

From source file:org.apache.camel.spring.javaconfig.test.JavaConfigContextLoader.java

/**
 * Loads a new {@link ApplicationContext context} based on the supplied {@code locations},
 * configures the context, and finally returns the context in fully <em>refreshed</em> state.
 * <p/>//from  w  ww.ja  va  2 s.  c o  m
 *
 * Configuration locations are either fully-qualified class names or base package names. These
 * locations will be given to a {@link JavaConfigApplicationContext} for configuration via the
 * {@link JavaConfigApplicationContext#addConfigClass(Class)} and
 * {@link JavaConfigApplicationContext#addBasePackage(String)} methods.
 *
 * @param locations the locations to use to load the application context
 * @return a new application context
 * @throws IllegalArgumentException if any of <var>locations</var> are not valid fully-qualified
 * Class or Package names
 */
public ApplicationContext loadContext(String... locations) {
    if (logger.isDebugEnabled()) {
        logger.debug("Creating a JavaConfigApplicationContext for " + Arrays.asList(locations));
    }

    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();

    ArrayList<Class<?>> configClasses = new ArrayList<Class<?>>();
    ArrayList<String> basePackages = new ArrayList<String>();
    for (String location : locations) {
        // if the location refers to a class, use it. Otherwise assume it's a base package name
        try {
            final Class<?> aClass = this.getClass().getClassLoader().loadClass(location);
            configClasses.add(aClass);
        } catch (ClassNotFoundException e) {
            if (Package.getPackage(location) == null) {
                throw new IllegalArgumentException(
                        String.format("A non-existent class or package name was specified: [%s]", location));
            }
            basePackages.add(location);
        }
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Setting config classes to " + configClasses);
        logger.debug("Setting base packages to " + basePackages);
    }

    for (Class<?> configClass : configClasses) {
        context.register(configClass);
    }

    for (String basePackage : basePackages) {
        context.scan(basePackage);
    }

    context.refresh();

    // Have to create a child context that implements BeanDefinitionRegistry
    // to pass to registerAnnotationConfigProcessors, since
    // JavaConfigApplicationContext does not
    final GenericApplicationContext gac = new GenericApplicationContext(context);
    AnnotationConfigUtils.registerAnnotationConfigProcessors(gac);
    // copy BeanPostProcessors to the child context
    for (String bppName : context.getBeanFactory().getBeanNamesForType(BeanPostProcessor.class)) {
        gac.registerBeanDefinition(bppName, context.getBeanFactory().getBeanDefinition(bppName));
    }
    gac.refresh();
    gac.registerShutdownHook();

    return gac;
}

From source file:org.apache.ignite.internal.util.spring.IgniteSpringHelperImpl.java

/**
 * @param stream Input stream containing Spring XML configuration.
 * @return Context./*from   w w w  .  ja v a2  s  .  c  om*/
 * @throws IgniteCheckedException In case of error.
 */
private ApplicationContext initContext(InputStream stream) throws IgniteCheckedException {
    GenericApplicationContext springCtx;

    try {
        springCtx = new GenericApplicationContext();

        XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(springCtx);

        reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_XSD);

        reader.loadBeanDefinitions(new InputStreamResource(stream));

        springCtx.refresh();
    } catch (BeansException e) {
        if (X.hasCause(e, ClassNotFoundException.class))
            throw new IgniteCheckedException(
                    "Failed to instantiate Spring XML application context "
                            + "(make sure all classes used in Spring configuration are present at CLASSPATH) ",
                    e);
        else
            throw new IgniteCheckedException(
                    "Failed to instantiate Spring XML application context" + ", err=" + e.getMessage() + ']',
                    e);
    }

    return springCtx;
}

From source file:org.apache.ignite.internal.util.spring.IgniteSpringHelperImpl.java

/**
 * @param url XML file URL./*from w w w.  j  a  v a2 s .c o m*/
 * @return Context.
 * @throws IgniteCheckedException In case of error.
 */
private ApplicationContext initContext(URL url) throws IgniteCheckedException {
    GenericApplicationContext springCtx;

    try {
        springCtx = new GenericApplicationContext();

        new XmlBeanDefinitionReader(springCtx).loadBeanDefinitions(new UrlResource(url));

        springCtx.refresh();
    } catch (BeansException e) {
        if (X.hasCause(e, ClassNotFoundException.class))
            throw new IgniteCheckedException("Failed to instantiate Spring XML application context "
                    + "(make sure all classes used in Spring configuration are present at CLASSPATH) "
                    + "[springUrl=" + url + ']', e);
        else
            throw new IgniteCheckedException("Failed to instantiate Spring XML application context [springUrl="
                    + url + ", err=" + e.getMessage() + ']', e);
    }

    return springCtx;
}

From source file:org.apache.ignite.internal.util.spring.IgniteSpringHelperImpl.java

/**
 * Creates Spring application context. Optionally excluded properties can be specified,
 * it means that if such a property is found in {@link org.apache.ignite.configuration.IgniteConfiguration}
 * then it is removed before the bean is instantiated.
 * For example, {@code streamerConfiguration} can be excluded from the configs that Visor uses.
 *
 * @param cfgUrl Resource where config file is located.
 * @param excludedProps Properties to be excluded.
 * @return Spring application context.//from   w w w .  j  av a2  s  .c  o  m
 * @throws IgniteCheckedException If configuration could not be read.
 */
public static ApplicationContext applicationContext(URL cfgUrl, final String... excludedProps)
        throws IgniteCheckedException {
    try {
        GenericApplicationContext springCtx = prepareSpringContext(excludedProps);

        new XmlBeanDefinitionReader(springCtx).loadBeanDefinitions(new UrlResource(cfgUrl));

        springCtx.refresh();

        return springCtx;
    } catch (BeansException e) {
        if (X.hasCause(e, ClassNotFoundException.class))
            throw new IgniteCheckedException("Failed to instantiate Spring XML application context "
                    + "(make sure all classes used in Spring configuration are present at CLASSPATH) "
                    + "[springUrl=" + cfgUrl + ']', e);
        else
            throw new IgniteCheckedException("Failed to instantiate Spring XML application context [springUrl="
                    + cfgUrl + ", err=" + e.getMessage() + ']', e);
    }
}

From source file:org.apache.ignite.internal.util.spring.IgniteSpringHelperImpl.java

/**
 * Creates Spring application context. Optionally excluded properties can be specified,
 * it means that if such a property is found in {@link org.apache.ignite.configuration.IgniteConfiguration}
 * then it is removed before the bean is instantiated.
 * For example, {@code streamerConfiguration} can be excluded from the configs that Visor uses.
 *
 * @param cfgStream Stream where config file is located.
 * @param excludedProps Properties to be excluded.
 * @return Spring application context./*from  w  w  w  .  jav  a2 s. c o  m*/
 * @throws IgniteCheckedException If configuration could not be read.
 */
public static ApplicationContext applicationContext(InputStream cfgStream, final String... excludedProps)
        throws IgniteCheckedException {
    try {
        GenericApplicationContext springCtx = prepareSpringContext(excludedProps);

        XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(springCtx);

        reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_XSD);

        reader.loadBeanDefinitions(new InputStreamResource(cfgStream));

        springCtx.refresh();

        return springCtx;
    } catch (BeansException e) {
        if (X.hasCause(e, ClassNotFoundException.class))
            throw new IgniteCheckedException(
                    "Failed to instantiate Spring XML application context "
                            + "(make sure all classes used in Spring configuration are present at CLASSPATH) ",
                    e);
        else
            throw new IgniteCheckedException(
                    "Failed to instantiate Spring XML application context [err=" + e.getMessage() + ']', e);
    }
}

From source file:org.apache.synapse.mediators.spring.SpringMediator.java

private synchronized void buildAppContext(MessageContext synCtx) {
    log.debug("Creating Spring ApplicationContext from property key : " + configKey);
    GenericApplicationContext appContext = new GenericApplicationContext();
    XmlBeanDefinitionReader xbdr = new XmlBeanDefinitionReader(appContext);
    xbdr.setValidating(false);/*from   www  .  j a va  2s . c o  m*/
    xbdr.loadBeanDefinitions(new InputStreamResource(
            Util.getStreamSource(synCtx.getConfiguration().getProperty(configKey)).getInputStream()));
    appContext.refresh();
    this.appContext = appContext;
}

From source file:org.craftercms.deployer.impl.DeploymentResolverImpl.java

protected ConfigurableApplicationContext loadApplicationContext(HierarchicalConfiguration config,
        File customDeploymentAppContextFile) throws IOException {
    GenericApplicationContext appContext = new GenericApplicationContext(mainApplicationContext);

    MutablePropertySources propertySources = appContext.getEnvironment().getPropertySources();
    propertySources/*from   w ww  .  j  a  v  a 2  s.  co  m*/
            .addFirst(new ApacheCommonsConfiguration2PropertySource(CONFIG_PROPERTY_SOURCE_NAME, config));

    XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(appContext);
    reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_XSD);

    if (baseDeploymentAppContextResource.exists()) {
        logger.debug("Loading base deployment application context at {}", baseDeploymentAppContextResource);

        reader.loadBeanDefinitions(baseDeploymentAppContextResource);
    }
    if (baseDeploymentAppContextOverrideResource.exists()) {
        logger.debug("Loading base deployment application context override at {}",
                baseDeploymentAppContextResource);

        reader.loadBeanDefinitions(baseDeploymentAppContextResource);
    }
    if (customDeploymentAppContextFile.exists()) {
        logger.debug("Loading custom deployment application context at {}", customDeploymentAppContextFile);

        try (InputStream in = new BufferedInputStream(new FileInputStream(customDeploymentAppContextFile))) {
            reader.loadBeanDefinitions(new InputSource(in));
        }
    }

    appContext.refresh();

    return appContext;
}

From source file:org.craftercms.deployer.impl.TargetServiceImpl.java

protected ConfigurableApplicationContext loadApplicationContext(HierarchicalConfiguration config,
        File contextFile) throws DeployerConfigurationException {
    GenericApplicationContext context = new GenericApplicationContext(mainApplicationContext);

    MutablePropertySources propertySources = context.getEnvironment().getPropertySources();
    propertySources/* www .j  ava  2 s  .c  o  m*/
            .addFirst(new ApacheCommonsConfiguration2PropertySource(CONFIG_PROPERTY_SOURCE_NAME, config));

    XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(context);
    reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_XSD);

    if (baseTargetContextResource.exists()) {
        logger.debug("Loading base target application context at {}", baseTargetContextResource);

        try {
            reader.loadBeanDefinitions(baseTargetContextResource);
        } catch (Exception e) {
            throw new DeployerConfigurationException(
                    "Failed to load application context at " + baseTargetContextResource, e);
        }
    }
    if (baseTargetContextOverrideResource.exists()) {
        logger.debug("Loading base target application context override at {}",
                baseTargetContextOverrideResource);

        try {
            reader.loadBeanDefinitions(baseTargetContextOverrideResource);
        } catch (Exception e) {
            throw new DeployerConfigurationException(
                    "Failed to load application context at " + baseTargetContextOverrideResource, e);
        }
    }
    if (contextFile.exists()) {
        logger.debug("Loading target application context at {}", contextFile);

        try (InputStream in = new BufferedInputStream(new FileInputStream(contextFile))) {
            reader.loadBeanDefinitions(new InputSource(in));
        } catch (Exception e) {
            throw new DeployerConfigurationException("Failed to load application context at " + contextFile, e);
        }
    }

    context.refresh();

    return context;
}

From source file:org.craftercms.engine.service.context.SiteContextFactory.java

protected ConfigurableApplicationContext getApplicationContext(SiteContext siteContext,
        URLClassLoader classLoader, HierarchicalConfiguration config, String[] applicationContextPaths,
        ResourceLoader resourceLoader) {
    try {/*from  ww w. j a  v  a  2s  .co  m*/
        List<Resource> resources = new ArrayList<>();

        for (String path : applicationContextPaths) {
            Resource resource = resourceLoader.getResource(path);
            if (resource.exists()) {
                resources.add(resource);
            }
        }

        if (CollectionUtils.isNotEmpty(resources)) {
            String siteName = siteContext.getSiteName();

            logger.info("--------------------------------------------------");
            logger.info("<Loading application context for site: " + siteName + ">");
            logger.info("--------------------------------------------------");

            GenericApplicationContext appContext = new GenericApplicationContext(mainApplicationContext);
            appContext.setClassLoader(classLoader);

            if (config != null) {
                MutablePropertySources propertySources = appContext.getEnvironment().getPropertySources();
                propertySources.addFirst(new ApacheCommonsConfiguration2PropertySource("siteConfig", config));
            }

            XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(appContext);
            reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_XSD);

            for (Resource resource : resources) {
                reader.loadBeanDefinitions(resource);
            }

            appContext.refresh();

            logger.info("--------------------------------------------------");
            logger.info("</Loading application context for site: " + siteName + ">");
            logger.info("--------------------------------------------------");

            return appContext;
        } else {
            return null;
        }
    } catch (Exception e) {
        throw new SiteContextCreationException(
                "Unable to load application context for site '" + siteContext.getSiteName() + "'", e);
    }
}

From source file:org.gridgain.grid.GridFactory.java

/**
 * Starts all grids specified within given Spring XML configuration file URL. If grid with given name
 * is already started, then exception is thrown. In this case all instances that may
 * have been started so far will be stopped too.
 * <p>//  www.  j  a v  a2s.co  m
 * Usually Spring XML configuration file will contain only one Grid definition. Note that
 * Grid configuration bean(s) is retrieved form configuration file by type, so the name of
 * the Grid configuration bean is ignored.
 *
 * @param springCfgUrl Spring XML configuration file URL. This cannot be {@code null}.
 * @param ctx Optional Spring application context.
 * @return Started grid. If Spring configuration contains multiple grid instances,
 *      then the 1st found instance is returned.
 * @throws GridException If grid could not be started or configuration
 *      read. This exception will be thrown also if grid with given name has already
 *      been started or Spring XML configuration file is invalid.
 */
// Warning is due to Spring.
public static Grid start(URL springCfgUrl, @Nullable ApplicationContext ctx) throws GridException {
    A.notNull(springCfgUrl, "springCfgUrl");

    boolean isLog4jUsed = GridFactory.class.getClassLoader()
            .getResource("org/apache/log4j/Appender.class") != null;

    Object rootLog = null;

    Object nullApp = null;

    if (isLog4jUsed)
        try {
            // Add no-op logger to remove no-appender warning.
            Class logCls = Class.forName("org.apache.log4j.Logger");

            rootLog = logCls.getMethod("getRootLogger").invoke(logCls);

            nullApp = Class.forName("org.apache.log4j.varia.NullAppender").newInstance();

            Class appCls = Class.forName("org.apache.log4j.Appender");

            rootLog.getClass().getMethod("addAppender", appCls).invoke(rootLog, nullApp);
        } catch (Exception e) {
            throw new GridException("Failed to add no-op logger for Log4j.", e);
        }

    GenericApplicationContext springCtx;

    try {
        springCtx = new GenericApplicationContext();

        new XmlBeanDefinitionReader(springCtx).loadBeanDefinitions(new UrlResource(springCfgUrl));

        springCtx.refresh();
    } catch (BeansException e) {
        throw new GridException("Failed to instantiate Spring XML application context [springUrl="
                + springCfgUrl + ", err=" + e.getMessage() + ']', e);
    }

    Map<String, GridConfiguration> cfgMap;

    try {
        cfgMap = springCtx.getBeansOfType(GridConfiguration.class);
    } catch (BeansException e) {
        throw new GridException(
                "Failed to instantiate bean [type=" + GridConfiguration.class + ", err=" + e.getMessage() + ']',
                e);
    }

    if (cfgMap == null)
        throw new GridException("Failed to find a single grid factory configuration in: " + springCfgUrl);

    if (isLog4jUsed) {
        try {
            // Remove previously added no-op logger.
            Class appenderCls = Class.forName("org.apache.log4j.Appender");

            rootLog.getClass().getMethod("removeAppender", appenderCls).invoke(rootLog, nullApp);
        } catch (Exception e) {
            throw new GridException("Failed to remove previously added no-op logger for Log4j.", e);
        }
    }

    if (cfgMap.isEmpty())
        throw new GridException("Can't find grid factory configuration in: " + springCfgUrl);

    List<GridNamedInstance> grids = new ArrayList<GridNamedInstance>(cfgMap.size());

    try {
        for (GridConfiguration cfg : cfgMap.values()) {
            assert cfg != null;

            // Use either user defined context or our one.
            GridNamedInstance grid = start0(cfg, ctx == null ? springCtx : ctx);

            // Add it if it was not stopped during startup.
            if (grid != null)
                grids.add(grid);
        }
    } catch (GridException e) {
        // Stop all instances started so far.
        for (GridNamedInstance grid : grids) {
            try {
                grid.stop(true, false);
            } catch (Exception e1) {
                U.error(grid.log, "Error when stopping grid: " + grid, e1);
            }
        }

        throw e;
    }

    // Return the first grid started.
    GridNamedInstance res = !grids.isEmpty() ? grids.get(0) : null;

    return res != null ? res.grid() : null;
}