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.jencks;
019    
020    import org.springframework.aop.TargetSource;
021    import org.springframework.beans.factory.InitializingBean;
022    
023    import javax.jms.Message;
024    import javax.jms.MessageListener;
025    
026    /**
027     * Represents a pool of MessageListener instances using Spring's
028     * TargetSource for the underlying pool.
029     *
030     * @version $Revision: 1.1.1.1 $
031     */
032    public class TargetSourceMessageListener implements MessageListener, InitializingBean {
033        private TargetSource targetSource;
034    
035        public void onMessage(Message message) {
036            MessageListener delegate = null;
037            try {
038                delegate = (MessageListener) targetSource.getTarget();
039            }
040            catch (Exception e) {
041                handleException(e);
042            }
043            try {
044                delegate.onMessage(message);
045            }
046            finally {
047                try {
048                    targetSource.releaseTarget(delegate);
049                }
050                catch (Exception e) {
051                    handleException(e);
052                }
053            }
054        }
055    
056        public void afterPropertiesSet() throws Exception {
057            if (targetSource == null) {
058                throw new IllegalArgumentException("targetSource must be set");
059            }
060        }
061    
062        public TargetSource getTargetSource() {
063            return targetSource;
064        }
065    
066        public void setTargetSource(TargetSource targetSource) {
067            this.targetSource = targetSource;
068        }
069    
070        protected void handleException(Exception e) {
071            throw new RuntimeException(e);
072        }
073    
074    }