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.hibernate.internal;
016
017import org.apache.tapestry5.hibernate.HibernateConfigurer;
018import org.apache.tapestry5.hibernate.HibernateEntityPackageManager;
019import org.apache.tapestry5.ioc.services.ClassNameLocator;
020import org.hibernate.cfg.Configuration;
021
022/**
023 * Adds entity classes from a given set of packages to the configuration.
024 */
025public final class PackageNameHibernateConfigurer implements HibernateConfigurer
026{
027    private final HibernateEntityPackageManager packageManager;
028
029    private final ClassNameLocator classNameLocator;
030
031    public PackageNameHibernateConfigurer(HibernateEntityPackageManager packageManager,
032            ClassNameLocator classNameLocator)
033    {
034        this.packageManager = packageManager;
035        this.classNameLocator = classNameLocator;
036    }
037
038    @Override
039    public void configure(Configuration configuration)
040    {
041        ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
042
043        for (String packageName : packageManager.getPackageNames())
044        {
045            configuration.addPackage(packageName);
046
047            for (String className : classNameLocator.locateClassNames(packageName))
048            {
049                try
050                {
051                    Class entityClass = contextClassLoader.loadClass(className);
052
053                    configuration.addAnnotatedClass(entityClass);
054                }
055                catch (ClassNotFoundException ex)
056                {
057                    throw new RuntimeException(ex);
058                }
059            }
060        }
061    }
062}