KickJava   Java API By Example, From Geeks To Geeks.

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


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 to get the information to build the html form
20  * used to put a comment on a user.
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_PutComment 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_PutComment()
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       int toId = request.getInt("toId");
50       String JavaDoc username = request.getString("username");
51       String JavaDoc password = request.getString("password");
52
53         // Retrieve the connection factory
54
connectionFactory = (TopicConnectionFactory) initialContext.lookup(BeanConfig.TopicConnectionFactoryName);
55
56       // get the post comment form
57
String JavaDoc html = getCommentForm(itemId, toId, username, password);
58
59       // send the reply
60
TemporaryTopic temporaryTopic = (TemporaryTopic) request.getJMSReplyTo();
61       if (temporaryTopic != null)
62       {
63         // create a connection
64
connection = connectionFactory.createTopicConnection();
65         // create a session: no transaction, auto ack
66
session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
67         TextMessage reply = session.createTextMessage();
68         reply.setJMSCorrelationID(correlationID);
69         reply.setText(html);
70         replier = session.createPublisher(null); // unidentified publisher
71
connection.start();
72         replier.publish(temporaryTopic, reply);
73         replier.close();
74         session.close();
75         connection.stop();
76         connection.close();
77       }
78     }
79     catch (Exception JavaDoc e)
80     {
81       throw new EJBException JavaDoc("Message traitment failed for MDB_PutComment: " +e);
82     }
83   }
84
85
86   /**
87    * Authenticate the user and get the information to build the html form.
88    *
89    * @return a string in html format
90    * @since 1.1
91    */

92   public String JavaDoc getCommentForm(int itemId, int toId, String JavaDoc username, String JavaDoc password) throws RemoteException JavaDoc
93   {
94     int userId = -1;
95     StringBuffer JavaDoc html = new StringBuffer JavaDoc();
96     PreparedStatement JavaDoc stmt = null;
97     ResultSet JavaDoc rs = null;
98     Connection JavaDoc conn = null;
99
100     // Authenticate the user who want to comment
101
if ((username != null && !username.equals("")) || (password != null && !password.equals("")))
102       {
103         TopicConnection authConnection;
104         TopicSession authSession;
105         Topic authTopic;
106         try
107         {
108           // create a connection
109
authConnection = connectionFactory.createTopicConnection();
110           // lookup the destination
111
authTopic = (Topic) initialContext.lookup(BeanConfig.PrefixTopicName+"topicAuth");
112           // create a session
113
authSession = authConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); // no transaction and auto ack
114
}
115         catch (Exception JavaDoc e)
116         {
117           throw new EJBException JavaDoc("Cannot connect to message bean MDB_Auth : " +e+"<br>");
118         }
119         try
120         {
121           // create a requestor to receive the reply
122
TopicRequestor requestor = new TopicRequestor(authSession, authTopic);
123           // create a message
124
MapMessage m = authSession.createMapMessage();
125           // set parameters
126
m.setStringProperty("nickname", username);
127           m.setStringProperty("password", password);
128           m.setJMSCorrelationID("auth");
129           // send the message and receive the reply
130
authConnection.start(); // allows message to be delivered (default is connection stopped)
131
MapMessage authReply = (MapMessage)requestor.request(m);
132           authConnection.stop();
133           // read the reply
134
userId = authReply.getInt("userId");
135           // close connection and session
136
requestor.close(); // also close the session
137
authConnection.close();
138         }
139         catch (Exception JavaDoc e)
140         {
141           throw new EJBException JavaDoc("user authentication failed: " +e+"<br>");
142         }
143         if (userId == -1)
144         {
145            html.append(" You don't have an account on RUBiS!<br>You have to register first.<br>");
146            return html.toString();
147         }
148       }
149     // Try to find the user corresponding to the 'to' ID
150
String JavaDoc toName=null, itemName=null;
151     try
152     {
153       conn = dataSource.getConnection();
154       stmt = conn.prepareStatement("SELECT nickname FROM users WHERE id=?");
155       stmt.setInt(1, toId);
156       rs = stmt.executeQuery();
157       if (rs.first())
158         toName = rs.getString("nickname");
159       stmt.close();
160     }
161     catch (Exception JavaDoc e)
162     {
163       try
164       {
165         if (stmt != null) stmt.close();
166         if (conn != null) conn.close();
167       }
168       catch (Exception JavaDoc ignore)
169       {
170       }
171       throw new RemoteException JavaDoc("Failed to execute Query for user name: " +e);
172     }
173
174     try
175     {
176       stmt = conn.prepareStatement("SELECT name FROM items WHERE id=?");
177       stmt.setInt(1, itemId);
178       rs = stmt.executeQuery();
179       if (rs.first())
180         itemName = rs.getString("name");
181       if (stmt != null) stmt.close();
182       if (conn != null) conn.close();
183     }
184     catch (Exception JavaDoc e)
185     {
186       try
187       {
188         if (stmt != null) stmt.close();
189         if (conn != null) conn.close();
190       }
191       catch (Exception JavaDoc ignore)
192       {
193       }
194       throw new RemoteException JavaDoc("Failed to execute Query for item name: " +e);
195     }
196
197     try
198     {
199       html.append("<center><h2>Give feedback about your experience with "+toName+"</h2><br>\n");
200       html.append("<form action=\""+BeanConfig.context+"/servlet/edu.rice.rubis.beans.servlets.StoreComment\" method=POST>\n");
201       html.append("<input type=hidden name=to value="+toId+">\n");
202       html.append("<input type=hidden name=from value="+userId+">\n");
203       html.append("<input type=hidden name=itemId value="+itemId+">\n");
204       html.append("<center><table>\n");
205       html.append("<tr><td><b>From</b><td>"+username+"\n");
206       html.append("<tr><td><b>To</b><td>"+toName+"\n");
207       html.append("<tr><td><b>About item</b><td>"+itemName+"\n");
208     }
209     catch (Exception JavaDoc e)
210     {
211       throw new RemoteException JavaDoc("Cannot build comment form: " +e);
212     }
213  
214     return html.toString();
215   }
216                    
217
218
219
220   // ======================== EJB related methods ============================
221

222   /**
223    * Set the associated context. The container call this method
224    * after the instance creation.
225    * The enterprise Bean instance should store the reference to the context
226    * object in an instance variable.
227    * This method is called with no transaction context.
228    *
229    * @param MessageDrivenContext A MessageDrivenContext interface for the instance.
230    * @throws EJBException Thrown by the method to indicate a failure caused by
231    * a system-level error.
232    */

233   public void setMessageDrivenContext(MessageDrivenContext JavaDoc ctx)
234   {
235     messageDrivenContext = ctx;
236     if (dataSource == null)
237     {
238       // Finds DataSource from JNDI
239
try
240       {
241         initialContext = new InitialContext JavaDoc();
242         dataSource = (DataSource JavaDoc)initialContext.lookup("java:comp/env/jdbc/rubis");
243       }
244       catch (Exception JavaDoc e)
245       {
246         throw new EJBException JavaDoc("Cannot get JNDI InitialContext");
247       }
248     }
249   }
250
251   /**
252    * The Message driven bean must define an ejbCreate methods with no args.
253    *
254    */

255   public void ejbCreate()
256   {
257
258   }
259  
260   /**
261    * A container invokes this method before it ends the life of the message-driven object.
262    * This happens when a container decides to terminate the message-driven object.
263    *
264    * This method is called with no transaction context.
265    *
266    * @throws EJBException Thrown by the method to indicate a failure caused by
267    * a system-level error.
268    */

269   public void ejbRemove() {}
270  
271 }
272
Popular Tags