Example usage for org.hibernate.cfg Configuration getProperty

List of usage examples for org.hibernate.cfg Configuration getProperty

Introduction

In this page you can find the example usage for org.hibernate.cfg Configuration getProperty.

Prototype

public String getProperty(String propertyName) 

Source Link

Document

Get a property value by name

Usage

From source file:org.pentaho.pat.plugin.PatLifeCycleListener.java

License:Open Source License

public void loaded() throws PluginLifecycleException {
    ClassLoader origContextClassloader = Thread.currentThread().getContextClassLoader();
    IServiceManager serviceManager = (IServiceManager) PentahoSystem.get(IServiceManager.class,
            PentahoSessionHolder.getSession());
    try {//from  w  w w  . ja  v  a2  s  . co m
        sessionBean = (SessionServlet) serviceManager.getServiceBean("gwt", "session.rpc"); //$NON-NLS-1$
        queryBean = (QueryServlet) serviceManager.getServiceBean("gwt", "query.rpc"); //$NON-NLS-1$
        discoveryBean = (DiscoveryServlet) serviceManager.getServiceBean("gwt", "discovery.rpc"); //$NON-NLS-1$
        platformBean = (PlatformServlet) serviceManager.getServiceBean("gwt", "platform.rpc"); //$NON-NLS-1$

        final IPluginManager pluginManager = (IPluginManager) PentahoSystem.get(IPluginManager.class,
                PentahoSessionHolder.getSession());
        final PluginClassLoader pluginClassloader = (PluginClassLoader) pluginManager
                .getClassLoader(PAT_PLUGIN_NAME);
        final String hibernateConfigurationFile = PentahoSystem
                .getSystemSetting("hibernate/hibernate-settings.xml", "settings/config-file", null); //$NON-NLS-1$
        final String pentahoHibConfigPath = PentahoSystem.getApplicationContext()
                .getSolutionPath(hibernateConfigurationFile);

        if (pluginClassloader == null)
            throw new ServiceException(Messages.getString("LifeCycleListener.NoPluginClassloader")); //$NON-NLS-1$

        Thread.currentThread().setContextClassLoader(pluginClassloader);
        final URL contextUrl = pluginClassloader.getResource(PAT_APP_CONTEXT);
        final URL patHibConfigUrl = pluginClassloader.getResource(PAT_HIBERNATE_CONFIG);
        final URL patPluginPropertiesUrl = pluginClassloader.getResource(PAT_PLUGIN_PROPERTIES);
        if (patHibConfigUrl == null)
            throw new ServiceException("File not found: PAT Hibernate Config : " + PAT_HIBERNATE_CONFIG);
        else
            LOG.debug(PAT_PLUGIN_NAME + ": PAT Hibernate Config:" + patHibConfigUrl.toString());

        if (patPluginPropertiesUrl == null)
            throw new ServiceException("File not found: PAT Plugin properties : " + PAT_PLUGIN_PROPERTIES);
        else
            LOG.debug(PAT_PLUGIN_NAME + ": PAT Plugin Properties:" + patPluginPropertiesUrl.toString());

        if (contextUrl != null) {
            String appContextUrl = contextUrl.toString();
            final ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(
                    new String[] { appContextUrl }, false);
            applicationContext.setClassLoader(pluginClassloader);
            applicationContext.setConfigLocation(appContextUrl);
            applicationContext.setAllowBeanDefinitionOverriding(true);

            final Configuration pentahoHibConfig = new Configuration();
            pentahoHibConfig.configure(new File(pentahoHibConfigPath));

            final AnnotationConfiguration patHibConfig = new AnnotationConfiguration();
            patHibConfig.configure(patHibConfigUrl);

            Properties properties = new Properties();
            properties.load(pluginClassloader.getResourceAsStream(PAT_PLUGIN_PROPERTIES));
            String hibernateDialectCfg = (String) properties.get("pat.plugin.datasource.hibernate.dialect");
            String hibernateDialect = null;
            if (StringUtils.isNotBlank(hibernateDialectCfg)) {
                if (hibernateDialectCfg.equals("auto")) {
                    hibernateDialect = pentahoHibConfig.getProperty("dialect");
                } else {
                    hibernateDialect = hibernateDialectCfg;
                }
            }

            if (StringUtils.isNotBlank(hibernateDialect)) {
                patHibConfig.setProperty("hibernate.dialect", hibernateDialect);
                LOG.info(PAT_PLUGIN_NAME + " : using hibernate dialect: " + hibernateDialect);
            }

            String dataSourceType = (String) properties.get("pat.plugin.datasource.type");
            String datasourceResource = null;
            if (StringUtils.isNotEmpty(dataSourceType) && dataSourceType.equals("jdbc")) {
                datasourceResource = PAT_DATASOURCE_JDBC;
                LOG.info(PAT_PLUGIN_NAME + " : using JDBC connection");

            }
            if (StringUtils.isNotEmpty(dataSourceType) && dataSourceType.equals("jndi")) {
                datasourceResource = PAT_DATASOURCE_JNDI;
                LOG.info(PAT_PLUGIN_NAME + " : using JNDI : " + (String) properties.get("jndi.name"));
            }

            XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource(datasourceResource));
            PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer();
            cfg.setLocation(new ClassPathResource(PAT_PLUGIN_PROPERTIES));
            cfg.postProcessBeanFactory(factory);

            XmlBeanFactory bfSession = new XmlBeanFactory(new ClassPathResource(PAT_SESSIONFACTORY), factory);

            PropertyPlaceholderConfigurer cfgSession = new PropertyPlaceholderConfigurer();
            cfgSession.setProperties(patHibConfig.getProperties());
            cfgSession.postProcessBeanFactory(bfSession);

            ClassPathXmlApplicationContext tmpCtxt = new ClassPathXmlApplicationContext();
            tmpCtxt.refresh();
            DefaultListableBeanFactory tmpBf = (DefaultListableBeanFactory) tmpCtxt.getBeanFactory();

            tmpBf.setParentBeanFactory(bfSession);

            applicationContext.setClassLoader(pluginClassloader);
            applicationContext.setParent(tmpCtxt);
            applicationContext.refresh();

            sessionBean.setStandalone(true);
            SessionServlet.setApplicationContext(applicationContext);
            sessionBean.init();

            queryBean.setStandalone(true);
            QueryServlet.setApplicationContext(applicationContext);
            queryBean.init();

            discoveryBean.setStandalone(true);
            DiscoveryServlet.setApplicationContext(applicationContext);
            discoveryBean.init();

            platformBean.setStandalone(true);
            PlatformServlet.setApplicationContext(applicationContext);
            platformBean.init();

            injectPentahoXmlaUrl();
        } else {
            throw new Exception(Messages.getString("LifeCycleListener.AppContextNotFound"));
        }

    } catch (ServiceException e1) {
        LOG.error(e1.getMessage(), e1);
    } catch (ServletException e) {
        LOG.error(e.getMessage(), e);
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
    } finally {
        // reset the classloader of the current thread
        if (origContextClassloader != null) {
            Thread.currentThread().setContextClassLoader(origContextClassloader);
        }
    }
}

