[portal-commits] JBoss Portal SVN: r5835 - in trunk/identity/src/main/org/jboss/portal/identity2: . db

portal-commits at lists.jboss.org portal-commits at lists.jboss.org
Wed Dec 13 10:23:24 EST 2006


Author: bdaw
Date: 2006-12-13 10:23:19 -0500 (Wed, 13 Dec 2006)
New Revision: 5835

Added:
   trunk/identity/src/main/org/jboss/portal/identity2/db/
   trunk/identity/src/main/org/jboss/portal/identity2/db/HibernateMembershipModuleImpl.java
   trunk/identity/src/main/org/jboss/portal/identity2/db/HibernateRoleImpl.java
   trunk/identity/src/main/org/jboss/portal/identity2/db/HibernateRoleModuleImpl.java
   trunk/identity/src/main/org/jboss/portal/identity2/db/HibernateUserImpl.java
   trunk/identity/src/main/org/jboss/portal/identity2/db/HibernateUserModuleImpl.java
   trunk/identity/src/main/org/jboss/portal/identity2/db/HibernateUserProfileModuleImpl.java
   trunk/identity/src/main/org/jboss/portal/identity2/db/ProfileMapImpl.java
Log:
refactored hibernate implementation of identity modules

Added: trunk/identity/src/main/org/jboss/portal/identity2/db/HibernateMembershipModuleImpl.java
===================================================================
--- trunk/identity/src/main/org/jboss/portal/identity2/db/HibernateMembershipModuleImpl.java	2006-12-13 15:22:51 UTC (rev 5834)
+++ trunk/identity/src/main/org/jboss/portal/identity2/db/HibernateMembershipModuleImpl.java	2006-12-13 15:23:19 UTC (rev 5835)
@@ -0,0 +1,254 @@
+/*
+* JBoss, a division of Red Hat
+* Copyright 2006, Red Hat Middleware, LLC, and individual contributors as indicated
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* This is free software; you can redistribute it and/or modify it
+* under the terms of the GNU Lesser General Public License as
+* published by the Free Software Foundation; either version 2.1 of
+* the License, or (at your option) any later version.
+*
+* This software is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+* Lesser General Public License for more details.
+*
+* You should have received a copy of the GNU Lesser General Public
+* License along with this software; if not, write to the Free
+* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+*/
+package org.jboss.portal.identity2.db;
+
+import org.jboss.portal.identity2.service.MembershipModuleService;
+import org.jboss.portal.identity2.User;
+import org.jboss.portal.identity2.Role;
+import org.jboss.portal.identity2.db.HibernateUserImpl;
+import org.jboss.portal.identity2.db.HibernateRoleImpl;
+import org.jboss.portal.identity.IdentityException;
+import org.jboss.portal.common.util.Tools;
+import org.hibernate.SessionFactory;
+import org.hibernate.Session;
+import org.hibernate.Query;
+import org.hibernate.HibernateException;
+
+import javax.naming.InitialContext;
+import java.util.Set;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Collections;
+
+/**
+ * @author <a href="mailto:boleslaw dot dawidowicz at jboss.org">Boleslaw Dawidowicz</a>
+ * @version $Revision: 1.1 $
+ */
+public class HibernateMembershipModuleImpl extends MembershipModuleService
+{
+   /** . */
+   private static final org.jboss.logging.Logger log = org.jboss.logging.Logger.getLogger(HibernateMembershipModuleImpl.class);
+   /** . */
+   protected SessionFactory sessionFactory;
+
+   /** . */
+   protected String sessionFactoryJNDIName;
+
+   protected void startService() throws Exception
+   {
+      //
+      sessionFactory = (SessionFactory)new InitialContext().lookup(sessionFactoryJNDIName);
+
+      super.startService();
+   }
+
+   protected void stopService() throws Exception
+   {
+
+      //
+      sessionFactory = null;
+
+      super.stopService();
+   }
+
+//   public SessionFactory getSessionFactory()
+//   {
+//      return sessionFactory;
+//   }
+
+   public String getSessionFactoryJNDIName()
+   {
+      return sessionFactoryJNDIName;
+   }
+
+   public void setSessionFactoryJNDIName(String sessionFactoryJNDIName)
+   {
+      this.sessionFactoryJNDIName = sessionFactoryJNDIName;
+   }
+
+   public Set getRoles(User user) throws IdentityException
+   {
+      //throw new UnsupportedOperationException("Not yet implemented");
+      if (!(user instanceof org.jboss.portal.identity2.db.HibernateUserImpl))
+      {
+         throw new IllegalArgumentException("User is not a HibernateUserImpl user");
+      }
+
+      // We return an immutable set to avoid modifications
+      HibernateUserImpl ui = (HibernateUserImpl)user;
+      Set roles = ui.getRoles();
+      Set copy = new HashSet();
+      for (Iterator iterator = roles.iterator(); iterator.hasNext();)
+      {
+         HibernateRoleImpl role = (HibernateRoleImpl)iterator.next();
+         copy.add(role);
+      }
+
+      return Collections.unmodifiableSet(copy);
+   }
+
+   public Set getUsers(Role role) throws IdentityException
+   {
+      if (!(role instanceof HibernateRoleImpl))
+      {
+         throw new IllegalArgumentException("User is not a HibernateRoleImpl user");
+      }
+
+      // We return an immutable set to avoid modifications
+      HibernateRoleImpl ri = (HibernateRoleImpl)role;
+      Set users = ri.getUsers();
+      Set copy = new HashSet();
+      for (Iterator iterator = users.iterator(); iterator.hasNext();)
+      {
+         HibernateUserImpl user = (HibernateUserImpl)iterator.next();
+         copy.add(user);
+      }
+
+      return Collections.unmodifiableSet(copy);
+   }
+
+   public void assignUsers(Role role, Set users) throws IdentityException
+   {
+      //throw new UnsupportedOperationException("Not yet implemented");
+      if (!(role instanceof HibernateRoleImpl))
+      {
+         throw new IllegalArgumentException("User is not a HibernateRoleImpl user");
+      }
+
+      for (Iterator i = users.iterator(); i.hasNext();)
+      {
+         Object o = i.next();
+         if (o instanceof HibernateUserImpl)
+         {
+            HibernateUserImpl user = (HibernateUserImpl)o;
+            user.getRoles().add(role);
+         }
+         else
+         {
+            throw new IllegalArgumentException("Only HibernateUserImpl roles can be accepted");
+         }
+      }
+
+   }
+
+   public void assignRoles(User user, Set roles) throws IdentityException
+   {
+      //throw new UnsupportedOperationException("Not yet implemented");
+      if (!(user instanceof HibernateUserImpl))
+      {
+         throw new IllegalArgumentException("User is not a HibernateUserImpl user");
+      }
+
+      // We make a defensive copy with unwrapped maps and update with a new set
+      Set copy = new HashSet();
+      for (Iterator i = roles.iterator(); i.hasNext();)
+      {
+         Object o = i.next();
+         if (o instanceof HibernateRoleImpl)
+         {
+            copy.add(o);
+         }
+         else
+         {
+            throw new IllegalArgumentException("Only HibernateRoleImpl roles can be accepted");
+         }
+      }
+
+      // Assign new roles
+      HibernateUserImpl ui = (HibernateUserImpl)user;
+      ui.setRoles(copy);
+   }
+
+   //TODO:
+   public Set findRoleMembers(String roleName, int offset, int limit, String userNameFilter) throws IdentityException
+   {
+      if (roleName != null)
+      {
+         try
+         {
+            Session session = getCurrentSession();
+
+            HibernateUserImpl userimpl = new HibernateUserImpl();
+            userimpl.setEnabled(true);
+
+            Query query;
+            if (userNameFilter.trim().length() != 0)
+            {
+               //
+               userNameFilter = "%" + userNameFilter.replaceAll("%", "") + "%";
+
+               //
+               query = session.createQuery("from HibernateUserImpl as user left join user.roles role where role.name=:name" + " AND user.userName LIKE :filter");
+               query.setString("filter", userNameFilter);
+            }
+            else
+            {
+               query = session.createQuery("from HibernateUserImpl as user left join user.roles role where role.name=:name");
+            }
+            query.setString("name", roleName);
+            query.setFirstResult(offset);
+            query.setMaxResults(limit);
+
+            Iterator iterator = query.iterate();
+            Set result = Tools.toSet(iterator);
+
+            Set newResult = new HashSet();
+            Iterator cleaner = result.iterator();
+            while (cleaner.hasNext())
+            {
+               Object[] oArr = (Object[])cleaner.next();
+               newResult.add(oArr[0]);
+            }
+
+            return newResult;
+         }
+         catch (HibernateException e)
+         {
+            String message = "Cannot find role  " + roleName;
+            log.error(message, e);
+            throw new IdentityException(message, e);
+         }
+      }
+      else
+      {
+         throw new IllegalArgumentException("id cannot be null");
+      }
+   }
+
+   /**
+    * Process Set of Map objects and returns a Set of HibernateRoleImpl objects
+    * @param maps
+    * @return
+    * @throws Exception
+    */
+
+   /** Can be subclasses to provide testing in a non JTA environement. */
+   protected Session getCurrentSession()
+   {
+      if (sessionFactory == null)
+      {
+         throw new IllegalStateException("No session factory");
+      }
+      return sessionFactory.getCurrentSession();
+   }
+}

