(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,
40             Group.class);
41         query.setParameter(Group.NAME_PARAM, aName);
42         List<Group> groups = query.getResultList();
43         if (groups.size() > 1) {
44             throw new RuntimeException(
45                 "More than one group with the same name '" + aName + "'");
46         }
47
48         if (groups.size() == 0) {
49             return null;
50         }
51         return groups.get(0);
52     }
53
54     @Override
55     public void groupModified(Group aGroup) {
56         assert aGroup.getPrimaryKey() != null;
57         Group merged = em.merge(aGroup);
58         // Need to flush so that version of the merged instance is updated so we
59         // can use
60         // the updated version in the original group passed in. That allows the
61         // same
62         // group object to continue to be used as a detached object.
63         em.flush();
64         JpaMergeSupport.merge(merged, aGroup);
65     }
66
67     @Override
68     public Set<Group> list() {
69         List<Group> groups = em.createNamedQuery(Group.QUERY_ALL_GROUPS,
70             Group.class).getResultList();
71         Set<Group> res = new TreeSet<Group>(groups);
72         return res;
73     }
74
75     @Override
76     public boolean remove(Group aGroup) {
77         Group group = find(aGroup.getName());
78         if (group == null) {
79             return false;
80         }
81         em.remove(group);
82         return true;
83     }
84
85     @Override
86     public int size() {
87         Long res = (Long) em.createNamedQuery(Group.QUERY_COUNT_GROUPS)
88             .getSingleResult();
89         return res.intValue();
90     }
91 }