From source file:org.sns.tool.hibernate.analyzer.HibernateAnalysis.java

License:Open Source License

public HibernateAnalysis(final Configuration configuration, final List<HibernateAnalysisRule> analyzers) {
    this.configuration = configuration;
    this.analysisRules = analyzers;

    // the following was copied from org.hibernate.cfg.Configuration.buildMapping() because buildMapping() was private
    this.mapping = new Mapping() {
        /**/*from  www .jav  a 2 s. c  om*/
         * Returns the identifier type of a mapped class
         */
        public Type getIdentifierType(String persistentClass) throws MappingException {
            final PersistentClass pc = configuration.getClassMapping(persistentClass);
            if (pc == null)
                throw new MappingException("persistent class not known: " + persistentClass);
            return pc.getIdentifier().getType();
        }

        public String getIdentifierPropertyName(String persistentClass) throws MappingException {
            final PersistentClass pc = configuration.getClassMapping(persistentClass);
            if (pc == null)
                throw new MappingException("persistent class not known: " + persistentClass);
            if (!pc.hasIdentifierProperty())
                return null;
            return pc.getIdentifierProperty().getName();
        }

        public Type getPropertyType(String persistentClass, String propertyName) throws MappingException {
            final PersistentClass pc = configuration.getClassMapping(persistentClass);
            if (pc == null)
                throw new MappingException("persistent class not known: " + persistentClass);
            Property prop = pc.getProperty(propertyName);
            if (prop == null)
                throw new MappingException("property not known: " + persistentClass + '.' + propertyName);
            return prop.getType();
        }
    };

    String dialectName = configuration.getProperty(Environment.DIALECT);
    if (dialectName == null)
        dialectName = org.hibernate.dialect.GenericDialect.class.getName();

    try {
        final Class cls = Class.forName(dialectName);
        this.dialect = (Dialect) cls.newInstance();
    } catch (Exception e) {
        throw new HibernateDiagramGeneratorException(e);
    }

    for (final Iterator classes = configuration.getClassMappings(); classes.hasNext();) {
        final PersistentClass pclass = (PersistentClass) classes.next();
        final Table table = (Table) pclass.getTable();

        tableToClassMap.put(table, pclass);
    }
}

