/**
 * JOnAS
 * Copyright (C) 2010 Bull S.A.S.
 * Contact: jonas-team@ow2.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 * --------------------------------------------------------------------------
 * $Id: JMSClientInterceptor.java 20987 2011-03-14 12:10:10Z benoitf $
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.audit.jms.interceptor;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;

import org.objectweb.joram.client.jms.MessageInterceptor;
import org.ow2.util.auditreport.api.IAuditID;
import org.ow2.util.auditreport.api.ICurrentInvocationID;
import org.ow2.util.auditreport.impl.CurrentInvocationID;
import org.ow2.util.log.Log;
import org.ow2.util.log.LogFactory;

/**
 * Client Interceptor.
 * @author Florent Benoit
 */
public class JMSClientInterceptor implements MessageInterceptor {

    /**
    * Logger.
    */
    private Log logger = LogFactory.getLog(JMSClientInterceptor.class);

    /**
     * Handle the given message.
     * @param msg the given message
     * @param session the JMS Session
     */
    public void handle(final Message msg, final Session session) {

        // Get current ID
        ICurrentInvocationID currentInvocationID = CurrentInvocationID.getInstance();

        // Existing ID ?
        IAuditID localID = currentInvocationID.getAuditID();

        // If there is an ID, propagate it
        if (localID != null) {
            localID.increment();

            // Store it in the message
            try {
                msg.setStringProperty(IAuditID.class.getName(), localID.getID());
            } catch (JMSException e) {
                // Unable to set the property
                logger.warn("Unable to set the property ''{0}'' on the message", IAuditID.class.getName(), e);
            }

        }
    }

}