Added: trunk/identity/src/main/org/jboss/portal/identity2/db/HibernateRoleImpl.java
===================================================================
--- trunk/identity/src/main/org/jboss/portal/identity2/db/HibernateRoleImpl.java	2006-12-13 15:22:51 UTC (rev 5834)
+++ trunk/identity/src/main/org/jboss/portal/identity2/db/HibernateRoleImpl.java	2006-12-13 15:23:19 UTC (rev 5835)
@@ -0,0 +1,149 @@
+/*
+* JBoss, a division of Red Hat
+* Copyright 2006, Red Hat Middleware, LLC, and individual contributors as indicated
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* This is free software; you can redistribute it and/or modify it
+* under the terms of the GNU Lesser General Public License as
+* published by the Free Software Foundation; either version 2.1 of
+* the License, or (at your option) any later version.
+*
+* This software is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+* Lesser General Public License for more details.
+*
+* You should have received a copy of the GNU Lesser General Public
+* License along with this software; if not, write to the Free
+* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+*/
+package org.jboss.portal.identity2.db;
+
+import org.jboss.portal.identity2.Role;
+
+import java.util.Set;
+import java.util.HashSet;
+
+/**
+ * @author <a href="mailto:julien at jboss.org">Julien Viet </a>
+ * @author <a href="mailto:theute at jboss.org">Thomas Heute </a>
+ * @author Roy Russo : roy at jboss dot org
+ * @author <a href="mailto:boleslaw dot dawidowicz at jboss.org">Boleslaw Dawidowicz</a>
+ * @version $Revision: 5448 $
+ */
+public class HibernateRoleImpl
+   implements Role
+{
+
+   private Long key;
+   private String name;
+   private Set users;
+   private String displayName;
+
+   /**
+    *
+    */
+   public HibernateRoleImpl()
+   {
+      this.key = null;
+      this.name = null;
+      this.displayName = null;
+      this.users = new HashSet();
+   }
+
+   /**
+    *
+    */
+   public HibernateRoleImpl(String name)
+   {
+      this.key = null;
+      this.name = name;
+      this.displayName = name;
+      this.users = new HashSet();
+   }
+
+   /**
+    *
+    */
+   public HibernateRoleImpl(String name, String displayName)
+   {
+      this.key = null;
+      this.name = name;
+      this.displayName = displayName;
+      this.users = new HashSet();
+   }
+
+   /**
+    * @hibernate.id column="jbp_rid" generator-class="native"
+    * <p/>
+    * Called by hibernate.
+    */
+   protected Long getKey()
+   {
+      return key;
+   }
+
+   /** Called by hibernate. */
+   protected void setKey(Long key)
+   {
+      this.key = key;
+   }
+
+   /** Called by hibernate. */
+   protected void setName(String name)
+   {
+      this.name = name;
+   }
+
+   /** Called by hibernate. */
+   protected void setUsers(Set users)
+   {
+      this.users = users;
+   }
+
+   // ******************************************************************************************************************
+
+   public Object getId()
+   {
+      return key;
+   }
+
+   /**
+    *
+    */
+   public String getName()
+   {
+      return name;
+   }
+
+   /**
+    *
+    */
+   public String getDisplayName()
+   {
+      return displayName;
+   }
+
+   /**
+    *
+    */
+   public void setDisplayName(String displayName)
+   {
+      this.displayName = displayName;
+   }
+
+   /**
+    *
+    */
+   public Set getUsers()
+   {
+      return users;
+   }
+
+   public String toString()
+   {
+      return "Role[" + key + "," + name + "]";
+   }
+}

