KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > jonas > jtests > beans > message > SenderSF


1 /*
2  * JOnAS: Java(TM) Open Application Server
3  * Copyright (C) 1999 Bull S.A.
4  * Contact: jonas-team@objectweb.org
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
19  * USA
20  *
21  * --------------------------------------------------------------------------
22  * $Id: SenderSF.java,v 1.9 2004/12/17 15:08:35 joaninh Exp $
23  * --------------------------------------------------------------------------
24  */

25
26 // SenderSF.java
27
// Stateful Session Bean
28

29 package org.objectweb.jonas.jtests.beans.message;
30
31 import java.rmi.RemoteException JavaDoc;
32 import java.util.Collection JavaDoc;
33 import java.util.Iterator JavaDoc;
34
35 import javax.ejb.CreateException JavaDoc;
36 import javax.ejb.EJBException JavaDoc;
37 import javax.ejb.FinderException JavaDoc;
38 import javax.ejb.SessionBean JavaDoc;
39 import javax.ejb.SessionContext JavaDoc;
40 import javax.jms.JMSException JavaDoc;
41 import javax.jms.MapMessage JavaDoc;
42 import javax.jms.Queue JavaDoc;
43 import javax.jms.QueueConnection JavaDoc;
44 import javax.jms.QueueConnectionFactory JavaDoc;
45 import javax.jms.QueueSender JavaDoc;
46 import javax.jms.QueueSession JavaDoc;
47 import javax.jms.Topic JavaDoc;
48 import javax.jms.TopicConnection JavaDoc;
49 import javax.jms.TopicConnectionFactory JavaDoc;
50 import javax.jms.TopicPublisher JavaDoc;
51 import javax.jms.TopicSession JavaDoc;
52 import javax.naming.InitialContext JavaDoc;
53 import javax.naming.NamingException JavaDoc;
54 import javax.rmi.PortableRemoteObject JavaDoc;
55
56 import org.objectweb.jonas.common.Log;
57 import org.objectweb.jonas.jtests.util.Env;
58 import org.objectweb.util.monolog.api.BasicLevel;
59 import org.objectweb.util.monolog.api.Logger;
60
61 /**
62  *
63  */

