Example usage for org.springframework.beans.factory.config ConfigurableListableBeanFactory getBean

List of usage examples for org.springframework.beans.factory.config ConfigurableListableBeanFactory getBean

Introduction

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

Prototype

Object getBean(String name) throws BeansException;

Source Link

Document

Return an instance, which may be shared or independent, of the specified bean.

Usage

From source file:org.projectforge.web.wicket.WicketApplication.java

@Override
protected void init() {
    super.init();
    // Own error page for deployment mode and UserException and AccessException.
    getRequestCycleListeners().add(new AbstractRequestCycleListener() {
        /**/*from  w  w w . ja  v  a  2s  .  c o m*/
         * Log only non ProjectForge exceptions.
         * @see org.apache.wicket.request.cycle.AbstractRequestCycleListener#onException(org.apache.wicket.request.cycle.RequestCycle,
         *      java.lang.Exception)
         */
        @Override
        public IRequestHandler onException(final RequestCycle cycle, final Exception ex) {
            // in case of expired session, please redirect to home page
            if (ex instanceof PageExpiredException) {
                return new RenderPageRequestHandler(new PageProvider(getHomePage()));
            }
            final Throwable rootCause = ExceptionHelper.getRootCause(ex);
            // log.error(rootCause.getMessage(), ex);
            // if (rootCause instanceof ProjectForgeException == false) {
            // return super.onException(cycle, ex);
            // }
            // return null;
            if (isDevelopmentSystem() == true) {
                log.error(ex.getMessage(), ex);
                if (rootCause instanceof SQLException) {
                    SQLException next = (SQLException) rootCause;
                    while ((next = next.getNextException()) != null) {
                        log.error(next.getMessage(), next);
                    }
                }
                return super.onException(cycle, ex);
            } else {
                // Show always this error page in production mode:
                return new RenderPageRequestHandler(new PageProvider(new ErrorPage(ex)));
            }
        }
    });

    getApplicationSettings().setDefaultMaximumUploadSize(Bytes.megabytes(100));
    getMarkupSettings().setDefaultMarkupEncoding("utf-8");
    final MyAuthorizationStrategy authStrategy = new MyAuthorizationStrategy();
    getSecuritySettings().setAuthorizationStrategy(authStrategy);
    getSecuritySettings().setUnauthorizedComponentInstantiationListener(authStrategy);
    // Prepend the resource bundle for overwriting some Wicket default localizations (such as StringValidator.*)
    getResourceSettings().getStringResourceLoaders().add(new BundleStringResourceLoader(RESOURCE_BUNDLE_NAME));
    getResourceSettings().setThrowExceptionOnMissingResource(false); // Don't throw MissingResourceException for missing i18n keys.
    getApplicationSettings().setPageExpiredErrorPage(PageExpiredPage.class); // Don't show expired page.
    // getSessionSettings().setMaxPageMaps(20); // Map up to 20 pages per session (default is 5).
    getComponentInstantiationListeners().add(new SpringComponentInjector(this));
    getApplicationSettings().setInternalErrorPage(ErrorPage.class);
    // getRequestCycleSettings().setGatherExtendedBrowserInfo(true); // For getting browser width and height.

    // Select2:
    // final ApplicationSettings select2Settings = ApplicationSettings.get();
    // select2Settings.setIncludeJavascript(false);

    final XmlWebApplicationContext webApplicationContext = (XmlWebApplicationContext) WebApplicationContextUtils
            .getWebApplicationContext(getServletContext());
    final ConfigurableListableBeanFactory beanFactory = webApplicationContext.getBeanFactory();
    beanFactory.autowireBeanProperties(this, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false);
    final LocalSessionFactoryBean localSessionFactoryBean = (LocalSessionFactoryBean) beanFactory
            .getBean("&sessionFactory");

    // if ("true".equals(System.getProperty(SYSTEM_PROPERTY_HSQLDB_18_UPDATE)) == true) {
    // try {
    // log.info("Send SHUTDOWN COMPACT to upgrade data-base version:");
    // final DataSource dataSource = (DataSource)beanFactory.getBean("dataSource");
    // dataSource.getConnection().createStatement().execute("SHUTDOWN COMPACT");
    // log.fatal("************ PLEASE RESTART APPLICATION NOW FOR PROPER INSTALLATION !!!!!!!!!!!!!! ************");
    // return;
    // } catch (final SQLException ex) {
    // log.fatal("Data-base SHUTDOWN COMPACT failed: " + ex.getMessage());
    // }
    // }
    final org.hibernate.cfg.Configuration hibernateConfiguration = localSessionFactoryBean.getConfiguration();
    HibernateUtils.setConfiguration(hibernateConfiguration);
    final ServletContext servletContext = getServletContext();
    final String configContextPath = configXml.getServletContextPath();
    String contextPath;
    if (StringUtils.isBlank(configContextPath) == true) {
        contextPath = servletContext.getContextPath();
        configXml.setServletContextPath(contextPath);
    } else {
        contextPath = configContextPath;
    }
    log.info("Using servlet context path: " + contextPath);
    if (configuration.getBeanFactory() == null) {
        configuration.setBeanFactory(beanFactory);
    }
    configuration.setConfigurationDao(configurationDao);
    SystemInfoCache.internalInitialize(systemInfoCache);
    WicketUtils.setContextPath(contextPath);
    UserFilter.initialize(userDao, contextPath);
    if (this.wicketApplicationFilter != null) {
        this.wicketApplicationFilter.setApplication(this);
    } else {
        throw new RuntimeException("this.wicketApplicationFilter is null");
    }
    daoRegistry.init();

    final PluginsRegistry pluginsRegistry = PluginsRegistry.instance();
    pluginsRegistry.set(beanFactory, getResourceSettings());
    pluginsRegistry.set(systemUpdater);
    pluginsRegistry.initialize();

    for (final Map.Entry<String, Class<? extends WebPage>> mountPage : WebRegistry.instance().getMountPages()
            .entrySet()) {
        final String path = mountPage.getKey();
        final Class<? extends WebPage> pageClass = mountPage.getValue();
        mountPage(path, pageClass);
        mountedPages.put(pageClass, path);
    }
    if (isDevelopmentSystem() == true) {
        if (isStripWicketTags() == true) {
            log.info("Strip Wicket tags also in development mode at default (see context.xml).");
            Application.get().getMarkupSettings().setStripWicketTags(true);
        }
        getDebugSettings().setOutputMarkupContainerClassName(true);
    }
    log.info("Default TimeZone is: " + TimeZone.getDefault());
    if ("UTC".equals(TimeZone.getDefault().getID()) == false) {
        for (final String str : UTC_RECOMMENDED) {
            log.fatal(str);
        }
        for (final String str : UTC_RECOMMENDED) {
            System.err.println(str);
        }
    }
    log.info("user.timezone is: " + System.getProperty("user.timezone"));
    cronSetup.initialize();
    log.info(AppVersion.APP_ID + " " + AppVersion.NUMBER + " (" + AppVersion.RELEASE_TIMESTAMP
            + ") initialized.");

    PFUserContext.setUser(DatabaseUpdateDao.__internalGetSystemAdminPseudoUser()); // Logon admin user.
    if (systemUpdater.isUpdated() == false) {
        // Force redirection to update page:
        UserFilter.setUpdateRequiredFirst(true);
    }
    PFUserContext.setUser(null);
    UserXmlPreferencesCache.setInternalInstance(userXmlPreferencesCache);
    LoginHandler loginHandler;
    if (StringUtils.isNotBlank(configXml.getLoginHandlerClass()) == true) {
        loginHandler = (LoginHandler) BeanHelper.newInstance(configXml.getLoginHandlerClass());
    } else {
        loginHandler = new LoginDefaultHandler();
    }
    if (loginHandler == null) {
        log.error("Can't load login handler '" + configXml.getLoginHandlerClass()
                + "'. No login will be possible!");
    } else {
        loginHandler.initialize();
        Login.getInstance().setLoginHandler(loginHandler);
    }
    try {
        StorageClient.getInstance(); // Initialize storage
    } catch (final Exception ex) {
        log.error(ex.getMessage(), ex);
    }
    getPageSettings().setRecreateMountedPagesAfterExpiry(false);

    // initialize ical4j to be more "relaxed"
    CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_PARSING, true);
    CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_UNFOLDING, true);
    CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_VALIDATION, true);

    // initialize styles compiler
    try {
        final LessWicketApplicationInstantiator lessInstantiator = new LessWicketApplicationInstantiator(this,
                "styles", "projectforge.less", "projectforge.css");
        lessInstantiator.instantiate();
    } catch (final Exception e) {
        log.error("Unable to instantiate wicket less compiler", e);
    }
}

