--- /dev/null
+/*
+ * Copyright 2005-2010 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wamblee.security.authentication.jpa;
+
+import java.util.List;
+import java.util.Set;
+import java.util.TreeSet;
+
+import javax.persistence.EntityManager;
+import javax.persistence.TypedQuery;
+
+import org.wamblee.persistence.JpaMergeSupport;
+import org.wamblee.security.authentication.Group;
+import org.wamblee.security.authentication.GroupSet;
+
+/**
+ * Group set backed by the database.
+ *
+ * @author Erik Brakkee
+ */
+public class JpaGroupSet implements GroupSet {
+
+ private EntityManager em;
+
+ public JpaGroupSet(EntityManager aEm) {
+ em = aEm;
+ }
+
+ @Override
+ public boolean add(Group aGroup) {
+ assert aGroup.getPrimaryKey() == null;
+ if (contains(aGroup)) {
+ return false;
+ }
+ em.persist(aGroup);
+ em.flush(); // to make sure the version is updated.
+ return true;
+ }
+
+ @Override
+ public boolean contains(Group aGroup) {
+ return find(aGroup.getName()) != null;
+ }
+
+ @Override
+ public Group find(String aName) {
+ TypedQuery<Group> query = em.createNamedQuery(Group.QUERY_FIND_BY_NAME,
+ Group.class);
+ query.setParameter(Group.NAME_PARAM, aName);
+ List<Group> groups = query.getResultList();
+ if (groups.size() > 1) {
+ throw new RuntimeException(
+ "More than one group with the same name '" + aName + "'");
+ }
+
+ if (groups.size() == 0) {
+ return null;
+ }
+ return groups.get(0);
+ }
+
+ @Override
+ public void groupModified(Group aGroup) {
+ assert aGroup.getPrimaryKey() != null;
+ Group merged = em.merge(aGroup);
+ // Need to flush so that version of the merged instance is updated so we
+ // can use
+ // the updated version in the original group passed in. That allows the
+ // same
+ // group object to continue to be used as a detached object.
+ em.flush();
+ JpaMergeSupport.merge(merged, aGroup);
+ }
+
+ @Override
+ public Set<Group> list() {
+ List<Group> groups = em.createNamedQuery(Group.QUERY_ALL_GROUPS,
+ Group.class).getResultList();
+ Set<Group> res = new TreeSet<Group>(groups);
+ return res;
+ }
+
+ @Override
+ public boolean remove(Group aGroup) {
+ Group group = find(aGroup.getName());
+ if (group == null) {
+ return false;
+ }
+ em.remove(group);
+ return true;
+ }
+
+ @Override
+ public int size() {
+ Long res = (Long) em.createNamedQuery(Group.QUERY_COUNT_GROUPS)
+ .getSingleResult();
+ return res.intValue();
+ }
+}