/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2012 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: WebServicesAuditTestCase.java 22467 2012-05-31 14:22:14Z benebrice $
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.tests.applications.wsadd.ws;

import java.io.IOException;

import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.ow2.util.auditreport.api.IAuditID;
import org.ow2.util.auditreport.impl.CurrentInvocationID;
import org.ow2.util.auditreport.impl.GenericAuditReport;
import org.ow2.util.auditreport.impl.JaxwsAuditReport;
import org.ow2.util.auditreport.impl.event.Event;
import org.ow2.util.event.api.EventPriority;
import org.ow2.util.event.api.IEvent;
import org.ow2.util.event.api.IEventListener;
import org.ow2.util.event.api.IEventService;
import org.ow2.util.event.impl.EventDispatcher;
/**
 * 
 * @author Brice Bene
 *
 */
public class AuditEventServiceServlet extends HttpServlet implements IEventListener{
    private IEventService eventService;
    private HttpServletRequest req;
    private HttpServletResponse resp;
    boolean ok = false;
    GenericAuditReport report;
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.req = req;
        this.resp = resp;
        
        try {
            InitialContext ic = new InitialContext();
            BundleContext bc = (BundleContext) ic.lookup("java:comp/env/BundleContext");
            ServiceReference<?> servRef = bc.getServiceReference(IEventService.class.getName());
            eventService = (IEventService) bc.getService(servRef);
            register();
            sendEvent();
        } catch (Exception e) {
            throw new IllegalStateException("Error on audit tests", e);
        } finally {
            unregister();
        }
        
    }
    
    public void register(){
        
//        if(eventService.getDispatcher("JAXWS") == null) {
//            EventDispatcher d= new EventDispatcher();
//            d.setNbWorkers(2);
//            d.start();
//            eventService.registerDispatcher("JAXWS", d);
//        }
        eventService.registerListener(this, "JAXWS");
    }
    
    public void sendEvent(){
        //Call the webservice
        try {
            String serviceURL = req.getScheme() + "://" + req.getLocalAddr() + ":" + req.getServerPort() + "/wsadd-sample/WSAddService";
            
            // Trigger the report generation
            DefaultHttpClient client = new DefaultHttpClient();
            HttpPost post = new HttpPost(serviceURL);
            InputStreamEntity entity = new InputStreamEntity(getClass().getResourceAsStream("/soap-request-add.xml"), -1);
            entity.setContentType("application/soap+xml");
            post.setEntity(entity);
            client.execute(post);

            // Wait for some times before failing the tests
            // That let some times for the report to be generated
            // wait up to 10 seconds (20 * 500ms)
            int i = 0;
            int times = 20;
            int sleepTime = 500;
            while ((report == null) && (i < times)) {
                Thread.sleep(sleepTime);
                i++;
            }

            // Fail if the report was not generated
            if (!ok) {
                resp.getWriter().println("Report was not generated after " + ((i * sleepTime) / 1000) + " seconds");
            }
        } catch (Exception e) {
            throw new IllegalStateException("Error send JAXWS event on test", e);
        }
            
    }
         
        
        
    public void unregister() {
        eventService.unregisterListener(this);
    }

    public boolean accept(IEvent event) {
       return true;
    }

    public EventPriority getPriority() {
        return EventPriority.ASYNC_HIGH;
    }

    public void handle(IEvent event) {
        report = (GenericAuditReport) ((Event) event).getReport();
        ok = true;
    }

}
