KickJava   Java API By Example, From Geeks To Geeks.

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


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
18 /**
19  * This is a stateless session bean used get the bid history of an item.
20  *
21  * @author <a HREF="mailto:cecchet@rice.edu">Emmanuel Cecchet</a> and <a HREF="mailto:julie.marguerite@inrialpes.fr">Julie Marguerite</a>
22  * @version 1.1
23  */

24
25 public class MDB_ViewBidHistory implements MessageDrivenBean JavaDoc, MessageListener
26 {
27   private DataSource JavaDoc dataSource;
28   private MessageDrivenContext JavaDoc messageDrivenContext;
29   private TopicConnectionFactory connectionFactory;
30   private TopicConnection connection;
31   private Topic topic;
32   private TopicSession session;
33   private TopicPublisher replier;
34   private Context JavaDoc initialContext = null;
35
36
37   public MDB_ViewBidHistory()
38   {
39
40   }
41
42   public void onMessage(Message message)
43   {
44     try
45     {
46       MapMessage request = (MapMessage)message;
47       String JavaDoc correlationID = request.getJMSCorrelationID();
48       int itemId = request.getInt("itemId");
49         // Retrieve the connection factory
50
connectionFactory = (TopicConnectionFactory) initialContext.lookup(BeanConfig.TopicConnectionFactoryName);
51       // get the bids history
52
String JavaDoc html = getBidHistory(itemId);
53       // send the reply
54
TemporaryTopic temporaryTopic = (TemporaryTopic) request.getJMSReplyTo();
55       if (temporaryTopic != null)
56       {
57         // create a connection
58
connection = connectionFactory.createTopicConnection();
59         // create a session: no transaction, auto ack
60
session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
61         TextMessage reply = session.createTextMessage();
62         reply.setJMSCorrelationID(correlationID);
63         reply.setText(html);
64         replier = session.createPublisher(null); // unidentified publisher
65
connection.start();
66         replier.publish(temporaryTopic, reply);
67         replier.close();
68         session.close();
69         connection.stop();
70         connection.close();
71       }
72     }
73     catch (Exception JavaDoc e)
74     {
75       throw new EJBException JavaDoc("Message traitment failed for MDB_ViewBidHistory: " +e);
76     }
77   }
78
79
80   /**
81    * Get the list of bids related to a specific item.
82    *
83    * @return a string in html format
84    * @since 1.1
85    */

86   public String JavaDoc getBidHistory(int itemId) throws RemoteException JavaDoc
87   {
88     StringBuffer JavaDoc html = null;
89     PreparedStatement JavaDoc stmt = null;
90     ResultSet JavaDoc rs = null;
91     Connection JavaDoc conn = null;
92     String JavaDoc date = null, bidderName = null, itemName = null;
93     float bid = 0;
94     int userId = -1;
95
96     // get the item
97
try
98     {
99       conn = dataSource.getConnection();
100       stmt = conn.prepareStatement("SELECT name FROM items WHERE id=?");
101       stmt.setInt(1, itemId);
102       rs = stmt.executeQuery();
103     }
104     catch (Exception JavaDoc e)
105     {
106       try
107       {
108         if (stmt != null) stmt.close();
109         if (conn != null) conn.close();
110       }
111       catch (Exception JavaDoc ignore)
112       {
113       }
114       throw new RemoteException JavaDoc("Failed to execute Query for item in items table: " +e);
115     }
116     try
117     {
118       if (!rs.first())
119       {
120         stmt.close();
121         stmt = conn.prepareStatement("SELECT name FROM old_items WHERE id=?");
122         stmt.setInt(1, itemId);
123         rs = stmt.executeQuery();
124
125       }
126     }
127     catch (Exception JavaDoc e)
128     {
129       try
130       {
131         if (stmt != null) stmt.close();
132         if (conn != null) conn.close();
133       }
134       catch (Exception JavaDoc ignore)
135       {
136       }
137       throw new RemoteException JavaDoc("Failed to execute Query for item in old_items table: " +e);
138     }
139     try
140     {
141       if ((rs == null) || (!rs.first())) // This item does not exist
142
{
143         stmt.close();
144         conn.close();
145         return "";
146       }
147       else
148       {
149         itemName = rs.getString("name");
150         html = new StringBuffer JavaDoc("<center><h3>Bid History for "+itemName+"<br></h3></center>");
151       }
152       stmt.close();
153     }
154     catch (Exception JavaDoc e)
155     {
156       try
157       {
158         if (conn != null) conn.close();
159       }
160       catch (Exception JavaDoc ignore)
161       {
162       }
163      throw new RemoteException JavaDoc("This item does not exist (got exception: " +e+")<br>");
164     }
165     // Get the list of the user's last bids
166
try
167     {
168       stmt = conn.prepareStatement("SELECT * FROM bids WHERE item_id=? ORDER BY date DESC");
169       stmt.setInt(1, itemId);
170       rs = stmt.executeQuery();
171       if (!rs.first())
172       {
173         stmt.close();
174         conn.close();
175         return html.append("<h3>There is no bid corresponding to this item.</h3><br>").toString();
176       }
177     }
178     catch (SQLException JavaDoc e)
179     {
180       try
181       {
182         if (stmt != null) stmt.close();
183         if (conn != null) conn.close();
184       }
185       catch (Exception JavaDoc ignore)
186       {
187       }
188       throw new RemoteException JavaDoc("Exception getting bids list: " +e+"<br>");
189     }
190     PreparedStatement JavaDoc userStmt = null;
191     try
192     {
193       html.append(printBidHistoryHeader());
194       userStmt = conn.prepareStatement("SELECT nickname FROM users WHERE id=?");
195       ResultSet JavaDoc urs = null;
196       do
197       {
198         // Get the bids
199
date = rs.getString("date");
200         bid = rs.getFloat("bid");
201         userId = rs.getInt("user_id");
202
203         userStmt.setInt(1, userId);
204         urs = userStmt.executeQuery();
205         if (urs.first())
206           bidderName = urs.getString("nickname");
207
208         html.append(printBidHistory(userId, bidderName, bid, date));
209       }
210       while(rs.next());
211       html.append(printBidHistoryFooter());
212       userStmt.close();
213       stmt.close();
214       conn.close();
215     }
216     catch (SQLException JavaDoc e)
217     {
218       try
219       {
220         if (userStmt != null) userStmt.close();
221         if (stmt != null) stmt.close();
222         if (conn != null) conn.close();
223       }
224       catch (Exception JavaDoc ignore)
225       {
226       }
227       throw new RemoteException JavaDoc("Exception getting bid: " +e+"<br>");
228     }
229     return html.toString();
230   }
231
232   /**
233    * Display bid history information as an HTML table row
234    *
235    * @return a <code>String</code> containing HTML code
236    * @exception RemoteException if an error occurs
237    * @since 1.0
238    */

239   public String JavaDoc printBidHistory(int userId, String JavaDoc bidderName, float bid, String JavaDoc date) throws RemoteException JavaDoc
240   {
241     return "<TR><TD><a HREF=\""+BeanConfig.context+"/servlet/edu.rice.rubis.beans.servlets.ViewUserInfo?userId="+userId+
242       "\">"+bidderName+"<TD>"+bid+"<TD>"+date+"\n";
243   }
244
245   /**
246    * Bids list header printed function
247    *
248    * @return a string in html format
249    * @since 1.1
250    */

251   public String JavaDoc printBidHistoryHeader()
252   {
253     return "<TABLE border=\"1\" summary=\"List of bids\">\n<THEAD>\n"+
254       "<TR><TH>User ID<TH>Bid amount<TH>Date of bid\n<TBODY>\n";
255   }
256
257   /**
258    * Bids list footer printed function
259    *
260    * @return a string in html format
261    * @since 1.1
262    */

263   public String JavaDoc printBidHistoryFooter()
264   {
265     return "</TABLE>\n";
266   }
267
268   // ======================== EJB related methods ============================
269

270   /**
271    * Set the associated context. The container call this method
272    * after the instance creation.
273    * The enterprise Bean instance should store the reference to the context
274    * object in an instance variable.
275    * This method is called with no transaction context.
276    *
277    * @param MessageDrivenContext A MessageDrivenContext interface for the instance.
278    * @throws EJBException Thrown by the method to indicate a failure caused by
279    * a system-level error.
280    */

281   public void setMessageDrivenContext(MessageDrivenContext JavaDoc ctx)
282   {
283     messageDrivenContext = ctx;
284     if (dataSource == null)
285     {
286       // Finds DataSource from JNDI
287
try
288       {
289         initialContext = new InitialContext JavaDoc();
290         dataSource = (DataSource JavaDoc)initialContext.lookup("java:comp/env/jdbc/rubis");
291       }
292       catch (Exception JavaDoc e)
293       {
294         throw new EJBException JavaDoc("Cannot get JNDI InitialContext");
295       }
296     }
297   }
298
299   /**
300    * The Message driven bean must define an ejbCreate methods with no args.
301    *
302    */

303   public void ejbCreate()
304   {
305
306   }
307  
308   /**
309    * A container invokes this method before it ends the life of the message-driven object.
310    * This happens when a container decides to terminate the message-driven object.
311    *
312    * This method is called with no transaction context.
313    *
314    * @throws EJBException Thrown by the method to indicate a failure caused by
315    * a system-level error.
316    */

317   public void ejbRemove() {}
318
319 }
320
Popular Tags