Example usage for org.springframework.beans.factory.config ConfigurableBeanFactory registerSingleton

List of usage examples for org.springframework.beans.factory.config ConfigurableBeanFactory registerSingleton

Introduction

In this page you can find the example usage for org.springframework.beans.factory.config ConfigurableBeanFactory registerSingleton.

Prototype

void registerSingleton(String beanName, Object singletonObject);

Source Link

Document

Register the given existing object as singleton in the bean registry, under the given bean name.

Usage

From source file:io.spring.initializr.web.test.MockMvcClientHttpRequestFactoryTestExecutionListener.java

@Override
public void beforeTestClass(TestContext testContext) throws Exception {
    ConfigurableBeanFactory beanFactory = (ConfigurableBeanFactory) testContext.getApplicationContext()
            .getAutowireCapableBeanFactory();
    if (!beanFactory.containsBean("mockMvcClientHttpRequestFactory")) {
        this.factory = new MockMvcClientHttpRequestFactory(beanFactory.getBean(MockMvc.class));
        beanFactory.registerSingleton("mockMvcClientHttpRequestFactory", this.factory);
    } else {/*w  w  w.j  a v a 2s.  c o  m*/
        this.factory = beanFactory.getBean("mockMvcClientHttpRequestFactory",
                MockMvcClientHttpRequestFactory.class);
    }
}

From source file:org.red5.server.war.RootContextLoaderServlet.java

/**
 * Main entry point for the Red5 Server as a war
 *///from  w ww . j  a  v a  2 s .c  o m
// Notification that the web application is ready to process requests
@Override
public void contextInitialized(ServletContextEvent sce) {
    if (null != servletContext) {
        return;
    }
    instance = this;
    System.setProperty("red5.deployment.type", "war");

    myClassloader = getClass().getClassLoader();

    servletContext = sce.getServletContext();
    String prefix = servletContext.getRealPath("/");

    servletContext.setAttribute("root.classloader", myClassloader);

    initRegistry(servletContext);

    long time = System.currentTimeMillis();

    logger.info("RED5 Server (http://www.osflash.org/red5)");
    logger.info("Root context loader");
    logger.debug("Path: " + prefix);

    try {
        // instance the context loader
        ContextLoader loader = createContextLoader();
        applicationContext = (ConfigurableWebApplicationContext) loader
                .initWebApplicationContext(servletContext);
        logger.debug("Root context path: " + applicationContext.getServletContext().getContextPath());

        ConfigurableBeanFactory factory = applicationContext.getBeanFactory();

        // register default
        factory.registerSingleton("default.context", applicationContext);

        // get the main factory
        parentFactory = (DefaultListableBeanFactory) factory.getParentBeanFactory();

        // create a wrapper around our primary context
        BeanFactoryReference beanfactoryRef = new ContextBeanFactoryReference(applicationContext);

        // set it in the root servlet context
        servletContext.setAttribute("bean.factory.ref", beanfactoryRef);

        // set a remoting codec factory for AMF use
        servletContext.setAttribute("remoting.codec.factory", parentFactory.getBean("remotingCodecFactory"));

        server = (Server) parentFactory.getBean("red5.server");

        clientRegistry = (ClientRegistry) factory.getBean("global.clientRegistry");

        globalInvoker = (ServiceInvoker) factory.getBean("global.serviceInvoker");

        globalStrategy = (MappingStrategy) factory.getBean("global.mappingStrategy");

        global = (GlobalScope) factory.getBean("global.scope");
        logger.debug("GlobalScope: " + global);
        global.setServer(server);
        global.register();
        global.start();

        globalResolver = new ScopeResolver();
        globalResolver.setGlobalScope(global);

        logger.debug("About to grab Webcontext bean for Global");
        Context globalContext = (Context) factory.getBean("global.context");
        globalContext.setCoreBeanFactory(parentFactory);
        globalContext.setClientRegistry(clientRegistry);
        globalContext.setServiceInvoker(globalInvoker);
        globalContext.setScopeResolver(globalResolver);
        globalContext.setMappingStrategy(globalStrategy);

        logger.debug("About to grab Webcontext bean for ROOT");
        Context webContext = (Context) factory.getBean("web.context");
        webContext.setCoreBeanFactory(parentFactory);
        webContext.setClientRegistry(clientRegistry);
        webContext.setServiceInvoker(globalInvoker);
        webContext.setScopeResolver(globalResolver);
        webContext.setMappingStrategy(globalStrategy);

        WebScope scope = (WebScope) factory.getBean("web.scope");
        scope.setServer(server);
        scope.setParent(global);
        scope.register();
        scope.start();

        // grab the scope list (other war/webapps)
        IRemotableList remote = (IRemotableList) Naming
                .lookup("rmi://localhost:" + rmiPort + "/subContextList");
        logger.debug("Children: " + remote.numChildren());
        if (remote.hasChildren()) {
            logger.debug("Children were detected");
            for (int i = 0; i < remote.numChildren(); i++) {
                logger.debug("Enumerating children");
                WebSettings settings = remote.getAt(i);
                registerSubContext(settings.getWebAppKey());
            }
            logger.debug("End of children...");
        }

    } catch (Throwable t) {
        logger.error(t);
    } finally {
        timer = new Timer();
        checkScopeList = new CheckScopeListTask();
        timer.scheduleAtFixedRate(checkScopeList, 1000, 30000);
    }

    long startupIn = System.currentTimeMillis() - time;
    logger.info("Startup done in: " + startupIn + " ms");

}

