KickJava   Java API By Example, From Geeks To Geeks.

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


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 in a specific region.
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_SearchItemsByRegion 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_SearchItemsByRegion()
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       Integer JavaDoc categoryId = new Integer JavaDoc(request.getInt("categoryId"));
49       Integer JavaDoc regionId = new Integer JavaDoc(request.getInt("regionId"));
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, regionId, 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_SearchItemsByRegion: " +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, Integer JavaDoc regionId, int page, int nbOfItems) throws RemoteException JavaDoc
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       stmt = conn.prepareStatement("SELECT items.name, items.id, items.end_date, items.max_bid, items.nb_of_bids, items.initial_price FROM items,users WHERE items.category=? AND items.seller=users.id AND users.region=? AND end_date>=NOW() LIMIT ?,?");
107       stmt.setInt(1, categoryId.intValue());
108       stmt.setInt(2, regionId.intValue());
109       stmt.setInt(3, page*nbOfItems);
110       stmt.setInt(4, nbOfItems);
111       rs = stmt.executeQuery();
112     }
113     catch (SQLException JavaDoc e)
114     {
115
116       throw new RemoteException JavaDoc("Failed to get the items: " +e);
117     }
118     try
119     {
120       while (rs.next())
121       {
122         itemName = rs.getString("name");
123         itemId = rs.getInt("id");
124         endDate = rs.getString("end_date");
125         maxBid = rs.getFloat("max_bid");
126         nbOfBids = rs.getInt("nb_of_bids");
127         initialPrice = rs.getFloat("initial_price");
128         if (maxBid <initialPrice)
129           maxBid = initialPrice;
130         html.append(printItem(itemName, itemId, maxBid, nbOfBids, endDate));
131       }
132       stmt.close();
133       conn.close();
134     }
135     catch (Exception JavaDoc e)
136     {
137       try
138       {
139         if (stmt != null) stmt.close();
140         if (conn != null) conn.close();
141       }
142       catch (Exception JavaDoc ignore)
143       {
144       }
145         throw new RemoteException JavaDoc("Cannot get items list: " +e);
146     }
147     return html.toString();
148   }
149
150
151   /**
152    * Display item information as an HTML table row
153    *
154    * @return a <code>String</code> containing HTML code
155    * @exception RemoteException if an error occurs
156    * @since 1.0
157    */

158   public String JavaDoc printItem(String JavaDoc name, int id, float maxBid, int nbOfBids, String JavaDoc endDate) throws RemoteException JavaDoc
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    * Set the associated context. The container call this method
173    * after the instance creation.
174    * The enterprise Bean instance should store the reference to the context
175    * object in an instance variable.
176    * This method is called with no transaction context.
177    *
178    * @param MessageDrivenContext A MessageDrivenContext interface for the instance.
179    * @throws EJBException Thrown by the method to indicate a failure caused by
180    * a system-level error.
181    */

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

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

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