From source file:org.sns.tool.hibernate.dbdd.DatabaseDesignGeneratorTask.java

License:Open Source License

public void execute() throws BuildException {
    if (hibernateConfigClass == null)
        throw new BuildException("hibernateConfigClass was not provided.");

    if (structureRulesClass == null)
        throw new BuildException("structureRulesClass was not provided.");

    if (docBookFile == null)
        throw new BuildException("indexFile was not provided.");

    try {/*from   w  w w . j  av  a2 s. co  m*/
        final Configuration configuration = (Configuration) hibernateConfigClass.newInstance();
        if (hibernateConfigFile != null)
            configuration.configure(hibernateConfigFile);

        final TableStructure structure;
        if (structureClass == null) {
            final TableStructureRules rules = (TableStructureRules) structureRulesClass.newInstance();
            structure = new DefaultTableStructure(configuration, rules);
        } else {
            final Constructor ctr = structureClass
                    .getConstructor(new Class[] { Configuration.class, TableStructureRules.class });
            final TableStructureRules rules = (TableStructureRules) structureRulesClass.newInstance();
            structure = (TableStructure) ctr.newInstance(new Object[] { configuration, rules });
        }

        if (dialectClass != null)
            configuration.setProperty(Environment.DIALECT, dialectClass);

        final DatabaseDiagramRenderer ddr = (DatabaseDiagramRenderer) databaseDiagramRendererClass
                .newInstance();
        final MappedClassDocumentationProviders mcdp = (MappedClassDocumentationProviders) mappedClassDocumentationProvidersClass
                .newInstance();

        log("Using Hibernate Configuration " + configuration.getClass());
        log("Using Structure " + structure.getClass());
        log("Using Structure Rules " + structure.getRules().getClass());
        log("Using Dialect " + configuration.getProperty(Environment.DIALECT));
        log("Using Renderer " + ddr.getClass());
        log("Using Mapped Class Documentation Providers " + mcdp.getClass());

        final ByteArrayOutputStream graphvizCmdOutputStreamBuffer = new ByteArrayOutputStream();
        final PrintStream graphvizCmdOutputStream = new PrintStream(graphvizCmdOutputStreamBuffer);

        final DatabaseDesignGeneratorConfig ddgConfig = new DatabaseDesignGeneratorConfig() {
            public File getImagesDirectory() {
                return destDir == null ? docBookFile.getParentFile() : destDir;
            }

            public Configuration getHibernateConfiguration() {
                return configuration;
            }

            public File getDocBookFile() {
                return docBookFile;
            }

            public File getAssociatedJavaDocHome() {
                return associatedJavaDocHome;
            }

            public String getDocumentTitle() {
                return documentTitle == null ? "No documentTitle attribute provided." : documentTitle;
            }

            public TableStructure getTableStructure() {
                return structure;
            }

            public DatabaseDiagramRenderer getDatabaseDiagramRenderer() {
                return ddr;
            }

            public MappedClassDocumentationProviders getMappedClassDocumentationProviders() {
                return mcdp;
            }

            public String getGraphvizDiagramOutputType() {
                return graphvizDotOutputType;
            }

            public String getGraphVizDotCommandSpec() {
                return graphvizDotCmdSpec;
            }

            public PrintStream getGraphVizDotLogOutputStream() {
                return graphvizCmdOutputStream;
            }
        };

        final DatabaseDesignGenerator ddg = new DatabaseDesignGenerator(ddgConfig);
        ddg.generateDatabaseDesign();

        if (logGraphvizOutput)
            log(graphvizCmdOutputStreamBuffer.toString());
    } catch (Exception e) {
        throw new BuildException(e);
    }
}

