KickJava   Java API By Example, From Geeks To Geeks.

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


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 java.net.URLEncoder JavaDoc;
18
19 /**
20  * This is a message driven bean used to get the list of
21  * categories from database and return the information to the BrowseCategories servlet.
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_BrowseCategories implements MessageDrivenBean JavaDoc, MessageListener
27 {
28   private DataSource JavaDoc dataSource;
29   private MessageDrivenContext JavaDoc messageDrivenContext;
30   private TopicConnectionFactory connectionFactory;
31   private TopicConnection connection;
32   private Topic topic;
33   private TopicSession session;
34   private TopicPublisher replier;
35   private Context JavaDoc initialContext = null;
36
37
38   public MDB_BrowseCategories()
39   {
40
41   }
42
43   public void onMessage(Message message)
44   {
45     try
46     {
47       MapMessage request = (MapMessage)message;
48       String JavaDoc correlationID = request.getJMSCorrelationID();
49       String JavaDoc region = request.getString("region");
50       String JavaDoc nickname = request.getString("nickname");
51       String JavaDoc password = request.getString("password");
52
53
54         // Retrieve the connection factory
55
connectionFactory = (TopicConnectionFactory) initialContext.lookup(BeanConfig.TopicConnectionFactoryName);
56       // get the list of categories
57
String JavaDoc html = getCategories(region, nickname, password);
58       // send the reply
59
TemporaryTopic temporaryTopic = (TemporaryTopic) request.getJMSReplyTo();
60       if (temporaryTopic != null)
61       {
62         // create a connection
63
connection = connectionFactory.createTopicConnection();
64         // create a session: no transaction, auto ack
65
session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
66         TextMessage reply = session.createTextMessage();
67         reply.setJMSCorrelationID(correlationID);
68         reply.setText(html);
69         replier = session.createPublisher(null); // unidentified publisher
70
connection.start();
71         replier.publish(temporaryTopic, reply);
72         replier.close();
73         session.close();
74         connection.stop();
75         connection.close();
76       }
77     }
78     catch (Exception JavaDoc e)
79     {
80       throw new EJBException JavaDoc("Message traitment failed for MDB_BrowseCategories: " +e);
81     }
82   }
83
84
85   /**
86    * Get all the categories from the database.
87    *
88    * @return a string that is the list of categories in html format
89    * @since 1.1
90    */

91   /** List all the categories in the database */
92   public String JavaDoc getCategories(String JavaDoc regionName, String JavaDoc username, String JavaDoc password) throws RemoteException JavaDoc
93   {
94     StringBuffer JavaDoc html = new StringBuffer JavaDoc();
95     Connection JavaDoc conn = null;
96     PreparedStatement JavaDoc stmt = null;
97     ResultSet JavaDoc rs = null;
98     String JavaDoc categoryName;
99     int categoryId;
100     int regionId = -1;
101     int userId = -1;
102
103     if (regionName != null && !regionName.equals(""))
104     {
105       // get the region ID
106
try
107       {
108         conn = dataSource.getConnection();
109         stmt = conn.prepareStatement("SELECT id FROM regions WHERE name=?");
110         stmt.setString(1, regionName);
111         rs = stmt.executeQuery();
112         stmt.close();
113       }
114       catch (SQLException JavaDoc e)
115       {
116         try
117         {
118           if (stmt != null) stmt.close();
119           if (conn != null) conn.close();
120         }
121         catch (Exception JavaDoc ignore)
122         {
123         }
124         throw new RemoteException JavaDoc("Failed to get region Id " +e);
125       }
126       try
127       {
128         if (rs.first())
129         {
130           regionId = rs.getInt("id");
131         }
132       }
133       catch (Exception JavaDoc e)
134       {
135         try
136         {
137           if (conn != null) conn.close();
138         }
139         catch (Exception JavaDoc ignore)
140         {
141         }
142         throw new EJBException JavaDoc(" Region "+regionName+" does not exist in the database!<br>(got exception: " +e+")");
143       }
144     }
145     else
146     {
147       // Authenticate the user who wants to sell items
148
if ((username != null && !username.equals("")) || (password != null && !password.equals("")))
149       {
150         TopicConnection authConnection;
151         TopicSession authSession;
152         Topic authTopic;
153         try
154         {
155           // create a connection
156
authConnection = connectionFactory.createTopicConnection();
157           // lookup the destination
158
authTopic = (Topic) initialContext.lookup(BeanConfig.PrefixTopicName+"topicAuth");
159           // create a session
160
authSession = authConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); // no transaction and auto ack
161
}
162         catch (Exception JavaDoc e)
163         {
164           throw new EJBException JavaDoc("Cannot connect to message bean MDB_Auth : " +e+"<br>");
165         }
166         try
167         {
168           // create a requestor to receive the reply
169
TopicRequestor requestor = new TopicRequestor(authSession, authTopic);
170           // create a message
171
MapMessage m = authSession.createMapMessage();
172           // set parameters
173
m.setStringProperty("nickname", username);
174           m.setStringProperty("password", password);
175           m.setJMSCorrelationID("auth");
176           // send the message and receive the reply
177
authConnection.start(); // allows message to be delivered (default is connection stopped)
178
MapMessage authReply = (MapMessage)requestor.request(m);
179           authConnection.stop();
180           // read the reply
181
userId = authReply.getInt("userId");
182           // close connection and session
183
requestor.close(); // also close the session
184
authConnection.close();
185         }
186         catch (Exception JavaDoc e)
187         {
188           throw new EJBException JavaDoc("user authentication failed: " +e+"<br>");
189         }
190         if (userId == -1)
191         {
192            html.append(" You don't have an account on RUBiS!<br>You have to register first.<br>");
193            return html.toString();
194         }
195       }
196     }
197     try
198     {
199       if (conn == null)
200         conn = dataSource.getConnection();
201       stmt = conn.prepareStatement("SELECT name, id FROM categories");
202       rs = stmt.executeQuery();
203     }
204     catch (SQLException JavaDoc e)
205     {
206       try
207       {
208         if (stmt != null) stmt.close();
209         if (conn != null) conn.close();
210       }
211       catch (Exception JavaDoc ignore)
212       {
213       }
214       throw new EJBException JavaDoc("Failed to get categories list " +e);
215     }
216     try
217     {
218       if (!rs.first())
219         html.append("<h2>Sorry, but there is no category available at this time. Database table is empty</h2><br>");
220       else
221       {
222         do
223         {
224           categoryName = rs.getString("name");
225           categoryId = rs.getInt("id");
226           if (regionId != -1)
227           {
228             html.append(printCategoryByRegion(categoryName, categoryId, regionId));
229           }
230           else
231           {
232             if (userId != -1)
233               html.append(printCategoryToSellItem(categoryName, categoryId, userId));
234             else
235               html.append(printCategory(categoryName, categoryId));
236           }
237         }
238         while (rs.next());
239       }
240       if (stmt != null) stmt.close();
241       if (conn != null) conn.close();
242     }
243     catch (Exception JavaDoc e)
244     {
245       try
246       {
247         if (stmt != null) stmt.close();
248         if (conn != null) conn.close();
249       }
250       catch (Exception JavaDoc ignore)
251       {
252       }
253       throw new EJBException JavaDoc("Exception getting category list: " + e);
254     }
255     return html.toString();
256   }
257
258   /**
259    * Display category information for the BrowseCategories servlet
260    *
261    * @return a <code>String</code> containing HTML code
262    * @since 1.0
263    */

