KickJava   Java API By Example, From Geeks To Geeks.

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


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: Sender1_2SF.java,v 1.3 2004/12/17 15:08:35 joaninh Exp $
23  * --------------------------------------------------------------------------
24  */

25
26 // SenderSF1_1.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.ConnectionFactory JavaDoc;
41 import javax.jms.Destination JavaDoc;
42 import javax.jms.JMSException JavaDoc;
43 import javax.jms.MapMessage JavaDoc;
44 import javax.jms.MessageProducer JavaDoc;
45 import javax.jms.Session JavaDoc;
46 import javax.naming.InitialContext JavaDoc;
47 import javax.naming.NamingException JavaDoc;
48 import javax.rmi.PortableRemoteObject JavaDoc;
49 import javax.transaction.UserTransaction JavaDoc;
50 import javax.transaction.NotSupportedException JavaDoc;
51 import javax.transaction.SystemException JavaDoc;
52
53 import org.objectweb.jonas.common.Log;
54 import org.objectweb.jonas.jtests.util.Env;
55 import org.objectweb.util.monolog.api.BasicLevel;
56 import org.objectweb.util.monolog.api.Logger;
57
58 /**
59  * This Session Bean is equivalent to the Sender1_1SF bean
60  * the only difference is it is bean managed transaction
61  * it is using ConnectionFactory, Connection, Session and MessageProducer
62  */