From source file:org.sns.tool.hibernate.document.diagram.HibernateDiagramGeneratorTask.java

License:Open Source License

public void execute() throws BuildException {
    if (hibernateConfigClass == null)
        throw new BuildException("hibernateConfigClass was not provided.");

    if (diagramFilterClass == null)
        throw new BuildException("diagramFilterClass was not provided.");

    try {// www.  j  a v a 2  s .c  om
        final HibernateDiagramGeneratorFilter filter = (HibernateDiagramGeneratorFilter) diagramFilterClass
                .newInstance();
        log("Using diagram filter " + filter.getClass());

        final Configuration configuration = (Configuration) hibernateConfigClass.newInstance();
        log("Using configuration " + configuration.getClass());

        if (dialectClass != null) {
            configuration.setProperty(Environment.DIALECT, dialectClass);
            log("Using dialect " + configuration.getProperty(Environment.DIALECT));
        }

        if (hibernateConfigFile != null) {
            configuration.configure(hibernateConfigFile);
            log("Using config file " + hibernateConfigFile);
        }

        final GraphvizDiagramGenerator gdg = new GraphvizDiagramGenerator(diagramId, true,
                GraphvizLayoutType.DOT);
        final HibernateDiagramGenerator hdg = new HibernateDiagramGenerator(configuration, gdg, filter);
        hdg.generate();
        gdg.generateDOTSource(dotFile);

        log("DOT file " + dotFile + " written.");
    } catch (IllegalAccessException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    } catch (IOException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    } catch (InstantiationException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    }
}

From source file:org.sns.tool.hibernate.struct.impl.DefaultTableStructure.java

License:Open Source License

