/**
 * 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: JaxwsEndpointAuditHandler.java 21004 2011-03-16 12:34:11Z sauthieg $
 * --------------------------------------------------------------------------
 */


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

import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;

import javax.management.MBeanException;
import javax.management.Notification;
import javax.xml.namespace.QName;
import javax.xml.ws.handler.Handler;
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;
import org.ow2.util.log.Log;
import org.ow2.util.log.LogFactory;

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

    public static final String REPORT_KEY = JaxwsEndpointAuditHandler.class.getName() + ".REPORT";

    public static final Log logger = LogFactory.getLog(JaxwsEndpointAuditHandler.class);

    private AtomicLong sequence = new AtomicLong();

    private boolean detailed = false;

    private ICurrentInvocationID current;

    public JaxwsEndpointAuditHandler(ICurrentInvocationID current) {
        this.current = current;
    }

    public boolean handleMessage(SOAPMessageContext context) {

        if (isOutbound(context)) {
            // Response
            // Close the report generation
            JaxwsAuditReport report = (JaxwsAuditReport) context.get(REPORT_KEY);
            if (report != null) {

                report.setEndProcessingTimestamp(System.nanoTime());

                // broadcast report...
                try {
                    sendNotification(createNotification(report));
                } catch (MBeanException e) {
                    // Ignored
                    logger.debug("Cannot send notification from webservice Audit System", e);
                }
            }

        } else { // inbound
            // Request
            // Init the report generation

            IAuditID auditId = current.getAuditID();

            if (auditId != null) {

                // If there is no ID set, just abort report generation

                JaxwsAuditReport report = new JaxwsAuditReport();
                report.setKeyID(auditId.getID());
                report.setRequestTimeStamp(System.nanoTime());

                report.setServiceQName(context.get(MessageContext.WSDL_SERVICE).toString());
                report.setPortQName(context.get(MessageContext.WSDL_PORT).toString());
                report.setOperationQName(context.get(MessageContext.WSDL_OPERATION).toString());

                report.setSoapRoles(context.getRoles());

                // Store the report
                context.put(REPORT_KEY, report);
            }
        }
        return true;
    }

    private Notification createNotification(final JaxwsAuditReport report) {
        return new Notification(JaxwsAuditReport.class.getName(),
                                this.getClass().getName(), // source ?
                                sequence.getAndIncrement(),
                                report.toString());
    }

    public boolean isDetailed() {
        return detailed;
    }

    public void setDetailed(boolean detailed) {
        this.detailed = detailed;
    }
}
