/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 1999-2005 Bull S.A.
 * Contact: jonas-team@objectweb.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 1any 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */

package org.objectweb.jonas.examples.clients.webservices;

import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;

import javax.wsdl.Definition;
import javax.wsdl.Port;
import javax.wsdl.Service;
import javax.wsdl.extensions.soap.SOAPAddress;
import javax.wsdl.factory.WSDLFactory;
import javax.wsdl.xml.WSDLReader;
import javax.xml.namespace.QName;

import com.meterware.httpunit.WebForm;
import com.meterware.httpunit.WebLink;
import com.meterware.httpunit.WebResponse;

/**
 * Define a class to test the webServices examples wsWarExample
 * Test WebServices deployment OK and test Call on deployed WebService
 * @author Guillaume Sauthier
 */
public abstract class A_WebServicesEndpoint extends A_WebServices {

    /**
     * property name => file1 WSDLHandler is mandatory for this test !
     */
    private static final String JPROP_WSDL_LOCATION = "jonas.service.publish.file.directory";

    public A_WebServicesEndpoint(String s, String urlPrefix) {
        super(s, urlPrefix);
    }

    public A_WebServicesEndpoint(String s, String urlPrefix, String username, String password) {
        super(s, urlPrefix, username, password);
    }

    /**
     * Check if Axis is Running
     * @param idServicesLink indicate where is the link to /services in the homepage
     * @param portName the name of the port we want to check
     * @throws Exception if an error occurs
     */
    public void checkAxisServicesAccessible(int idServicesLink, String context, String portName) throws Exception {

        WebResponse wr = wc.getResponse(url + "index.html");
        WebLink services = wr.getLinks()[idServicesLink];

        // click the link
        WebResponse swr = services.click();

        // traverse the links and find the interresting one.
        boolean found = false;
        for (int i = 0; i < swr.getLinks().length; i++) {
            String ws_url = swr.getLinks()[i].getURLString();
            if (ws_url.equalsIgnoreCase(url + context + "/" + portName + "?jwsdl"))
                found = true;
        }
        if (!found)
            fail("endpoint '" + portName + "' not found in /" + context);

    }

    /**
     * Check if WSDL is generated
     * @param idWSDLServiceLink indicate where we can find the link
     *        to WSDL of the port we want to test. (first, second, ...)
     * @throws Exception if an error occurs
     */
    public void checkAxisWSDL(String path) throws Exception {

        WebResponse wr = wc.getResponse(url + path);
        assertEquals("Must be an XML mime type", "text/xml", wr.getContentType());

    }

    /**
     * Check if deployed WebService is running
     * @param formPage the filename of the webpage containing the form
     * @param endpoint the URL where local service can be found
     * @param name the name to set as parameter
     * @param pageTitle title of the returned page
     * @throws Exception if an error occurs
     */
    public void checkDeployedWebService(String formPage,
                                        String endpoint,
                                        String name,
                                        String pageTitle) throws Exception {

        // Get the page containing the form
        WebResponse wr = wc.getResponse(url + formPage);

        // get the form named "prepare"
        WebForm form = wr.getFormWithName("prepare");
        // set all parameters
        form.setParameter("name", name);
        // submit
        WebResponse wr2 = form.submit();

        String text = wr2.getText();

        String valTitle = "<title>" + pageTitle + "</title>";
        String valURL = "Working with URL : <i>" + endpoint + "</i><br/>";
        String valHello = "<b>result of sayHello(name) method :</b><i>Hello " + name + "</i><br/>";
        String valQuotes = "<b>result of getCotes() method :</b><i>12</i><br/>";

        assertTrue("incorrect title", (text.indexOf(valTitle) != -1));
        assertTrue("incorrect URL", (text.indexOf(valURL) != -1));
        assertTrue("incorrect Name", (text.indexOf(valHello) != -1));
        assertTrue("incorrect Cotes", (text.indexOf(valQuotes) != -1));

    }


    /**
     * Check if WSDL has been published.
     * @param wsdlFilename the filename of the WSDL file
     * @param tns targetNameSpace of the Definition
     * @param serviceName the localpart of the Service QName
     * @param portName the name of the WSDL' Port
     * @param endpoint the expected URL
     * @throws Exception if an error occurs
     */
    public void checkWSDLPublication(String wsdlFilename,
                                     String tns,
                                     String serviceName,
                                     String portName,
                                     String endpoint) throws Exception {

        String jonasbase = System.getProperty("jonas.base");
        Properties props = new Properties();
        props.load(new FileInputStream(new File(jonasbase, "conf" + File.separator + "file1.properties")));
        String wsdlLoc = props.getProperty(JPROP_WSDL_LOCATION);

        File wsdl = new File(wsdlLoc, wsdlFilename);

        assertTrue("WSDL is not created", wsdl.exists());
        assertTrue("WSDL is not a file", wsdl.isFile());

        WSDLFactory f = WSDLFactory.newInstance();
        WSDLReader r = f.newWSDLReader();

        r.setFeature("javax.wsdl.verbose", true);
        r.setFeature("javax.wsdl.importDocuments", false);

        Definition def = r.readWSDL(wsdl.getPath());
        Service s = def.getService(new QName(tns, serviceName));
        Port p = s.getPort(portName);
        SOAPAddress sa = (SOAPAddress) p.getExtensibilityElements().get(0);

        assertEquals("URL has not been updated", endpoint, sa.getLocationURI());

    }


}
