KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > edu > rice > rubis > beans > MDB_StoreBuyNow


1 package edu.rice.rubis.beans;
2
3 import java.rmi.RemoteException JavaDoc;
4 import javax.ejb.MessageDrivenBean JavaDoc;
5 import javax.ejb.MessageDrivenContext JavaDoc;
6 import javax.ejb.EJBException JavaDoc;
7 import javax.jms.*;
8 import javax.naming.Context JavaDoc;
9 import javax.naming.InitialContext JavaDoc;
10 import javax.rmi.PortableRemoteObject JavaDoc;
11 import javax.sql.DataSource JavaDoc;
12 import java.sql.Connection JavaDoc;
13 import java.sql.PreparedStatement JavaDoc;
14 import java.sql.ResultSet JavaDoc;
15 import java.sql.SQLException JavaDoc;
16 import java.io.Serializable JavaDoc;
17 import javax.transaction.UserTransaction JavaDoc;
18
19 /**
20  * This is a stateless session bean used when a user buy an item.
21  *
22  * @author <a HREF="mailto:cecchet@rice.edu">Emmanuel Cecchet</a> and <a HREF="mailto:julie.marguerite@inrialpes.fr">Julie Marguerite</a>
23  * @version 1.1
24  */

25
26 public class MDB_StoreBuyNow implements MessageDrivenBean JavaDoc, MessageListener
27 {
28       // private UserTransaction utx = null;
29

30   private DataSource JavaDoc dataSource;
31   private MessageDrivenContext JavaDoc messageDrivenContext;
32   private TopicConnectionFactory connectionFactory;
33   private TopicConnection connection;
34   private Topic topic;
35   private TopicSession session;
36   private Context JavaDoc initialContext = null;
37
38
39   public MDB_StoreBuyNow()
40   {
41
42   }
43
44   public void onMessage(Message message)
45   {
46     try
47     {
48       MapMessage request = (MapMessage)message;
49       int itemId = request.getInt("itemId");
50       int userId = request.getInt("userId");
51       int qty = request.getInt("quantity");
52
53        // add the new comment in the database
54
createBuyNow(itemId, userId, qty);
55     }
56     catch (Exception JavaDoc e)
57     {
58       throw new EJBException JavaDoc("Message traitment failed for MDB_StoreBuyNow: " +e);
59     }
60   }
61
62   /**
63    * Create a buyNow and update the item.
64    *
65    * @param itemId id of the item related to the comment
66    * @param userId id of the buyer
67    * @param qty quantity of items
68    * @since 1.1
69    */

70   public void createBuyNow(int itemId, int userId, int qty) throws RemoteException JavaDoc
71   {
72     PreparedStatement JavaDoc stmt = null;
73     ResultSet JavaDoc rs = null;
74     Connection JavaDoc conn = null;
75
76       // utx = messageDrivenContext.getUserTransaction();
77
try
78     {
79        // utx.begin();
80
// Try to find the Item corresponding to the Item ID
81
String JavaDoc now = TimeManagement.currentDateToString();
82       int quantity;
83       try
84       {
85         conn = dataSource.getConnection();
86         stmt = conn.prepareStatement("SELECT quantity, end_date FROM items WHERE id=?");
87         stmt.setInt(1, itemId);
88         rs = stmt.executeQuery();
89       }
90       catch (SQLException JavaDoc e)
91       {
92         try { stmt.close(); } catch (Exception JavaDoc ignore) {}
93         try { conn.close(); } catch (Exception JavaDoc ignore) {}
94         throw new RemoteException JavaDoc("Failed to execute Query for the item: " +e+"<br>");
95       }
96       PreparedStatement JavaDoc update = null;
97       try
98       {
99         if (rs.first())
100         {
101           quantity = rs.getInt("quantity");
102           quantity = quantity -qty;
103            if (quantity == 0)
104           {
105             update = conn.prepareStatement("UPDATE items SET end_date=?,quantity=? WHERE id=?");
106             update.setString(1, now);
107             update.setInt(2, quantity);
108             update.setInt(3, itemId);
109             update.executeUpdate();
110           }
111           else
112           {
113             update = conn.prepareStatement("UPDATE items SET quantity=? WHERE id=?");
114             update.setInt(1, quantity);
115             update.setInt(2, itemId);
116             update.executeUpdate();
117           }
118           update.close();
119         }
120         stmt.close();
121       }
122       catch (Exception JavaDoc e)
123       {
124         try { update.close(); } catch (Exception JavaDoc ignore) {}
125         try { stmt.close(); } catch (Exception JavaDoc ignore) {}
126         try { conn.close(); } catch (Exception JavaDoc ignore) {}
127         throw new RemoteException JavaDoc("Failed to update item's quantity: " +e+"<br>");
128       }
129       try
130       {
131         stmt = conn.prepareStatement("INSERT INTO buy_now VALUES (NULL, \""+userId+
132                                      "\", \""+itemId+"\", \""+qty+"\", \""+now+"\")");
133         stmt.executeUpdate();
134       }
135       catch (Exception JavaDoc e)
136       {
137         try { stmt.close(); } catch (Exception JavaDoc ignore) {}
138         try { conn.close(); } catch (Exception JavaDoc ignore) {}
139         throw new RemoteException JavaDoc("Failed to create buy_now item: " +e+"<br>");
140       }
141       if (stmt != null) stmt.close();
142       if (conn != null) conn.close();
143        // utx.commit();
144

145     }
146     catch (Exception JavaDoc e)
147     {
148       try { stmt.close(); } catch (Exception JavaDoc ignore) {}
149       try { conn.close(); } catch (Exception JavaDoc ignore) {}
150        // try
151
// {
152
// utx.rollback();
153
throw new RemoteException JavaDoc("Cannot insert the item into buy_now items table: " +e+"<br>");
154        // }
155
// catch (Exception se)
156
// {
157
// throw new RemoteException("Transaction rollback failed: " + e +"<br>");
158
// }
159
}
160   }
161
162   // ======================== EJB related methods ============================
163

164   /**
165    * Set the associated context. The container call this method
166    * after the instance creation.
167    * The enterprise Bean instance should store the reference to the context
168    * object in an instance variable.
169    * This method is called with no transaction context.
170    *
171    * @param MessageDrivenContext A MessageDrivenContext interface for the instance.
172    * @throws EJBException Thrown by the method to indicate a failure caused by
173    * a system-level error.
174    */

175   public void setMessageDrivenContext(MessageDrivenContext JavaDoc ctx)
176   {
177     messageDrivenContext = ctx;
178     if (dataSource == null)
179     {
180       // Finds DataSource from JNDI
181
try
182       {
183         initialContext = new InitialContext JavaDoc();
184         dataSource = (DataSource JavaDoc)initialContext.lookup("java:comp/env/jdbc/rubis");
185       }
186       catch (Exception JavaDoc e)
187       {
188         throw new EJBException JavaDoc("Cannot get JNDI InitialContext");
189       }
190     }
191   }
192
193   /**
194    * The Message driven bean must define an ejbCreate methods with no args.
195    *
196    */

197   public void ejbCreate()
198   {
199
200   }
201  
202   /**
203    * A container invokes this method before it ends the life of the message-driven object.
204    * This happens when a container decides to terminate the message-driven object.
205    *
206    * This method is called with no transaction context.
207    *
208    * @throws EJBException Thrown by the method to indicate a failure caused by
209    * a system-level error.
210    */

211   public void ejbRemove() {}
212
213
214
215 }
216
Popular Tags