Added: trunk/identity/src/main/org/jboss/portal/identity2/db/HibernateRoleModuleImpl.java
===================================================================
--- trunk/identity/src/main/org/jboss/portal/identity2/db/HibernateRoleModuleImpl.java	2006-12-13 15:22:51 UTC (rev 5834)
+++ trunk/identity/src/main/org/jboss/portal/identity2/db/HibernateRoleModuleImpl.java	2006-12-13 15:23:19 UTC (rev 5835)
@@ -0,0 +1,393 @@
+/*
+* JBoss, a division of Red Hat
+* Copyright 2006, Red Hat Middleware, LLC, and individual contributors as indicated
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* This is free software; you can redistribute it and/or modify it
+* under the terms of the GNU Lesser General Public License as
+* published by the Free Software Foundation; either version 2.1 of
+* the License, or (at your option) any later version.
+*
+* This software is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+* Lesser General Public License for more details.
+*
+* You should have received a copy of the GNU Lesser General Public
+* License along with this software; if not, write to the Free
+* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+*/
+package org.jboss.portal.identity2.db;
+
+import org.jboss.portal.identity2.RoleModule;
+import org.jboss.portal.identity2.Role;
+import org.jboss.portal.identity.IdentityException;
+import org.jboss.portal.identity2.User;
+import org.jboss.portal.identity2.db.HibernateRoleImpl;
+import org.jboss.portal.identity2.db.HibernateUserImpl;
+import org.jboss.portal.common.util.JNDI;
+import org.jboss.portal.common.util.Tools;
+import org.jboss.portal.identity2.service.RoleModuleService;
+import org.hibernate.SessionFactory;
+import org.hibernate.Session;
+import org.hibernate.Criteria;
+import org.hibernate.HibernateException;
+import org.hibernate.Query;
+import org.hibernate.criterion.Restrictions;
+
+import javax.naming.InitialContext;
+import java.util.Set;
+import java.util.Iterator;
+import java.util.HashSet;
+import java.util.Collections;
+
+/**
+ * @author <a href="mailto:julien at jboss.org">Julien Viet </a>
+ * @author <a href="mailto:theute at jboss.org">Thomas Heute </a>
+ * @author Roy Russo : roy at jboss dot org
+ * @version $Revision: 5448 $
+ * @portal.core
+ */
+public class HibernateRoleModuleImpl extends RoleModuleService
+{
+
+   /** . */
+      private static final org.jboss.logging.Logger log = org.jboss.logging.Logger.getLogger(HibernateRoleModuleImpl.class);
+      /** . */
+      protected SessionFactory sessionFactory;
+
+      /** . */
+      protected String sessionFactoryJNDIName;
+
+      protected void startService() throws Exception
+      {
+         //
+         sessionFactory = (SessionFactory)new InitialContext().lookup(sessionFactoryJNDIName);
+
+         super.startService();
+      }
+
+      protected void stopService() throws Exception
+      {
+
+         //
+         sessionFactory = null;
+
+         super.stopService();
+      }
+
+//   public SessionFactory getSessionFactory()
+//   {
+//      return sessionFactory;
+//   }
+
+      public String getSessionFactoryJNDIName()
+      {
+         return sessionFactoryJNDIName;
+      }
+
+      public void setSessionFactoryJNDIName(String sessionFactoryJNDIName)
+      {
+         this.sessionFactoryJNDIName = sessionFactoryJNDIName;
+      }
+
+
+   public Role findRoleByName(String name) throws IdentityException
+   {
+      if (name != null)
+      {
+         try
+         {
+            Session session = getCurrentSession();
+            Criteria criteria = session.createCriteria(HibernateRoleImpl.class);
+            criteria.add(Restrictions.naturalId().set("name", name));
+            criteria.setCacheable(true);
+            HibernateRoleImpl role = (HibernateRoleImpl)criteria.uniqueResult();
+            if (role == null)
+            {
+               throw new IdentityException("No such role " + name);
+            }
+            return role;
+         }
+         catch (HibernateException e)
+         {
+            String message = "Cannot find role by name " + name;
+            log.error(message, e);
+            throw new IdentityException(message, e);
+         }
+      }
+      else
+      {
+         throw new IllegalArgumentException("name cannot be null");
+      }
+   }
+
+   public Set findRolesByNames(String[] names) throws IdentityException
+   {
+      if (names != null)
+      {
+         try
+         {
+            Session session = getCurrentSession();
+            StringBuffer queryString = new StringBuffer("from HibernateRoleImpl as g where g.name=?");
+            for (int i = 1; i < names.length; i++)
+            {
+               queryString.append(" or g.name=?");
+            }
+            Query query = session.createQuery(queryString.toString());
+            for (int i = 0; i < names.length; i++)
+            {
+               query.setString(i, names[i]);
+            }
+            Iterator iterator = query.iterate();
+            return Tools.toSet(iterator);
+         }
+         catch (HibernateException e)
+         {
+            String message = "Cannot find roles";
+            log.error(message, e);
+            throw new IdentityException(message, e);
+         }
+      }
+      else
+      {
+         throw new IllegalArgumentException("name cannot be null");
+      }
+   }
+
+   public Role findRoleById(String id) throws IllegalArgumentException, IdentityException
+   {
+      if (id == null)
+      {
+         throw new IllegalArgumentException("The id is null");
+      }
+      try
+      {
+         return findRoleById(new Long(id));
+      }
+      catch (NumberFormatException e)
+      {
+         throw new IllegalArgumentException("Cannot parse id into an long " + id);
+      }
+   }
+
+   public Role findRoleById(Object id) throws IdentityException
+   {
+      if (id instanceof Long)
+      {
+         try
+         {
+            Session session = getCurrentSession();
+            HibernateRoleImpl role = (HibernateRoleImpl)session.get(HibernateRoleImpl.class, (Long)id);
+            if (role == null)
+            {
+               throw new IdentityException("No role found for " + id);
+            }
+            return role;
+         }
+         catch (HibernateException e)
+         {
+            String message = "Cannot find role by id " + id;
+            log.error(message, e);
+            throw new IdentityException(message, e);
+         }
+      }
+      else
+      {
+         throw new IllegalArgumentException("The id is not an long : " + id);
+      }
+   }
+
+   public Role createRole(String name, String displayName) throws IdentityException
+   {
+      if (name != null)
+      {
+         try
+         {
+            HibernateRoleImpl role = new HibernateRoleImpl(name, displayName);
+            Session session = getCurrentSession();
+            session.save(role);
+            return role;
+         }
+         catch (HibernateException e)
+         {
+            String message = "Cannot create role " + name;
+            log.error(message, e);
+            throw new IdentityException(message, e);
+         }
+      }
+      else
+      {
+         throw new IllegalArgumentException("name cannot be null");
+      }
+   }
+
+   public void removeRole(Object id) throws IdentityException
+   {
+      if (id instanceof Long)
+      {
+         try
+         {
+            Session session = getCurrentSession();
+            HibernateRoleImpl role = (HibernateRoleImpl)session.load(HibernateRoleImpl.class, (Long)id);
+            Iterator users = role.getUsers().iterator();
+            while (users.hasNext())
+            {
+               HibernateUserImpl user = (HibernateUserImpl)users.next();
+               user.getRoles().remove(role);
+            }
+            session.delete(role);
+            session.flush();
+         }
+         catch (HibernateException e)
+         {
+            String message = "Cannot remove role  " + id;
+            log.error(message, e);
+            throw new IdentityException(message, e);
+         }
+      }
+      else
+      {
+         throw new IllegalArgumentException("The id is not an long : " + id);
+      }
+   }
+
+   public int getRolesCount() throws IdentityException
+   {
+      try
+      {
+         Session session = getCurrentSession();
+         Query query = session.createQuery("select count(g.id) from HibernateRoleImpl as g");
+         return ((Number)query.uniqueResult()).intValue();
+      }
+      catch (HibernateException e)
+      {
+         String message = "Cannot count roles";
+         log.error(message, e);
+         throw new IdentityException(message, e);
+      }
+   }
+
+   public Set findRoles() throws IdentityException
+   {
+      try
+      {
+         Session session = getCurrentSession();
+         Query query = session.createQuery("from HibernateRoleImpl");
+         Iterator iterator = query.iterate();
+         return Tools.toSet(iterator);
+      }
+      catch (HibernateException e)
+      {
+         String message = "Cannot find roles";
+         log.error(message, e);
+         throw new IdentityException(message, e);
+      }
+   }
+
+   public Set findRoleMembers(String roleName, int offset, int limit, String userNameFilter) throws IdentityException
+   {
+      if (roleName != null)
+      {
+         try
+         {
+            Session session = getCurrentSession();
+
+            HibernateUserImpl HibernateUserImpl = new HibernateUserImpl();
+            HibernateUserImpl.setEnabled(true);
+
+            Query query;
+            if (userNameFilter.trim().length() != 0)
+            {
+               //
+               userNameFilter = "%" + userNameFilter.replaceAll("%", "") + "%";
+
+               //
+               query = session.createQuery("from HibernateUserImpl as user left join user.roles role where role.name=:name" + " AND user.userName LIKE :filter");
+               query.setString("filter", userNameFilter);
+            }
+            else
+            {
+               query = session.createQuery("from HibernateUserImpl as user left join user.roles role where role.name=:name");
+            }
+            query.setString("name", roleName);
+            query.setFirstResult(offset);
+            query.setMaxResults(limit);
+
+            Iterator iterator = query.iterate();
+            Set result = Tools.toSet(iterator);
+
+            Set newResult = new HashSet();
+            Iterator cleaner = result.iterator();
+            while (cleaner.hasNext())
+            {
+               Object[] oArr = (Object[])cleaner.next();
+               newResult.add(oArr[0]);
+            }
+
+            return newResult;
+         }
+         catch (HibernateException e)
+         {
+            String message = "Cannot find role  " + roleName;
+            log.error(message, e);
+            throw new IdentityException(message, e);
+         }
+      }
+      else
+      {
+         throw new IllegalArgumentException("id cannot be null");
+      }
+   }
+
+   public void setRoles(User user, Set roles) throws IdentityException
+   {
+      if (!(user instanceof HibernateUserImpl))
+      {
+         throw new IllegalArgumentException("User is not a db user");
+      }
+
+      // We make a defensive copy and update with a new set
+      Set copy = new HashSet();
+      for (Iterator i = roles.iterator(); i.hasNext();)
+      {
+         Object o = i.next();
+         if (o instanceof HibernateRoleImpl)
+         {
+            copy.add(o);
+         }
+         else
+         {
+            throw new IllegalArgumentException("Only db roles can be accepted");
+         }
+      }
+
+      // Assign new roles
+      HibernateUserImpl ui = (HibernateUserImpl)user;
+      ui.setRoles(copy);
+   }
+
+   public Set getRoles(User user) throws IdentityException
+   {
+      if (!(user instanceof HibernateUserImpl))
+      {
+         throw new IllegalArgumentException("User is not a db user");
+      }
+
+      // We return an immutable set to avoid modifications
+      HibernateUserImpl ui = (HibernateUserImpl)user;
+      return Collections.unmodifiableSet(ui.getRoles());
+   }
+
+   /** Can be subclasses to provide testing in a non JTA environement. */
+   protected Session getCurrentSession()
+   {
+      if (sessionFactory == null)
+      {
+         throw new IllegalStateException("No session factory");
+      }
+      return sessionFactory.getCurrentSession();
+   }
+}

