// PublishTwoServices.java
//
// Generated: Mon Feb 10 12:25:36 GMT 2003
// For details see http://industry.ebi.ac.uk/soaplab
//

import org.uddi4j.*;
import org.uddi4j.client.*;
import org.uddi4j.datatype.*;
import org.uddi4j.datatype.assertion.*;
import org.uddi4j.datatype.binding.*;
import org.uddi4j.datatype.business.*;
import org.uddi4j.datatype.service.*;
import org.uddi4j.datatype.tmodel.*;
import org.uddi4j.request.*;
import org.uddi4j.response.*;
import org.uddi4j.util.*;

import java.net.URL;
import java.util.Vector;
import java.util.Hashtable;

/**
 * A class for publishing services in a UDDI registry using UDDI4J API.
 * <p>
 * For details see <a href="http://industry.ebi.ac.uk/soaplab/UserGuide.html#reg" target="_top">Soaplab documentation</a>.
 */
public class PublishTwoServices {

	// names of possible command-line parameters
	static final String USERID      = "-USERID";
	static final String PASSWORD    = "-PASSWORD";
	static final String PUBLISHURL  = "-PUBLISHURL";
	static final String INQUIRYURL  = "-INQUIRYURL";
	static final String PROVIDER    = "-PROVIDER";
	static final String TAXONOMY    = "-TAXONOMY";

	// names of service attributes
	static final String SRV_NAME         = "1";
	static final String SRV_URL          = "2";
	static final String SRV_WSDL_URL     = "3";
	static final String SRV_VERSION      = "4";
	static final String SRV_DESCRIPTION  = "5";
	static final String SRV_TYPE         = "6";
	static final String SRV_PROVIDER     = "7";

	static Hashtable knownParams;
	static Hashtable[] s = new Hashtable [1];
	static boolean unpublish = false;
	static boolean list = false;

	/**************************************************************************
	 * static initializer
	 **************************************************************************/
	static {
		knownParams = new Hashtable();
		//
		//              parameter name     default value
		//              --------------     -------------
		knownParams.put (USERID,           "testuser");
		knownParams.put (PASSWORD,         "testuser");
		knownParams.put (PUBLISHURL,       "http://localhost:8080/RegistryServer/");
		knownParams.put (INQUIRYURL,       "http://localhost:8080/RegistryServer/");
		knownParams.put (PROVIDER,         "SRDC");
		knownParams.put (TAXONOMY,         "unknown taxonomy name");
		/*knownParams.put (USERID,           "serkankirbas");
		knownParams.put (PASSWORD,         "e120320");
		knownParams.put (PUBLISHURL,       "http://harem:8080/uddi/publishing");
		knownParams.put (INQUIRYURL,       "http://harem:8080/uddi/inquiry");
		knownParams.put (PROVIDER,         "SRDC");
		knownParams.put (TAXONOMY,         "unknown taxonomy name");*/

		//
		// one hashtable (with service attributes) per service
		//
		s[0] = new Hashtable();
		s[0].put (SRV_NAME,        "NEWSERVICE");
		s[0].put (SRV_URL,         "http://localhost:8080/chdamadeus-jaxrpc/chdamadeus");
		s[0].put (SRV_WSDL_URL,    "http://localhost:8080/wsdl/amadeus.wsdl");
		s[0].put (SRV_VERSION,     "2");
		s[0].put (SRV_DESCRIPTION, "Demo");
		s[0].put (SRV_TYPE,        "Demo");

		/*s[1] = new Hashtable();
		s[1].put (SRV_NAME,        "showdb");
		s[1].put (SRV_URL,         "http://industry.ebi.ac.uk/soap/soaplab/display::showdb");
		s[1].put (SRV_WSDL_URL,    "http://industry.ebi.ac.uk/soap/soaplab/display::showdb?wsdl");
		s[1].put (SRV_VERSION,     "2.6.0");
		s[1].put (SRV_DESCRIPTION, "Displays information on the currently available databases");
		s[1].put (SRV_TYPE,        "Display, Information");*/


	}


