KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > mr > ra > inbound > MantaAsfEndpointWorker


1 /*
2  * Copyright 2002 by
3  * <a HREF="http://www.coridan.com">Coridan</a>
4  * <a HREF="mailto: support@coridan.com ">support@coridan.com</a>
5  *
6  * The contents of this file are subject to the Mozilla Public License Version
7  * 1.1 (the "License"); you may not use this file except in compliance with the
8  * License. You may obtain a copy of the License at
9  * http://www.mozilla.org/MPL/
10  *
11  * Software distributed under the License is distributed on an "AS IS" basis,
12  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
13  * for the specific language governing rights and limitations under the
14  * License.
15  *
16  * The Original Code is "MantaRay" (TM).
17  *
18  * The Initial Developer of the Original Code is Coridan.
19  * Portions created by the Initial Developer are Copyright (C) 2006
20  * Coridan Inc. All Rights Reserved.
21  *
22  * Contributor(s): all the names of the contributors are added in the source
23  * code where applicable.
24  *
25  * Alternatively, the contents of this file may be used under the terms of the
26  * LGPL license (the "GNU LESSER GENERAL PUBLIC LICENSE"), in which case the
27  * provisions of LGPL are applicable instead of those above. If you wish to
28  * allow use of your version of this file only under the terms of the LGPL
29  * License and not to allow others to use your version of this file under
30  * the MPL, indicate your decision by deleting the provisions above and
31  * replace them with the notice and other provisions required by the LGPL.
32  * If you do not delete the provisions above, a recipient may use your version
33  * of this file under either the MPL or the GNU LESSER GENERAL PUBLIC LICENSE.
34  
35  *
36  * This library is free software; you can redistribute it and/or modify it
37  * under the terms of the MPL as stated above or under the terms of the GNU
38  * Lesser General Public License as published by the Free Software Foundation;
39  * either version 2.1 of the License, or any later version.
40  *
41  * This library is distributed in the hope that it will be useful, but WITHOUT
42  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
43  * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
44  * License for more details.
45  */

46
47 package org.mr.ra.inbound;
48
49
50 import javax.jms.ConnectionConsumer JavaDoc;
51 import javax.jms.ExceptionListener JavaDoc;
52 import javax.jms.JMSException JavaDoc;
53 import javax.jms.Session JavaDoc;
54 import javax.jms.Topic JavaDoc;
55 import javax.resource.ResourceException JavaDoc;
56 import javax.resource.spi.work.Work JavaDoc;
57 import javax.resource.spi.work.WorkEvent JavaDoc;
58 import javax.resource.spi.work.WorkException JavaDoc;
59 import javax.resource.spi.work.WorkListener JavaDoc;
60 import javax.resource.spi.work.WorkManager JavaDoc;
61
62 import org.apache.commons.logging.Log;
63 import org.apache.commons.logging.LogFactory;
64 import org.mr.api.jms.MantaDestination;
65 import org.mr.api.jms.MantaQueue;
66 import org.mr.api.jms.MantaTopic;
67 import org.mr.api.jms.MantaXAConnection;
68 import org.mr.ra.ResourceAdapterImpl;
69
70 /**
71  * @version $Revision: 1.1.1.1 $ $Date: 2005/03/11 21:15:09 $
72  */

