View Javadoc
1   package ejava.examples.blpurchase.blimpl;
2   
3   import java.util.Random;
4   
5   import javax.persistence.EntityManager;
6   
7   import org.slf4j.Logger;
8   import org.slf4j.LoggerFactory;
9   
10  import ejava.examples.blpurchase.bl.Purchasing;
11  import ejava.examples.blpurchase.bo.Account;
12  import ejava.examples.blpurchase.bo.Cart;
13  import ejava.examples.blpurchase.bo.Product;
14  
15  /**
16   * This class implements basic logic used to implement the purchasing
17   * aspects of the application.
18   */
19  public class PurchasingImpl implements Purchasing {
20  	private static final Logger logger = LoggerFactory.getLogger(PurchasingImpl.class);
21  	private EntityManager em;
22  	private Random random=new Random();
23  	
24  	public void setEntityManager(EntityManager em) {
25  		this.em = em;
26  	}
27  
28  	@Override
29  	public Account createAccount(String email, String firstName, String lastName) {
30  		int count=em.createNamedQuery(Account.FIND_BY_EMAIL_QUERY)
31  				.setParameter("email", email)
32  				.setMaxResults(1)
33  				.getResultList()
34  				.size();
35  		if (count==0) {
36  			Account account = new Account(email, firstName, lastName);
37  			account.setPassword(generatePassword());
38  			em.persist(account);
39  			logger.debug("created account: {}", account);
40  			return account;
41  		}
42  
43  		return null; //don't return legacy accounts -- they have the password
44  	}
45  
46  	@Override
47  	public double checkout(String email, String password) {
48  		Cart cart = em.find(Cart.class, email);
49  		if (cart == null) {
50  			logger.warn("cart not found");
51  			return 0;
52  		}
53  		
54  		Account account = cart.getAccount();
55  		if (!account.getPassword().equals(password)) {
56  			logger.warn("wrong password");
57  			return 0;
58  		}
59  		
60  		double total = 0;
61  		for (Product product : cart.getProducts()) {
62  			total += product.getPrice();
63  		}
64  		if (logger.isDebugEnabled()) {
65  		    logger.debug("checked out {} products for {}", cart.getProducts().size(), email);
66  		}
67  		cart.getProducts().clear();
68  		
69  		return total;
70  	}
71  
72  	private String generatePassword() {
73  		byte[] password = new byte[8];
74  		for (int i=0; i<password.length; i++) {
75  			password[i] = (byte)('a' + random.nextInt(25));
76  		}
77  		return new String(password);
78  	}
79  }