Added: trunk/identity/src/main/org/jboss/portal/identity2/db/HibernateUserImpl.java
===================================================================
--- trunk/identity/src/main/org/jboss/portal/identity2/db/HibernateUserImpl.java	2006-12-13 15:22:51 UTC (rev 5834)
+++ trunk/identity/src/main/org/jboss/portal/identity2/db/HibernateUserImpl.java	2006-12-13 15:23:19 UTC (rev 5835)
@@ -0,0 +1,538 @@
+/*
+* JBoss, a division of Red Hat
+* Copyright 2006, Red Hat Middleware, LLC, and individual contributors as indicated
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* This is free software; you can redistribute it and/or modify it
+* under the terms of the GNU Lesser General Public License as
+* published by the Free Software Foundation; either version 2.1 of
+* the License, or (at your option) any later version.
+*
+* This software is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+* Lesser General Public License for more details.
+*
+* You should have received a copy of the GNU Lesser General Public
+* License along with this software; if not, write to the Free
+* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+*/
+package org.jboss.portal.identity2.db;
+
+import org.jboss.portal.identity2.User;
+import org.jboss.portal.common.util.Tools;
+import org.jboss.portal.common.p3p.P3PConstants;
+import org.jboss.portal.identity2.ProfileMap;
+
+import java.util.Map;
+import java.util.HashMap;
+import java.util.Set;
+import java.util.Date;
+import java.util.HashSet;
+import java.util.Collections;
+import java.lang.reflect.Field;
+import java.text.SimpleDateFormat;
+import java.text.DateFormat;
+import java.text.ParseException;
+
+/**
+ * User interface implementation.
+ *
+ * @author <a href="mailto:julien at jboss.org">Julien Viet </a>
+ * @author <a href="mailto:theute at jboss.org">Thomas Heute </a>
+ * @author <a href="mailto:mageshbk at jboss.com">Magesh Kumar Bojan </a>
+ * @author <a href="mailto:boleslaw dot dawidowicz at jboss.org">Boleslaw Dawidowicz</a>
+ * @version $Revision: 5448 $
+ */
+public class HibernateUserImpl
+   implements User
+{
+
+   static final Map ACCESSORS = HibernateUserImpl.buildAccessors();
+
+   private static Map buildAccessors()
+   {
+      Map map = new HashMap();
+
+      // Map attributes defined by the JSR 168 spec P3P.
+      map.put(P3PConstants.INFO_USER_NAME_NICKNAME, new StringPropertyAccessor(P3PConstants.INFO_USER_NAME_NICKNAME, "userName", false, false));
+      map.put(P3PConstants.INFO_USER_BUSINESS_INFO_ONLINE_EMAIL, new StringPropertyAccessor(P3PConstants.INFO_USER_BUSINESS_INFO_ONLINE_EMAIL, "realEmail", true, true));
+      map.put(P3PConstants.INFO_USER_NAME_GIVEN, new StringPropertyAccessor(P3PConstants.INFO_USER_NAME_GIVEN, "givenName", true, true));
+      map.put(P3PConstants.INFO_USER_NAME_FAMILY, new StringPropertyAccessor(P3PConstants.INFO_USER_NAME_FAMILY, "familyName", true, true));
+
+      // Map attributes specific to JBoss Portal
+      map.put(org.jboss.portal.identity2.User.INFO_USER_EMAIL_FAKE, new StringPropertyAccessor(org.jboss.portal.identity2.User.INFO_USER_EMAIL_FAKE, "fakeEmail", true, true));
+      map.put(org.jboss.portal.identity2.User.INFO_USER_REGISTRATION_DATE, new DatePropertyAccessor(org.jboss.portal.identity2.User.INFO_USER_REGISTRATION_DATE, "registrationDate", false, false));
+      map.put(org.jboss.portal.identity2.User.INFO_USER_VIEW_EMAIL_VIEW_REAL, new BooleanPropertyAccessor(org.jboss.portal.identity2.User.INFO_USER_VIEW_EMAIL_VIEW_REAL, "viewRealEmail", true, false));
+      map.put(org.jboss.portal.identity2.User.INFO_USER_ENABLED, new BooleanPropertyAccessor(org.jboss.portal.identity2.User.INFO_USER_ENABLED, "enabled", true, false));
+
+      //
+      return Collections.unmodifiableMap(map);
+   }
+
+   protected ProfileMap profileMap;
+
+   /*
+    * P3P mapped persistent fields.
+    */
+
+   protected String userName;
+   protected String givenName;
+   protected String familyName;
+   protected String realEmail;
+
+   /*
+    * Non mapped persistent fields.
+    */
+
+   protected Long key;
+   protected boolean enabled;
+   protected String password;
+
+   /*
+    * Extension mapped persistent fields.
+    */
+
+   protected String fakeEmail;
+   protected boolean viewRealEmail;
+   protected Date registrationDate;
+
+   /*
+    * Persistent associations
+    */
+
+   protected Map dynamic;
+   protected Set roles;
+
+   /**
+    *
+    */
+   public HibernateUserImpl()
+   {
+      this.key = null;
+      this.userName = null;
+      this.dynamic = null;
+      this.roles = null;
+      this.registrationDate = null;
+      this.enabled = false;
+      this.profileMap = new ProfileMapImpl(this);
+   }
+
+   /**
+    *
+    */
+   public HibernateUserImpl(String userName)
+   {
+      this.key = null;
+      this.userName = userName;
+      this.dynamic = new HashMap();
+      this.roles = new HashSet();
+      this.registrationDate = new Date();
+      this.enabled = false;
+      this.profileMap = new ProfileMapImpl(this);
+   }
+
+   /** Called by hibernate. */
+   public Long getKey()
+   {
+      return key;
+   }
+
+   /** Called by hibernate. */
+   protected void setKey(Long key)
+   {
+      this.key = key;
+   }
+
+   /** Called by hibernate. */
+   protected void setUserName(String userName)
+   {
+      this.userName = userName;
+   }
+
+   /** Called by Hibernate. */
+   protected Map getDynamic()
+   {
+      return dynamic;
+   }
+
+   /** Called by Hibernate. */
+   protected void setDynamic(Map dynamic)
+   {
+      this.dynamic = dynamic;
+   }
+
+   public ProfileMap getProfileMap()
+   {
+      return profileMap;
+   }
+
+   // User implementation **********************************************************************************************
+
+   /**
+    *
+    */
+   public Object getId()
+   {
+      return key;
+   }
+
+   /**
+    *
+    */
+   public String getUserName()
+   {
+      return userName;
+   }
+
+   /**
+    *
+    */
+   public String getGivenName()
+   {
+      return givenName;
+   }
+
+   public void setGivenName(String givenName)
+   {
+      this.givenName = givenName;
+   }
+
+   /**
+    *
+    */
+   public String getFamilyName()
+   {
+      return familyName;
+   }
+
+   public void setFamilyName(String familyName)
+   {
+      this.familyName = familyName;
+   }
+
+   public void updatePassword(String password)
+   {
+      this.password = Tools.md5AsHexString(password);
+   }
+
+   /**
+    *
+    */
+   public String getRealEmail()
+   {
+      return realEmail;
+   }
+
+   /**
+    *
+    */
+   public void setRealEmail(String realEmail)
+   {
+      this.realEmail = realEmail;
+   }
+
+   /**
+    *
+    */
+   public String getFakeEmail()
+   {
+      return fakeEmail;
+   }
+
+   /**
+    *
+    */
+   public void setFakeEmail(String fakeEmail)
+   {
+      this.fakeEmail = fakeEmail;
+   }
+
+   /**
+    *
+    */
+   public Date getRegistrationDate()
+   {
+      return registrationDate;
+   }
+
+   /**
+    *
+    */
+   public void setRegistrationDate(Date registrationDate)
+   {
+      this.registrationDate = registrationDate;
+   }
+
+   /**
+    *
+    */
+   public boolean getViewRealEmail()
+   {
+      return viewRealEmail;
+   }
+
+   /**
+    *
+    */
+   public void setViewRealEmail(boolean viewRealEmail)
+   {
+      this.viewRealEmail = viewRealEmail;
+   }
+
+   /**
+    *
+    */
+   public boolean getEnabled()
+   {
+      return enabled;
+   }
+
+   /**
+    *
+    */
+   public void setEnabled(boolean enable)
+   {
+      this.enabled = enable;
+   }
+
+   public String getPassword()
+   {
+      return password;
+   }
+
+   public void setPassword(String password)
+   {
+      this.password = password;
+   }
+
+   /** Returns the roles related to this user. */
+   public Set getRoles()
+   {
+      return roles;
+   }
+
+   /** Update the roles. */
+   public void setRoles(Set roles)
+   {
+      this.roles = roles;
+   }
+
+   public boolean validatePassword(String password)
+   {
+      if (password != null)
+      {
+         String hashedPassword = Tools.md5AsHexString(password);
+         return hashedPassword.equals(this.password);
+      }
+      return false;
+   }
+
+   /**
+    *
+    */
+   public String toString()
+   {
+      return "User[" + key + "," + userName + "]";
+   }
+
+
+   /** An accessor that maps a user field to a property name. */
+   static abstract class PropertyAccessor
+   {
+
+      protected final String propertyName;
+      protected final Field field;
+      protected final boolean writable;
+      protected final boolean nullable;
+
+      public PropertyAccessor(String propertyName, String fieldName, boolean writable, boolean nullable)
+      {
+         try
+         {
+            this.propertyName = propertyName;
+            this.writable = writable;
+            this.field = HibernateUserImpl.class.getDeclaredField(fieldName);
+            this.nullable = nullable;
+         }
+         catch (NoSuchFieldException e)
+         {
+            throw new Error(e);
+         }
+      }
+
+      public String getPropertyName()
+      {
+         return propertyName;
+      }
+
+      public boolean isNullable()
+      {
+         return nullable;
+      }
+
+      public boolean isWritable()
+      {
+         return writable;
+      }
+
+      /**
+       * @param instance the user instance
+       * @param string   the value
+       * @throws IllegalArgumentException if the string cannot be converted to an object
+       */
+      public void set(Object instance, String string) throws IllegalArgumentException
+      {
+         try
+         {
+            if (string == null)
+            {
+               field.set(instance, null);
+            }
+            else
+            {
+               Object object = toObject(string);
+               field.set(instance, object);
+            }
+         }
+         catch (IllegalAccessException e)
+         {
+            throw new Error(e);
+         }
+      }
+
+      /**
+       * @param instance the user instance
+       * @return the converted value
+       * @throws IllegalArgumentException if the object cannot be converted to a string
+       */
+      public String get(Object instance) throws IllegalArgumentException
+      {
+         try
+         {
+            Object object = field.get(instance);
+            if (object == null)
+            {
+               return null;
+            }
+            else
+            {
+               return toString(object);
+            }
+         }
+         catch (IllegalAccessException e)
+         {
+            throw new Error(e);
+         }
+      }
+
+      /**
+       * Perform the to object conversion.
+       *
+       * @param value the value to convert
+       * @return the converted value
+       * @throws IllegalArgumentException if the string cannot be converted to an object
+       */
+      protected abstract Object toObject(String value) throws IllegalArgumentException;
+
+      /**
+       * Perform the to strong conversion.
+       *
+       * @param value the value to convert
+       * @return the converted value
+       * @throws IllegalArgumentException if the object cannot be converted to a string
+       */
+      protected abstract String toString(Object value);
+
+      public String toString()
+      {
+         return "PropertyAccessor[" + propertyName + "," + field + "]";
+      }
+   }
+
+   static class StringPropertyAccessor extends PropertyAccessor
+   {
+      public StringPropertyAccessor(String propertyName, String fieldName, boolean writable, boolean nullable)
+      {
+         super(propertyName, fieldName, writable, nullable);
+      }
+
+      protected Object toObject(String value)
+      {
+         return value;
+      }
+
+      protected String toString(Object value)
+      {
+         return (String)value;
+      }
+   }
+
+   static class BooleanPropertyAccessor extends PropertyAccessor
+   {
+      public BooleanPropertyAccessor(String propertyName, String fieldName, boolean writable, boolean nullable)
+      {
+         super(propertyName, fieldName, writable, nullable);
+      }
+
+      protected Object toObject(String value) throws IllegalArgumentException
+      {
+         if ("true".equalsIgnoreCase(value))
+         {
+            return Boolean.TRUE;
+         }
+         else if ("false".equalsIgnoreCase(value))
+         {
+            return Boolean.FALSE;
+         }
+         else
+         {
+            throw new IllegalArgumentException("The value " + value + " cannot be converted to boolean for accessor " + toString());
+         }
+      }
+
+      protected String toString(Object value)
+      {
+         return value.toString();
+      }
+   }
+
+   static class DatePropertyAccessor extends PropertyAccessor
+   {
+      private static final ThreadLocal formatLocal = new ThreadLocal()
+      {
+         protected Object initialValue()
+         {
+            return new SimpleDateFormat();
+         }
+      };
+
+      public DatePropertyAccessor(String propertyName, String fieldName, boolean writable, boolean nullable)
+      {
+         super(propertyName, fieldName, writable, nullable);
+      }
+
+      protected Object toObject(String value) throws IllegalArgumentException
+      {
+         try
+         {
+            DateFormat format = (DateFormat)HibernateUserImpl.DatePropertyAccessor.formatLocal.get();
+            Date date = format.parse(value);
+            return date;
+         }
+         catch (ParseException e)
+         {
+            throw new IllegalArgumentException();
+         }
+      }
+
+      protected String toString(Object value)
+      {
+         Date date = (Date)value;
+         DateFormat format = (DateFormat)HibernateUserImpl.DatePropertyAccessor.formatLocal.get();
+         return format.format(date);
+      }
+   }
+}

