KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectstyle > cayenne > event > JMSBridge


1 /* ====================================================================
2  *
3  * The ObjectStyle Group Software License, version 1.1
4  * ObjectStyle Group - http://objectstyle.org/
5  *
6  * Copyright (c) 2002-2005, Andrei (Andrus) Adamchik and individual authors
7  * of the software. All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  *
13  * 1. Redistributions of source code must retain the above copyright
14  * notice, this list of conditions and the following disclaimer.
15  *
16  * 2. Redistributions in binary form must reproduce the above copyright
17  * notice, this list of conditions and the following disclaimer in
18  * the documentation and/or other materials provided with the
19  * distribution.
20  *
21  * 3. The end-user documentation included with the redistribution, if any,
22  * must include the following acknowlegement:
23  * "This product includes software developed by independent contributors
24  * and hosted on ObjectStyle Group web site (http://objectstyle.org/)."
25  * Alternately, this acknowlegement may appear in the software itself,
26  * if and wherever such third-party acknowlegements normally appear.
27  *
28  * 4. The names "ObjectStyle Group" and "Cayenne" must not be used to endorse
29  * or promote products derived from this software without prior written
30  * permission. For written permission, email
31  * "andrus at objectstyle dot org".
32  *
33  * 5. Products derived from this software may not be called "ObjectStyle"
34  * or "Cayenne", nor may "ObjectStyle" or "Cayenne" appear in their
35  * names without prior written permission.
36  *
37  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
38  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
39  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
40  * DISCLAIMED. IN NO EVENT SHALL THE OBJECTSTYLE GROUP OR
41  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
42  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
43  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
44  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
45  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
46  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
47  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
48  * SUCH DAMAGE.
49  * ====================================================================
50  *
51  * This software consists of voluntary contributions made by many
52  * individuals and hosted on ObjectStyle Group web site. For more
53  * information on the ObjectStyle Group, please see
54  * <http://objectstyle.org/>.
55  */

56 package org.objectstyle.cayenne.event;
57
58 import java.io.Serializable JavaDoc;
59
60 import javax.jms.Message JavaDoc;
61 import javax.jms.MessageFormatException JavaDoc;
62 import javax.jms.MessageListener JavaDoc;
63 import javax.jms.ObjectMessage JavaDoc;
64 import javax.jms.Session JavaDoc;
65 import javax.jms.Topic JavaDoc;
66 import javax.jms.TopicConnection JavaDoc;
67 import javax.jms.TopicConnectionFactory JavaDoc;
68 import javax.jms.TopicPublisher JavaDoc;
69 import javax.jms.TopicSession JavaDoc;
70 import javax.jms.TopicSubscriber JavaDoc;
71 import javax.naming.Context JavaDoc;
72 import javax.naming.InitialContext JavaDoc;
73 import javax.naming.NameNotFoundException JavaDoc;
74 import javax.naming.NamingException JavaDoc;
75
76 import org.apache.log4j.Logger;
77
78 /**
79  * Implementation of EventBridge that passes and receives events via JMS
80  * (Java Messaging Service). JMSBridge uses "publish/subscribe" model for communication
81  * with external agents.
82  *
83  * @author Andrei Adamchik
84  * @since 1.1
85  */

