(no commit message)
[utils] / security / impl / src / test / 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.usermgt.Group;
11 import org.wamblee.usermgt.GroupSet;
12
13 public class JpaGroupSet implements GroupSet {
14     
15     private EntityManager em; 
16     
17     public JpaGroupSet(EntityManager aEm) { 
18         em = aEm;
19     }
20
21     @Override
22     public boolean add(Group aGroup) {
23         assert aGroup.getPrimaryKey() == null;
24         if (contains(aGroup)) {
25             return false;
26         }
27         em.persist(aGroup);
28         return true;
29     }
30
31     @Override
32     public boolean contains(Group aGroup) {
33            return find(aGroup.getName()) != null;  
34     }
35
36     @Override
37     public Group find(String aName) {
38         TypedQuery<Group> query = em.createNamedQuery(Group.QUERY_FIND_BY_NAME, Group.class);
39         query.setParameter(Group.NAME_PARAM, aName);
40         List<Group> groups = query.getResultList();
41         if (groups.size() > 1) {
42             throw new RuntimeException(
43                 "More than one group with the same name '" + aName + "'");
44         }
45
46         if (groups.size() == 0) {
47             return null;
48         }
49         return groups.get(0);
50     }
51
52     @Override
53     public void groupModified(Group aGroup) {
54         assert aGroup.getPrimaryKey() != null;
55         em.merge(aGroup);
56     }
57
58     @Override
59     public Set<Group> list() {
60         List<Group> groups = em.createNamedQuery(Group.QUERY_ALL_GROUPS, Group.class).getResultList();
61         Set<Group> res = new TreeSet<Group>(groups);
62         return res; 
63     }
64
65     @Override
66     public boolean remove(Group aGroup) {
67         Group group = find(aGroup.getName());
68         if ( group == null ) { 
69             return false; 
70         }
71         em.remove(group);
72         return true;
73     }
74
75     @Override
76     public int size() {
77         Long res = (Long)em.createNamedQuery(Group.QUERY_COUNT_GROUPS).getSingleResult();
78         return res.intValue();
79     }
80 }