public Group fetchGroupForUpdate(final User user, final Long groupId)
     throws GroupNotFoundException, AccessDeniedException {
   final GroupImpl group = entityManager.find(GroupImpl.class, groupId);
   if (group == null) throw new GroupNotFoundException();
   if (group.getOwner().equals(user)) return group;
   throw new AccessDeniedException();
 }
 public Group createGroup(final User user, final String name, final String description)
     throws NameClashException {
   final GroupImpl group = new GroupImpl(name, user, description, new Date());
   try {
     entityManager.persist(group);
     joinGroup(user, group.getId());
     return group;
   } catch (EntityExistsException e) {
     throw new NameClashException();
   }
 }
 private boolean isGroupMember(final User user, final GroupImpl group) {
   final Query query =
       entityManager.createNativeQuery(
           "select 1 from GROUP_USER where USER_ID=:userId AND GROUP_ID=:groupId");
   query.setParameter("userId", user.getId());
   query.setParameter("groupId", group.getId());
   return query.getResultList().size() > 0;
 }
 public void updateGroup(
     final User user, final Long groupId, final String name, final String description)
     throws GroupNotFoundException, AccessDeniedException, NameClashException {
   final GroupImpl group = entityManager.find(GroupImpl.class, groupId);
   if (group == null) throw new GroupNotFoundException();
   if (group.getOwner().equals(user)) {
     final Query query =
         entityManager.createNativeQuery(
             "update GROUPS SET NAME=:name, DESCRIPTION=:description where ID=:groupId and OWNER_ID=:userId");
     query.setParameter("name", name);
     query.setParameter("description", description);
     query.setParameter("groupId", groupId);
     query.setParameter("userId", user.getId());
     try {
       query.executeUpdate();
     } catch (EntityExistsException e) {
       throw new NameClashException();
     }
   } else throw new AccessDeniedException();
 }
 private void updateLastGroupVisit(final User user, final GroupImpl group) {
   if (group != null) {
     final Query query =
         entityManager.createNativeQuery(
             "update GROUP_USER SET LAST_VISIT=:now where GROUP_ID=:groupId and USER_ID=:userId");
     query.setParameter("now", new Date());
     query.setParameter("groupId", group.getId());
     query.setParameter("userId", user.getId());
     query.executeUpdate();
   }
 }