64 public class SenderSF implements SessionBean JavaDoc {
65
66     static protected Logger logger = null;
67     SessionContext JavaDoc ejbContext;
68     private transient InitialContext JavaDoc ictx = null;
69     private transient TopicConnectionFactory JavaDoc tcf = null;
70     private transient TopicConnection JavaDoc tc = null;
71     private transient QueueConnectionFactory JavaDoc qcf = null;
72     private transient QueueConnection JavaDoc qc = null;
73     private transient MRecordHome ehome = null;
74     private static int count = 1;
75
76     // ------------------------------------------------------------------
77
// SessionBean implementation
78
// ------------------------------------------------------------------
79

80     /**
81      * Set the associated session context. The container calls this method
82      * after the instance creation.
83      * The enterprise Bean instance should store the reference to the context
84      * object in an instance variable.
85      * This method is called with no transaction context.
86      *
87      * @param sessionContext A SessionContext interface for the instance.
88      * @throws EJBException Thrown by the method to indicate a failure caused by
89      * a system-level error.
90      */

91     public void setSessionContext(SessionContext JavaDoc ctx) {
92         if (logger == null)
93             logger = Log.getLogger(Log.JONAS_TESTS_PREFIX);
94         logger.log(BasicLevel.DEBUG, "");
95         ejbContext = ctx;
96     }
97     
98     /**
99      * A container invokes this method before it ends the life of the session object.
100      * This happens as a result of a client's invoking a remove operation, or when a
101      * container decides to terminate the session object after a timeout.
102      * This method is called with no transaction context.
103      *
104      * @throws EJBException Thrown by the method to indicate a failure caused by
105      * a system-level error.
106      */

107     public void ejbRemove() {
108         logger.log(BasicLevel.DEBUG, "");
109         try {
110             tc.close();
111             qc.close();
112         } catch (Exception JavaDoc e) {
113             logger.log(BasicLevel.ERROR, "Exception on close:" + e);
114         }
115     }
116     
117     /**
118      * The Session bean must define 1 or more ejbCreate methods.
119      *
120      * @throws CreateException Failure to create a session EJB object.
121      */

122     public void ejbCreate() throws CreateException JavaDoc {
123         logger.log(BasicLevel.DEBUG, "");
124         // Lookup Connection Factories
125
try {
126             ictx = new InitialContext JavaDoc();
127             tcf = (TopicConnectionFactory JavaDoc) ictx.lookup("TCF");
128             qcf = (QueueConnectionFactory JavaDoc) ictx.lookup("QCF");
129         } catch (NamingException JavaDoc e) {
130             logger.log(BasicLevel.ERROR, "SenderSF : Cannot lookup Connection Factories: "+e);
131             throw new CreateException JavaDoc("SenderSF: Cannot lookup Connection Factories");
132         }
133
134         // Create Connections
135
try {
136             qc = qcf.createQueueConnection();
137             tc = tcf.createTopicConnection();
138         } catch (JMSException JavaDoc e) {
139             logger.log(BasicLevel.ERROR, "SenderSF : Cannot create connections: "+e);
140             throw new CreateException JavaDoc("SenderSF: Cannot create connections");
141         }
142
143         // Lookup Entity Home for checking
144
String JavaDoc BEAN_HOME = "messageMRecordECHome";
145         try {
146             ehome = (MRecordHome) PortableRemoteObject.narrow(ictx.lookup(BEAN_HOME), MRecordHome.class);
147         } catch (NamingException JavaDoc e) {
148             logger.log(BasicLevel.ERROR, "SenderSF ejbCreate: Cannot get entity home: "+e);
149             throw new CreateException JavaDoc("SenderSF: Cannot get entity home");
150         }
151     }
152
153     /**
154      * A container invokes this method on an instance before the instance
155      * becomes disassociated with a specific EJB object.
156      */

157     public void ejbPassivate() {
158         logger.log(BasicLevel.DEBUG, "");
159     }
160
161     /**
162      * A container invokes this method when the instance is taken out of
163      * the pool of available instances to become associated with a specific
164      * EJB object.
165      */

166     public void ejbActivate() {
167         logger.log(BasicLevel.DEBUG, "");
168     }
169     
170     // ------------------------------------------------------------------
171
// private methods
172
// ------------------------------------------------------------------
173

174     /**
175      * return a unique identifier
176      */

177     private String JavaDoc getUUID() {
178         long uuid;
179         synchronized(getClass()) {
180             uuid = System.currentTimeMillis() * 256 + count;
181             count++;
182         }
183         return String.valueOf(uuid);
184     }
185
186     // ------------------------------------------------------------------
187
// Sender implementation
188
// ------------------------------------------------------------------
189

190     /**
191      * send a message on topic
192      * @param String destination
193      * @param int value set in message
194      * @param int nb of messages sent
195      */

196     public void sendOnTopic(String JavaDoc dest, int val, int nb) {
197         logger.log(BasicLevel.DEBUG, "");
198         // Lookup destinations
199
Topic JavaDoc topic = null;
200         try {
201             topic = (Topic JavaDoc) ictx.lookup(dest);
202         } catch (NamingException JavaDoc e) {
203             throw new EJBException JavaDoc("sendOnTopic: Cannot lookup "+dest);
204         }
205
206         // Create TopicSession
207
// Create Session at each request : Avoids the bug in JMS
208
// about Session not enlisted in transactions if open first.
209
TopicSession JavaDoc ss = null;
210         try {
211             // (true, 0) are the recommanded args, although they are not taken
212
// in account by the container.
213
ss = tc.createTopicSession(true, 0);
214         } catch (JMSException JavaDoc e) {
215             throw new EJBException JavaDoc("Cannot create Session: "+e);
216         }
217
218         // Create the TopicPublisher
219
TopicPublisher JavaDoc publisher = null;
220         try {
221             publisher = ss.createPublisher(topic);
222         } catch (JMSException JavaDoc e) {
223             throw new EJBException JavaDoc("Cannot create TopicPublisher: "+e);
224         }
225
226         // Publish messages on the topic
227
try {
228             for (int i = 0; i < nb; i++) {
229                 MapMessage JavaDoc mess = ss.createMapMessage();
230                 mess.setString("Id", getUUID());
231                 mess.setString("Text", dest);
232                 mess.setInt("Value", val);
233                 publisher.publish(mess);
234             }
235         } catch (JMSException JavaDoc e) {
236             throw new EJBException JavaDoc("Cannot send message: "+e);
237         }
238
239         // Close Session: This is mandatory for the correct behaviour of
240
// XA protocol. An XA END must be sent before commit or rollback.
241
try {
242             ss.close();
243         } catch (JMSException JavaDoc e) {
244             throw new EJBException JavaDoc("Cannot close session: "+e);
245         }
246     }
247
248     /**
249      * send messages on topic (transacted)
250      * @param String destination
251      * @param int value set in message
252      * @param int nb of messages sent
253      */

254     public void sendOnTopicTx(String JavaDoc dest, int val, int nb) {
255         sendOnTopic(dest, val, nb);
256     }
257
258     /**
259      * send a message on queue
260      * @param String destination
261      * @param int value set in message
262      * @param int nb of messages sent
263      */

264     public void sendOnQueue(String JavaDoc dest, int val, int nb) {
265         logger.log(BasicLevel.DEBUG, "");
266         // Lookup destination
267
Queue JavaDoc queue = null;
268         try {
269             queue = (Queue JavaDoc) ictx.lookup(dest);
270         } catch (NamingException JavaDoc e) {
271             throw new EJBException JavaDoc("sendOnQueue: Cannot lookup "+dest);
272         }
273
274         // Create QueueSession
275
// Must create Session at each request because of the bug in JMS
276
// about Session not enlisted in transactions if open first.
277
QueueSession JavaDoc ss = null;
278         try {
279             // (true, 0) are the recommanded args, although they are not taken
280
// in account by the container.
281
ss = qc.createQueueSession(true, 0);
282         } catch (JMSException JavaDoc e) {
283             throw new EJBException JavaDoc("Cannot create Session: "+e);
284         }
285
286         // Create the QueueSender
287
QueueSender JavaDoc sender = null;
288         try {
289             sender = ss.createSender(queue);
290         } catch (JMSException JavaDoc e) {
291             throw new EJBException JavaDoc("Cannot create QueueSender: "+e);
292         }
293
294         // Publish messages on the queue
295
try {
296             for (int i = 0; i < nb; i++) {
297                 MapMessage JavaDoc mess = ss.createMapMessage();
298                 mess.setString("Id", getUUID());
299                 mess.setString("Text", dest);
300                 mess.setInt("Value", val);
301                 sender.send(mess);
302             }
303         } catch (JMSException JavaDoc e) {
304             throw new EJBException JavaDoc("Cannot send message: "+e);
305         }
306
307         // Close Session: This is mandatory for the correct behaviour of
308
// XA protocol. An XA END must be sent before commit or rollback.
309
try {
310             ss.close();
311         } catch (JMSException JavaDoc e) {
312             throw new EJBException JavaDoc("Cannot close session: "+e);
313         }
314     }
315
316     /**
317      * send messages on queue (transacted)
318      * @param String destination
319      * @param int value set in message
320      * @param int nb of messages sent
321      */

322     public void sendOnQueueTx(String JavaDoc dest, int val, int nb) {
323         sendOnQueue(dest, val, nb);
324     }
325
326     /**
327      * Checking send methods
328      * @param int value looked in messages received
329      * @param int nb of messages that could be received
330      * @param int nb of seconds max to wait for all messages
331      * @return actual nb of messages received
332      */

333     public int check(int val, int nb, int sec) {
334         Collection JavaDoc elist = null;
335         int retval = 0;
336         for (int i = 0; i <= sec; i++) {
337             logger.log(BasicLevel.DEBUG, "sec : " + i + "/" + sec);
338             try {
339                 elist = ehome.findByValue(val);
340                 retval = elist.size();
341                 if (retval >= nb) {
342                     // clean database before returning
343
Iterator JavaDoc it = elist.iterator();
344                     while (it.hasNext()) {
345                         MRecord ent = (MRecord) PortableRemoteObject.narrow(it.next(), MRecord.class);
346                         try {
347                             ent.remove();
348                         } catch (Exception JavaDoc e) {
349                             throw new EJBException JavaDoc("Error on remove");
350                         }
351                     }
352                     return retval;
353                 }
354             } catch (FinderException JavaDoc e) {
355             } catch (RemoteException JavaDoc e) {
356                 return retval;
357             }
358             try {
359                 Thread.sleep(1000);
360             } catch (InterruptedException JavaDoc e) {
361             }
362         }
363         return retval;
364     }
365
366     /**
367      * Clean all entity beans for this value
368      */

369     public void clean(int val) {
370         logger.log(BasicLevel.DEBUG, "");
371         Collection JavaDoc elist = null;
372         try {
373             elist = ehome.findByValue(val);
374         } catch (FinderException JavaDoc e) {
375             return;
376         } catch (Exception JavaDoc e) {
377             throw new EJBException JavaDoc("Error on find");
378         }
379         Iterator JavaDoc it = elist.iterator();
380         while (it.hasNext()) {
381             MRecord ent = (MRecord) PortableRemoteObject.narrow(it.next(), MRecord.class);
382             try {
383                 ent.remove();
384             } catch (Exception JavaDoc e) {
385                 throw new EJBException JavaDoc("Error on remove");
386             }
387         }
388     }
389     
390 }
391
Popular Tags