From source file:org.red5.server.ContextLoader.java

/**
 * Loads context (Red5 application) and stores it in context map, then adds
 * it's beans to parent (that is, Red5) 
 *
 * @param name          Context name//  w w  w.  j ava  2 s  . c  o  m
 * @param config        Filename
 */
protected void loadContext(String name, String config) {
    ApplicationContext context = new FileSystemXmlApplicationContext(new String[] { config }, parentContext);
    contextMap.put(name, context);
    // add the context to the parent, this will be red5.xml
    ConfigurableBeanFactory factory = ((ConfigurableApplicationContext) applicationContext).getBeanFactory();
    // Register context in parent bean factory
    factory.registerSingleton(name, context);
}

From source file:org.red5.server.war.MainServlet.java

/**
 * Main entry point for the Red5 Server as a war
 *///from  w  ww  . j a  v a 2 s .c  o  m
// Notification that the web application is ready to process requests
public void contextInitialized(ServletContextEvent sce) {
    System.setProperty("red5.deployment.type", "war");

    if (null != servletContext) {
        return;
    }
    servletContext = sce.getServletContext();
    String prefix = servletContext.getRealPath("/");

    long time = System.currentTimeMillis();

    logger.info("RED5 Server (http://www.osflash.org/red5)");
    logger.info("Loading red5 global context from: " + red5Config);
    logger.info("Path: " + prefix);

    try {
        // Detect root of Red5 configuration and set as system property
        String root;
        String classpath = System.getProperty("java.class.path");
        File fp = new File(prefix + red5Config);
        fp = fp.getCanonicalFile();
        if (!fp.isFile()) {
            // Given file does not exist, search it on the classpath
            String[] paths = classpath.split(System.getProperty("path.separator"));
            for (String element : paths) {
                fp = new File(element + "/" + red5Config);
                fp = fp.getCanonicalFile();
                if (fp.isFile()) {
                    break;
                }
            }
        }
        if (!fp.isFile()) {
            throw new Exception(
                    "could not find configuration file " + red5Config + " on your classpath " + classpath);
        }

        root = fp.getAbsolutePath();
        root = root.replace('\\', '/');
        int idx = root.lastIndexOf('/');
        root = root.substring(0, idx);
        // update classpath
        System.setProperty("java.class.path",
                classpath + File.pathSeparatorChar + root + File.pathSeparatorChar + root + "/classes");
        logger.debug("New classpath: " + System.getProperty("java.class.path"));
        // set configuration root
        System.setProperty("red5.config_root", root);
        logger.info("Setting configuation root to " + root);

        // Setup system properties so they can be evaluated
        Properties props = new Properties();
        props.load(new FileInputStream(root + "/red5.properties"));
        for (Object o : props.keySet()) {
            String key = (String) o;
            if (StringUtils.isNotBlank(key)) {
                System.setProperty(key, props.getProperty(key));
            }
        }

        // Store root directory of Red5
        idx = root.lastIndexOf('/');
        root = root.substring(0, idx);
        if (System.getProperty("file.separator").equals("/")) {
            // Workaround for linux systems
            root = "/" + root;
        }
        System.setProperty("red5.root", root);
        logger.info("Setting Red5 root to " + root);

        Class contextClass = org.springframework.web.context.support.XmlWebApplicationContext.class;
        ConfigurableWebApplicationContext applicationContext = (ConfigurableWebApplicationContext) BeanUtils
                .instantiateClass(contextClass);

        String[] strArray = servletContext.getInitParameter(ContextLoader.CONFIG_LOCATION_PARAM)
                .split("[,\\s]");
        logger.info("Config location files: " + strArray.length);
        applicationContext.setConfigLocations(strArray);
        applicationContext.setServletContext(servletContext);
        applicationContext.refresh();

        // set web application context as an attribute of the servlet
        // context so that it may be located via Springs
        // WebApplicationContextUtils
        servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,
                applicationContext);

        ConfigurableBeanFactory factory = applicationContext.getBeanFactory();
        // register default
        // add the context to the parent
        factory.registerSingleton("default.context", applicationContext);

    } catch (Throwable e) {
        logger.error("", e);
    }

    long startupIn = System.currentTimeMillis() - time;
    logger.info("Startup done in: " + startupIn + " ms");

}

