Example usage for org.hibernate.cfg Configuration setInterceptor

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

Introduction

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

Prototype

public Configuration setInterceptor(Interceptor interceptor) 

Source Link

Document

Set the current Interceptor

Usage

From source file:org.openbravo.dal.core.DalSessionFactoryController.java

License:Open Source License

@Override
protected void setInterceptor(Configuration configuration) {
    configuration.setInterceptor(new OBInterceptor());
}

From source file:org.ow2.bonita.env.descriptor.HibernateSessionFactoryDescriptor.java

License:Open Source License

private static void addInterceptor(Configuration configuration) {
    String interceptorClassName = configuration.getProperty("bonita.hibernate.interceptor");
    if (interceptorClassName != null) {
        if (LOG.isLoggable(Level.INFO)) {
            LOG.info("Adding interceptor: " + interceptorClassName);
        }//from  ww  w  .  j  a  v a  2  s.  co m
        Class<?> interceptorClass = ReflectUtil.loadClass(Thread.currentThread().getContextClassLoader(),
                interceptorClassName);
        EmptyInterceptor interceptor = (EmptyInterceptor) ReflectUtil.newInstance(interceptorClass);
        configuration.setInterceptor(interceptor);
    }
}

From source file:org.seasar.hibernate3.impl.S2SessionFactoryImpl.java

License:Apache License

public synchronized SessionFactory getSessionFactory() {
    if (sessionFactory_ != null) {
        return sessionFactory_;
    }//  ww  w. ja  v a  2  s  . c o m

    Configuration cfg = new Configuration();
    cfg.configure(ResourceUtil.getResource(configPath_));
    if (interceptor_ != null) {
        cfg.setInterceptor(interceptor_);
    }
    sessionFactory_ = cfg.buildSessionFactory();
    return sessionFactory_;
}

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  av  a2s  . c om*/
    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.squashtest.tm.service.internal.hibernate.SquashEntityManagerFactoryBuilderImpl.java

License:Open Source License

protected Configuration extendConfiguration(Configuration conf) {
    String dialect = conf.getProperty("hibernate.dialect");

    SessionFactoryEnhancer.registerExtensions(conf, configureFunctionSupport(dialect));

    conf.setNamingStrategy(new UppercaseUnderscoreNamingStrategy());
    conf.setInterceptor(new AuditLogInterceptor());

    return conf;//from w w w. j av a2 s . c  o  m
}

From source file:owldb.util.HibernateUtil.java

License:Open Source License

/**
 * Constructor.//from  ww w .j  a  v a2s.  c  om
 * 
 * @param ontologyManager The owl ontology manager
 * @param hibernateProperties Additional Hibernate settings
 */
public HibernateUtil(final OWLOntologyManager ontologyManager, final Properties hibernateProperties) {
    try {
        final Configuration configuration = new Configuration();
        configuration.configure();
        final Interceptor interceptor = new OWLDBInterceptor(ontologyManager);
        configuration.setInterceptor(interceptor);

        final EventListeners listeners = configuration.getEventListeners();
        final OWLDBEventListener dbListener = new OWLDBEventListener();
        listeners.setSaveOrUpdateEventListeners(
                new SaveOrUpdateEventListener[] { dbListener, new DefaultSaveOrUpdateEventListener() });
        listeners.setSaveEventListeners(
                new SaveOrUpdateEventListener[] { dbListener, new DefaultSaveEventListener() });
        listeners.setPostCommitDeleteEventListeners(new PostDeleteEventListener[] { dbListener });
        listeners.setPostCommitInsertEventListeners(new PostInsertEventListener[] { dbListener });

        // Enable second level cache if not set otherwise
        if (hibernateProperties.get(Environment.USE_SECOND_LEVEL_CACHE) == null)
            hibernateProperties.setProperty(Environment.USE_SECOND_LEVEL_CACHE, "true");
        // Enable query cache if not set otherwise and second level is enabled
        if ("true".equals(hibernateProperties.get(Environment.USE_SECOND_LEVEL_CACHE))
                && hibernateProperties.get(Environment.USE_QUERY_CACHE) == null)
            hibernateProperties.setProperty(Environment.USE_QUERY_CACHE, "true");

        // Add additional specific Hibernate properties
        configuration.addProperties(hibernateProperties);

        // Create the SessionFactory from the configuration.
        this.factory = configuration.buildSessionFactory();
    } catch (final Throwable ex) {
        LOGGER.error("Initial SessionFactory creation failed.", ex);
        throw new ExceptionInInitializerError(ex);
    }
}