/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2011 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 (at your option) 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 *
 * --------------------------------------------------------------------------
 * $Id: JaxwsClientAuditHandler.java 21566 2011-08-08 12:28:12Z cazauxj $
 * --------------------------------------------------------------------------
 */


package org.ow2.jonas.ws.jaxws.base.audit;

import java.util.Collections;
import java.util.List;
import java.util.Map;

import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPMessageContext;

import org.ow2.util.auditreport.api.IAuditID;
import org.ow2.util.auditreport.api.ICurrentInvocationID;

/**
 * A {@code JaxwsAuditHandler} is ...
 *
 * @author Guillaume Sauthier
 */
public class JaxwsClientAuditHandler extends AbstractJaxwsAuditHandler {

    private ICurrentInvocationID current;

    public JaxwsClientAuditHandler(final ICurrentInvocationID current) {
        this.current = current;
    }

    public boolean handleMessage(final SOAPMessageContext context) {

        if (isOutbound(context)) {
            // Request
            // Need to add a new header in the outbound message that will store the token

            // Creates a new child ID
            IAuditID old = current.newInvocation();
            IAuditID id = current.getAuditID();

            // Place it in the HTTP Headers of the request
            Map<String, List<String>> headers = (Map<String, List<String>>) context.get(MessageContext.HTTP_REQUEST_HEADERS);
            if (headers != null) {
	        headers.put("Invocation-ID", Collections.singletonList(id.getID()));
            }

            // Reset the current to the parent
            current.setAuditID(old);

        }
        // Nothing to do for inbound response (else)

        return true;
    }

}
