/**
 * 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 21566 2011-08-08 12:28:12Z cazauxj $
 * --------------------------------------------------------------------------
 */


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

import java.util.concurrent.atomic.AtomicLong;

import javax.management.MBeanException;
import javax.management.Notification;
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.auditreport.impl.JaxwsAuditReport;
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 String AUDIT_ID_KEY = JaxwsEndpointAuditHandler.class.getName() + ".AUDIT_ID";

    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);
                }

                // Restore the Audit ID in the thread.
                // is equivalent to a current.pop() if it was existing
                IAuditID old = (IAuditID) context.get(AUDIT_ID_KEY);
                if (old != null) {
                    current.setAuditID(old);
                }
            }

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

            IAuditID oldId = current.getAuditID();

            if (oldId != null) {

                // Generate a new ID (will appear as a new node in the UI)
                current.newInvocation();
                IAuditID id = current.getAuditID();

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

                JaxwsAuditReport report = new JaxwsAuditReport();
                report.setKeyID(id.getID());
                report.setRequestTimeStamp(System.currentTimeMillis());
                report.setStartProcessingTimestamp(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);

                // Store the old ID
                context.put(AUDIT_ID_KEY, oldId);
            }
        }
        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;
    }
}