86 public class JMSBridge extends EventBridge implements MessageListener JavaDoc {
87     private static Logger logObj = Logger.getLogger(JMSBridge.class);
88
89     protected String JavaDoc topicConnectionFactoryName;
90
91     protected TopicConnection JavaDoc sendConnection;
92     protected TopicSession JavaDoc sendSession;
93     protected TopicConnection JavaDoc receivedConnection;
94     protected TopicPublisher JavaDoc publisher;
95     protected TopicSubscriber JavaDoc subscriber;
96
97     public JMSBridge(EventSubject localSubject, String JavaDoc externalSubject) {
98         super(localSubject, externalSubject);
99     }
100
101     /**
102      * JMS MessageListener implementation. Injects received events to the EventManager
103      * local event queue.
104      */

105     public void onMessage(Message JavaDoc message) {
106
107         try {
108             Object JavaDoc vmID = message.getObjectProperty(VM_ID_PROPERRTY);
109             if (VM_ID.equals(vmID)) {
110                 logObj.debug("Message from same VM ignoring.");
111                 return;
112             }
113
114             if (!(message instanceof ObjectMessage JavaDoc)) {
115                 if (logObj.isDebugEnabled()) {
116                     logObj.debug("Unsupported message, ignoring: " + vmID);
117                 }
118
119                 return;
120             }
121
122             ObjectMessage JavaDoc objectMessage = (ObjectMessage JavaDoc) message;
123             CayenneEvent event = messageObjectToEvent(objectMessage.getObject());
124             if (event != null) {
125                 if (logObj.isDebugEnabled()) {
126                     logObj.debug(
127                         "Received CayenneEvent: "
128                             + event.getClass().getName()
129                             + ", id: "
130                             + vmID);
131                 }
132
133                 onExternalEvent(event);
134             }
135
136         } catch (MessageFormatException JavaDoc mfex) {
137             Exception JavaDoc linkedException = mfex.getLinkedException();
138             Exception JavaDoc logException = (linkedException != null) ? linkedException : mfex;
139             logObj.info("Message Format Exception: ", logException);
140         } catch (Exception JavaDoc ex) {
141             logObj.info("Exception while processing message: ", ex);
142         }
143     }
144
145     /**
146      * @return Name of javax.jms.TopicConnectionFactory accessible via JNDI.
147      */

148     public String JavaDoc getTopicConnectionFactoryName() {
149         return topicConnectionFactoryName;
150     }
151     
152     public void setTopicConnectionFactoryName(String JavaDoc name) {
153         this.topicConnectionFactoryName = name;
154     }
155
156     /**
157      * Starts up JMS machinery for "publish/subscribe" model.
158      */

159     protected void startupExternal() throws Exception JavaDoc {
160         Context JavaDoc jndiContext = new InitialContext JavaDoc();
161         TopicConnectionFactory JavaDoc connectionFactory =
162             (TopicConnectionFactory JavaDoc) jndiContext.lookup(topicConnectionFactoryName);
163
164         Topic JavaDoc topic = null;
165
166         try {
167             topic = (Topic JavaDoc) jndiContext.lookup(externalSubject);
168         } catch (NameNotFoundException JavaDoc ex) {
169             // can't find topic, try to create it
170
topic = topicNotFound(jndiContext, ex);
171
172             if (topic == null) {
173                 throw ex;
174             }
175         }
176
177         // config publisher
178
if (receivesLocalEvents()) {
179             this.sendConnection = connectionFactory.createTopicConnection();
180             this.sendSession =
181                 sendConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
182             this.publisher = sendSession.createPublisher(topic);
183         }
184
185         // config subscriber
186
if (receivesExternalEvents()) {
187             this.receivedConnection = connectionFactory.createTopicConnection();
188             this.subscriber =
189                 receivedConnection.createTopicSession(
190                     false,
191                     Session.AUTO_ACKNOWLEDGE).createSubscriber(
192                     topic);
193             this.subscriber.setMessageListener(this);
194             this.receivedConnection.start();
195         }
196     }
197
198     /**
199      * Attempts to create missing Topic. Since Topic creation is JMS-implementation specific,
200      * this task is left to subclasses. Current implementation simply rethrows the exception.
201      */

202     protected Topic JavaDoc topicNotFound(Context JavaDoc jndiContext, NamingException JavaDoc ex)
203         throws Exception JavaDoc {
204         throw ex;
205     }
206
207     /**
208      * Closes all resources used to communicate via JMS.
209      */

210     protected void shutdownExternal() throws Exception JavaDoc {
211         Exception JavaDoc lastException = null;
212
213         if (publisher != null) {
214             try {
215                 publisher.close();
216             } catch (Exception JavaDoc ex) {
217                 lastException = ex;
218             }
219         }
220
221         if (subscriber != null) {
222             try {
223                 subscriber.close();
224             } catch (Exception JavaDoc ex) {
225                 lastException = ex;
226             }
227         }
228
229         if (receivedConnection != null) {
230             try {
231                 receivedConnection.close();
232             } catch (Exception JavaDoc ex) {
233                 lastException = ex;
234             }
235         }
236
237         if (sendSession != null) {
238             try {
239                 sendSession.close();
240             } catch (Exception JavaDoc ex) {
241                 lastException = ex;
242             }
243         }
244
245         if (sendConnection != null) {
246             try {
247                 sendConnection.close();
248             } catch (Exception JavaDoc ex) {
249                 lastException = ex;
250             }
251         }
252
253         publisher = null;
254         subscriber = null;
255         receivedConnection = null;
256         sendConnection = null;
257         sendSession = null;
258
259         if (lastException != null) {
260             throw lastException;
261         }
262     }
263
264     protected void sendExternalEvent(CayenneEvent localEvent) throws Exception JavaDoc {
265         logObj.debug("Sending event remotely: " + localEvent);
266         ObjectMessage JavaDoc message =
267             sendSession.createObjectMessage(eventToMessageObject(localEvent));
268         message.setObjectProperty(VM_ID_PROPERRTY, VM_ID);
269         publisher.publish(message);
270     }
271
272     /**
273      * Converts CayenneEvent to a serializable object that will be sent via JMS.
274      * Default implementation simply returns the event, but subclasses can customize
275      * this behavior.
276      */

277     protected Serializable JavaDoc eventToMessageObject(CayenneEvent event) throws Exception JavaDoc {
278         return event;
279     }
280
281     /**
282      * Converts a Serializable instance to CayenneEvent. Returns null if the object
283      * is not supported. Default implementation simply tries to cast the object to
284      * CayenneEvent, but subclasses can customize this behavior.
285      */

286     protected CayenneEvent messageObjectToEvent(Serializable JavaDoc object) throws Exception JavaDoc {
287         return (object instanceof CayenneEvent) ? (CayenneEvent) object : null;
288     }
289 }
290
Popular Tags