63 public class Sender1_2SF implements SessionBean JavaDoc {
64
65     static protected Logger logger = null;
66     SessionContext JavaDoc ejbContext;
67     private transient InitialContext JavaDoc ictx = null;
68     private transient ConnectionFactory JavaDoc cf = null;
69     private transient javax.jms.Connection JavaDoc c = null;
70     private transient MRecordHome ehome = null;
71     private static int count = 1;
72     private static UserTransaction JavaDoc utx = null;
73     // ------------------------------------------------------------------
74
// SessionBean implementation
75
// ------------------------------------------------------------------
76

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

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

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

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

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

162     public void ejbActivate() {
163         logger.log(BasicLevel.DEBUG, "");
164     }
165     
166     // ------------------------------------------------------------------
167
// private methods
168
// ------------------------------------------------------------------
169

170     /**
171      * return a unique identifier
172      */

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

186     /**
187      * send a message on destination (topic or queue)
188      * @param Session session
189      * @param String destination
190      * @param int value set in message
191      * @param int nb of messages sent
192      * @param boolean commit transaction if true
193      */

194     public void sendOnDestination(Session JavaDoc ss, String JavaDoc dst, int val, int nb) {
195
196         // Lookup destinations
197
Destination JavaDoc dest = null;
198         try {
199             dest = (Destination JavaDoc) ictx.lookup(dst);
200         } catch (NamingException JavaDoc e) {
201             throw new EJBException JavaDoc("sendOnDestination: Cannot lookup "+dest);
202         }
203
204        // Create the MessageProducer for destination
205
MessageProducer JavaDoc producer = null;
206         try {
207             producer = ss.createProducer(dest);
208         } catch (JMSException JavaDoc e) {
209             throw new EJBException JavaDoc("Cannot create MessageProducer: "+e);
210         }
211
212         // Send messages on the destination
213
try {
214             for (int i = 0; i < nb; i++) {
215                 MapMessage JavaDoc mess = ss.createMapMessage();
216                 mess.setString("Id", getUUID());
217                 mess.setString("Text",dst);
218                 mess.setInt("Value", val);
219                 producer.send(mess);
220             }
221         } catch (JMSException JavaDoc e) {
222             throw new EJBException JavaDoc("Cannot send message: "+e);
223         }
224
225     }
226
227     /**
228      * send a message on destination (topic or queue)
229      * the transaction is demarcated before the session creation
230      * @param String destination
231      * @param int value set in message
232      * @param int nb of messages sent
233      * @param boolean commit transaction if true
234      */

235     public void sendOnDestinationWithTxBeforeSession(String JavaDoc dst, int val, int nb, boolean commit)
236         throws RemoteException JavaDoc {
237         logger.log(BasicLevel.DEBUG, "");
238
239         // Obtain the UserTransaction interface
240
try {
241             utx = ejbContext.getUserTransaction();
242         } catch (IllegalStateException JavaDoc e) {
243             logger.log(BasicLevel.ERROR, "Can't get UserTransaction");
244             throw new RemoteException JavaDoc("Can't get UserTransaction:", e);
245         }
246
247
248
249         // Start a global transaction
250
try {
251             utx.begin();
252         } catch (NotSupportedException JavaDoc e) {
253             logger.log(BasicLevel.ERROR, "Can't start Transaction");
254             throw new RemoteException JavaDoc("Can't start Transaction:", e);
255         } catch (SystemException JavaDoc e) {
256             logger.log(BasicLevel.ERROR, "Can't start Transaction");
257             throw new RemoteException JavaDoc("Can't start Transaction:", e);
258         }
259
260
261         // Create Session
262
// Create Session at each request : Avoids the bug in JMS
263
// about Session not enlisted in transactions if open first.
264
Session JavaDoc ss = null;
265         try {
266             // (true, 0) are the recommanded args, although they are not taken
267
// in account by the container.
268
ss = c.createSession(true, 0);
269         } catch (JMSException JavaDoc e) {
270             throw new EJBException JavaDoc("Cannot create Session: "+e);
271         }
272         sendOnDestination(ss, dst, val, nb);
273
274
275         // Close Session: This is mandatory for the correct behaviour of
276
// XA protocol. An XA END must be sent before commit or rollback.
277
try {
278             ss.close();
279         } catch (JMSException JavaDoc e) {
280             throw new EJBException JavaDoc("Cannot close session: "+e);
281         }
282
283         try {
284             // commit or rollback the transaction depending on commit parameter
285
if(commit) {
286                  utx.commit();
287             } else {
288                  utx.rollback();
289             }
290
291         } catch (Exception JavaDoc e) {
292             logger.log(BasicLevel.ERROR, "Can't rollback Transaction");
293             throw new RemoteException JavaDoc("Can't rollback Transaction:", e);
294         }
295     }
296
297     /**
298      * send messages on destination (topic or queue)
299      * the transaction is demarcated after the session creation
300      * @param String destination
301      * @param int value set in message
302      * @param int nb of messages sent
303      * @param boolean commit transaction if true
304      */

305     public void sendOnDestinationWithTxAfterSession(String JavaDoc dst, int val, int nb, boolean commit)
306         throws RemoteException JavaDoc {
307
308        // Obtain the UserTransaction interface
309
try {
310             utx = ejbContext.getUserTransaction();
311         } catch (IllegalStateException JavaDoc e) {
312             logger.log(BasicLevel.ERROR, "Can't get UserTransaction");
313             throw new RemoteException JavaDoc("Can't get UserTransaction:", e);
314         }
315
316        Session JavaDoc ss = null;
317         try {
318  
319             ss = c.createSession(false, 0);
320         } catch (JMSException JavaDoc e) {
321             throw new EJBException JavaDoc("Cannot create Session: "+e);
322         }
323
324        // Start a global transaction
325
try {
326             utx.begin();
327         } catch (NotSupportedException JavaDoc e) {
328             logger.log(BasicLevel.ERROR, "Can't start Transaction");
329             throw new RemoteException JavaDoc("Can't start Transaction:", e);
330         } catch (SystemException JavaDoc e) {
331             logger.log(BasicLevel.ERROR, "Can't start Transaction");
332             throw new RemoteException JavaDoc("Can't start Transaction:", e);
333         }
334         sendOnDestination(ss, dst, val, nb);
335        // Close Session: This is mandatory for the correct behaviour of
336
// XA protocol. An XA END must be sent before commit or rollback.
337
try {
338             ss.close();
339         } catch (JMSException JavaDoc e) {
340             throw new EJBException JavaDoc("Cannot close session: "+e);
341         }
342
343         try {
344             // commit or rollback the transaction depending on commit parameter
345
if(commit) {
346                  utx.commit();
347             } else {
348                  utx.rollback();
349             }
350
351         } catch (Exception JavaDoc e) {
352             logger.log(BasicLevel.ERROR, "Can't rollback Transaction");
353             throw new RemoteException JavaDoc("Can't rollback Transaction:", e);
354         }
355     }
356
357   
358
359     /**
360      * Checking send methods
361      * @param int value looked in messages received
362      * @param int nb of messages that could be received
363      * @param int nb of seconds max to wait for all messages
364      * @return actual nb of messages received
365      */

366     public int check(int val, int nb, int sec) {
367         Collection JavaDoc elist = null;
368         int retval = 0;
369         for (int i = 0; i <= sec; i++) {
370             logger.log(BasicLevel.DEBUG, "sec : " + i + "/" + sec);
371             try {
372                 elist = ehome.findByValue(val);
373                 retval = elist.size();
374                 if (retval >= nb) {
375                     // clean database before returning
376
Iterator JavaDoc it = elist.iterator();
377                     while (it.hasNext()) {
378                         MRecord ent = (MRecord) PortableRemoteObject.narrow(it.next(), MRecord.class);
379                         try {
380                             ent.remove();
381                         } catch (Exception JavaDoc e) {
382                             throw new EJBException JavaDoc("Error on remove");
383                         }
384                     }
385                     return retval;
386                 }
387             } catch (FinderException JavaDoc e) {
388             } catch (RemoteException JavaDoc e) {
389                 return retval;
390             }
391             try {
392                 Thread.sleep(1000);
393             } catch (InterruptedException JavaDoc e) {
394             }
395         }
396         return retval;
397     }
398
399     /**
400      * Clean all entity beans for this value
401      */

402     public void clean(int val) {
403         logger.log(BasicLevel.DEBUG, "");
404         Collection JavaDoc elist = null;
405         try {
406             elist = ehome.findByValue(val);
407         } catch (FinderException JavaDoc e) {
408             return;
409         } catch (Exception JavaDoc e) {
410             throw new EJBException JavaDoc("Error on find");
411         }
412         Iterator JavaDoc it = elist.iterator();
413         while (it.hasNext()) {
414             MRecord ent = (MRecord) PortableRemoteObject.narrow(it.next(), MRecord.class);
415             try {
416                 ent.remove();
417             } catch (Exception JavaDoc e) {
418                 throw new EJBException JavaDoc("Error on remove");
419             }
420         }
421     }
422     
423 }
424
Popular Tags