/**
 * 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: WebServicesAuditTestCase.java 21212 2011-04-27 12:23:56Z sauthieg $
 * --------------------------------------------------------------------------
 */


package org.ow2.jonas.itests.cargo.jrmp;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.management.Notification;
import javax.management.NotificationListener;
import javax.management.ObjectName;
import javax.xml.namespace.QName;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.ow2.util.auditreport.impl.JaxwsAuditReport;
import org.ow2.util.auditreport.impl.util.ObjectEncoder;
import org.testng.annotations.Test;

import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.fail;

/**
 * A {@code WebServicesAuditTestCase} is ...
 *
 * @author Guillaume Sauthier
 */
public class WebServicesAuditTestCase extends TestCommons {

    private JaxwsAuditReport report;
    private boolean ok = false;

    @Test
    public void testInvocationIdIsPropagatedThroughHttp() throws Exception {
        String serviceURL = "http://localhost:" + this.webcontainerPort + "/wsadd-sample/PropagationChecker";

        String invocationId = "parent/0:local/1";

        DefaultHttpClient httpclient = new DefaultHttpClient();

        HttpGet get = new HttpGet(serviceURL);
        get.setHeader("Invocation-ID", invocationId);
        HttpResponse response = httpclient.execute(get);


        // Get hold of the response entity
        HttpEntity entity = response.getEntity();

        // If the response does not enclose an entity, there is no need
        // to worry about connection release
        if (entity != null) {
            InputStream instream = entity.getContent();

            BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
            // do something useful with the response
            String line = reader.readLine();
            assertEquals(line, invocationId);

            // Closing the input stream will trigger connection release
            instream.close();

            // When HttpClient instance is no longer needed,
            // shut down the connection manager to ensure
            // immediate deallocation of all system resources
            httpclient.getConnectionManager().shutdown();

        } else {
            fail("No output for PropagateServlet, was expecting an Invocation-ID");
        }

    }

    @Test(timeOut = 11000)
    public void testNotificationReportIsSend() throws Exception {

        final QName serviceQName = new QName("http://wsadd.applis.tests.jonas.ow2.org/", "WSAddService");
        final QName portQName = new QName("http://wsadd.applis.tests.jonas.ow2.org/", "WSAddPort");
        final QName operationQName = new QName("http://wsadd.applis.tests.jonas.ow2.org/", "add");

        // Hookup a Listener
        mBeanServerConnection.addNotificationListener(endpointHandler(), new NotificationListener() {
            public void handleNotification(Notification notification, Object handback) {

                assertNotNull(notification.getMessage());
                report = ObjectEncoder.decode(notification.getMessage(), JaxwsAuditReport.class);

                assertEquals(QName.valueOf(report.getServiceQName()), serviceQName);
                assertEquals(QName.valueOf(report.getPortQName()), portQName);
                assertEquals(QName.valueOf(report.getOperationQName()), operationQName);

                ok = true;
            }
        }, null, null);

        // Call the webservice
        String serviceURL = "http://localhost:" + this.webcontainerPort + "/wsadd-sample/WSAddService";

        // Trigger the report generation
        DefaultHttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(serviceURL);
        InputStreamEntity entity = new InputStreamEntity(getClass().getResourceAsStream("../jrmp/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) {
            fail("Report was not generated after " + ((i * sleepTime) / 1000) + " seconds");
        }

    }

    private ObjectName endpointHandler() throws Exception {
        return ObjectName.getInstance("jonas:type=Auditors,auditorType=wsendpoint");
    }
}
