View Javadoc
1   package info.ejava.examples.ejb.cdisales.dao;
2   
3   import java.util.ArrayList;
4   import java.util.List;
5   import java.util.Set;
6   
7   import info.ejava.examples.ejb.cdisales.bl.InvalidAccount;
8   import info.ejava.examples.ejb.cdisales.bl.UserMgmt;
9   import info.ejava.examples.ejb.cdisales.bo.Member;
10  
11  import javax.enterprise.inject.Vetoed;
12  import javax.persistence.EntityManager;
13  import javax.validation.ConstraintViolation;
14  import javax.validation.Validator;
15  
16  /**
17   * This bean will be "Produced" and injected from a factory
18   */
19  //@Vetoed //don't use this class as a source for obtaining a UserMgmt or UserMgmtDAO.
20  //that is being implemented by a factory elsewhere
21  public class UserMgmtDAO implements UserMgmt {
22      private EntityManager em;
23      private Validator validator;
24      
25      public void setEntityManager(EntityManager em) {
26          this.em = em;
27      }
28      public void setValidator(Validator validator) {
29          this.validator=validator;
30      }
31  
32      @Override
33      public Member createMember(Member member) throws InvalidAccount {
34          Set<ConstraintViolation<Member>> errors = validator.validate(member);
35          if (errors!=null && !errors.isEmpty()) {
36              List<String> errorText = new ArrayList<String>(errors.size());
37              for (ConstraintViolation<Member> v: errors) {
38                  errorText.add(v.toString());
39              }
40              throw new InvalidAccount("invalid account:" + errorText);
41          }
42          
43          if (findMemberByLogin(member.getLogin())!=null) {
44              throw new InvalidAccount(String.format("login [%s] already exists", member.getLogin()));
45          }
46          
47          em.persist(member);
48          return member;
49      }
50  
51      @Override
52      public Member getMember(int id) {
53          return em.find(Member.class, id);
54      }
55  
56      @Override
57      public Member findMemberByLogin(String login) {
58          if (login==null) { return null; }
59          List<Member> members = em.createNamedQuery("CDIMember.getMemberByLogin",Member.class)
60                  .setParameter("login", login)
61                  .getResultList();
62          return members.isEmpty() ? null : members.get(0);  
63      }
64  }