/** 
 * 
 * Copyright 2004 Protique Ltd
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at 
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
 * See the License for the specific language governing permissions and 
 * limitations under the License. 
 * 
 **/
package org.codehaus.activemq.bean;

import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import javax.jms.TextMessage;

/**
 * A simple Bridge POJO which will copy messages from one destination to
 * another optionally performing some kind of transformation.
 *
 * @version $Revision: 1.1 $
 */
public class BridgeBean implements MessageListener {
    private Session session;
    private MessageProducer producer;
    private Destination destination;

    public BridgeBean(Session session, MessageProducer producer, Destination destination) {
        this.session = session;
        this.producer = producer;
        this.destination = destination;
    }

    public void onMessage(Message inputMessage) {
        try {
            Message outputMessage = createOutputMessage(inputMessage);
            enrich(outputMessage, inputMessage);
            producer.send(destination, outputMessage);
        }
        catch (JMSException e) {
            onJMSException(e);
        }
    }

    /**
     * A strategy method to allow a message to be enriched, such as
     * to append some properties from the input message
     *
     * @param outputMessage
     * @param inputMessage
     */
    protected void enrich(Message outputMessage, Message inputMessage) {
    }

    /**
     * A strategy method to create a new message given an input message
     *
     * @param message
     * @return
     * @throws javax.jms.JMSException
     */
    protected Message createOutputMessage(Message message) throws JMSException {
        if (message instanceof ObjectMessage) {
            ObjectMessage objMsg = (ObjectMessage) message;
            return session.createObjectMessage(objMsg.getObject());
        }
        else if (message instanceof TextMessage) {
            TextMessage txtMsg = (TextMessage) message;
            return session.createTextMessage(txtMsg.getText());
        }
        else {
            // TODO handle Map message, ByteMessage, StreamMessage
            return session.createMessage();
        }
    }

    /**
     * Handle a JMS exception being thrown
     *
     * @param e
     */
    protected void onJMSException(JMSException e) {
        throw new RuntimeException(e);
    }
}
