001    // Copyright 2007, 2008, 2010 The Apache Software Foundation
002    //
003    // Licensed under the Apache License, Version 2.0 (the "License");
004    // you may not use this file except in compliance with the License.
005    // You may obtain a copy of the License at
006    //
007    // http://www.apache.org/licenses/LICENSE-2.0
008    //
009    // Unless required by applicable law or agreed to in writing, software
010    // distributed under the License is distributed on an "AS IS" BASIS,
011    // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
012    // See the License for the specific language governing permissions and
013    // limitations under the License.
014    
015    package org.apache.tapestry5.internal.hibernate;
016    
017    import org.apache.tapestry5.hibernate.HibernateConfigurer;
018    import org.apache.tapestry5.hibernate.HibernateEntityPackageManager;
019    import org.apache.tapestry5.ioc.services.ClassNameLocator;
020    import org.hibernate.cfg.AnnotationConfiguration;
021    import org.hibernate.cfg.Configuration;
022    
023    /**
024     * Adds entity classes from a given set of packages to the configuration.
025     */
026    public final class PackageNameHibernateConfigurer implements HibernateConfigurer
027    {
028        private final HibernateEntityPackageManager packageManager;
029    
030        private final ClassNameLocator classNameLocator;
031    
032        public PackageNameHibernateConfigurer(HibernateEntityPackageManager packageManager,
033                ClassNameLocator classNameLocator)
034        {
035            this.packageManager = packageManager;
036            this.classNameLocator = classNameLocator;
037        }
038    
039        public void configure(Configuration configuration)
040        {
041            AnnotationConfiguration cfg = (AnnotationConfiguration) configuration;
042    
043            ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
044    
045            for (String packageName : packageManager.getPackageNames())
046            {
047                cfg.addPackage(packageName);
048    
049                for (String className : classNameLocator.locateClassNames(packageName))
050                {
051                    try
052                    {
053                        Class entityClass = contextClassLoader.loadClass(className);
054    
055                        cfg.addAnnotatedClass(entityClass);
056                    }
057                    catch (ClassNotFoundException ex)
058                    {
059                        throw new RuntimeException(ex);
060                    }
061                }
062            }
063        }
064    }