/*
 * JBoss, the OpenSource J2EE webOS
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package org.jboss.webservice.server;

// $Id: PortComponentLinkServlet.java,v 1.3.4.1 2004/11/16 11:42:23 tdiesler Exp $

import org.jboss.logging.Logger;
import org.jboss.mx.util.MBeanServerLocator;
import org.jboss.webservice.AxisServiceMBean;
import org.jboss.webservice.PortComponentInfo;

import javax.management.MBeanServer;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * A servlet that reports the serviceURL for a given service ID.
 * <p/>
 * See {@link org.jboss.webservice.AxisService} for details on the registry of
 * {@link PortComponentInfo} objects.
 * <p/>
 * When the web service client ENC is setup, it may contain port-component-link
 * entries that point to service endpoints in the same top level deployment.
 * The final serviceURL of those endpoints will become available after the
 * reference to the javax.xml.rpc.Service is bound to JNDI.
 * <p/>
 * When the client does a lookup of the javax.xml.rpc.Service from JNDI the ObjectFactory
 * will contact this servlet for the final serviceURL. It is acceptable that the client
 * wsdl does not contain the correct serviceURL if the client is using the port-component-link element.
 *
 * @author Thomas.Diesler@jboss.org
 * @since 29-May-2004
 */
public class PortComponentLinkServlet extends HttpServlet
{
   // provide logging
   private static final Logger log = Logger.getLogger(PortComponentLinkServlet.class);

   /**
    * Get the serviceURL as string for a given serviceID.
    */
   protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
   {
      String serviceID = req.getParameter("serviceID");
      if (serviceID == null)
         throw new IllegalArgumentException("Cannot obtain request parameter 'serviceID'");

      PortComponentInfo pcInfo = null;
      try
      {
         MBeanServer server = MBeanServerLocator.locateJBoss();
         pcInfo = (PortComponentInfo)server.invoke(AxisServiceMBean.OBJECT_NAME, "getPortComponentInfo",
                 new Object[]{serviceID}, new String[]{String.class.getName()});
      }
      catch (Exception e)
      {
         throw new ServletException(e);
      }

      if (pcInfo == null)
         throw new IllegalStateException("Cannot resolve port-component-link: " + serviceID);

      res.setContentType("text/plain");
      PrintWriter out = res.getWriter();

      String serviceEndpointURL = pcInfo.getServiceEndpointURL();
      out.println(serviceEndpointURL);

      log.debug("Resolved " + serviceID + " to: " + serviceEndpointURL);

      out.close();
   }
}