public DefaultTableStructure(final Configuration configuration, final TableStructureRules rules) {
    this.configuration = configuration;
    this.configuration.buildMappings();
    this.rules = rules;

    for (final Iterator classes = configuration.getClassMappings(); classes.hasNext();) {
        final PersistentClass pclass = (PersistentClass) classes.next();
        final Table table = (Table) pclass.getTable();

        boolean isChildTable = false;
        for (final Iterator fKeys = table.getForeignKeyIterator(); fKeys.hasNext();) {
            final ForeignKey foreignKey = (ForeignKey) fKeys.next();
            if (rules.isParentRelationship(this, foreignKey)) {
                isChildTable = true;//from w  ww  .  ja va2  s . c o m
                break;
            }
        }

        if (!isChildTable) {
            final TableStructureNode topLevelNode = createNode(pclass, table, null, 0);
            topLevelTableNodes.add(topLevelNode);
            categorize(topLevelNode);
        }
    }

    for (final Iterator classes = configuration.getClassMappings(); classes.hasNext();) {
        final PersistentClass pclass = (PersistentClass) classes.next();
        final Table table = (Table) pclass.getTable();

        tableToClassMap.put(table, pclass);
    }

    // the following was copied from org.hibernate.cfg.Configuration.buildMapping() because buildMapping() was private
    this.mapping = new Mapping() {
        public Type getReferencedPropertyType(String string, String string1) throws MappingException {
            return null;
        }

        /**
         * Returns the identifier type of a mapped class
         */
        public Type getIdentifierType(String persistentClass) throws MappingException {
            final PersistentClass pc = configuration.getClassMapping(persistentClass);
            if (pc == null)
                throw new MappingException("persistent class not known: " + persistentClass);
            return pc.getIdentifier().getType();
        }

        public String getIdentifierPropertyName(String persistentClass) throws MappingException {
            final PersistentClass pc = configuration.getClassMapping(persistentClass);
            if (pc == null)
                throw new MappingException("persistent class not known: " + persistentClass);
            if (!pc.hasIdentifierProperty())
                return null;
            return pc.getIdentifierProperty().getName();
        }

        public Type getPropertyType(String persistentClass, String propertyName) throws MappingException {
            final PersistentClass pc = configuration.getClassMapping(persistentClass);
            if (pc == null)
                throw new MappingException("persistent class not known: " + persistentClass);
            Property prop = pc.getProperty(propertyName);
            if (prop == null)
                throw new MappingException("property not known: " + persistentClass + '.' + propertyName);
            return prop.getType();
        }
    };

    String dialectName = configuration.getProperty(Environment.DIALECT);
    if (dialectName == null)
        dialectName = org.hibernate.dialect.GenericDialect.class.getName();

    try {
        final Class cls = Class.forName(dialectName);
        this.dialect = (Dialect) cls.newInstance();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    resolveDependencies();
}

From source file:org.specrunner.hibernate3.PluginConfiguration.java

License:Open Source License

/**
 * Change URL if thread safe is true.//  ww w . j a  v a 2 s  .  com
 * 
 * @param context
 *            The context.
 * @param cfg
 *            The configuration.
 */
protected void changeUrl(IContext context, Configuration cfg) {
    String url = String
            .valueOf(SRServices.get(IConcurrentMapping.class).get("url", cfg.getProperty(Environment.URL)));
    cfg.setProperty(Environment.URL, url);
    Node node = context.getNode();
    if (node instanceof Element) {
        Element ele = (Element) node;
        Attribute att = ele.getAttribute("title");
        if (att == null) {
            att = new Attribute("title", "");
            ele.addAttribute(att);
        }
        att.setValue("URL='" + url + "'");
    }
    if (UtilLog.LOG.isInfoEnabled()) {
        UtilLog.LOG.info("Connection URL set to '" + url + "'.");
    }
}

From source file:org.springframework.orm.hibernate3.LocalSessionFactoryBean.java

License:Apache License

@Override
@SuppressWarnings("unchecked")
protected SessionFactory buildSessionFactory() throws Exception {
    // Create Configuration instance.
    Configuration config = newConfiguration();

    DataSource dataSource = getDataSource();
    if (dataSource != null) {
        // Make given DataSource available for SessionFactory configuration.
        configTimeDataSourceHolder.set(dataSource);
    }// www.j a v a2s .  co  m
    if (this.jtaTransactionManager != null) {
        // Make Spring-provided JTA TransactionManager available.
        configTimeTransactionManagerHolder.set(this.jtaTransactionManager);
    }
    if (this.cacheRegionFactory != null) {
        // Make Spring-provided Hibernate RegionFactory available.
        configTimeRegionFactoryHolder.set(this.cacheRegionFactory);
    }
    if (this.lobHandler != null) {
        // Make given LobHandler available for SessionFactory configuration.
        // Do early because because mapping resource might refer to custom types.
        configTimeLobHandlerHolder.set(this.lobHandler);
    }

    // Analogous to Hibernate EntityManager's Ejb3Configuration:
    // Hibernate doesn't allow setting the bean ClassLoader explicitly,
    // so we need to expose it as thread context ClassLoader accordingly.
    Thread currentThread = Thread.currentThread();
    ClassLoader threadContextClassLoader = currentThread.getContextClassLoader();
    boolean overrideClassLoader = (this.beanClassLoader != null
            && !this.beanClassLoader.equals(threadContextClassLoader));
    if (overrideClassLoader) {
        currentThread.setContextClassLoader(this.beanClassLoader);
    }

    try {
        if (isExposeTransactionAwareSessionFactory()) {
            // Set Hibernate 3.1+ CurrentSessionContext implementation,
            // providing the Spring-managed Session as current Session.
            // Can be overridden by a custom value for the corresponding Hibernate property.
            config.setProperty(Environment.CURRENT_SESSION_CONTEXT_CLASS, SpringSessionContext.class.getName());
        }

        if (this.jtaTransactionManager != null) {
            // Set Spring-provided JTA TransactionManager as Hibernate property.
            config.setProperty(Environment.TRANSACTION_STRATEGY, JTATransactionFactory.class.getName());
            config.setProperty(Environment.TRANSACTION_MANAGER_STRATEGY,
                    LocalTransactionManagerLookup.class.getName());
        } else {
            // Makes the Hibernate Session aware of the presence of a Spring-managed transaction.
            // Also sets connection release mode to ON_CLOSE by default.
            config.setProperty(Environment.TRANSACTION_STRATEGY, SpringTransactionFactory.class.getName());
        }

        if (this.entityInterceptor != null) {
            // Set given entity interceptor at SessionFactory level.
            config.setInterceptor(this.entityInterceptor);
        }

        if (this.namingStrategy != null) {
            // Pass given naming strategy to Hibernate Configuration.
            config.setNamingStrategy(this.namingStrategy);
        }

        if (this.typeDefinitions != null) {
            // Register specified Hibernate type definitions.
            Mappings mappings = config.createMappings();
            for (TypeDefinitionBean typeDef : this.typeDefinitions) {
                mappings.addTypeDef(typeDef.getTypeName(), typeDef.getTypeClass(), typeDef.getParameters());
            }
        }

        if (this.filterDefinitions != null) {
            // Register specified Hibernate FilterDefinitions.
            for (FilterDefinition filterDef : this.filterDefinitions) {
                config.addFilterDefinition(filterDef);
            }
        }

        if (this.configLocations != null) {
            for (Resource resource : this.configLocations) {
                // Load Hibernate configuration from given location.
                config.configure(resource.getURL());
            }
        }

        if (this.hibernateProperties != null) {
            // Add given Hibernate properties to Configuration.
            config.addProperties(this.hibernateProperties);
        }

        if (dataSource != null) {
            Class<?> providerClass = LocalDataSourceConnectionProvider.class;
            if (isUseTransactionAwareDataSource() || dataSource instanceof TransactionAwareDataSourceProxy) {
                providerClass = TransactionAwareDataSourceConnectionProvider.class;
            } else if (config.getProperty(Environment.TRANSACTION_MANAGER_STRATEGY) != null) {
                providerClass = LocalJtaDataSourceConnectionProvider.class;
            }
            // Set Spring-provided DataSource as Hibernate ConnectionProvider.
            config.setProperty(Environment.CONNECTION_PROVIDER, providerClass.getName());
        }

        if (this.cacheRegionFactory != null) {
            // Expose Spring-provided Hibernate RegionFactory.
            config.setProperty(Environment.CACHE_REGION_FACTORY, LocalRegionFactoryProxy.class.getName());
        }

        if (this.mappingResources != null) {
            // Register given Hibernate mapping definitions, contained in resource files.
            for (String mapping : this.mappingResources) {
                Resource resource = new ClassPathResource(mapping.trim(), this.beanClassLoader);
                config.addInputStream(resource.getInputStream());
            }
        }

        if (this.mappingLocations != null) {
            // Register given Hibernate mapping definitions, contained in resource files.
            for (Resource resource : this.mappingLocations) {
                config.addInputStream(resource.getInputStream());
            }
        }

        if (this.cacheableMappingLocations != null) {
            // Register given cacheable Hibernate mapping definitions, read from the file system.
            for (Resource resource : this.cacheableMappingLocations) {
                config.addCacheableFile(resource.getFile());
            }
        }

        if (this.mappingJarLocations != null) {
            // Register given Hibernate mapping definitions, contained in jar files.
            for (Resource resource : this.mappingJarLocations) {
                config.addJar(resource.getFile());
            }
        }

        if (this.mappingDirectoryLocations != null) {
            // Register all Hibernate mapping definitions in the given directories.
            for (Resource resource : this.mappingDirectoryLocations) {
                File file = resource.getFile();
                if (!file.isDirectory()) {
                    throw new IllegalArgumentException(
                            "Mapping directory location [" + resource + "] does not denote a directory");
                }
                config.addDirectory(file);
            }
        }

        // Tell Hibernate to eagerly compile the mappings that we registered,
        // for availability of the mapping information in further processing.
        postProcessMappings(config);
        config.buildMappings();

        if (this.entityCacheStrategies != null) {
            // Register cache strategies for mapped entities.
            for (Enumeration<?> classNames = this.entityCacheStrategies.propertyNames(); classNames
                    .hasMoreElements();) {
                String className = (String) classNames.nextElement();
                String[] strategyAndRegion = StringUtils
                        .commaDelimitedListToStringArray(this.entityCacheStrategies.getProperty(className));
                if (strategyAndRegion.length > 1) {
                    config.setCacheConcurrencyStrategy(className, strategyAndRegion[0], strategyAndRegion[1]);
                } else if (strategyAndRegion.length > 0) {
                    config.setCacheConcurrencyStrategy(className, strategyAndRegion[0]);
                }
            }
        }

        if (this.collectionCacheStrategies != null) {
            // Register cache strategies for mapped collections.
            for (Enumeration<?> collRoles = this.collectionCacheStrategies.propertyNames(); collRoles
                    .hasMoreElements();) {
                String collRole = (String) collRoles.nextElement();
                String[] strategyAndRegion = StringUtils
                        .commaDelimitedListToStringArray(this.collectionCacheStrategies.getProperty(collRole));
                if (strategyAndRegion.length > 1) {
                    config.setCollectionCacheConcurrencyStrategy(collRole, strategyAndRegion[0],
                            strategyAndRegion[1]);
                } else if (strategyAndRegion.length > 0) {
                    config.setCollectionCacheConcurrencyStrategy(collRole, strategyAndRegion[0]);
                }
            }
        }

        if (this.eventListeners != null) {
            // Register specified Hibernate event listeners.
            for (Map.Entry<String, Object> entry : this.eventListeners.entrySet()) {
                String listenerType = entry.getKey();
                Object listenerObject = entry.getValue();
                if (listenerObject instanceof Collection) {
                    Collection<Object> listeners = (Collection<Object>) listenerObject;
                    EventListeners listenerRegistry = config.getEventListeners();
                    Object[] listenerArray = (Object[]) Array
                            .newInstance(listenerRegistry.getListenerClassFor(listenerType), listeners.size());
                    listenerArray = listeners.toArray(listenerArray);
                    config.setListeners(listenerType, listenerArray);
                } else {
                    config.setListener(listenerType, listenerObject);
                }
            }
        }

        // Perform custom post-processing in subclasses.
        postProcessConfiguration(config);

        // Build SessionFactory instance.
        logger.info("Building new Hibernate SessionFactory");
        this.configuration = config;
        return newSessionFactory(config);
    }

    finally {
        if (dataSource != null) {
            configTimeDataSourceHolder.remove();
        }
        if (this.jtaTransactionManager != null) {
            configTimeTransactionManagerHolder.remove();
        }
        if (this.cacheRegionFactory != null) {
            configTimeRegionFactoryHolder.remove();
        }
        if (this.lobHandler != null) {
            configTimeLobHandlerHolder.remove();
        }
        if (overrideClassLoader) {
            // Reset original thread context ClassLoader.
            currentThread.setContextClassLoader(threadContextClassLoader);
        }
    }
}

From source file:org.springframework.orm.hibernate3.LocalSessionFactoryBeanTests.java

License:Apache License

@Test
@SuppressWarnings("serial")
public void testLocalSessionFactoryBeanWithDataSource() throws Exception {
    final DriverManagerDataSource ds = new DriverManagerDataSource();
    final List invocations = new ArrayList();
    LocalSessionFactoryBean sfb = new LocalSessionFactoryBean() {
        @Override//from   www.jav  a  2  s.c om
        protected Configuration newConfiguration() {
            return new Configuration() {
                @Override
                public Configuration addInputStream(InputStream is) {
                    try {
                        is.close();
                    } catch (IOException ex) {
                    }
                    invocations.add("addResource");
                    return this;
                }
            };
        }

        @Override
        protected SessionFactory newSessionFactory(Configuration config) {
            assertEquals(LocalDataSourceConnectionProvider.class.getName(),
                    config.getProperty(Environment.CONNECTION_PROVIDER));
            assertEquals(ds, LocalSessionFactoryBean.getConfigTimeDataSource());
            invocations.add("newSessionFactory");
            return null;
        }
    };
    sfb.setDataSource(ds);
    sfb.afterPropertiesSet();
    assertTrue(sfb.getConfiguration() != null);
    assertEquals("newSessionFactory", invocations.get(0));
}

From source file:org.springframework.orm.hibernate3.LocalSessionFactoryBeanTests.java

License:Apache License

@Test
@SuppressWarnings("serial")
public void testLocalSessionFactoryBeanWithCacheRegionFactory() throws Exception {
    final RegionFactory regionFactory = new NoCachingRegionFactory(null);
    final List invocations = new ArrayList();
    LocalSessionFactoryBean sfb = new LocalSessionFactoryBean() {
        @Override//  w w w.j a  v  a2s.co  m
        protected Configuration newConfiguration() {
            return new Configuration() {
                @Override
                public Configuration addInputStream(InputStream is) {
                    try {
                        is.close();
                    } catch (IOException ex) {
                    }
                    invocations.add("addResource");
                    return this;
                }
            };
        }

        @Override
        protected SessionFactory newSessionFactory(Configuration config) {
            assertEquals(LocalRegionFactoryProxy.class.getName(),
                    config.getProperty(Environment.CACHE_REGION_FACTORY));
            assertSame(regionFactory, LocalSessionFactoryBean.getConfigTimeRegionFactory());
            invocations.add("newSessionFactory");
            return null;
        }
    };
    sfb.setCacheRegionFactory(regionFactory);
    sfb.afterPropertiesSet();
    assertTrue(sfb.getConfiguration() != null);
    assertEquals("newSessionFactory", invocations.get(0));
}

From source file:org.springframework.orm.hibernate3.LocalSessionFactoryBeanTests.java

License:Apache License

@Test
@SuppressWarnings("serial")
public void testLocalSessionFactoryBeanWithTransactionAwareDataSource() throws Exception {
    final DriverManagerDataSource ds = new DriverManagerDataSource();
    final List invocations = new ArrayList();
    LocalSessionFactoryBean sfb = new LocalSessionFactoryBean() {
        @Override/*from   ww w.j  ava  2  s  . c o  m*/
        protected Configuration newConfiguration() {
            return new Configuration() {
                @Override
                public Configuration addInputStream(InputStream is) {
                    try {
                        is.close();
                    } catch (IOException ex) {
                    }
                    invocations.add("addResource");
                    return this;
                }
            };
        }

        @Override
        protected SessionFactory newSessionFactory(Configuration config) {
            assertEquals(TransactionAwareDataSourceConnectionProvider.class.getName(),
                    config.getProperty(Environment.CONNECTION_PROVIDER));
            assertEquals(ds, LocalSessionFactoryBean.getConfigTimeDataSource());
            invocations.add("newSessionFactory");
            return null;
        }
    };
    sfb.setDataSource(ds);
    sfb.setUseTransactionAwareDataSource(true);
    sfb.afterPropertiesSet();
    assertTrue(sfb.getConfiguration() != null);
    assertEquals("newSessionFactory", invocations.get(0));
}