From source file:org.red5.server.war.WarLoaderServlet.java

/**
 * Main entry point for the Red5 Server as a war
 *//*  ww w .j a v a 2s. c  o m*/
// Notification that the web application is ready to process requests
@Override
public void contextInitialized(ServletContextEvent sce) {
    if (null != servletContext) {
        return;
    }
    System.setProperty("red5.deployment.type", "war");

    servletContext = sce.getServletContext();
    String prefix = servletContext.getRealPath("/");

    long time = System.currentTimeMillis();

    logger.info("RED5 Server (http://www.osflash.org/red5)");
    logger.info("WAR loader");
    logger.debug("Path: " + prefix);

    try {
        // instance the context loader
        contextLoader = createContextLoader();
        applicationContext = (ConfigurableWebApplicationContext) contextLoader
                .initWebApplicationContext(servletContext);
        logger.debug("Root context path: " + applicationContext.getServletContext().getContextPath());

        ConfigurableBeanFactory factory = applicationContext.getBeanFactory();

        // register default
        factory.registerSingleton("default.context", applicationContext);

        // get the main factory
        parentFactory = (DefaultListableBeanFactory) factory.getParentBeanFactory();

    } catch (Throwable t) {
        logger.error("", t);
    }

    long startupIn = System.currentTimeMillis() - time;
    logger.info("Startup done in: " + startupIn + " ms");

}

From source file:org.springframework.xd.dirt.plugins.spark.streaming.SparkStreamingPlugin.java

