KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > xpetstore > services > petstore > ejb > PetstoreBean


1 package xpetstore.services.petstore.ejb;
2
3
4 import java.sql.SQLException JavaDoc;
5 import java.util.ArrayList JavaDoc;
6 import java.util.Collection JavaDoc;
7 import java.util.Date JavaDoc;
8 import java.util.Iterator JavaDoc;
9 import java.util.List JavaDoc;
10 import java.util.Map JavaDoc;
11
12 import javax.ejb.EJBException JavaDoc;
13 import javax.ejb.Local JavaDoc;
14 import javax.ejb.Stateless JavaDoc;
15 import javax.ejb.TransactionAttribute JavaDoc;
16 import javax.ejb.TransactionAttributeType JavaDoc;
17
18 import javax.persistence.EntityManager;
19 import javax.persistence.PersistenceContext;
20
21 import org.jboss.annotation.ejb.LocalBinding;
22
23 import xpetstore.domain.catalog.ejb.Category;
24 import xpetstore.domain.catalog.ejb.Item;
25 import xpetstore.domain.catalog.ejb.Product;
26 import xpetstore.domain.customer.ejb.Customer;
27 import xpetstore.domain.order.ejb.Order;
28 import xpetstore.domain.order.ejb.OrderItem;
29 import xpetstore.domain.order.model.OrderStatus;
30
31 import xpetstore.domain.signon.ejb.Account;
32
33 import xpetstore.services.petstore.exceptions.CartEmptyOrderException;
34 import xpetstore.services.petstore.exceptions.DuplicateEmailException;
35
36 import xpetstore.util.JMSUtil;
37 import xpetstore.util.JNDINames;
38 import xpetstore.util.Page;
39
40
41 /**
42  * @author <a HREF="mailto:tchbansi@sourceforge.net">Herve Tchepannou</a>
43  *
44  * @ ejb.bean
45  * name="Petstore"
46  * type="Stateless"
47  * view-type="local"
48  * @ ejb.transaction
49  * type="Required"
50  * @ ejb.ejb-ref
51  * ejb-name="Category"
52  * view-type="local"
53  * ref-name="ejb/CategoryLocal"
54  * @ ejb.ejb-ref
55  * ejb-name="Item"
56  * view-type="local"
57  * ref-name="ejb/ItemLocal"
58  * @ ejb.ejb-ref
59  * ejb-name="Product"
60  * view-type="local"
61  * ref-name="ejb/ProductLocal"
62  * @ ejb.ejb-ref
63  * ejb-name="Customer"
64  * view-type="local"
65  * ref-name="ejb/CustomerLocal"
66  * @ ejb.ejb-ref
67  * ejb-name="Account"
68  * view-type="local"
69  * ref-name="ejb/AccountLocal"
70  * @ ejb.ejb-ref
71  * ejb-name="Order"
72  * view-type="local"
73  * ref-name="ejb/OrderLocal"
74  * @ ejb.resource-ref
75  * res-ref-name="${jndi.queue.ConnectionFactory}"
76  * res-type="javax.jms.QueueConnectionFactory"
77  * res-auth="Container"
78  * jndi-name="${orion.queue.ConnectionFactory}"
79  * @ ejb.resource-ref
80  * res-ref-name="${jndi.queue.order}"
81  * res-type="javax.jms.Queue"
82  * res-auth="Container"
83  * jndi-name="${orion.queue.order}"
84  * @ ejb.resource-ref
85  * res-ref-name="${jndi.datasource}"
86  * res-type="javax.sql.DataSource"
87  * res-auth="Container"
88  * jndi-name="${orion.datasource}"
89  *
90  * @ jboss.resource-ref
91  * res-ref-name="${jndi.queue.ConnectionFactory}"
92  * jndi-name="${jboss.queue.ConnectionFactory}"
93  * @ jboss.resource-ref
94  * res-ref-name="${jndi.queue.order}"
95  * jndi-name="${jboss.queue.order}"
96  * @ jboss.resource-ref
97  * res-ref-name="${jndi.datasource}"
98  * jndi-name="${jboss.datasource}"
99  *
100  * @ weblogic.resource-description
101  * res-ref-name="${jndi.queue.ConnectionFactory}"
102  * jndi-name="${weblogic.queue.ConnectionFactory}"
103  * @ weblogic.resource-description
104  * res-ref-name="${jndi.queue.order}"
105  * jndi-name="${weblogic.queue.order}"
106  * @ weblogic.resource-description
107  * res-ref-name="${jndi.datasource}"
108  * jndi-name="${weblogic.datasource}"
109  */

