KickJava   Java API By Example, From Geeks To Geeks.

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


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 items
21  * that belong to a specific category.
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_SearchItemsByCategory 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   public MDB_SearchItemsByCategory()
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 id = request.getInt("categoryId");
49       Integer JavaDoc categoryId = new Integer JavaDoc(id);
50       int page = request.getInt("page");
51       int nbOfItems = request.getInt("nbItems");
52
53         // Retrieve the connection factory
54
connectionFactory = (TopicConnectionFactory) initialContext.lookup(BeanConfig.TopicConnectionFactoryName);
55
56       // get the list of categories
57
String JavaDoc html = getItems(categoryId, page, nbOfItems);
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_SearchItemsByCategory: " +e);
82     }
83   }
84
85   /**
86    * Get the items in a specific category.
87    *
88    * @return a string that is the list of items in html format
89    * @since 1.1
90    */

91   public String JavaDoc getItems(Integer JavaDoc categoryId, int page, int nbOfItems)
92   {
93     Connection JavaDoc conn = null;
94     PreparedStatement JavaDoc stmt = null;
95     ResultSet JavaDoc rs = null;
96     String JavaDoc itemName, endDate;
97     int itemId;
98     float maxBid, initialPrice;
99     int nbOfBids=0;
100     StringBuffer JavaDoc html = new StringBuffer JavaDoc();
101
102     // get the list of items
103
try
104     {
105       conn = dataSource.getConnection();
106
107       stmt = conn.prepareStatement("SELECT items.name, items.id, items.end_date, items.max_bid, items.nb_of_bids, items.initial_price FROM items WHERE items.category=? AND end_date>=NOW() LIMIT ?,?");
108       stmt.setInt(1, categoryId.intValue());
109       stmt.setInt(2, page*nbOfItems);
110       stmt.setInt(3, nbOfItems);
111       rs = stmt.executeQuery();
112
113     }
114     catch (SQLException JavaDoc e)
115     {
116
117       throw new EJBException JavaDoc("Failed to get the items: " +e);
118     }
119     try
120     {
121       while (rs.next())
122       {
123         itemName = rs.getString("name");
124         itemId = rs.getInt("id");
125         endDate = rs.getString("end_date");
126         maxBid = rs.getFloat("max_bid");
127         nbOfBids = rs.getInt("nb_of_bids");
128         initialPrice = rs.getFloat("initial_price");
129         if (maxBid <initialPrice)
130           maxBid = initialPrice;
131         html.append(printItem(itemName, itemId, maxBid, nbOfBids, endDate));
132       }
133       stmt.close();
134       conn.close();
135     }
136     catch (Exception JavaDoc e)
137     {
138       try
139       {
140         if (stmt != null) stmt.close();
141         if (conn != null) conn.close();
142       }
143       catch (Exception JavaDoc ignore)
144       {
145       }
146       throw new EJBException JavaDoc("Cannot get items list: " +e);
147     }
148     return html.toString();
149   }
150
151
152   /**
153    * Display item information as an HTML table row
154    *
155    * @return a <code>String</code> containing HTML code
156    * @since 1.0
157    */

158   public String JavaDoc printItem(String JavaDoc name, int id, float maxBid, int nbOfBids, String JavaDoc endDate)
159   {
160     return "<TR><TD><a HREF=\""+BeanConfig.context+"/servlet/edu.rice.rubis.beans.servlets.ViewItem?itemId="+id+"\">"+name+
161       "<TD>"+maxBid+
162       "<TD>"+nbOfBids+
163       "<TD>"+endDate+
164       "<TD><a HREF=\""+BeanConfig.context+"/servlet/edu.rice.rubis.beans.servlets.PutBidAuth?itemId="+id+"\"><IMG SRC=\""+BeanConfig.context+"/bid_now.jpg\" height=22 width=90></a>\n";
165   }
166
167   
168
169
170   // ======================== EJB related methods ============================
171

172   /**
173    * Set the associated context. The container call this method
174    * after the instance creation.
175    * The enterprise Bean instance should store the reference to the context
176    * object in an instance variable.
177    * This method is called with no transaction context.
178    *
179    * @param MessageDrivenContext A MessageDrivenContext interface for the instance.
180    * @throws EJBException Thrown by the method to indicate a failure caused by
181    * a system-level error.
182    */

183   public void setMessageDrivenContext(MessageDrivenContext JavaDoc ctx)
184   {
185     messageDrivenContext = ctx;
186     if (dataSource == null)
187     {
188       // Finds DataSource from JNDI
189
try
190       {
191         initialContext = new InitialContext JavaDoc();
192         dataSource = (DataSource JavaDoc)initialContext.lookup("java:comp/env/jdbc/rubis");
193       }
194       catch (Exception JavaDoc e)
195       {
196         throw new EJBException JavaDoc("Cannot get JNDI InitialContext");
197       }
198     }
199   }
200
201   /**
202    * The Message driven bean must define an ejbCreate methods with no args.
203    *
204    */

205   public void ejbCreate()
206   {
207
208   }
209  
210   /**
211    * A container invokes this method before it ends the life of the message-driven object.
212    * This happens when a container decides to terminate the message-driven object.
213    *
214    * This method is called with no transaction context.
215    *
216    * @throws EJBException Thrown by the method to indicate a failure caused by
217    * a system-level error.
218    */

219   public void ejbRemove() {}
220  
221
222 }
223
Popular Tags