	/*************************************************************************
	 * Return a help text...
	 *************************************************************************/
	public static String getUsage() {
		return
			"Usage:\n" +
			"   java PublishTwoServices -h[elp]\n" +
			"\n" +
			"   To publish (register) services:\n" +
			"   java PublishTwoServices [-userid <userid>] [-password <password>]\n" +
			"              [-inquiryurl <inquiry_url>] [-publishurl <publish_url>]\n" +
			"              [-provider <provider>] [-taxonomy <taxonomy>]\n" +
			"\n" +
			"   To unpublish (unregister) services:\n" +
			"   java PublishTwoServices -u[npublish]\n" +
			"              [-userid <userid>] [-password <password>]\n" +
			"              [-inquiryurl <inquiry_url>] [-publishurl <publish_url>]\n" +
			"              [-provider <provider>]\n" +
			"\n" +
			"   To list all services registrable/unregitrabvle by this class:\n" +
			"   java PublishTwoServices -l[ist]\n" +
			"\n" +
			"where:\n" +
			"   inquiry_url  ... a URL of a UDDI server for queries\n" +
			"                    (default: http://localhost:8080/inquiry)\n" +
			"   publish_url  ... a URL of a UDDI server for publishing\n" +
			"                    (default: http://localhost:8080/publish)\n" +
			"   userid       ... a user name used to connect to a UDDI server\n" +
			"                    (default: anonymous)\n" +
			"   password     ... a passord for the user above\n" +
			"                    (default: )\n" +
			"   provider     ... a name of a provider of all services\n" +
			"                    registered byte this class\n" +
			"   taxonomy     ... a name of a taxonomy used for registration\n" +
			"                    of all services byte this class\n" +
			"\n";
	}

	/**************************************************************************
	 * Read parameters from the command-line arguments, combine them with
	 * the default parameters in 'knownParams'. It changes 'knownParams'.
	 **************************************************************************/
	static public void extractParams (String[] params) {

		// first look for several no-value options
		for (int i = 0; i < params.length; i++) {
			if (params[i].equals ("-h") || params[i].equals ("-help")) {
				System.out.print (getUsage());
				System.exit (0);
			}
			if (params[i].equals ("-l") || params[i].equals ("-list")) {
				list = true;
				return;
			}
			if (params[i].equals ("-u") || params[i].equals ("-unpublish")) {
				unpublish = true;
			}
		}

		// then for all one-value parameters
		for (int i = 0; i < params.length - 1; i++) {
			String name = params[i].toUpperCase();
			if (knownParams.containsKey (name)) {
				knownParams.put (name, params [i+1]);
				i++;
			}
		}
	}

