KickJava   Java API By Example, From Geeks To Geeks.

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


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 import java.net.URLEncoder JavaDoc;
19
20 /**
21  * This is a stateless session bean used to get the information about a user.
22  *
23  * @author <a HREF="mailto:cecchet@rice.edu">Emmanuel Cecchet</a> and <a HREF="mailto:julie.marguerite@inrialpes.fr">Julie Marguerite</a>
24  * @version 1.1
25  */

26
27 public class MDB_ViewUserInfo implements MessageDrivenBean JavaDoc, MessageListener
28 {
29   private DataSource JavaDoc dataSource;
30   private MessageDrivenContext JavaDoc messageDrivenContext;
31   private TopicConnectionFactory connectionFactory;
32   private TopicConnection connection;
33   private Topic topic;
34   private TopicSession session;
35   private TopicPublisher replier;
36   private Context JavaDoc initialContext = null;
37
38
39   public MDB_ViewUserInfo()
40   {
41
42   }
43
44   public void onMessage(Message message)
45   {
46     try
47     {
48       MapMessage request = (MapMessage)message;
49       String JavaDoc correlationID = request.getJMSCorrelationID();
50       int userId = request.getInt("userId");
51
52         // Retrieve the connection factory
53
connectionFactory = (TopicConnectionFactory) initialContext.lookup(BeanConfig.TopicConnectionFactoryName);
54
55       // get the list of categories
56
String JavaDoc html = getUserInfo(userId);
57
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_ViewUserInfo: " +e);
81     }
82   }
83
84   /**
85    * Get the comment related to a specific user.
86    *
87    * @param userHome an <code>UserHome</code> value
88    * @param userId a user id
89    * @return a string in html format
90    * @since 1.1
91    */

92   public String JavaDoc getComments(int userId, Connection JavaDoc conn) throws RemoteException JavaDoc
93   {
94     StringBuffer JavaDoc html;
95     PreparedStatement JavaDoc stmt = null;
96     ResultSet JavaDoc rs = null;
97     String JavaDoc comment=null, date=null;
98     int authorId;
99
100     // Try to find the comments corresponding for this user
101
try
102     {
103       stmt = conn.prepareStatement("SELECT * FROM comments WHERE to_user_id=?");
104       stmt.setInt(1, userId);
105       rs = stmt.executeQuery();
106     }
107     catch (SQLException JavaDoc e)
108     {
109       try
110       {
111         if (stmt != null) stmt.close();
112         if (conn != null) conn.close();
113       }
114       catch (Exception JavaDoc ignore)
115       {
116       }
117       throw new RemoteException JavaDoc("Failed to get categories list " +e);
118     }
119     try
120     {
121       if (!rs.first())
122        html = new StringBuffer JavaDoc("<h3>There is no comment yet for this user.</h3><br>");
123       else
124       {
125         html = new StringBuffer JavaDoc("<br><hr><br><h3>Comments for this user</h3><br>");
126
127         html.append(printCommentHeader());
128         // Display each comment and the name of its author
129
PreparedStatement JavaDoc authorStmt = null;
130         try
131         {
132           authorStmt = conn.prepareStatement("SELECT nickname FROM users WHERE id=?");
133           do
134           {
135             comment = rs.getString("comment");
136             date = rs.getString("date");
137             authorId = rs.getInt("from_user_id");
138
139             String JavaDoc authorName = "none";
140             ResultSet JavaDoc authorRS = null;
141             authorStmt.setInt(1, authorId);
142             authorRS = authorStmt.executeQuery();
143             if (authorRS.first())
144               authorName = authorRS.getString("nickname");
145             html.append(printComment(authorName, date, comment, authorId));
146           }
147           while (rs.next());
148           authorStmt.close();
149           stmt.close();
150         }
151         catch (Exception JavaDoc e)
152         {
153           try
154           {
155             if (authorStmt != null) authorStmt.close();
156             if (stmt != null) stmt.close();
157             if (conn != null) conn.close();
158           }
159           catch (Exception JavaDoc ignore)
160           {
161           }
162           throw new RemoteException JavaDoc("This author does not exist (got exception: " +e+")<br>");
163         }
164         
165         html.append(printCommentFooter());
166       }
167     }
168     catch (Exception JavaDoc e)
169     {
170       try
171       {
172         if (stmt != null) stmt.close();
173         if (conn != null) conn.close();
174       }
175       catch (Exception JavaDoc ignore)
176       {
177       }
178       throw new RemoteException JavaDoc("Exception getting comment list: " + e +"<br>");
179     }
180     return html.toString();
181   }
182
183
184   /**
185    * Get the information about a user.
186    *
187    * @param userId a user id
188    * @return a string in html format
189    * @since 1.1
190    */

191   public String JavaDoc getUserInfo(int userId) throws RemoteException JavaDoc
192   {
193     StringBuffer JavaDoc html = new StringBuffer JavaDoc();
194     Connection JavaDoc conn = null;
195     PreparedStatement JavaDoc stmt = null;
196     ResultSet JavaDoc rs = null;
197  
198
199     // Try to find the user corresponding to the userId
200
try
201     {
202       conn = dataSource.getConnection();
203       stmt = conn.prepareStatement("SELECT * FROM users WHERE id=?");
204       stmt.setInt(1, userId);
205       rs = stmt.executeQuery();
206     }
207     catch (SQLException JavaDoc e)
208     {
209       try
210       {
211         if (stmt != null) stmt.close();
212         if (conn != null) conn.close();
213       }
214       catch (Exception JavaDoc ignore)
215       {
216       }
217       throw new RemoteException JavaDoc("Failed to get user information from database: " +e);
218     }
219
220     try
221     {
222       if (rs.first())
223       {
224         String JavaDoc firstname = rs.getString("firstname");
225         String JavaDoc lastname = rs.getString("lastname");
226         String JavaDoc nickname = rs.getString("nickname");
227         String JavaDoc email = rs.getString("email");
228         String JavaDoc date = rs.getString("creation_date");
229         int rating = rs.getInt("rating");
230
231         html.append(getHTMLGeneralUserInformation(firstname, lastname, nickname, email, date, rating));
232         html.append(getComments(userId, conn));
233       }
234       else
235         html.append("This user does not exist!<br>");
236       stmt.close();
237       conn.close();
238     }
239     catch (Exception JavaDoc e)
240     {
241       try
242       {
243         if (stmt != null) stmt.close();
244         if (conn != null) conn.close();
245       }
246       catch (Exception JavaDoc ignore)
247       {
248       }
249       throw new RemoteException JavaDoc("Cannot get user information (got exception: " +e+")<br>");
250     }
251     return html.toString();
252   }
253
254   /**
255    * Returns a string displaying general information about the user.
256    * The string contains HTML tags.
257    *
258    * @return string containing general user information
259    * @exception RemoteException if an error occurs
260    */

261   public String JavaDoc getHTMLGeneralUserInformation(String JavaDoc firstname, String JavaDoc lastname, String JavaDoc nickname, String JavaDoc email, String JavaDoc creationDate, int rating) throws RemoteException JavaDoc
262   {
263     return "<h2>Information about "+nickname+"<br></h2>"+
264       "Real life name : "+firstname+" "+lastname+"<br>"
265       +"Email address : "+email+"<br>"
266       +"User since : "+creationDate+"<br>"
267       +"Current rating : <b>"+rating+"</b><br>";
268   }
269
270   /**
271    * Comment header printed function
272    *
273    * @return a string in html format
274    * @since 1.1
275    */

276   public String JavaDoc printCommentHeader()
277   {
278     return "<DL>\n";
279   }
280
281   /**
282    * Display comment information as an HTML table row
283    *
284    * @return a <code>String</code> containing HTML code
285    * @exception RemoteException if an error occurs
286    * @since 1.0
287    */

288   public String JavaDoc printComment(String JavaDoc userName, String JavaDoc date, String JavaDoc comment, int fromUserId) throws RemoteException JavaDoc
289   {
290     return "<DT><b><BIG><a HREF=\""+BeanConfig.context+"/servlet/edu.rice.rubis.beans.servlets.ViewUserInfo?userId="+fromUserId+"\">"+userName+"</a></BIG></b>"+
291       " wrote the "+date+"<DD><i>"+comment+"</i><p>\n";
292   }
293
294   /**
295    * Comment footer printed function
296    *
297    * @return a string in html format
298    * @since 1.1
299    */

300   public String JavaDoc printCommentFooter()
301   {
302     return "</DL>\n";
303   }
304
305  
306
307   // ======================== EJB related methods ============================
308

309   /**
310    * Set the associated context. The container call this method
311    * after the instance creation.
312    * The enterprise Bean instance should store the reference to the context
313    * object in an instance variable.
314    * This method is called with no transaction context.
315    *
316    * @param MessageDrivenContext A MessageDrivenContext interface for the instance.
317    * @throws EJBException Thrown by the method to indicate a failure caused by
318    * a system-level error.
319    */

320   public void setMessageDrivenContext(MessageDrivenContext JavaDoc ctx)
321   {
322     messageDrivenContext = ctx;
323     if (dataSource == null)
324     {
325       // Finds DataSource from JNDI
326
try
327       {
328         initialContext = new InitialContext JavaDoc();
329         dataSource = (DataSource JavaDoc)initialContext.lookup("java:comp/env/jdbc/rubis");
330       }
331       catch (Exception JavaDoc e)
332       {
333         throw new EJBException JavaDoc("Cannot get JNDI InitialContext");
334       }
335     }
336   }
337
338   /**
339    * The Message driven bean must define an ejbCreate methods with no args.
340    *
341    */

342   public void ejbCreate()
343   {
344
345   }
346  
347   /**
348    * A container invokes this method before it ends the life of the message-driven object.
349    * This happens when a container decides to terminate the message-driven object.
350    *
351    * This method is called with no transaction context.
352    *
353    * @throws EJBException Thrown by the method to indicate a failure caused by
354    * a system-level error.
355    */

356   public void ejbRemove() {}
357
358
359
360 }
361
Popular Tags