/*
 * JBoss, the OpenSource J2EE webOS
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package org.jboss.test.hibernate;

import org.jboss.test.hibernate.model.User;
import org.jboss.naming.Util;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import java.util.List;

/**
 * A service bean used to interact with a bound hibernate session for
 * testing purposes.
 *
 * @author <a href="mailto:steve@hibernate.org">Steve Ebersole</a>
 * @version $Revision: 1.3.2.1 $
 */
public class ProfileService
{
   private static final String SESSION_FACTORY_NAME = "java:/hibernate/SessionFactory";

   public User loadUser(long id) throws HibernateException
   {
      return loadUser( new Long(id) );
   }

   public User loadUser(Long id) throws HibernateException
   {
      return (User) getSession().load(User.class, id);
   }

   public List listUsers() throws HibernateException
   {
      return getSession()
            .createQuery("from User")
            .list();
   }

   public User locateUser(String handle) throws HibernateException
   {
      return (User) getSession()
            .createQuery("from User as u where u.handle = :handle")
            .setString("handle", handle)
            .uniqueResult();
   }

   public User storeUser(User user) throws HibernateException
   {
      getSession().saveOrUpdate(user);
      getSession().flush();
      return user;
   }

   private Session getSession()
   {
      try
      {
         SessionFactory sf = ( SessionFactory ) Util.lookup( SESSION_FACTORY_NAME, SessionFactory.class );
         return sf.getCurrentSession();
      }
      catch( HibernateException e )
      {
         throw e;
      }
      catch( Exception e )
      {
         throw new HibernateException( "Unable to locate current session", e ); 
      }
   }
}