264   public String JavaDoc printCategory(String JavaDoc name, int id)
265   {
266     return "<a HREF=\""+BeanConfig.context+"/servlet/edu.rice.rubis.beans.servlets.SearchItemsByCategory?category="+id+
267                   "&categoryName="+URLEncoder.encode(name)+"\">"+name+"</a><br>\n";
268   }
269
270   /**
271    * Display category information for the BrowseCategories servlet
272    *
273    * @return a <code>String</code> containing HTML code
274    * @since 1.0
275    */

276   public String JavaDoc printCategoryByRegion(String JavaDoc name, int id, int regionId)
277   {
278     return "<a HREF=\""+BeanConfig.context+"/servlet/edu.rice.rubis.beans.servlets.SearchItemsByRegion?category="+id+
279       "&categoryName="+URLEncoder.encode(name)+"&region="+regionId+"\">"+name+"</a><br>\n";
280   }
281
282
283   /**
284    * Display category information for the BrowseCategories servlet
285    *
286    * @return a <code>String</code> containing HTML code
287    * @since 1.0
288    */

289   public String JavaDoc printCategoryToSellItem(String JavaDoc name, int id, int userId)
290   {
291     return "<a HREF=\""+BeanConfig.context+"/servlet/edu.rice.rubis.beans.servlets.SellItemForm?category="+id+"&user="+userId+"\">"+name+"</a><br>\n";
292   }
293
294
295   // ======================== EJB related methods ============================
296

297   /**
298    * Set the associated context. The container call this method
299    * after the instance creation.
300    * The enterprise Bean instance should store the reference to the context
301    * object in an instance variable.
302    * This method is called with no transaction context.
303    *
304    * @param MessageDrivenContext A MessageDrivenContext interface for the instance.
305    * @throws EJBException Thrown by the method to indicate a failure caused by
306    * a system-level error.
307    */

308   public void setMessageDrivenContext(MessageDrivenContext JavaDoc ctx)
309   {
310     messageDrivenContext = ctx;
311     if (dataSource == null)
312     {
313       // Finds DataSource from JNDI
314
try
315       {
316         initialContext = new InitialContext JavaDoc();
317         dataSource = (DataSource JavaDoc)initialContext.lookup("java:comp/env/jdbc/rubis");
318       }
319       catch (Exception JavaDoc e)
320       {
321         throw new EJBException JavaDoc("Cannot get JNDI InitialContext");
322       }
323     }
324   }
325
326   /**
327    * The Message driven bean must define an ejbCreate methods with no args.
328    *
329    */

330   public void ejbCreate()
331   {
332
333   }
334  
335   /**
336    * A container invokes this method before it ends the life of the message-driven object.
337    * This happens when a container decides to terminate the message-driven object.
338    *
339    * This method is called with no transaction context.
340    *
341    * @throws EJBException Thrown by the method to indicate a failure caused by
342    * a system-level error.
343    */

344   public void ejbRemove() {}
345  
346
347
348
349 }
350
Popular Tags