110 @Stateless JavaDoc(name="Petstore")
111 @LocalBinding(jndiBinding="ejb/Petstore")
112 @Local JavaDoc(Petstore.class)
113 @TransactionAttribute JavaDoc(TransactionAttributeType.REQUIRED)
114 public class PetstoreBean implements Petstore
115 {
116  // private static final Logger log = Logger.getLogger(PetstoreBean.class);
117

118    @PersistenceContext
119    private EntityManager manager;
120    
121     /**
122      * @ ejb.interface-method
123      * @ ejb.transaction
124      * type="NotSupported"
125      * @ ejb.transaction
126      * type="NotSupported"
127      */

128     public boolean authenticate( String JavaDoc userId,
129                                  String JavaDoc password )
130     {
131        try
132        {
133          Account act = manager.find(Account.class, userId );
134          System.out.println("!! PetstoreBean.authenticate " + act + " " + userId + " " + password);
135          if (act == null)
136             return false;
137          return act.matchPassword( password );
138        }
139        catch (Exception JavaDoc e)
140        {
141           e.printStackTrace();
142           return false;
143        }
144     }
145
146  
147
148     /**
149      * @ ejb.interface-method
150      * @ ejb.transaction
151      * type="NotSupported"
152      */

153     public Category getCategory( String JavaDoc categoryId )
154     {
155         return manager.find(Category.class, categoryId );
156     }
157
158     /**
159      * @ ejb.interface-method
160      * @ ejb.transaction
161      * type="NotSupported"
162      */

163     public Page getCategories( int start,
164                                int count )
165     {
166        return toPage( manager.createQuery("SELECT Category c FROM Category").getResultList(), start, count, Category.class );
167     }
168
169     /**
170      * @ ejb.interface-method
171      * @ ejb.transaction
172      * type="NotSupported"
173      */

174     public Product getProduct( String JavaDoc productId )
175     {
176         return manager.find( Product.class, productId );
177     }
178
179     /**
180      * @ ejb.interface-method
181      */

182     public Product getProductByItem( String JavaDoc itemId )
183     {
184         Item item = manager.find( Item.class, itemId );
185         return item.getProduct( );
186     }
187
188     /**
189      * @ ejb.interface-method
190      */

191     public Page getProducts( String JavaDoc categoryId,
192                              int start,
193                              int count )
194     {
195        try
196        {
197           System.out.println("!! PetstoreBean.getProducts manager " + manager);
198          Category cat = manager.find( Category.class, categoryId );
199          System.out.println("!! PetstoreBean.getProducts cat " + cat);
200          if (cat != null)
201             return toPage( cat.getProducts( ), start, count, Product.class );
202          else
203             return Page.EMPTY_PAGE;
204        }
205        catch (Exception JavaDoc e)
206        {
207           e.printStackTrace();
208           return null;
209        }
210     }
211
212     /**
213      * @ ejb.interface-method
214      * @ ejb.transaction
215      * type="NotSupported"
216      */

217     public Page searchProducts( String JavaDoc key,
218                                 int start,
219                                 int count )
220     {
221        return toPage(manager.createNativeQuery("SELECT productId,name,description FROM T_PRODUCT WHERE (productId LIKE " + key + ") OR (name LIKE " + key + ") OR (description LIKE " + key + ")").getResultList(), start, count, Product.class);
222     }
223
224     /**
225      * @ ejb.interface-method
226      * @ ejb.transaction
227      * type="NotSupported"
228      */

229     public Item getItem( String JavaDoc itemId )
230     {
231         return manager.find( Item.class, itemId );
232     }
233
234     /**
235      * @ ejb.interface-method
236      */

237     public Page getItems( String JavaDoc productId,
238                           int start,
239                           int count )
240     {
241          Product prod = manager.find( Product.class, productId );
242          return toPage( prod.getItems( ), start, count, Item.class );
243     }
244
245     /**
246      * @ ejb.interface-method
247      */

248     public String JavaDoc createCustomer( Customer customer )
249         throws DuplicateEmailException
250     {
251        System.out.println("!!PetstoreBean.createCustomer " + customer);
252        
253         /* Make sure that the customer email is unique */
254          String JavaDoc email = customer.getEmail( );
255          List JavaDoc customers = null;
256          try
257          {
258             customers = manager.createQuery("SELECT c FROM Customer c WHERE c.email = '" + email + "'").getResultList();
259             
260          }
261          catch (Exception JavaDoc e)
262          {
263             
264          }
265          
266          if (customers != null && customers.size() > 0)
267             throw new DuplicateEmailException( email );
268       
269          /* create the account */
270          Account account = customer.getAccount( );
271          
272          customer.setUserId(account.getUserId());
273
274          manager.persist(account);
275          
276          manager.persist(customer);
277          
278          System.out.println("!!PetstoreBean.createCustomer userId " + customer);
279          
280          return customer.getUserId( );
281     }
282
283     /**
284      * @ ejb.interface-method
285      */

286     public void updateCustomer( Customer customer )
287     {
288        manager.merge(customer);
289     }
290
291     /**
292      * @ ejb.interface-method
293      */

294     public Customer getCustomer( String JavaDoc userId )
295     {
296         return manager.find( Customer.class, userId );
297     }
298
299     /**
300      * @param userId Id of the customer
301      * @param orderDate Creation date of the order
302      * @param items <code>java.lang.Map</code> containing the items
303      * ordered. The key is the itemId, and the value
304      * a </code>java.lang.Integer</code> representing the
305      * quantity ordered
306      *
307      * @ ejb.interface-method
308      */

309     public Integer JavaDoc createOrder( String JavaDoc userId,
310                                 Date JavaDoc orderDate,
311                                 Map JavaDoc items )
312         throws CartEmptyOrderException
313     {
314         /* Make sure that the cart is not empty */
315         if ( items.size( ) == 0 )
316         {
317             throw new CartEmptyOrderException( );
318         }
319
320         /* Get the customer */
321         Customer cst = manager.find( Customer.class, userId );
322
323         /* Create the order */
324         Order order = new Order( );
325         order.setOrderDate( orderDate );
326         order.setStatus( OrderStatus.PENDING );
327         order.setStreet1( cst.getStreet1( ) );
328         order.setStreet2( cst.getStreet2( ) );
329         order.setCity( cst.getCity( ) );
330         order.setState( cst.getState( ) );
331         order.setZipcode( cst.getZipcode( ) );
332         order.setCountry( cst.getCountry( ) );
333         order.setCreditCardNumber( cst.getCreditCardNumber( ) );
334         order.setCreditCardType( cst.getCreditCardType( ) );
335         order.setCreditCardExpiryDate( cst.getCreditCardExpiryDate( ) );
336
337         order.setCustomer( cst );
338         
339         manager.persist(order);
340
341         /* Add the items */
342         Iterator JavaDoc keys = items.keySet( ).iterator( );
343         while ( keys.hasNext( ) )
344         {
345             String JavaDoc itemId = ( String JavaDoc ) keys.next( );
346             Integer JavaDoc qty = ( Integer JavaDoc ) items.get( itemId );
347             
348             Item item = manager.find(Item.class, itemId);
349             
350             System.out.println("!!PetstoreBean.createOrder item " + item + " " + itemId);
351             
352             OrderItem orderItem = new OrderItem( qty, item.getListPrice( ) );
353             orderItem.setItem( item );
354             
355             manager.persist(orderItem);
356             
357             order.addOrderItem(orderItem);
358             
359             order.addOrderItem( orderItem );
360         }
361
362         /* Process the item ansynchronously */
363         try
364         {
365             JMSUtil.sendToJMSQueue( JNDINames.QUEUE_ORDER, order.getOrderUId( ), false );
366         }
367         catch ( Exception JavaDoc e )
368         {
369             throw new EJBException JavaDoc( e );
370         }
371
372         return order.getOrderUId( );
373     }
374
375     /**
376      * @ ejb.interface-method
377      * @ ejb.transaction
378      * type="NotSupported"
379      */

380     public Page getCustomerOrders( String JavaDoc userId,
381                                    int start,
382                                    int count )
383     {
384        List JavaDoc col = manager.createQuery("SELECT Order o FROM Order WHERE o.customer.userId = " + userId).getResultList();
385        return toPage( col, start, count, Order.class );
386     }
387
388     /**
389      * @ ejb.interface-method
390      * @ ejb.transaction
391      * type="NotSupported"
392      */

393     public Order getOrder( Integer JavaDoc orderUId )
394     {
395         return manager.find( Order.class, orderUId );
396     }
397
398     /**
399      * @ ejb.interface-method
400      */

401     public Page getOrderItems( Integer JavaDoc orderUId,
402                                int start,
403                                int count )
404     {
405         Collection JavaDoc col;
406       
407          Order order = manager.find( Order.class, orderUId );
408          if (order != null)
409             col = order.getOrderItems( );
410          else
411             col = new ArrayList JavaDoc( );
412      
413         return toPage( col, start, count, OrderItem.class );
414     }
415
416     private Page toPage( Collection JavaDoc col,
417                          int start,
418                          int count,
419                          Class JavaDoc type )
420     {
421         int size = col.size( );
422         if ( size == 0 )
423         {
424             return Page.EMPTY_PAGE;
425         }
426
427         ArrayList JavaDoc lst = new ArrayList JavaDoc( );
428         Iterator JavaDoc it = col.iterator( );
429         for ( int i = 0, imax = start + count; ( i < imax ) && it.hasNext( );
430               i++ )
431         {
432             Object JavaDoc obj = it.next( );
433             if ( i >= start )
434             {
435                 lst.add( obj );
436             }
437         }
438
439         return new Page( lst, start, ( start + count ) < size );
440     }
441 }
442
Popular Tags