From source file:org.springframework.batch.core.jsr.launch.support.BatchPropertyBeanPostProcessor.java

@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
    if (!(beanFactory instanceof ConfigurableListableBeanFactory)) {
        throw new IllegalArgumentException(
                "BatchPropertyBeanPostProcessor requires a ConfigurableListableBeanFactory");
    }/*from  ww w .j  a v  a2  s  .  c  om*/

    ConfigurableListableBeanFactory configurableListableBeanFactory = (ConfigurableListableBeanFactory) beanFactory;

    BeanExpressionContext beanExpressionContext = new BeanExpressionContext(configurableListableBeanFactory,
            configurableListableBeanFactory.getBean(StepScope.class));

    this.jsrExpressionParser = new JsrExpressionParser(new StandardBeanExpressionResolver(),
            beanExpressionContext);
}

From source file:org.springframework.context.support.DefaultLifecycleProcessor.java

/**
 * Retrieve all applicable Lifecycle beans: all singletons that have already been created,
 * as well as all SmartLifecycle beans (even if they are marked as lazy-init).
 * @return the Map of applicable beans, with bean names as keys and bean instances as values
 *//*w w  w . j  av  a2 s.c  o  m*/
protected Map<String, Lifecycle> getLifecycleBeans() {
    ConfigurableListableBeanFactory beanFactory = getBeanFactory();
    Map<String, Lifecycle> beans = new LinkedHashMap<>();
    String[] beanNames = beanFactory.getBeanNamesForType(Lifecycle.class, false, false);
    for (String beanName : beanNames) {
        String beanNameToRegister = BeanFactoryUtils.transformedBeanName(beanName);
        boolean isFactoryBean = beanFactory.isFactoryBean(beanNameToRegister);
        String beanNameToCheck = (isFactoryBean ? BeanFactory.FACTORY_BEAN_PREFIX + beanName : beanName);
        if ((beanFactory.containsSingleton(beanNameToRegister)
                && (!isFactoryBean || matchesBeanType(Lifecycle.class, beanNameToCheck, beanFactory)))
                || matchesBeanType(SmartLifecycle.class, beanNameToCheck, beanFactory)) {
            Object bean = beanFactory.getBean(beanNameToCheck);
            if (bean != this && bean instanceof Lifecycle) {
                beans.put(beanNameToRegister, (Lifecycle) bean);
            }
        }
    }
    return beans;
}

