/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2004-2005 Bull S.A.
 * 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 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 * --------------------------------------------------------------------------
 * $Id: JAxisServlet.java 15428 2008-10-07 11:20:29Z sauthieg $
 * --------------------------------------------------------------------------
 */
package org.ow2.jonas.ws.axis;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.namespace.QName;

import org.ow2.jonas.deployment.ws.PortComponentDesc;
import org.ow2.jonas.deployment.ws.WSDeploymentDescException;

import org.apache.axis.AxisEngine;
import org.apache.axis.AxisFault;
import org.apache.axis.ConfigurationException;
import org.apache.axis.description.OperationDesc;
import org.apache.axis.description.ServiceDesc;
import org.apache.axis.server.AxisServer;
import org.apache.axis.transport.http.AxisServlet;


/**
 * JOnAS AxisServlet version.
 * When displaying the port list, This class set the right URL.
 * @author Guillaume Sauthier
 */
public class JAxisServlet extends AxisServlet {

    /**
     * Serial Version UID.
     */
    private static final long serialVersionUID = 8738737484808995721L;

    /**
     * This method lists the available services; it is called when there is
     * nothing to execute on a GET
     * @param response HTTP response
     * @param writer writer
     * @param request HTTP request
     * @throws ConfigurationException cannot find axis WSDDConfiguration
     * @throws AxisFault cannot find endpoint URL
     */
    protected void reportAvailableServices(HttpServletResponse response,
                                           PrintWriter writer,
                                           HttpServletRequest request) throws
            ConfigurationException, AxisFault {
        AxisEngine engine = getEngine();

        response.setContentType("text/html; charset=utf-8");
        writer.println("<h2>And now... Some Services</h2>");

        Iterator i;
        try {
            i = engine.getConfig().getDeployedServices();
        } catch (ConfigurationException configException) {
            //turn any internal configuration exceptions back into axis faults
            //if that is what they are
            if (configException.getContainedException() instanceof AxisFault) {
                throw (AxisFault) configException.getContainedException();
            } else {
                throw configException;
            }
        }

        // Before calling  super method, add the WSDL in ServletContext
        InitialContext iCtx;
        AxisServer axisServer = getEngine();
        org.ow2.jonas.deployment.ws.ServiceDesc serviceDesc = null;
        try {
            iCtx = new InitialContext();
            serviceDesc = (org.ow2.jonas.deployment.ws.ServiceDesc) iCtx.lookup("java:comp/jonas/" + axisServer.getName() + "/dd");
        } catch (NamingException e) {
            log.debug("Cannot find ServiceDesc in context 'java:comp/jonas/" + axisServer.getName() + "/dd'", e);
            throw new AxisFault("Servlet name not found : " + axisServer.getName(), e);
        }

        writer.println("<ul>");
        while (i.hasNext()) {
            ServiceDesc sd = (ServiceDesc) i.next();
            StringBuffer sb = new StringBuffer();
            sb.append("<li>");
            String name = sd.getName();
            sb.append(name);
            sb.append(" <a href=\"");
            String endpointURL = null;
            QName portName = getWsdlPortName(serviceDesc, name);
            try {
                endpointURL = serviceDesc.getWSDL().getLocation(portName).toExternalForm();
            } catch (WSDeploymentDescException e) {
                throw new AxisFault("Cannot find endpoint URL for server " + axisServer.getName() + " and port " + name, e);
            }
            sb.append(endpointURL);
            sb.append("?jwsdl\"><i>(wsdl)</i></a></li>");
            writer.println(sb.toString());
            ArrayList operations = sd.getOperations();
            if (!operations.isEmpty()) {
                writer.println("<ul>");
                for (Iterator it = operations.iterator(); it.hasNext();) {
                    OperationDesc desc = (OperationDesc) it.next();
                    writer.println("<li>" + desc.getName());
                }
                writer.println("</ul>");
            }
        }
        writer.println("</ul>");
    }

    /**
     * @param serviceDesc JOnAS ServiceDesc
     * @param axisServiceName the axis service name is linked to the J2EE port-component name
     * @return Returns the wsdl:port name
     */
    private QName getWsdlPortName(org.ow2.jonas.deployment.ws.ServiceDesc serviceDesc, String axisServiceName) {
        QName wsdlPortName = null;
        for (Iterator p = serviceDesc.getPortComponents().iterator(); p.hasNext() || wsdlPortName == null;) {
            PortComponentDesc pcd = (PortComponentDesc) p.next();
            if (axisServiceName.equals(pcd.getServiceName())) {
                wsdlPortName = pcd.getQName();
            }
        }
        return wsdlPortName;
    }

}