KickJava   Java API By Example, From Geeks To Geeks.

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


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 to create e new bid for 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_StoreBid implements MessageDrivenBean JavaDoc, MessageListener
27 {
28
29   // private UserTransaction utx = null;
30

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

76   public void createBid(int userId, int itemId, float bid, float maxBid, int qty) throws RemoteException JavaDoc
77   {
78     PreparedStatement JavaDoc stmt = null;
79     ResultSet JavaDoc rs = null;
80     Connection JavaDoc conn = null;
81
82     // utx = messageDrivenContext.getUserTransaction();
83
try
84     {
85       // utx.begin();
86
try
87       {
88         // create new bid
89
conn = dataSource.getConnection();
90         String JavaDoc now = TimeManagement.currentDateToString();
91         stmt = conn.prepareStatement("INSERT INTO bids VALUES (NULL, \""+userId+
92                    "\", \""+itemId+"\", \""+qty+"\", \""+
93                    bid+"\", \""+maxBid+"\", \""+now+"\")");
94         stmt.executeUpdate();
95         stmt.close();
96       }
97       catch (SQLException JavaDoc e)
98       {
99         try { stmt.close(); } catch (Exception JavaDoc ignore) {}
100         try { conn.close(); } catch (Exception JavaDoc ignore) {}
101         throw new RemoteException JavaDoc("Error while storing the bid (got exception: " +e+")<br>");
102       }
103       // update the number of bids and the current price for the item
104
PreparedStatement JavaDoc update = null;
105       try
106       {
107         stmt = conn.prepareStatement("SELECT nb_of_bids, max_bid FROM items WHERE id=?");
108         stmt.setInt(1, itemId);
109         rs = stmt.executeQuery();
110         if (rs.first())
111         {
112           int nbOfBids = rs.getInt("nb_of_bids");
113           nbOfBids++;
114           float oldMaxBid = rs.getFloat("max_bid");
115           if (bid > oldMaxBid)
116           {
117             oldMaxBid = bid;
118             update = conn.prepareStatement("UPDATE items SET max_bid=?,nb_of_bids=? WHERE id=?"); // AND replaced by ","
119
update.setFloat(1, oldMaxBid);
120             update.setInt(2, nbOfBids);
121             update.setInt(3, itemId);
122             update.executeUpdate();
123           }
124           else
125           {
126             update = conn.prepareStatement("UPDATE items SET nb_of_bids=? WHERE id=?");
127             update.setInt(1, nbOfBids);
128             update.setInt(2, itemId);
129             update.executeUpdate();
130           }
131           update.close();
132         }
133         stmt.close();
134       }
135       catch (Exception JavaDoc ex)
136       {
137         try { update.close(); } catch (Exception JavaDoc ignore) {}
138         try { stmt.close(); } catch (Exception JavaDoc ignore) {}
139         try { conn.close(); } catch (Exception JavaDoc ignore) {}
140         throw new RemoteException JavaDoc("Failed to update nb of bids and max bid: " + ex);
141       }
142       if (conn != null) conn.close();
143       // utx.commit();
144
}
145     catch (Exception JavaDoc e)
146     {
147       try { conn.close(); } catch (Exception JavaDoc ignore) {}
148       // try
149
// {
150
// utx.rollback();
151
throw new RemoteException JavaDoc("Failed to create a new bid (got exception: " +e+")<br>");
152        // }
153
// catch (Exception se)
154
// {
155
// throw new RemoteException("Transaction rollback failed: " + e +"<br>");
156
// }
157
}
158   }
159
160
161   // ======================== EJB related methods ============================
162

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

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

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

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