001// Copyright 2007, 2008, 2010, 2011 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
015package org.apache.tapestry5.internal.hibernate;
016
017import org.apache.tapestry5.hibernate.HibernateConfigurer;
018import org.apache.tapestry5.hibernate.HibernateEntityPackageManager;
019import org.apache.tapestry5.ioc.services.ClassNameLocator;
020import org.hibernate.cfg.AnnotationConfiguration;
021import org.hibernate.cfg.Configuration;
022
023/**
024 * Adds entity classes from a given set of packages to the configuration.
025 */
026public 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    @Override
040    public void configure(Configuration configuration)
041    {
042        ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
043
044        for (String packageName : packageManager.getPackageNames())
045        {
046            configuration.addPackage(packageName);
047
048            for (String className : classNameLocator.locateClassNames(packageName))
049            {
050                try
051                {
052                    Class entityClass = contextClassLoader.loadClass(className);
053
054                    configuration.addAnnotatedClass(entityClass);
055                }
056                catch (ClassNotFoundException ex)
057                {
058                    throw new RuntimeException(ex);
059                }
060            }
061        }
062    }
063}