KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > javaee > blueprints > autoid > CatalogFacade


1 /*
2  * Copyright 2006 Sun Microsystems, Inc. All rights reserved. You may not modify, use, reproduce, or distribute this software except in compliance with the terms of the License at:
3  * http://developer.sun.com/berkeley_license.html
4  * $Id: CatalogFacade.java,v 1.3 2006/06/22 22:33:34 smitha Exp $
5  */

6
7 package com.sun.javaee.blueprints.autoid;
8
9 import java.util.*;
10
11 import javax.servlet.*;
12 import javax.ejb.*;
13 import javax.annotation.*;
14 import javax.persistence.*;
15 import javax.transaction.*;
16
17 import com.sun.javaee.blueprints.autoid.*;
18 import com.sun.javaee.blueprints.autoid.model.*;
19
20 public class CatalogFacade implements ServletContextListener {
21     
22     @PersistenceUnit(unitName="CatalogPu")
23     private EntityManagerFactory emf;
24     @Resource UserTransaction utx;
25     
26     public CatalogFacade(){}
27     
28     public void contextDestroyed(ServletContextEvent sce) {
29         if (emf.isOpen()) {
30             emf.close();
31         }
32     }
33     
34     public void contextInitialized(ServletContextEvent sce) {
35         ServletContext context = sce.getServletContext();
36         context.setAttribute("CatalogFacade", this);
37     }
38     
39     public void addItem(Item item) throws InvalidItemException{
40         EntityManager em = emf.createEntityManager();
41         if(item.getName().length() == 0) throw new InvalidItemException("The item" +
42                 " name cannot be empty. Please specify a name for the item. ");
43         try{
44             utx.begin();
45             em.joinTransaction();
46             em.persist(item);
47             utx.commit();
48         } catch(Exception JavaDoc exe){
49             System.err.println("Error persisting item: "+exe);
50             try {
51                 utx.rollback();
52             } catch (Exception JavaDoc e) { throw new RuntimeException JavaDoc("Error persisting item: "+
53                     e.getMessage(), e);}
54             throw new RuntimeException JavaDoc("Error persisting item: "+
55                     exe.getMessage(), exe);
56         } finally {
57             em.close();
58         }
59     }
60     public Item getItem(int itemID){
61         EntityManager em = emf.createEntityManager();
62         Item item = em.find(Item.class,itemID);
63         em.close();
64         return item;
65     }
66     
67     public List<Item> getAllItems(){
68         EntityManager em = emf.createEntityManager();
69         List<Item> items = em.createQuery("SELECT OBJECT(i) FROM Item i").getResultList();
70         em.close();
71         return items;
72     }
73 }
74
Popular Tags