From source file:org.springframework.data.gemfire.client.GemfireDataSourcePostProcessor.java

private void createClientRegions(ConfigurableListableBeanFactory beanFactory) {
    GemfireFunctionOperations functionTemplate = new GemfireOnServersFunctionTemplate(cache);

    Iterable<String> regionNames = functionTemplate.executeAndExtract(new ListRegionsOnServerFunction());

    ClientRegionFactory<?, ?> clientRegionFactory = null;

    if (regionNames != null && regionNames.iterator().hasNext()) {
        clientRegionFactory = cache.createClientRegionFactory(ClientRegionShortcut.PROXY);
    }//from w w  w . jav  a 2s . co  m

    for (String regionName : regionNames) {
        boolean createRegion = true;

        if (beanFactory.containsBean(regionName)) {
            Object existingBean = beanFactory.getBean(regionName);
            Assert.isTrue(existingBean instanceof Region, String.format(
                    "Cannot create a ClientRegion bean named '%1$s'. A bean with this name of type '%2$s' already exists.",
                    regionName, existingBean.getClass().getName()));
            createRegion = false;
        }

        if (createRegion) {
            if (logger.isDebugEnabled()) {
                logger.debug(String.format("Creating Client Region bean with name '%s'...", regionName));
            }
            beanFactory.registerSingleton(regionName, clientRegionFactory.create(regionName));
        } else {
            if (logger.isDebugEnabled()) {
                logger.debug(String.format("A Region named '%s' is already defined.", regionName));
            }
        }
    }
}