package example.ejb.impl; import example.ejb.interfaces.UserCredentialManager; import example.ejb.interfaces.NoSuchUserException; import example.ejb.interfaces.IncorrectPasswordException; import example.entity.UserCredential; import example.entity.LoginAttempt; import javax.ejb.*; import javax.persistence.*; @Stateless @Local public class UserCredentialManagerBean implements UserCredentialManager { @PersistenceContext private EntityManager em; public void createUser(UserCredential uc) { // em.persist makes the new object as persistent and managed. em.persist(uc); } /** * This method runs in a new transaction because it logs an unsuccessful * login attempt. */ @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) public void authenticate(String name, String password) throws NoSuchUserException, IncorrectPasswordException { UserCredential uc = em.find(UserCredential.class, name); // em.find returns null if not found, hence null check. if (uc == null) { throw new NoSuchUserException("There is no user by name [" + name + "]."); } final boolean matchingPassword = uc.isMatchingPassword(password); LoginAttempt attempt = new LoginAttempt(uc, matchingPassword); uc.addLoginAttempt(attempt); em.persist(attempt); if (!matchingPassword) { throw new IncorrectPasswordException("Password is incorrect. " + "Your login attempt may be reported to sys-admin."); } } public void removeUser(String name) { UserCredential uc = em.find(UserCredential.class, name); // em.find returns null if not found, hence null check. if (uc != null) { em.remove(uc); } else { throw new EJBException("No such user"); } } public UserCredential lookupUser(String name) { System.out.println("Inside EJB: em = " + em); System.out.println("Inside EJB: delegate = " + em.getDelegate()); return em.find(UserCredential.class, name); } }