KickJava   Java API By Example, From Geeks To Geeks.

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


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 item.
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_RegisterItem implements MessageDrivenBean JavaDoc, MessageListener
27 {
28   private UserTransaction JavaDoc 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_RegisterItem()
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 name = request.getString("name");
52       String JavaDoc description = request.getString("description");
53       float initialPrice = request.getFloat("initialPrice");
54       int quantity = request.getInt("quantity");
55       float reservePrice = request.getFloat("reservePrice");
56       float buyNow = request.getFloat("buyNow");
57       String JavaDoc startDate = request.getString("startDate");
58       String JavaDoc endDate = request.getString("endDate");
59       int userId = request.getInt("userId");
60       int categoryId = request.getInt("categoryId");
61
62         // Retrieve the connection factory
63
connectionFactory = (TopicConnectionFactory) initialContext.lookup(BeanConfig.TopicConnectionFactoryName);
64
65       // add a new item in the database
66
String JavaDoc html = createItem(name, description, initialPrice, quantity, reservePrice, buyNow, startDate, endDate, userId, categoryId);
67
68       // send the reply
69
TemporaryTopic temporaryTopic = (TemporaryTopic) request.getJMSReplyTo();
70       if (temporaryTopic != null)
71       {
72         // create a connection
73
connection = connectionFactory.createTopicConnection();
74         // create a session: no transaction, auto ack
75
session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
76         TextMessage reply = session.createTextMessage();
77         reply.setJMSCorrelationID(correlationID);
78         reply.setText(html);
79         replier = session.createPublisher(null); // unidentified publisher
80
connection.start();
81         replier.publish(temporaryTopic, reply);
82         replier.close();
83         session.close();
84         connection.stop();
85         connection.close();
86       }
87     }
88     catch (Exception JavaDoc e)
89     {
90       throw new EJBException JavaDoc("Message traitment failed for MDB_RegisterItem: " +e);
91     }
92   }
93
94   /**
95    * Create a new item.
96    *
97    * @param name name of the item
98    * @param description item's description
99    * @param initialPrice item's initial price
100    * @param quantity number of items
101    * @param reservePrice item's reserve price
102    * @param buyNow item's price to buy it now
103    * @param startDate auction's start date
104    * @param endDate auction's end date
105    * @param userId seller id
106    * @param catagoryId category id
107    * @return a string in html format
108    * @since 1.1
109    */

110   public String JavaDoc createItem(String JavaDoc name, String JavaDoc description, float initialPrice, int quantity, float reservePrice, float buyNow, String JavaDoc startDate, String JavaDoc endDate, int userId, int categoryId) throws RemoteException JavaDoc
111   {
112     String JavaDoc html;
113     int itemId = -1;
114     Connection JavaDoc conn = null;
115     PreparedStatement JavaDoc stmt = null;
116
117     utx = messageDrivenContext.getUserTransaction();
118     // Try to create a new item
119
try
120     {
121       utx.begin();
122       try
123       {
124         conn = dataSource.getConnection();
125         stmt = conn.prepareStatement("INSERT INTO items VALUES (NULL, \""+name+
126                                      "\", \""+description+"\", \""+initialPrice+"\", \""+
127                                      quantity+"\", \""+reservePrice+"\", \""+buyNow+
128                                      "\", 0, 0, \""+startDate+"\", \""+endDate+"\", \""+userId+
129                                      "\", "+ categoryId+")");
130         stmt.executeUpdate();
131         stmt.close();
132       }
133       catch (Exception JavaDoc e)
134       {
135         try { stmt.close(); } catch (Exception JavaDoc ignore) {}
136         try { conn.close(); } catch (Exception JavaDoc ignore) {}
137         throw new RemoteException JavaDoc("Failed to create the item: " +e);
138       }
139       // To test if the item was correctly added in the database
140
try
141       {
142         stmt = conn.prepareStatement("SELECT id FROM items WHERE name=?");
143         stmt.setString(1, name);
144         ResultSet JavaDoc irs = stmt.executeQuery();
145         if (!irs.first())
146         {
147           try { stmt.close(); } catch (Exception JavaDoc ignore) {}
148           try { conn.close(); } catch (Exception JavaDoc ignore) {}
149           throw new RemoteException JavaDoc("This item does not exist in the database.");
150         }
151         itemId = irs.getInt("id");
152         
153         html = "<TR><TD>Item id<TD>"+itemId+"\n";
154       }
155       catch (Exception JavaDoc e)
156       {
157         try { stmt.close(); } catch (Exception JavaDoc ignore) {}
158         try { conn.close(); } catch (Exception JavaDoc ignore) {}
159         throw new RemoteException JavaDoc("Failed to retrieve the item id: " +e);
160       }
161       if (stmt != null) stmt.close();
162       if (conn != null) conn.close();
163       utx.commit();
164     }
165     catch (Exception JavaDoc e)
166     {
167       try { stmt.close(); } catch (Exception JavaDoc ignore) {}
168       try { conn.close(); } catch (Exception JavaDoc ignore) {}
169       try
170       {
171         utx.rollback();
172         throw new RemoteException JavaDoc("Item registration failed (got exception: " +e+")<br>");
173       }
174       catch (Exception JavaDoc se)
175       {
176         throw new RemoteException JavaDoc("Transaction rollback failed: " + e +"<br>");
177       }
178     }
179     return html;
180   }
181   
182   // ======================== EJB related methods ============================
183

184   /**
185    * Set the associated context. The container call this method
186    * after the instance creation.
187    * The enterprise Bean instance should store the reference to the context
188    * object in an instance variable.
189    * This method is called with no transaction context.
190    *
191    * @param MessageDrivenContext A MessageDrivenContext interface for the instance.
192    * @throws EJBException Thrown by the method to indicate a failure caused by
193    * a system-level error.
194    */

195   public void setMessageDrivenContext(MessageDrivenContext JavaDoc ctx)
196   {
197     messageDrivenContext = ctx;
198     if (dataSource == null)
199     {
200       // Finds DataSource from JNDI
201
try
202       {
203         initialContext = new InitialContext JavaDoc();
204         dataSource = (DataSource JavaDoc)initialContext.lookup("java:comp/env/jdbc/rubis");
205       }
206       catch (Exception JavaDoc e)
207       {
208         throw new EJBException JavaDoc("Cannot get JNDI InitialContext");
209       }
210     }
211   }
212
213   /**
214    * The Message driven bean must define an ejbCreate methods with no args.
215    *
216    */

217   public void ejbCreate()
218   {
219
220   }
221  
222   /**
223    * A container invokes this method before it ends the life of the message-driven object.
224    * This happens when a container decides to terminate the message-driven object.
225    *
226    * This method is called with no transaction context.
227    *
228    * @throws EJBException Thrown by the method to indicate a failure caused by
229    * a system-level error.
230    */

231   public void ejbRemove() {}
232
233
234 }
235
Popular Tags