001    /**
002     * Licensed to the Apache Software Foundation (ASF) under one or more
003     * contributor license agreements.  See the NOTICE file distributed with
004     * this work for additional information regarding copyright ownership.
005     * The ASF licenses this file to You under the Apache License, Version 2.0
006     * (the "License"); you may not use this file except in compliance with
007     * the License.  You may obtain a copy of the License at
008     *
009     *      http://www.apache.org/licenses/LICENSE-2.0
010     *
011     * Unless required by applicable law or agreed to in writing, software
012     * distributed under the License is distributed on an "AS IS" BASIS,
013     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014     * See the License for the specific language governing permissions and
015     * limitations under the License.
016     */
017    
018    package org.apache.activemq.web;
019    
020    import java.io.Externalizable;
021    import java.io.IOException;
022    import java.io.ObjectInput;
023    import java.io.ObjectOutput;
024    import java.util.ArrayList;
025    import java.util.HashMap;
026    import java.util.Iterator;
027    import java.util.List;
028    import java.util.Map;
029    import java.util.concurrent.Semaphore;
030    
031    import javax.jms.Connection;
032    import javax.jms.ConnectionFactory;
033    import javax.jms.DeliveryMode;
034    import javax.jms.Destination;
035    import javax.jms.JMSException;
036    import javax.jms.Message;
037    import javax.jms.MessageConsumer;
038    import javax.jms.MessageProducer;
039    import javax.jms.Session;
040    import javax.servlet.ServletContext;
041    import javax.servlet.http.HttpServletRequest;
042    import javax.servlet.http.HttpSession;
043    import javax.servlet.http.HttpSessionActivationListener;
044    import javax.servlet.http.HttpSessionBindingEvent;
045    import javax.servlet.http.HttpSessionBindingListener;
046    import javax.servlet.http.HttpSessionEvent;
047    
048    import org.apache.activemq.ActiveMQConnectionFactory;
049    import org.apache.activemq.MessageAvailableConsumer;
050    import org.apache.activemq.camel.component.ActiveMQComponent;
051    import org.apache.activemq.camel.component.ActiveMQConfiguration;
052    import org.apache.activemq.pool.PooledConnectionFactory;
053    import org.apache.camel.CamelContext;
054    import org.apache.camel.ProducerTemplate;
055    import org.apache.camel.impl.DefaultCamelContext;
056    import org.apache.commons.logging.Log;
057    import org.apache.commons.logging.LogFactory;
058    
059    import sun.util.logging.resources.logging;
060    
061    /**
062     * Represents a messaging client used from inside a web container typically
063     * stored inside a HttpSession TODO controls to prevent DOS attacks with users
064     * requesting many consumers TODO configure consumers with small prefetch.
065     * 
066     * @version $Revision: 1.1.1.1 $
067     */
068    public class WebClient implements HttpSessionActivationListener, HttpSessionBindingListener, Externalizable {
069    
070        public static final String WEB_CLIENT_ATTRIBUTE = "org.apache.activemq.webclient";
071        public static final String CONNECTION_FACTORY_ATTRIBUTE = "org.apache.activemq.connectionFactory";
072        public static final String CONNECTION_FACTORY_PREFETCH_PARAM = "org.apache.activemq.connectionFactory.prefetch";
073        public static final String CONNECTION_FACTORY_OPTIMIZE_ACK_PARAM = "org.apache.activemq.connectionFactory.optimizeAck";
074        public static final String BROKER_URL_INIT_PARAM = "org.apache.activemq.brokerURL";
075    
076        private static final Log LOG = LogFactory.getLog(WebClient.class);
077    
078        private static transient ConnectionFactory factory;
079    
080        private transient Map<Destination, MessageConsumer> consumers = new HashMap<Destination, MessageConsumer>();
081        private transient Connection connection;
082        private transient Session session;
083        private transient MessageProducer producer;
084        private int deliveryMode = DeliveryMode.NON_PERSISTENT;
085    
086        private final Semaphore semaphore = new Semaphore(1);
087    
088        private CamelContext camelContext;
089        private ProducerTemplate producerTemplate;
090    
091        public WebClient() {
092            if (factory == null) {
093                throw new IllegalStateException("initContext(ServletContext) not called");
094            }
095        }
096    
097        /**
098         * Helper method to get the client for the current session, lazily creating
099         * a client if there is none currently
100         * 
101         * @param request is the current HTTP request
102         * @return the current client or a newly creates
103         */
104        public static WebClient getWebClient(HttpServletRequest request) {
105            HttpSession session = request.getSession(true);
106            WebClient client = getWebClient(session);
107            if (client == null || client.isClosed()) {
108                client = WebClient.createWebClient(request);
109                session.setAttribute(WEB_CLIENT_ATTRIBUTE, client);
110            }
111    
112            return client;
113        }
114    
115        /**
116         * @return the web client for the current HTTP session or null if there is
117         *         not a web client created yet
118         */
119        public static WebClient getWebClient(HttpSession session) {
120            return (WebClient)session.getAttribute(WEB_CLIENT_ATTRIBUTE);
121        }
122    
123        public static void initContext(ServletContext context) {
124            initConnectionFactory(context);
125            context.setAttribute("webClients", new HashMap<String, WebClient>());
126        }
127    
128        public int getDeliveryMode() {
129            return deliveryMode;
130        }
131    
132        public void setDeliveryMode(int deliveryMode) {
133            this.deliveryMode = deliveryMode;
134        }
135    
136        public synchronized void closeConsumers() {
137            for (Iterator<MessageConsumer> it = consumers.values().iterator(); it.hasNext();) {
138                MessageConsumer consumer = it.next();
139                it.remove();
140                try {
141                    consumer.setMessageListener(null);
142                    if (consumer instanceof MessageAvailableConsumer) {
143                        ((MessageAvailableConsumer)consumer).setAvailableListener(null);
144                    }
145                    consumer.close();
146                } catch (JMSException e) {
147                    LOG.debug("caught exception closing consumer", e);
148                }
149            }
150        }
151    
152        public synchronized void close() {
153            try {
154                closeConsumers();
155                if (connection != null) {
156                    connection.close();
157                }
158                if (producerTemplate != null) {
159                    producerTemplate.stop();
160                }
161            } catch (Exception e) {
162                LOG.debug("caught exception closing consumer", e);
163            } finally {
164                producer = null;
165                session = null;
166                connection = null;
167                producerTemplate = null;
168                if (consumers != null) {
169                    consumers.clear();
170                }
171                consumers = null;
172            }
173        }
174    
175        public boolean isClosed() {
176            return consumers == null;
177        }
178    
179        public void writeExternal(ObjectOutput out) throws IOException {
180            if (consumers != null) {
181                out.write(consumers.size());
182                Iterator<Destination> i = consumers.keySet().iterator();
183                while (i.hasNext()) {
184                    out.writeObject(i.next().toString());
185                }
186            } else {
187                out.write(-1);
188            }
189    
190        }
191    
192        public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
193            int size = in.readInt();
194            if (size >= 0) {
195                consumers = new HashMap<Destination, MessageConsumer>();
196                for (int i = 0; i < size; i++) {
197                    String destinationName = in.readObject().toString();
198    
199                    try {
200                        Destination destination = destinationName.startsWith("topic://") ? (Destination)getSession().createTopic(destinationName) : (Destination)getSession().createQueue(destinationName);
201                        consumers.put(destination, getConsumer(destination, true));
202                    } catch (JMSException e) {
203                        LOG.debug("Caought Exception ", e);
204                        IOException ex = new IOException(e.getMessage());
205                        ex.initCause(e.getCause() != null ? e.getCause() : e);
206                        throw ex;
207    
208                    }
209                }
210            }
211        }
212    
213        public void send(Destination destination, Message message) throws JMSException {
214            getProducer().send(destination, message);
215            if (LOG.isDebugEnabled()) {
216                LOG.debug("Sent! to destination: " + destination + " message: " + message);
217            }
218        }
219    
220        public void send(Destination destination, Message message, boolean persistent, int priority, long timeToLive) throws JMSException {
221            int deliveryMode = persistent ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT;
222            getProducer().send(destination, message, deliveryMode, priority, timeToLive);
223            if (LOG.isDebugEnabled()) {
224                LOG.debug("Sent! to destination: " + destination + " message: " + message);
225            }
226        }
227    
228        public Session getSession() throws JMSException {
229            if (session == null) {
230                session = createSession();
231            }
232            return session;
233        }
234    
235        public Connection getConnection() throws JMSException {
236            if (connection == null) {
237                connection = factory.createConnection();
238                connection.start();
239            }
240            return connection;
241        }
242    
243        protected static synchronized void initConnectionFactory(ServletContext servletContext) {
244            if (factory == null) {
245                factory = (ConnectionFactory)servletContext.getAttribute(CONNECTION_FACTORY_ATTRIBUTE);
246            }
247            if (factory == null) {
248                String brokerURL = servletContext.getInitParameter(BROKER_URL_INIT_PARAM);
249    
250                LOG.debug("Value of: " + BROKER_URL_INIT_PARAM + " is: " + brokerURL);
251    
252                if (brokerURL == null) {
253                    throw new IllegalStateException("missing brokerURL (specified via " + BROKER_URL_INIT_PARAM + " init-Param");
254                }
255    
256                ActiveMQConnectionFactory amqfactory = new ActiveMQConnectionFactory(brokerURL);
257    
258                // Set prefetch policy for factory
259                if (servletContext.getInitParameter(CONNECTION_FACTORY_PREFETCH_PARAM) != null) {
260                    int prefetch = Integer.valueOf(servletContext.getInitParameter(CONNECTION_FACTORY_PREFETCH_PARAM)).intValue();
261                    amqfactory.getPrefetchPolicy().setAll(prefetch);
262                }
263    
264                // Set optimize acknowledge setting
265                if (servletContext.getInitParameter(CONNECTION_FACTORY_OPTIMIZE_ACK_PARAM) != null) {
266                    boolean optimizeAck = Boolean.valueOf(servletContext.getInitParameter(CONNECTION_FACTORY_OPTIMIZE_ACK_PARAM)).booleanValue();
267                    amqfactory.setOptimizeAcknowledge(optimizeAck);
268                }
269    
270                factory = amqfactory;
271    
272                servletContext.setAttribute(CONNECTION_FACTORY_ATTRIBUTE, factory);
273            }
274        }
275        
276        public synchronized CamelContext getCamelContext() {
277            if (camelContext == null) {
278                    LOG.debug("Creating camel context");
279                    camelContext = new DefaultCamelContext();
280                    ActiveMQConfiguration conf = new ActiveMQConfiguration();
281                    conf.setConnectionFactory(new PooledConnectionFactory((ActiveMQConnectionFactory)factory));
282                    ActiveMQComponent component = new ActiveMQComponent(conf);
283                    camelContext.addComponent("activemq", component);
284            }
285            return camelContext;
286        }
287        
288        public synchronized ProducerTemplate getProducerTemplate() throws Exception {
289            if (producerTemplate == null) {
290                    LOG.debug("Creating producer template");
291                    producerTemplate = getCamelContext().createProducerTemplate();
292                    producerTemplate.start();
293            }
294            return producerTemplate;
295        }
296    
297        public synchronized MessageProducer getProducer() throws JMSException {
298            if (producer == null) {
299                producer = getSession().createProducer(null);
300                producer.setDeliveryMode(deliveryMode);
301            }
302            return producer;
303        }
304    
305        public void setProducer(MessageProducer producer) {
306            this.producer = producer;
307        }
308    
309        public synchronized MessageConsumer getConsumer(Destination destination) throws JMSException {
310            return getConsumer(destination, true);
311        }
312    
313        public synchronized MessageConsumer getConsumer(Destination destination, boolean create) throws JMSException {
314            MessageConsumer consumer = consumers.get(destination);
315            if (create && consumer == null) {
316                consumer = getSession().createConsumer(destination);
317                consumers.put(destination, consumer);
318            }
319            return consumer;
320        }
321    
322        public synchronized void closeConsumer(Destination destination) throws JMSException {
323            MessageConsumer consumer = consumers.get(destination);
324            if (consumer != null) {
325                consumers.remove(destination);
326                consumer.setMessageListener(null);
327                if (consumer instanceof MessageAvailableConsumer) {
328                    ((MessageAvailableConsumer)consumer).setAvailableListener(null);
329                }
330                consumer.close();
331            }
332        }
333    
334        public synchronized List<MessageConsumer> getConsumers() {
335            return new ArrayList<MessageConsumer>(consumers.values());
336        }
337    
338        protected Session createSession() throws JMSException {
339            return getConnection().createSession(false, Session.AUTO_ACKNOWLEDGE);
340        }
341    
342        public Semaphore getSemaphore() {
343            return semaphore;
344        }
345    
346        public void sessionWillPassivate(HttpSessionEvent event) {
347            close();
348        }
349    
350        public void sessionDidActivate(HttpSessionEvent event) {
351        }
352    
353        public void valueBound(HttpSessionBindingEvent event) {
354        }
355    
356        public void valueUnbound(HttpSessionBindingEvent event) {
357            close();
358        }
359    
360        protected static WebClient createWebClient(HttpServletRequest request) {
361            return new WebClient();
362        }
363    
364    }