KickJava   Java API By Example, From Geeks To Geeks.

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


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 register a new user.
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_RegisterUser implements MessageDrivenBean JavaDoc, MessageListener
27 {
28   // private UserTransaction utx = null;
29

30   private DataSource JavaDoc dataSource;
31   private MessageDrivenContext JavaDoc messageDrivenContext;
32   private TopicConnectionFactory connectionFactory;
33   private TopicConnection connection;
34   private Topic topic;
35   private TopicSession session;
36   private TopicPublisher replier;
37   private Context JavaDoc initialContext = null;
38
39
40   public MDB_RegisterUser()
41   {
42
43   }
44
45   public void onMessage(Message message)
46   {
47     try
48     {
49       MapMessage request = (MapMessage)message;
50       String JavaDoc correlationID = request.getJMSCorrelationID();
51       String JavaDoc firstname = request.getString("firstname");
52       String JavaDoc lastname = request.getString("lastname");
53       String JavaDoc nickname = request.getString("nickname");
54       String JavaDoc email = request.getString("email");
55       String JavaDoc password = request.getString("password");
56       String JavaDoc region = request.getString("region");
57         // Retrieve the connection factory
58
connectionFactory = (TopicConnectionFactory) initialContext.lookup(BeanConfig.TopicConnectionFactoryName);
59
60       // add a new user in the database
61
String JavaDoc html = createUser(firstname, lastname, nickname, email, password, region);
62
63       // send the reply
64
TemporaryTopic temporaryTopic = (TemporaryTopic) request.getJMSReplyTo();
65       if (temporaryTopic != null)
66       {
67         // create a connection
68
connection = connectionFactory.createTopicConnection();
69         // create a session: no transaction, auto ack
70
session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
71         TextMessage reply = session.createTextMessage();
72         reply.setJMSCorrelationID(correlationID);
73         reply.setText(html);
74         replier = session.createPublisher(null); // unidentified publisher
75
connection.start();
76         replier.publish(temporaryTopic, reply);
77         replier.close();
78         session.close();
79         connection.stop();
80         connection.close();
81       }
82     }
83     catch (Exception JavaDoc e)
84     {
85       throw new EJBException JavaDoc("Message traitment failed for MDB_RegisterUser: " +e);
86     }
87   }
88
89   /**
90    * Create a new user.
91    *
92    * @param firstname user's first name
93    * @param lastname user's last name
94    * @param nickname user's nick name
95    * @param email user's email
96    * @param password user's password
97    * @param regionName name of the region where the user live
98    * @return a string in html format
99    * @since 1.1
100    */

101   public String JavaDoc createUser(String JavaDoc firstname, String JavaDoc lastname, String JavaDoc nickname, String JavaDoc email, String JavaDoc password, String JavaDoc regionName) throws RemoteException JavaDoc
102   {
103     StringBuffer JavaDoc html = new StringBuffer JavaDoc();
104     Connection JavaDoc conn = null;
105     PreparedStatement JavaDoc stmt = null;
106     ResultSet JavaDoc rs = null;
107     int regionId = -1;
108     int userId = -1;
109     int rating = 0;
110     float balance = 0;
111     String JavaDoc creationDate = null;
112
113     // utx = messageDrivenContext.getUserTransaction(); //bean managed transaction
114
try
115     {
116       // utx.begin();
117
conn = dataSource.getConnection();
118       stmt = conn.prepareStatement("SELECT id FROM regions WHERE name=?");
119       stmt.setString(1, regionName);
120       rs = stmt.executeQuery();
121       if (rs.first())
122       {
123         regionId = rs.getInt("id");
124       }
125       stmt.close();
126     }
127     catch (Exception JavaDoc e)
128     {
129       try { stmt.close(); } catch (Exception JavaDoc ignore) {}
130       try { conn.close(); } catch (Exception JavaDoc ignore) {}
131       throw new RemoteException JavaDoc(" Region "+regionName+" does not exist in the database!<br>(got exception: " +e+")<br>\n");
132     }
133     // Try to create a new user
134
try
135     {
136       stmt = conn.prepareStatement("SELECT nickname FROM users WHERE nickname=?");
137       stmt.setString(1, nickname);
138       rs = stmt.executeQuery();
139       stmt.close();
140       conn.close();
141       if (rs.first())
142       {
143         html.append("The nickname you have choosen is already taken by someone else. Please choose a new nickname.<br>");
144         return html.toString();
145       }
146     }
147     catch (Exception JavaDoc fe)
148     {
149       try { stmt.close(); } catch (Exception JavaDoc ignore) {}
150       try { conn.close(); } catch (Exception JavaDoc ignore) {}
151       throw new RemoteException JavaDoc("Failed to execute Query to check the nickname: " +fe);
152     }
153     try
154     {
155       try
156       {
157         creationDate = TimeManagement.currentDateToString();
158         conn = dataSource.getConnection();
159         stmt = conn.prepareStatement("INSERT INTO users VALUES (NULL, \""+firstname+
160                                      "\", \""+lastname+"\", \""+nickname+"\", \""+
161                                      password+"\", \""+email+"\", 0, 0,\""+creationDate+"\", "+
162                                      regionId+")");
163         stmt.executeUpdate();
164         stmt.close();
165       }
166       catch (SQLException JavaDoc e)
167       {
168         try { stmt.close(); } catch (Exception JavaDoc ignore) {}
169         try { conn.close(); } catch (Exception JavaDoc ignore) {}
170         throw new RemoteException JavaDoc("RUBiS internal error: User registration failed (got exception: " +e+")<br>");
171       }
172       try
173       {
174         stmt = conn.prepareStatement("SELECT id, rating, balance FROM users WHERE nickname=?");
175         stmt.setString(1, nickname);
176         ResultSet JavaDoc urs = stmt.executeQuery();
177         if (urs.first())
178         {
179           userId = urs.getInt("id");
180           rating = urs.getInt("rating");
181           balance = urs.getFloat("balance");
182         }
183         stmt.close();
184       }
185       catch (SQLException JavaDoc e)
186       {
187         try { stmt.close(); } catch (Exception JavaDoc ignore) {}
188         try { conn.close(); } catch (Exception JavaDoc ignore) {}
189         throw new RemoteException JavaDoc("Failed to execute Query for user: " +e);
190       }
191       if (conn != null) conn.close();
192
193       html.append("User id :"+userId+"<br>\n");
194       html.append("Creation date :"+creationDate+"<br>\n");
195       html.append("Rating :"+rating+"<br>\n");
196       html.append("Balance :"+balance+"<br>\n");
197
198       // utx.commit();
199
}
200     catch (Exception JavaDoc e)
201     {
202       try { stmt.close(); } catch (Exception JavaDoc ignore) {}
203       try { conn.close(); } catch (Exception JavaDoc ignore) {}
204       // try
205
// {
206
// utx.rollback();
207
throw new RemoteException JavaDoc("User registration failed (got exception: " +e+")<br>");
208        // }
209
// catch (Exception se)
210
// {
211
// throw new RemoteException("Transaction rollback failed: " + e +"<br>");
212
// }
213
}
214     return html.toString();
215   }
216
217   // ======================== EJB related methods ============================
218

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

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

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

266   public void ejbRemove() {}
267
268 }
269
Popular Tags