Added: trunk/identity/src/main/org/jboss/portal/identity2/db/HibernateUserModuleImpl.java
===================================================================
--- trunk/identity/src/main/org/jboss/portal/identity2/db/HibernateUserModuleImpl.java	2006-12-13 15:22:51 UTC (rev 5834)
+++ trunk/identity/src/main/org/jboss/portal/identity2/db/HibernateUserModuleImpl.java	2006-12-13 15:23:19 UTC (rev 5835)
@@ -0,0 +1,291 @@
+/*
+* JBoss, a division of Red Hat
+* Copyright 2006, Red Hat Middleware, LLC, and individual contributors as indicated
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* This is free software; you can redistribute it and/or modify it
+* under the terms of the GNU Lesser General Public License as
+* published by the Free Software Foundation; either version 2.1 of
+* the License, or (at your option) any later version.
+*
+* This software is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+* Lesser General Public License for more details.
+*
+* You should have received a copy of the GNU Lesser General Public
+* License along with this software; if not, write to the Free
+* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+*/
+package org.jboss.portal.identity2.db;
+
+import org.jboss.portal.jems.as.system.AbstractJBossService;
+import org.jboss.portal.identity2.UserModule;
+import org.jboss.portal.identity2.User;
+import org.jboss.portal.identity.IdentityException;
+import org.jboss.portal.identity.NoSuchUserException;
+import org.jboss.portal.identity2.db.HibernateUserImpl;
+import org.jboss.portal.common.util.JNDI;
+import org.jboss.portal.common.util.Tools;
+import org.jboss.portal.identity2.service.UserModuleService;
+import org.hibernate.SessionFactory;
+import org.hibernate.Session;
+import org.hibernate.Query;
+import org.hibernate.HibernateException;
+
+import javax.naming.InitialContext;
+import java.io.Serializable;
+import java.util.Set;
+import java.util.Iterator;
+
+/**
+ * @author <a href="mailto:julien at jboss.org">Julien Viet </a>
+ * @version $Revision: 5448 $
+ * @portal.core
+ */
+public class HibernateUserModuleImpl extends UserModuleService
+{
+
+   /** . */
+      private static final org.jboss.logging.Logger log = org.jboss.logging.Logger.getLogger(HibernateUserModuleImpl.class);
+      /** . */
+      protected SessionFactory sessionFactory;
+
+      /** . */
+      protected String sessionFactoryJNDIName;
+
+      protected void startService() throws Exception
+      {
+         //
+         sessionFactory = (SessionFactory)new InitialContext().lookup(sessionFactoryJNDIName);
+
+         super.startService();
+      }
+
+      protected void stopService() throws Exception
+      {
+
+         //
+         sessionFactory = null;
+
+         super.stopService();
+      }
+
+//   public SessionFactory getSessionFactory()
+//   {
+//      return sessionFactory;
+//   }
+
+      public String getSessionFactoryJNDIName()
+      {
+         return sessionFactoryJNDIName;
+      }
+
+      public void setSessionFactoryJNDIName(String sessionFactoryJNDIName)
+      {
+         this.sessionFactoryJNDIName = sessionFactoryJNDIName;
+      }
+
+
+   public User findUserByUserName(String userName) throws IdentityException
+   {
+      if (userName != null)
+      {
+         try
+         {
+            Session session = getCurrentSession();
+            Query query = session.createQuery("from HibernateUserImpl where userName=:userName");
+            query.setParameter("userName", userName);
+            query.setCacheable(true);
+            HibernateUserImpl user = (HibernateUserImpl)query.uniqueResult();
+            if (user == null)
+            {
+               throw new NoSuchUserException("No such user " + userName);
+            }
+            return user;
+         }
+         catch (HibernateException e)
+         {
+            String message = "Cannot find user by name " + userName;
+            log.error(message, e);
+            throw new IdentityException(message, e);
+         }
+      }
+      else
+      {
+         throw new IllegalArgumentException("user name cannot be null");
+      }
+   }
+
+   public User findUserById(String id) throws IllegalArgumentException, IdentityException, NoSuchUserException
+   {
+      if (id == null)
+      {
+         throw new IllegalArgumentException("The id is null");
+      }
+      try
+      {
+         return findUserById(new Long(id));
+      }
+      catch (NumberFormatException e)
+      {
+         throw new IllegalArgumentException("Cannot parse id into an long " + id);
+      }
+   }
+
+   public User findUserById(Object id) throws IllegalArgumentException, IdentityException, NoSuchUserException
+   {
+      if (id instanceof Long)
+      {
+         try
+         {
+            Session session = getCurrentSession();
+            HibernateUserImpl user = (HibernateUserImpl)session.get(HibernateUserImpl.class, (Long)id);
+            if (user == null)
+            {
+               throw new NoSuchUserException("No user found for " + id);
+            }
+            return user;
+         }
+         catch (HibernateException e)
+         {
+            String message = "Cannot find user by id " + id;
+            log.error(message, e);
+            throw new IdentityException(message, e);
+         }
+      }
+      else
+      {
+         throw new IllegalArgumentException("The id is not an long : " + id);
+      }
+   }
+
+   public User createUser(String userName, String password) throws IdentityException
+   {
+      if (userName != null)
+      {
+         try
+         {
+            HibernateUserImpl user = new HibernateUserImpl(userName);
+            user.updatePassword(password);
+            //user.setRealEmail(realEmail);
+            Session session = getCurrentSession();
+            session.save(user);
+            return user;
+         }
+         catch (HibernateException e)
+         {
+            String message = "Cannot create user " + userName;
+            log.error(message, e);
+            throw new IdentityException(message, e);
+         }
+      }
+      else
+      {
+         throw new IllegalArgumentException("name cannot be null");
+      }
+   }
+
+   public void removeUser(Object id) throws IdentityException
+   {
+      if (id instanceof Long)
+      {
+         try
+         {
+            Session session = getCurrentSession();
+            HibernateUserImpl user = (HibernateUserImpl)session.load(HibernateUserImpl.class, (Serializable)id);
+            if (user == null)
+            {
+               throw new NoSuchUserException("No such user " + id);
+            }
+            session.delete(user);
+            session.flush();
+         }
+         catch (HibernateException e)
+         {
+            String message = "Cannot remove user " + id;
+            log.error(message, e);
+            throw new IdentityException(message, e);
+         }
+      }
+      else
+      {
+         throw new IllegalArgumentException("The id is not an long : " + id);
+      }
+   }
+
+   public Set findUsers(int offset, int limit) throws IdentityException
+   {
+      try
+      {
+         Session session = getCurrentSession();
+         Query query = session.createQuery("from HibernateUserImpl");
+         query.setFirstResult(offset);
+         query.setMaxResults(limit);
+         Iterator iterator = query.iterate();
+         return Tools.toSet(iterator);
+      }
+      catch (HibernateException e)
+      {
+         String message = "Cannot find user range [" + offset + "," + limit + "]";
+         log.error(message, e);
+         throw new IdentityException(message, e);
+      }
+   }
+
+   public Set findUsersFilteredByUserName(String filter, int offset, int limit) throws IdentityException
+   {
+      try
+      {
+         // Remove all occurences of % and add ours
+         filter = "%" + filter.replaceAll("%", "") + "%";
+
+         //
+         Session session = getCurrentSession();
+         Query query = session.createQuery("from HibernateUserImpl as u where u.userName like :filter");
+         query.setString("filter", filter);
+         query.setFirstResult(offset);
+         query.setMaxResults(limit);
+         Iterator iterator = query.iterate();
+         return Tools.toSet(iterator);
+      }
+      catch (HibernateException e)
+      {
+         String message = "Cannot find user range [" + offset + "," + limit + "]";
+         log.error(message, e);
+         throw new IdentityException(message, e);
+      }
+   }
+
+   public int getUserCount() throws IdentityException
+   {
+      try
+      {
+         Session session = getCurrentSession();
+         Query query = session.createQuery("select count(u.key) from HibernateUserImpl as u");
+         return ((Number)query.uniqueResult()).intValue();
+      }
+      catch (HibernateException e)
+      {
+         String message = "Cannot count users";
+         log.error(message, e);
+         throw new IdentityException(message, e);
+      }
+   }
+
+   /**
+    * Can be subclasses to provide testing in a non JTA environement.
+    *
+    * @throws IllegalStateException if no session factory is present
+    */
+   protected Session getCurrentSession() throws IllegalStateException
+   {
+      if (sessionFactory == null)
+      {
+         throw new IllegalStateException("No session factory");
+      }
+      return sessionFactory.getCurrentSession();
+   }
+}