	/**************************************************************************
	 * Main entry
	 **************************************************************************/
	public static void main (String[] args) {
		try {

			System.setProperty ("hpsoap.logDirectory",".");
			System.setProperty ("hpsoap.logFileName", "uddi4j.log");
			System.setProperty ("org.uddi4j.logEnabled","true"); 

			extractParams (args);

			// just list all service names
			if (list) {
				for (int i = 0; i < 2; i++)
					System.out.println (s[i].get (SRV_NAME));
				System.exit (0);
			}

			// do the real stuff
			UDDIProxy proxy    = new UDDIProxy (new URL ((String)knownParams.get (INQUIRYURL)),
					new URL ((String)knownParams.get (PUBLISHURL)));
			AuthToken token    = proxy.get_authToken ((String)knownParams.get (USERID),
					(String)knownParams.get (PASSWORD));

			/* Check whether the business (service provider) exists in */
			/* UDDI and, if not, create one                            */

			String businessKey = ensureBusinessExists (proxy, token);

			/* Check whether the given taxonomy of services exists in */
			/* UDDI and, if not, create one                           */

			String taxonomy = ensureTaxonomyExists (proxy, token);

			System.out.println("Business:"+businessKey+" Taxonomy:"+taxonomy);

			/* Publish/Unpublish all services */
			String srvName;
			String srvVersion;
			if (unpublish) {
				for (int i = 0; i < 1; i++) {
					srvName    = (String)s[i].get (SRV_NAME);
					srvVersion = (String)s[i].get (SRV_VERSION);
					System.out.println ("Unregistering " + srvName + "_" + srvVersion);
					unpublishService (proxy, token, businessKey, srvName, srvVersion);
				}
			} else {
				for (int i = 0; i < 1; i++) {
					srvName = (String)s[i].get (SRV_NAME);
					System.out.println ("Registering " + srvName);
					publishService (proxy, token, businessKey, taxonomy, s[i]);
				}
			}
		} catch (UDDIException e) {
			DispositionReport dr = e.getDispositionReport();
			if (dr!=null) {
				System.out.println("UDDIException faultCode:" + e.getFaultCode() +
						"\n operator:" + dr.getOperator() +
						"\n generic:"  + dr.getGeneric() +
						"\n errno:"    + dr.getErrno() +
						"\n errCode:"  + dr.getErrCode() +
						"\n errInfoText:" + dr.getErrInfoText());
			}
			e.printStackTrace();

			// Catch any other exception that may occur
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	//
	public static String ensureBusinessExists (UDDIProxy proxy, AuthToken token)
		throws Exception {

			/* Find all businesses matching the service provider's name */

			FindQualifiers query      = new FindQualifiers ();
			Vector         qualifiers = new Vector();

			qualifiers.add (new FindQualifier ("exactNameMatch"));
			query.setFindQualifierVector (qualifiers);

			Vector names=new Vector();
			Name name=new Name((String)knownParams.get (PROVIDER));
			names.addElement(name);

			BusinessList  businesses = proxy.find_business (names,null,null,null, null, query, 100);

			BusinessInfos infoList = businesses.getBusinessInfos ();

			if (infoList.size () > 0) {
				return infoList.get (0).getBusinessKey ();
			}

			/* If there are no exact matches, the business (service provider) is */
			/* not registered, so create and publish the business details        */

			BusinessEntity providerEntity = new BusinessEntity ("", (String)knownParams.get (PROVIDER));
			Vector         entities       = new Vector ();

			entities.addElement (providerEntity);

			/* Extract the key from the newly published business so that we can */
			/* publish our service                                              */

			BusinessDetail providerDetails        = proxy.save_business (token.getAuthInfoString (), entities);
			Vector         businessEntities       = providerDetails.getBusinessEntityVector();
			BusinessEntity returnedBusinessEntity = (BusinessEntity) businessEntities.elementAt (0);

			return returnedBusinessEntity.getBusinessKey ();
		}



	public static String ensureTaxonomyExists (UDDIProxy proxy, AuthToken token)
		throws Exception {

			/* Find all taxonomies matching the given taxonomy */

			FindQualifiers query      = new FindQualifiers ();
			Vector         qualifiers = new Vector ();

			qualifiers.add (new FindQualifier ("exactNameMatch"));
			query.setFindQualifierVector (qualifiers);

			TModelList  models   = proxy.find_tModel ((String)knownParams.get (TAXONOMY), null, null, query, 100);
			TModelInfos infoList = models.getTModelInfos ();

			if (infoList.size () > 0) {
				return infoList.get (0).getTModelKey ();
			}

			/* If there are no exact matches, the taxonomy is not     */
			/* registered, so create and publish the business details */

			TModel taxonomyDetail = new TModel ("", (String)knownParams.get (TAXONOMY));
			Vector entities       = new Vector ();

			entities.addElement (taxonomyDetail);

			/* Extract the key from the newly published business so that we can */
			/* publish our service                                              */

			TModelDetail taxonomyDetails        = proxy.save_tModel (token.getAuthInfoString (), entities);
			Vector       tModelEntities         = taxonomyDetails.getTModelVector();
			TModel       returnedTModelEntity = (TModel) tModelEntities.elementAt (0);

			return returnedTModelEntity.getTModelKey ();
		}


	//
	public static void publishService (UDDIProxy proxy, AuthToken token, String businessKey, String taxonomy, Hashtable attrs)
		throws Exception {


			/* If service is already published, don't publish again */

			FindQualifiers query      = new FindQualifiers ();
			Vector         qualifiers = new Vector();

			qualifiers.add (new FindQualifier ("exactNameMatch"));
			query.setFindQualifierVector (qualifiers);

			Vector names=new Vector();
			Name name=new Name((String)attrs.get (SRV_NAME) + "_" + (String)attrs.get (SRV_VERSION));
			names.addElement(name);

			ServiceList  servicesList = proxy.find_service (businessKey, names, null, null, query, 100);
			ServiceInfos infoList = servicesList.getServiceInfos ();

			if (infoList.size () > 0) {
				return;
			}

			/* Construct a service description */

			BusinessService businessService = new BusinessService  ();

			businessService.setBusinessKey (businessKey);
			businessService.setServiceKey ("");
			name=new Name((String)attrs.get(SRV_NAME)+"_" +(String)attrs.get(SRV_VERSION));
			businessService.setDefaultName(name);

			TModelInstanceDetails bindingTModels  = new TModelInstanceDetails ();
			AccessPoint           accessURL       = new AccessPoint ((String)attrs.get (SRV_URL), "http");
			TModelInstanceInfo    interfaceInfo   = new TModelInstanceInfo ();
			InstanceDetails       interfaceDetail = new InstanceDetails ();
			OverviewDoc           overviewWSDL    = new OverviewDoc ();

			overviewWSDL.   setOverviewURL     ((String)attrs.get (SRV_WSDL_URL));
			interfaceDetail.setOverviewDoc     (overviewWSDL);
			interfaceInfo.  setInstanceDetails (interfaceDetail);
			interfaceInfo.setTModelKey(taxonomy);
			bindingTModels. add                (interfaceInfo);

			BindingTemplates bindings        = new BindingTemplates ();
			BindingTemplate  endpointBinding = new BindingTemplate  ("", bindingTModels);

			endpointBinding.setAccessPoint      (accessURL);
			bindings.       add                 (endpointBinding);
			businessService.setBindingTemplates (bindings);

			CategoryBag    classifications = new CategoryBag ();
			KeyedReference category     = new KeyedReference ("Type", (String)attrs.get (SRV_TYPE), taxonomy);

			classifications.add                         (category);
			businessService.setCategoryBag              (classifications);
			businessService.setDefaultDescriptionString ((String)attrs.get (SRV_DESCRIPTION));

			/* Publish service */

			Vector services = new Vector ();
			services.addElement (businessService);
			System.out.println(token.getAuthInfoString ()+" "+name.getText()+" "+businessKey);
			proxy.save_service (token.getAuthInfoString (), services);
		}

	//
	public static void unpublishService (UDDIProxy proxy, AuthToken token, String businessKey,
			String serviceName, String serviceVersion)
		throws Exception {

			/* Find all services belonging to this provider and matching the service name */

			FindQualifiers query      = new FindQualifiers ();
			Vector         qualifiers = new Vector();

			qualifiers.add (new FindQualifier ("exactNameMatch"));
			query.setFindQualifierVector (qualifiers);
			Vector names=new Vector();
			Name name=new Name(serviceName + "_" + serviceVersion);
			names.addElement(name);

			ServiceList  services = proxy.find_service (businessKey, names, null, null, query, 100);
			ServiceInfos infoList = services.getServiceInfos ();

			/* If there are no services of this name, then there is nothing to unpublish */

			if (infoList.size () == 0) {
				return;
			}

			/* If there is one, delete it */

			String serviceKey = infoList.get (0).getServiceKey ();

			proxy.delete_service (token.getAuthInfoString (), serviceKey);
		}
}