@Override
public void postProcessModule(Module module) {
    ConfigurableApplicationContext moduleContext = module.getApplicationContext();
    ConfigurableEnvironment env = moduleContext.getEnvironment();
    String transport = env.getProperty("XD_TRANSPORT");
    Properties messageBusProperties = getMessageBusProperties(module);
    Properties inboundModuleProperties = this.extractConsumerProducerProperties(module)[0];
    Properties outboundModuleProperties = this.extractConsumerProducerProperties(module)[1];
    String defaultStorageLevel = env.getProperty(SparkStreamingSupport.SPARK_STORAGE_LEVEL_PROP);
    StorageLevel configuredStorageLevel = StorageLevel
            .fromString(StringUtils.hasText(defaultStorageLevel) ? defaultStorageLevel
                    : SparkStreamingSupport.SPARK_DEFAULT_STORAGE_LEVEL);
    String storageLevelFromModule = module.getProperties()
            .getProperty(SparkStreamingSupport.SPARK_STORAGE_LEVEL_MODULE_OPTION);
    StorageLevel storageLevel = StringUtils.hasText(storageLevelFromModule)
            ? StorageLevel.fromString(storageLevelFromModule)
            : configuredStorageLevel;//w w w . j a  va2 s  .c o m
    MessageBusReceiver receiver = null;
    if (transport.equals("local")) {
        SparkStreamingSupport processor;
        Properties sparkConfigs = null;
        try {
            processor = module.getComponent(SparkStreamingSupport.class);
            Assert.notNull(processor,
                    "Problem getting the spark streaming module. Is the module context active?");
            sparkConfigs = getSparkModuleProperties(processor);
        } catch (NoSuchBeanDefinitionException e) {
            throw new IllegalStateException("Either java or scala module should be present.");
        }
        String sparkMasterUrl = env.getProperty(SparkStreamingSupport.SPARK_MASTER_URL_PROP);
        if (sparkConfigs != null
                && StringUtils.hasText(sparkConfigs.getProperty(SparkStreamingSupport.SPARK_MASTER_URL_PROP))) {
            sparkMasterUrl = sparkConfigs.getProperty(SparkStreamingSupport.SPARK_MASTER_URL_PROP);
        }
        Assert.notNull(sparkMasterUrl, "Spark Master URL must be set.");
        if (!sparkMasterUrl.startsWith("local")) {
            throw new IllegalStateException("Spark cluster mode must be 'local' for 'local' XD transport.");
        }
        LocalMessageBusHolder messageBusHolder = new LocalMessageBusHolder();
        LocalMessageBusHolder.set(module.getComponent(MessageBus.class));
        receiver = new MessageBusReceiver(messageBusHolder, storageLevel, messageBusProperties,
                inboundModuleProperties, ModuleTypeConversionSupport.getInputMimeType(module));
        if (module.getType().equals(ModuleType.processor)) {
            MessageBusSender sender = new MessageBusSender(messageBusHolder, getOutputChannelName(module),
                    buildTapChannelName(module), messageBusProperties, outboundModuleProperties,
                    ModuleTypeConversionSupport.getOutputMimeType(module), module.getProperties());
            ConfigurableBeanFactory beanFactory = module.getApplicationContext().getBeanFactory();
            beanFactory.registerSingleton("messageBusSender", sender);
        }
    } else {
        receiver = new MessageBusReceiver(storageLevel, messageBusProperties, inboundModuleProperties,
                ModuleTypeConversionSupport.getInputMimeType(module));
        if (module.getType().equals(ModuleType.processor)) {
            ConfigurableBeanFactory beanFactory = module.getApplicationContext().getBeanFactory();
            MessageBusSender sender = new MessageBusSender(getOutputChannelName(module),
                    buildTapChannelName(module), messageBusProperties, outboundModuleProperties,
                    ModuleTypeConversionSupport.getOutputMimeType(module), module.getProperties());
            beanFactory.registerSingleton("messageBusSender", sender);
        }
    }
    registerMessageBusReceiver(receiver, module);

    // This used to be in SSDModule.start
    try {
        SparkStreamingSupport processor = module.getComponent(SparkStreamingSupport.class);
        Assert.notNull(processor, "Problem getting the spark streaming module. Is the module context active?");
        Properties sparkConfigs = getSparkModuleProperties(processor);
        startSparkStreamingContext(sparkConfigs, processor, module);
    } catch (NoSuchBeanDefinitionException e) {
        throw new IllegalStateException("Either java or scala module should be present.");
    }

}

From source file:org.springframework.xd.dirt.plugins.spark.streaming.SparkStreamingPlugin.java

/**
 * Register the messsage bus receiver.// w w  w  .  j a  va  2 s  . com
 * @param receiver the message bus receiver
 * @param module the spark streaming module
 */

private void registerMessageBusReceiver(MessageBusReceiver receiver, Module module) {
    receiver.setInputChannelName(getInputChannelName(module));
    ConfigurableBeanFactory beanFactory = module.getApplicationContext().getBeanFactory();
    beanFactory.registerSingleton("messageBusReceiver", receiver);
}