001    /**
002     * 
003     * Copyright 2005 LogicBlaze, Inc.
004     * 
005     * Licensed under the Apache License, Version 2.0 (the "License"); 
006     * you may not use this file except in compliance with the License. 
007     * 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.logicblaze.lingo.jms.impl;
019    
020    import javax.jms.Connection;
021    import javax.jms.ConnectionFactory;
022    import javax.jms.JMSException;
023    import javax.jms.MessageProducer;
024    import javax.jms.Session;
025    
026    /**
027     * A default implementation of the {@link org.logicblaze.lingo.jms.JmsProducer} which contains a reference to the
028     * connection, session and producer so that it can easily close down all its resources properly.
029     *
030     * @version $Revision: 1.1 $
031     */
032    public class DefaultJmsProducer extends JmsProducerImpl {
033    
034        private Connection connection;
035    
036        public static DefaultJmsProducer newInstance(ConnectionFactory factory) throws JMSException {
037            Connection connection = factory.createConnection();
038    
039            // lets start the connection in case that we consume on the same connection
040            connection.start();
041    
042            return newInstance(connection);
043        }
044    
045        public static DefaultJmsProducer newInstance(Connection connection) throws JMSException {
046            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
047            MessageProducer producer = session.createProducer(null);
048            return new DefaultJmsProducer(connection, session, producer);
049        }
050    
051        public DefaultJmsProducer(Connection connection, Session session, MessageProducer producer) {
052            super(session, producer);
053            this.connection = connection;
054        }
055    
056        public Connection getConnection() {
057            return connection;
058        }
059    
060        public void close() throws JMSException {
061            super.close();
062            if (connection != null) {
063                Connection tmp = connection;
064                connection = null;
065                tmp.close();
066            }
067        }
068    }