Added: trunk/identity/src/main/org/jboss/portal/identity2/db/HibernateUserProfileModuleImpl.java
===================================================================
--- trunk/identity/src/main/org/jboss/portal/identity2/db/HibernateUserProfileModuleImpl.java	2006-12-13 15:22:51 UTC (rev 5834)
+++ trunk/identity/src/main/org/jboss/portal/identity2/db/HibernateUserProfileModuleImpl.java	2006-12-13 15:23:19 UTC (rev 5835)
@@ -0,0 +1,280 @@
+/*
+* JBoss, a division of Red Hat
+* Copyright 2006, Red Hat Middleware, LLC, and individual contributors as indicated
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* This is free software; you can redistribute it and/or modify it
+* under the terms of the GNU Lesser General Public License as
+* published by the Free Software Foundation; either version 2.1 of
+* the License, or (at your option) any later version.
+*
+* This software is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+* Lesser General Public License for more details.
+*
+* You should have received a copy of the GNU Lesser General Public
+* License along with this software; if not, write to the Free
+* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+*/
+package org.jboss.portal.identity2.db;
+
+import org.jboss.portal.identity2.User;
+import org.jboss.portal.identity2.UserProfileModule;
+import org.jboss.portal.identity2.IdentityContext;
+import org.jboss.portal.identity2.info.ProfileInfo;
+import org.jboss.portal.identity2.info.PropertyInfo;
+import org.jboss.portal.identity2.db.HibernateUserImpl;
+import org.hibernate.SessionFactory;
+import org.hibernate.Session;
+import org.hibernate.Query;
+import org.hibernate.HibernateException;
+
+import javax.naming.InitialContext;
+import org.jboss.portal.identity2.service.UserProfileModuleService;
+import org.jboss.portal.identity.IdentityException;
+import org.jboss.portal.identity.NoSuchUserException;
+
+import java.util.Map;
+import java.util.Set;
+import java.util.Iterator;
+import java.util.HashMap;
+
+/**
+ * @author <a href="mailto:boleslaw.dawidowicz at jboss.org">Boleslaw Dawidowicz</a>
+ * @version $Revision: 1.1 $
+ */
+public class HibernateUserProfileModuleImpl extends UserProfileModuleService
+{
+
+   /** . */
+   private static final org.jboss.logging.Logger log = org.jboss.logging.Logger.getLogger(HibernateUserProfileModuleImpl.class);
+   /** . */
+   protected SessionFactory sessionFactory;
+
+   /** . */
+   protected String sessionFactoryJNDIName;
+
+   private boolean synchronizeNonExistingUsers = true;
+
+   private boolean acceptOtherImplementations = true;
+
+   protected void startService() throws Exception
+   {
+      //
+      sessionFactory = (SessionFactory)new InitialContext().lookup(sessionFactoryJNDIName);
+
+      super.startService();
+
+   }
+
+   protected void stopService() throws Exception
+   {
+      //
+      sessionFactory = null;
+      super.stopService();
+   }
+
+//   public SessionFactory getSessionFactory()
+//   {
+//      return sessionFactory;
+//   }
+
+   public String getSessionFactoryJNDIName()
+   {
+      return sessionFactoryJNDIName;
+   }
+
+   public void setSessionFactoryJNDIName(String sessionFactoryJNDIName)
+   {
+      this.sessionFactoryJNDIName = sessionFactoryJNDIName;
+   }
+
+   public Object getProperty(User user, String propertyName) throws IdentityException
+   {
+      if (user == null)
+      {
+         throw new IllegalArgumentException("User cannot be null");
+      }
+      if (propertyName == null)
+      {
+         throw new IllegalArgumentException("Property name need to have value");
+      }
+
+      HibernateUserImpl dbUser = processUser(user);
+
+      PropertyInfo pi = getProfileInfo().getPropertyInfo(propertyName);
+
+      if (pi == null)
+      {
+         throw new IdentityException("Cannot find profile information about property: " + propertyName);
+      }
+
+      return dbUser.getProfileMap().get(propertyName);
+   }
+
+   public void setProperty(User user, String propertyName, Object propertyValue) throws IdentityException
+   {
+      if (user == null)
+      {
+         throw new IllegalArgumentException("User cannot be null");
+      }
+      if (propertyName == null)
+      {
+         throw new IllegalArgumentException("Property name need to have value");
+      }
+
+      HibernateUserImpl dbUser = processUser(user);
+
+
+      PropertyInfo pi = getProfileInfo().getPropertyInfo(propertyName);
+
+      if (pi == null)
+      {
+         throw new IdentityException("Cannot find profile information about property: " + propertyName);
+      }
+      else if (!pi.getAccessMode().equals(PropertyInfo.ACCESS_MODE_READ_WRITE))
+      {
+         throw new IdentityException("Property is not allowed for write access: " + propertyName);
+      }
+
+      //if value is null reset property
+
+      dbUser.getProfileMap().put(propertyName, propertyValue);
+   }
+
+   public Map getProperties(User user) throws IdentityException
+   {
+      if (user == null)
+      {
+         throw new IllegalArgumentException("User cannot be null");
+      }
+
+      HibernateUserImpl dbUser = processUser(user);
+
+
+
+      //make a copy
+      Map props = new HashMap();
+      Map profile = dbUser.getProfileMap();
+      Set keys = profile.keySet();
+      for (Iterator iterator = keys.iterator(); iterator.hasNext();)
+      {
+         String key = (String)iterator.next();
+         props.put(key, profile.get(key));
+      }
+      return props;
+   }
+
+
+
+   /** Can be subclasses to provide testing in a non JTA environement. */
+   protected Session getCurrentSession()
+   {
+      if (sessionFactory == null)
+      {
+         throw new IllegalStateException("No session factory");
+      }
+      return sessionFactory.getCurrentSession();
+   }
+
+   protected HibernateUserImpl processUser(User user) throws IdentityException
+   {
+      if (user instanceof HibernateUserImpl)
+      {
+         return (HibernateUserImpl)user;
+      }
+      else if (!isAcceptOtherImplementations())
+      {
+         throw new IllegalArgumentException("This UserProfileModule implementation support only HibenrateUserImpl objects - set acceptOtherImplementations option to true");
+      }
+      if (log.isDebugEnabled()) log.debug("Processing non HibernateUserImpl object: " + user.getClass());
+      //if not Hibernate user try to obtain it using userName
+      Session session = getCurrentSession();
+      Query query = session.createQuery("from HibernateUserImpl where userName=:userName");
+      query.setParameter("userName", user.getUserName());
+      query.setCacheable(true);
+      HibernateUserImpl hu = (HibernateUserImpl)query.uniqueResult();
+
+      if (hu != null )
+      {
+         return hu;
+      }
+      else if (!isSynchronizeNonExistingUsers())
+      {
+         throw new IdentityException("No user in DB - set synchronizeNonExistingUsers option to true");
+      }
+      else
+      {
+         try
+         {
+            hu = new HibernateUserImpl(user.getUserName());
+            user.updatePassword(user.getPassword());
+            session = getCurrentSession();
+            session.save(user);
+            return hu;
+         }
+         catch (HibernateException e)
+         {
+            String message = "Cannot create user " + user.getUserName();
+            log.error(message, e);
+            throw new IdentityException(message, e);
+         }
+      }
+
+
+   }
+
+
+   /**
+    * obtains UserProfile object - if module is used as a Delegate it tries to obtain it from the main one.
+    * @return
+    * @throws IdentityException
+    */
+   public ProfileInfo getProfileInfo() throws IdentityException
+   {
+      ProfileInfo profileInfo = super.getProfileInfo();
+      if (profileInfo != null)
+      {
+         return profileInfo;
+      }
+      else
+      {
+         //obtain main UserProfileModule
+         UserProfileModule module = (UserProfileModule)getIdentityContext().getObject(IdentityContext.TYPE_USER_PROFILE_MODULE);
+         if (module == this)
+         {
+            throw new IdentityException("ProfileInfo not accessible - check configuration");
+         }
+         else
+         {
+            setProfileInfo(module.getProfileInfo());
+            return profileInfo;
+         }
+      }
+   }
+
+
+   public boolean isSynchronizeNonExistingUsers()
+   {
+      return synchronizeNonExistingUsers;
+   }
+
+   public void setSynchronizeNonExistingUsers(boolean synchronizeNonExistingUsers)
+   {
+      this.synchronizeNonExistingUsers = synchronizeNonExistingUsers;
+   }
+
+
+   public boolean isAcceptOtherImplementations()
+   {
+      return acceptOtherImplementations;
+   }
+
+   public void setAcceptOtherImplementations(boolean acceptOtherImplementations)
+   {
+      this.acceptOtherImplementations = acceptOtherImplementations;
+   }
+}