73 public class MantaAsfEndpointWorker extends MantaBaseEndpointWorker {
74     
75     private static final Log log = LogFactory.getLog(MantaAsfEndpointWorker.class);
76     
77     private static final long INITIAL_RECONNECT_DELAY = 1000; // 1 second.
78
private static final long MAX_RECONNECT_DELAY = 1000*30; // 30 seconds.
79
private static final ThreadLocal JavaDoc threadLocal = new ThreadLocal JavaDoc();
80     
81     private ConnectionConsumer JavaDoc consumer;
82     private ServerSessionPoolImpl serverSessionPool;
83     private MantaDestination dest;
84     private boolean running;
85     private Work JavaDoc connectWork;
86     protected MantaXAConnection connection;
87     
88     private long reconnectDelay=INITIAL_RECONNECT_DELAY;
89     
90     /**
91      * @param adapter
92      * @param key
93      * @throws ResourceException
94      */

95     public MantaAsfEndpointWorker(final ResourceAdapterImpl adapter,
96                                   EndpointKey key) throws ResourceException JavaDoc {
97         super(adapter, key);
98         connectWork = new Work JavaDoc() {
99
100             public void release() {
101             }
102
103             synchronized public void run() {
104                 if(!isRunning())
105                     return;
106                 
107                 if(connection != null)
108                     return;
109                 
110                 ActivationSpecImpl activationSpec = endpointActivationKey.getActivationSpec();
111                 try {
112                     connection = adapter.makeConnection(activationSpec);
113                     connection.start();
114                     connection.setExceptionListener(new ExceptionListener JavaDoc() {
115                         public void onException(JMSException JavaDoc error) {
116                             reconnect(error);
117                         }
118                     });
119                     
120                     if (activationSpec.isDurableSubscription()) {
121                         consumer = connection.createDurableConnectionConsumer(
122                                 (Topic JavaDoc) dest,
123                                 activationSpec.getSubscriptionName(),
124                                 emptyToNull(activationSpec.getMessageSelector()),
125                                 serverSessionPool,
126                                 activationSpec.getMaxMessagesPerSessionsIntValue());
127                         //activationSpec.getMaxMessagesPerSessionsIntValue(),
128
//activationSpec.getNoLocalBooleanValue());
129
} else {
130                         consumer = connection.createConnectionConsumer(
131                                 dest,
132                                 emptyToNull(activationSpec.getMessageSelector()),
133                                 serverSessionPool,
134                                 activationSpec.getMaxMessagesPerSessionsIntValue());
135                         //activationSpec.getMaxMessagesPerSessionsIntValue(),
136
//activationSpec.getNoLocalBooleanValue());
137
}
138                     // the following is required because without it a consumer
139
// with listener would require to start a new local transaction (when
140
// it receive a message) before the mdb container requires to start
141
// an XA transaction.
142
// Starting an XA txn during a local txn will cause an exception.
143
//((MantaConnectionConsumer)consumer).disableLocalTransactionsForListener();
144
} catch (JMSException JavaDoc error) {
145                     reconnect(error);
146                 }
147             }
148         };
149         
150         ActivationSpecImpl activationSpec = endpointActivationKey.getActivationSpec();
151         if ("javax.jms.Queue".equals(activationSpec.getDestinationType())) {
152             dest = new MantaQueue(activationSpec.getDestination());
153         } else if ("javax.jms.Topic".equals(activationSpec.getDestinationType())) {
154             try {
155                 dest = new MantaTopic(activationSpec.getDestination());
156             } catch (JMSException JavaDoc e) {
157                 log.error(e.getMessage());
158                 throw new ResourceException JavaDoc("Unable to create resource: ",e);
159             }
160         } else {
161             throw new ResourceException JavaDoc("Unknown destination type: " + activationSpec.getDestinationType());
162         }
163     }
164     
165     synchronized public void start() throws WorkException JavaDoc, ResourceException JavaDoc {
166         if (running)
167             return;
168         running = true;
169         log.debug("Starting");
170         serverSessionPool = new ServerSessionPoolImpl(this, endpointActivationKey.getActivationSpec().getMaxSessionsIntValue());
171         connect();
172         log.debug("Started");
173     }
174     
175     /**
176      *
177      */

178     synchronized public void stop() throws InterruptedException JavaDoc {
179         if (!running)
180             return;
181         running = false;
182         log.debug("Disconnecting");
183         serverSessionPool.close();
184         disconnect();
185         log.debug("Disconnected");
186     }
187     
188     private boolean isRunning() {
189         return running;
190     }
191     
192     synchronized private void connect() {
193         if (!running)
194             return;
195         
196         try {
197 // WorkListener wl = new WorkListener() {
198
//
199
// public void workAccepted(WorkEvent arg0) {
200
//
201
// log.info("Connect work accepted");
202
// }
203
//
204
// public void workRejected(WorkEvent arg0) {
205
// log.info("Connect work rejected");
206
// }
207
//
208
// public void workStarted(WorkEvent arg0) {
209
// log.info("Connect work started");
210
// }
211
//
212
// public void workCompleted(WorkEvent arg0) {
213
// log.info("Connect work completed");
214
// }
215
//
216
// };
217
workManager.scheduleWork(connectWork, WorkManager.INDEFINITE, null, null);
218         } catch (WorkException JavaDoc e) {
219             running = false;
220             log.error("Work Manager did not accept work: ",e);
221         }
222     }
223     
224     /**
225      *
226      */

227     synchronized private void disconnect() {
228         safeClose(consumer);
229         consumer=null;
230         safeClose(connection);
231         connection=null;
232     }
233     
234     synchronized private void reconnect(JMSException JavaDoc error) {
235         log.debug("Reconnect cause: ", error);
236         // Only log errors if the server is really down.. And not a temp failure.
237
if(reconnectDelay == MAX_RECONNECT_DELAY) {
238             log.info("Endpoint connection failed: "+error.getMessage());
239             log.info("Endpoint will try to reconnect in "+(MAX_RECONNECT_DELAY/1000)+" seconds");
240         }
241         try {
242             disconnect();
243             Thread.sleep(reconnectDelay);
244             
245             // Use exponential rollback.
246
reconnectDelay*=2;
247             if(reconnectDelay > MAX_RECONNECT_DELAY)
248                 reconnectDelay = MAX_RECONNECT_DELAY;
249             
250             connect();
251         } catch (InterruptedException JavaDoc e) {
252             e.printStackTrace();
253         }
254     }
255     
256     protected void registerThreadSession(Session JavaDoc session) {
257         threadLocal.set(session);
258     }
259     
260     protected void unregisterThreadSession(Session JavaDoc session) {
261         threadLocal.set(null);
262     }
263     
264     private String JavaDoc emptyToNull(String JavaDoc value) {
265         if (value == null || value.length() == 0) {
266             return null;
267         }
268         return value;
269     }
270     
271 }
272
Popular Tags