(no commit message)
[utils] / security / impl / src / main / java / org / wamblee / usermgt / jpa / JpaGroupSet.java
1 package org.wamblee.usermgt.jpa;
2
3 import java.util.List;
4 import java.util.Set;
5 import java.util.TreeSet;
6
7 import javax.persistence.EntityManager;
8 import javax.persistence.TypedQuery;
9
10 import org.wamblee.persistence.JpaMergeSupport;
11 import org.wamblee.usermgt.Group;
12 import org.wamblee.usermgt.GroupSet;
13
14 public class JpaGroupSet implements GroupSet {
15     
16     private EntityManager em; 
17     
18     public JpaGroupSet(EntityManager aEm) { 
19         em = aEm;
20     }
21
22     @Override
23     public boolean add(Group aGroup) {
24         assert aGroup.getPrimaryKey() == null;
25         if (contains(aGroup)) {
26             return false;
27         }
28         em.persist(aGroup);
29         return true;
30     }
31
32     @Override
33     public boolean contains(Group aGroup) {
34            return find(aGroup.getName()) != null;  
35     }
36
37     @Override
38     public Group find(String aName) {
39         TypedQuery<Group> query = em.createNamedQuery(Group.QUERY_FIND_BY_NAME, Group.class);
40         query.setParameter(Group.NAME_PARAM, aName);
41         List<Group> groups = query.getResultList();
42         if (groups.size() > 1) {
43             throw new RuntimeException(
44                 "More than one group with the same name '" + aName + "'");
45         }
46
47         if (groups.size() == 0) {
48             return null;
49         }
50         return groups.get(0);
51     }
52
53     @Override
54     public void groupModified(Group aGroup) {
55         assert aGroup.getPrimaryKey() != null;
56         Group merged = em.merge(aGroup);
57         // Need to flush so that version of the merged instance is updated so we can use 
58         // the updated version in the original group passed in. That allows the same 
59         // group object to continue to be used as a detached object. 
60         em.flush();
61         JpaMergeSupport.merge(merged, aGroup);
62     }
63
64     @Override
65     public Set<Group> list() {
66         List<Group> groups = em.createNamedQuery(Group.QUERY_ALL_GROUPS, Group.class).getResultList();
67         Set<Group> res = new TreeSet<Group>(groups);
68         return res; 
69     }
70
71     @Override
72     public boolean remove(Group aGroup) {
73         Group group = find(aGroup.getName());
74         if ( group == null ) { 
75             return false; 
76         }
77         em.remove(group);
78         return true;
79     }
80
81     @Override
82     public int size() {
83         Long res = (Long)em.createNamedQuery(Group.QUERY_COUNT_GROUPS).getSingleResult();
84         return res.intValue();
85     }
86 }