Added: trunk/identity/src/main/org/jboss/portal/identity2/db/ProfileMapImpl.java
===================================================================
--- trunk/identity/src/main/org/jboss/portal/identity2/db/ProfileMapImpl.java	2006-12-13 15:22:51 UTC (rev 5834)
+++ trunk/identity/src/main/org/jboss/portal/identity2/db/ProfileMapImpl.java	2006-12-13 15:23:19 UTC (rev 5835)
@@ -0,0 +1,275 @@
+/*
+* JBoss, a division of Red Hat
+* Copyright 2006, Red Hat Middleware, LLC, and individual contributors as indicated
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* This is free software; you can redistribute it and/or modify it
+* under the terms of the GNU Lesser General Public License as
+* published by the Free Software Foundation; either version 2.1 of
+* the License, or (at your option) any later version.
+*
+* This software is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+* Lesser General Public License for more details.
+*
+* You should have received a copy of the GNU Lesser General Public
+* License along with this software; if not, write to the Free
+* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+*/
+package org.jboss.portal.identity2.db;
+
+import org.jboss.portal.identity2.ProfileMap;
+import org.jboss.portal.identity2.db.HibernateUserImpl;
+
+import java.util.Iterator;
+import java.util.Set;
+import java.util.HashSet;
+import java.util.Collection;
+import java.util.ArrayList;
+import java.util.Map;
+import java.util.HashMap;
+import java.util.Collections;
+
+/**
+ * A mutable map that expose user properties.
+ *
+ * @author <a href="mailto:julien at jboss.org">Julien Viet</a>
+ * @version $Revision: 5448 $
+ */
+public class ProfileMapImpl implements ProfileMap
+{
+
+   /** . */
+   private HibernateUserImpl user;
+
+   public ProfileMapImpl(HibernateUserImpl user)
+   {
+      if (user == null)
+      {
+         throw new IllegalArgumentException();
+      }
+      this.user = user;
+   }
+
+   public boolean isReadOnly(Object key)
+   {
+      if (key == null)
+      {
+         return false;
+      }
+      if (key instanceof String == false)
+      {
+         throw new ClassCastException("Key must be a string");
+      }
+      HibernateUserImpl.PropertyAccessor accessor = (HibernateUserImpl.PropertyAccessor)HibernateUserImpl.ACCESSORS.get(key);
+      return accessor != null && !accessor.isWritable();
+   }
+
+   public int size()
+   {
+      return HibernateUserImpl.ACCESSORS.size() + user.getDynamic().size();
+   }
+
+   public boolean isEmpty()
+   {
+      return false;
+   }
+
+   /** @throws ClassCastException if the key is not an instance of string */
+   public boolean containsKey(Object key) throws ClassCastException
+   {
+      if (key == null)
+      {
+         return false;
+      }
+      if (key instanceof String == false)
+      {
+         throw new ClassCastException("Key must be a string");
+      }
+      HibernateUserImpl.PropertyAccessor accessor = (HibernateUserImpl.PropertyAccessor)HibernateUserImpl.ACCESSORS.get(key);
+      if (accessor != null)
+      {
+         return true;
+      }
+      return user.getDynamic().containsKey(key);
+   }
+
+   /** @throws ClassCastException if the value is not an instance of string */
+   public boolean containsValue(Object value) throws ClassCastException
+   {
+      if (value == null)
+      {
+         throw new NullPointerException("Key cannot be null");
+      }
+      if (value instanceof String == false)
+      {
+         throw new ClassCastException("Value must be a string");
+      }
+      for (Iterator i = HibernateUserImpl.ACCESSORS.values().iterator(); i.hasNext();)
+      {
+         HibernateUserImpl.PropertyAccessor accessor = (HibernateUserImpl.PropertyAccessor)i.next();
+         Object value2 = accessor.get(user);
+         if (value == value2 || value.equals(value2))
+         {
+            return true;
+         }
+      }
+      return user.getDynamic().containsValue(value);
+   }
+
+   /** @throws ClassCastException if the key is not an instance of string */
+   public Object get(Object key)
+   {
+      if (key == null)
+      {
+         return null;
+      }
+      if (key instanceof String == false)
+      {
+         throw new ClassCastException("Key must be a string");
+      }
+      HibernateUserImpl.PropertyAccessor accessor = (HibernateUserImpl.PropertyAccessor)HibernateUserImpl.ACCESSORS.get(key);
+      if (accessor != null)
+      {
+         return accessor.get(user);
+      }
+      return user.getDynamic().get(key);
+   }
+
+   /**
+    * Put a value in the dynamic map.
+    * <p/>
+    * If the key is not an instance of string then an IllegalArgumentException is thrown. If the value is mapped to an
+    * accessor of a non writable field then an IllegalArgumentException is thrown. If the value is mapped to an accessor
+    * of a non nullable field and the field is null then an IllegalArgumentException is thrown.
+    *
+    * @throws IllegalArgumentException
+    */
+   public Object put(Object key, Object newValue) throws IllegalArgumentException
+   {
+      if (key == null)
+      {
+         return null;
+      }
+      if (key instanceof String == false)
+      {
+         throw new ClassCastException("Key is not a String");
+      }
+      HibernateUserImpl.PropertyAccessor accessor = (HibernateUserImpl.PropertyAccessor)HibernateUserImpl.ACCESSORS.get(key);
+      if (accessor != null)
+      {
+         if (newValue == null && !accessor.isNullable())
+         {
+            throw new NullPointerException("Key " + key + " is not nullable");
+         }
+         if (!accessor.isWritable())
+         {
+            throw new IllegalArgumentException("Key " + key + " is not modifiable");
+         }
+         else
+         {
+            Object oldValue = accessor.get(user);
+            accessor.set(user, (String)newValue);
+            return oldValue;
+         }
+      }
+      if (newValue instanceof String == false)
+      {
+         throw new ClassCastException("Dynamic value must be a string");
+      }
+      return user.getDynamic().put(key, newValue);
+   }
+
+   /**
+    * Only affect dynamic properties, otherwise it throws an IllegalArgumentException.
+    *
+    * @throws IllegalArgumentException if the key is a not a dynamic property
+    */
+   public Object remove(Object key) throws IllegalArgumentException
+   {
+      if (key instanceof String == false)
+      {
+         throw new ClassCastException("Key is not a String");
+      }
+      HibernateUserImpl.PropertyAccessor accessor = (HibernateUserImpl.PropertyAccessor)HibernateUserImpl.ACCESSORS.get(key);
+      if (accessor != null)
+      {
+         throw new IllegalArgumentException("Key " + key + " is not removable");
+      }
+      return user.getDynamic().remove(key);
+   }
+
+   /** Clear only dynamic properties. */
+   public void clear()
+   {
+      user.getDynamic().clear();
+   }
+
+   public Set keySet()
+   {
+      // Get
+      Set set = new HashSet(size());
+
+      //
+      set.addAll(user.getDynamic().keySet());
+      set.addAll(HibernateUserImpl.ACCESSORS.keySet());
+      return set;
+   }
+
+   public Collection values()
+   {
+      ArrayList collection = new ArrayList(size());
+      for (Iterator i = HibernateUserImpl.ACCESSORS.values().iterator(); i.hasNext();)
+      {
+         HibernateUserImpl.PropertyAccessor accessor = (HibernateUserImpl.PropertyAccessor)i.next();
+         collection.add(accessor.get(user));
+      }
+      collection.addAll(user.getDynamic().values());
+      return collection;
+   }
+
+   /** Returns an immutable collection of entries. */
+   public Set entrySet()
+   {
+      Map copy = new HashMap(user.getDynamic());
+      for (Iterator i = HibernateUserImpl.ACCESSORS.values().iterator(); i.hasNext();)
+      {
+         HibernateUserImpl.PropertyAccessor accessor = (HibernateUserImpl.PropertyAccessor)i.next();
+         copy.put(accessor.getPropertyName(), accessor.get(user));
+      }
+      return Collections.unmodifiableMap(copy).entrySet();
+   }
+
+   public void putAll(Map map)
+   {
+      // todo : check all properties ok with changes before proceeding
+      for (Iterator i = map.entrySet().iterator(); i.hasNext();)
+      {
+         Entry entry = (Entry)i.next();
+         Object key = entry.getKey();
+         if (key instanceof String)
+         {
+            Object value = entry.getValue();
+            HibernateUserImpl.PropertyAccessor accessor = (HibernateUserImpl.PropertyAccessor)HibernateUserImpl.ACCESSORS.get(key);
+            if (accessor != null)
+            {
+               if (accessor.isWritable())
+               {
+                  accessor.set(user, (String)value);
+               }
+               else
+               {
+                  // julien : Do something better ?
+               }
+            }
+            else
+            {
+               user.getDynamic().put(key, value);
+            }
+         }
+      }
+   }
+}




More information about the portal-commits mailing list