FileDocCategorySizeDatePackage
RegistrySetup.javaAPI DocExample25421Mon Mar 10 00:24:52 GMT 2003ora.jwsnut.chapter7.setup

RegistrySetup.java

package ora.jwsnut.chapter7.setup;

import java.net.PasswordAuthentication;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.security.auth.x500.X500PrivateCredential;
import javax.xml.registry.BulkResponse;
import javax.xml.registry.BusinessLifeCycleManager;
import javax.xml.registry.BusinessQueryManager;
import javax.xml.registry.Connection;
import javax.xml.registry.ConnectionFactory;
import javax.xml.registry.JAXRException;
import javax.xml.registry.RegistryService;
import javax.xml.registry.infomodel.Association;
import javax.xml.registry.infomodel.Classification;
import javax.xml.registry.infomodel.ClassificationScheme;
import javax.xml.registry.infomodel.Concept;
import javax.xml.registry.infomodel.EmailAddress;
import javax.xml.registry.infomodel.ExternalLink;
import javax.xml.registry.infomodel.ExtrinsicObject;
import javax.xml.registry.infomodel.Key;
import javax.xml.registry.infomodel.Organization;
import javax.xml.registry.infomodel.PersonName;
import javax.xml.registry.infomodel.PostalAddress;
import javax.xml.registry.infomodel.RegistryObject;
import javax.xml.registry.infomodel.Service;
import javax.xml.registry.infomodel.ServiceBinding;
import javax.xml.registry.infomodel.SpecificationLink;
import javax.xml.registry.infomodel.TelephoneNumber;
import javax.xml.registry.infomodel.User;
import ora.jwsnut.chapter7.util.Utils;

// Installs test data in or removes test data from the registry
public class RegistrySetup {

    // The BusinessQueryManager
    private static BusinessQueryManager bqm;
    
    // The BusinessLifeCycleManager
    private static BusinessLifeCycleManager blcm;

    // true if connected to Internet
    private static boolean connected;
    
    public static void main(String[] args) {
        
        boolean install = false;
        boolean isUddi = false;
        HashSet credentials = new HashSet();
        String authMethod = null;
        
        // Figure out whether we are connected to the Internet
        String value = System.getProperty("jwsnutExamples.connected");
        connected = value != null && value.equalsIgnoreCase("true");

        // Validate arguments
        if (args.length == 0) {
            usage();
        }
        String registryType = args[0];
        int index = -1;
     
        if (registryType.equals("-uddi")) {
            if (args.length != 6) {
                usage();
            }
            
            // UDDI registry uses username/password for authentication
            isUddi = true;
            index = 3;
            authMethod = "UDDI_GET_AUTHTOKEN";
            String user = args[1];
            String password = args[2];
            PasswordAuthentication auth = 
                        new PasswordAuthentication(user, password.toCharArray());
            credentials.add(auth);            
        } else if (registryType.equals("-ebxml")) {
            if (args.length != 8) {
                usage();
            }
            
            // ebXML registry requires a certificate
            index = 5;
            authMethod = "CLIENT_CERTIFICATE";
            String keyStoreName = args[1];
            String keyStoreAlias = args[2];
            String keyStorePwd = args[3];
		String keyPwd = args[4];
            try {
                X500PrivateCredential cred = Utils.getCredentials(keyStoreName, keyStoreAlias, 
                                                                  keyPwd, keyStorePwd);
                credentials.add(cred);
            } catch (Throwable t) {
                System.out.println("Failed when getting certificate");
                t.printStackTrace(System.out);
                System.exit(1);
            }
        } else {
            usage();
        }
        
        // Process the common arguments
        String queryURL = args[index];
        String lifecycleURL = args[index + 1];
        String operation = args[index + 2];
        if (operation.equals("install")) {
            install = true;
        } else if (!operation.equals("delete")) {
            usage();
        }        
        
        try {
            // Get the ConnectionFactory
            Properties props = new Properties();
            props.put("javax.xml.registry.queryManagerURL", queryURL);
            props.put("javax.xml.registry.lifeCycleManagerURL", lifecycleURL);
            props.put("javax.xml.registry.security.authenticationMethod", authMethod);
            
            // Use the JAXR default postal address mapping scheme
            if (isUddi) {
                props.setProperty("javax.xml.registry.postalAddressScheme", 
                                    "PostalAddressAttributes");
                props.setProperty("javax.xml.registry.semanticEquivalences",
                  "urn:uuid:PostalAddressAttributes/StreetNumber," +
                  "urn:uuid:PostalAddressAttributes/StreetNumber|" +
                  "urn:uuid:PostalAddressAttributes/Street," +
                  "urn:uuid:PostalAddressAttributes/Street|" +
                  "urn:uuid:PostalAddressAttributes/City," +
                  "urn:uuid:PostalAddressAttributes/City|" +
                  "urn:uuid:PostalAddressAttributes/State," +
                  "urn:uuid:PostalAddressAttributes/State|" +
                  "urn:uuid:PostalAddressAttributes/PostalCode," +
                  "urn:uuid:PostalAddressAttributes/PostalCode|" +
                  "urn:uuid:PostalAddressAttributes/Country," +
                  "urn:uuid:PostalAddressAttributes/Country");
            }
            
            ConnectionFactory cf = ConnectionFactory.newInstance();
            cf.setProperties(props);
            
            // Get and initialize the connection
            Connection conn = cf.createConnection();
            conn.setCredentials(credentials);
            conn.setSynchronous(true);
            
            // Get the RegistryService and the managers
            RegistryService registry = conn.getRegistryService();
            bqm = registry.getBusinessQueryManager();            
            blcm = registry.getBusinessLifeCycleManager();

            // Perform the requested action
            if (install) {
                System.out.println("Installing registry data");
                if (installRegistryObjects()) {
                    installCustomEnumeration(isUddi);
                }
            } else {
                System.out.println("Removing registry data");
                deleteRegistryObjects();
                deleteCustomEnumeration(isUddi);
            }
            System.out.println("Finished");
            
            // Close connection
            conn.close();           
            
        } catch (Throwable t) {
            System.out.println(t);
            t.printStackTrace(System.out);
            System.exit(1);
        }    
        
        System.exit(0);
    }
    
    // Installs the required registry objects
    private static boolean installRegistryObjects() throws Throwable {
        // ArrayLists used when Collections are required
        ArrayList list = new ArrayList();
        
        // First check whether the setup has already been done
        list.add("OReilly & Associates, Inc");
        BulkResponse res = bqm.findOrganizations(null, list, null, null, null, null);
        if (!res.getCollection().isEmpty()) {
            System.out.println("Data already installed");
            return false;
        }
        list.clear();
        
        // Create the organizations        
        // Create O'Reilly and Associates and set the
        // telephone number and external link to the home page.
        Organization ora = blcm.createOrganization(
                        blcm.createInternationalString("OReilly & Associates, Inc"));
        ora.setDescription(blcm.createInternationalString("Book Publisher"));
        TelephoneNumber number = blcm.createTelephoneNumber();
        number.setNumber("(+1)800-998-9938");
        list.add(number);
        ora.setTelephoneNumbers(list);
        list.clear();  

        ExternalLink eLink;
        if (connected) {        
            eLink = blcm.createExternalLink("http://www.oreilly.com",
                                            "OReilly & Associates home page");
            eLink.setValidateURI(connected);
            list.add(eLink);
            ora.setExternalLinks(list);
            list.clear();
        }
        
        // Create the O'Reilly submitting user and include the address,
        // phone number and e-mail
        User user = blcm.createUser();
        PersonName personName = blcm.createPersonName("OReilly Corporate");
        user.setPersonName(personName);
        user.setDescription(blcm.createInternationalString("OReilly corporate contact"));
        PostalAddress address = blcm.createPostalAddress(
                            "1005", "Gravenstein Highway North", "Sebastopol",
                            "CA", "USA", "95472", "Headquarters");
        list.add(address);
        user.setPostalAddresses(list);
        list.clear();

        EmailAddress email = blcm.createEmailAddress("corporate@oreilly.com");
        list.add(email);
        user.setEmailAddresses(list);
        list.clear();

        list.add(number);
        user.setTelephoneNumbers(list);
        list.clear();
        
        // Install the primary contact for O'Reilly
        ora.setPrimaryContact(user);
        
        // Create Keyboard Edge Limited.
        Organization kbedge = blcm.createOrganization(
                        blcm.createInternationalString("Keyboard Edge Limited"));
        kbedge.setDescription(
            blcm.createInternationalString("Software consultancy and technical writing"));
        number = blcm.createTelephoneNumber();
        number.setNumber("(+44)123-456789");
        list.add(number);
        kbedge.setTelephoneNumbers(list);
        list.clear();
        
        // Create the Keyboard Edge Ltd submitting user and include the address
        user = blcm.createUser();
        personName = blcm.createPersonName("Kim Topley");
        user.setDescription(blcm.createInternationalString("Keyboard Edge Limited primary contact"));        
        user.setPersonName(personName);
        address = blcm.createPostalAddress(
                            "99", "Imaginary Road", "Some City",
                            "Berkshire", "GB", "RG99 9ZZ", "Headquarters");
        list.add(address);
        user.setPostalAddresses(list);
        list.clear();
                
        email = blcm.createEmailAddress("info@topley.demon.co.uk");
        list.add(email);
        user.setEmailAddresses(list);
        list.clear();

        list.add(number);
        user.setTelephoneNumbers(list);
        list.clear();
        
        // Install the primary contact for Keyboard Edge Limited
        kbedge.setPrimaryContact(user);

        // Create an entry for Amazon.com
        Organization amazon = blcm.createOrganization(
                        blcm.createInternationalString("Amazon.com"));
        amazon.setDescription(
            blcm.createInternationalString("Amazon.com e-commerce web services"));
        number = blcm.createTelephoneNumber();
        number.setNumber("206-266-2335");
        list.add(number);
        amazon.setTelephoneNumbers(list);
        list.clear();
        
        if (connected) {
            eLink = blcm.createExternalLink("http://www.amazon.com",
                                            "Amazon.com home page");
            eLink.setValidateURI(connected);
            list.add(eLink);
            amazon.setExternalLinks(list);
            list.clear();
        }

        // Create the Amazon submitting user 
        user = blcm.createUser();
        personName = blcm.createPersonName("Amazon.com Corporate");
        user.setDescription(blcm.createInternationalString("Amazon.com primary contact"));        
        user.setPersonName(personName);
        address = blcm.createPostalAddress(
                            "1200", "12th Avenue South", "Seattle",
                            "Washington", "US", "98144", "Headquarters");
        list.add(address);
        user.setPostalAddresses(list);
        list.clear();

        list.add(number);
        user.setTelephoneNumbers(list);
        list.clear();        
                
        email = blcm.createEmailAddress("info@amazon.com");
        list.add(email);
        user.setEmailAddresses(list);
        list.clear();
        
        // Install the primary contact for Amazon.com
        amazon.setPrimaryContact(user);        
        
        // Create a Service entry
        Service service = blcm.createService("Amazon web service");
        service.setName(blcm.createInternationalString("Amazon web service"));
        service.setDescription(
                blcm.createInternationalString("Web services that allow developers to create" +
                                                " applications that consume Amazon.com core features"));
        
        // Add a ServiceBinding
        ServiceBinding binding = blcm.createServiceBinding();
        binding.setName(blcm.createInternationalString("Amazon service binding"));
        binding.setDescription(blcm.createInternationalString("Access to Amazon web services"));
        binding.setValidateURI(connected);
        binding.setAccessURI("http://soap.amazon.com/onca/soap");
        
        // Set up a SpecificationLink
        ClassificationScheme uddiTypes = bqm.findClassificationSchemeByName(null, "uddi-org:types");
        RegistryObject specObject = null;
        if (uddiTypes != null) {
            // This is a UDDI registry
            Concept sConcept = blcm.createConcept(null, "AmazonWSDL", "AmazonWSDL");
            if (connected) {
                eLink = blcm.createExternalLink("http://soap.amazon.com/schemas/AmazonWebServices.wsdl", 
                                                "WSDL Specification");
                eLink.setValidateURI(connected);
                sConcept.addExternalLink(eLink);
            }

            Classification wsdlClass = blcm.createClassification(uddiTypes, "wsdlSpec", "wsdlSpec");
            sConcept.addClassification(wsdlClass);
            list.add(sConcept);
            res = blcm.saveConcepts(list);
            list.clear();
            Collection coll = res.getCollection();
            sConcept.setKey((Key)coll.iterator().next());
            specObject = sConcept;
        } else {
            // This is an ebXML registry. Add an ExtrinsicObject,
            // but only if we are connected to the Internet
            if (connected) {
                ExtrinsicObject eObj = blcm.createExtrinsicObject(
                    new DataHandler(new URL("http://soap.amazon.com/schemas/AmazonWebServices.wsdl")));
                specObject = eObj;
            }
        }
        if (specObject != null) {
            SpecificationLink sLink = blcm.createSpecificationLink();
            sLink.setName(blcm.createInternationalString("WSDL specification"));    
            sLink.setUsageDescription(sLink.getName());
            sLink.setSpecificationObject(specObject);
            binding.addSpecificationLink(sLink);
        }

        // Add the binding to the service and
        // the service to the organization
        list.add(binding);
        service.addServiceBindings(list);
        list.clear();
        amazon.addService(service);
        
        // Apply standard classifications to each organization
        ClassificationScheme naics = bqm.findClassificationSchemeByName(null, "%naics%");
        if (naics == null) {
            naics = bqm.findClassificationSchemeByName(null, "%NAICS%");
            if (naics == null) {
                System.out.println("COULD NOT FIND NAICS CLASSIFICATION SCHEME.");
                System.exit(1);
            }
        }
        ClassificationScheme isocs = bqm.findClassificationSchemeByName(null, "%iso%");
        if (isocs == null) {
            isocs = bqm.findClassificationSchemeByName(null, "%ISO%");
            if (isocs == null) {
                System.out.println("COULD NOT FIND ISO CLASSIFICATION SCHEME.");
                System.exit(1);
            }
        }
      
        // O'Reilly & Associates
        ArrayList oraClass = new ArrayList();
        oraClass.add(blcm.createClassification(naics, "Book Publishers", "51113"));        
        oraClass.add(blcm.createClassification(isocs, "United States", "US"));
        ora.addClassifications(oraClass);
        
        // Keyboard Edge Limited
        ArrayList kbedgeClass = new ArrayList();
        kbedgeClass.add(blcm.createClassification(naics, "Custom Computer Programming Services", "541511"));
        kbedgeClass.add(blcm.createClassification(isocs, "United Kingdom", "GB"));
        kbedge.addClassifications(kbedgeClass);
        
        // Amazon.com
        ArrayList amazonClass = new ArrayList();
        amazonClass.add(blcm.createClassification(naics, "Book, Periodical, and Music Stores", "4512"));
        amazonClass.add(blcm.createClassification(isocs, "United States", "US"));
        amazon.addClassifications(amazonClass);        
        
        // Save everything
        ArrayList orgs = new ArrayList();
        orgs.add(ora);
        orgs.add(kbedge);
        orgs.add(amazon);
        res = blcm.saveOrganizations(orgs);

        Collection exceptions = res.getExceptions();
        if (exceptions != null && !exceptions.isEmpty()){
            System.out.println("Error while saving organizations");
            Iterator iter = exceptions.iterator();
            while (iter.hasNext()) {
                ((Exception)iter.next()).printStackTrace(System.out);
            }
        }
        
        // ebXML registry (currently) does not save referenced services!
        if (uddiTypes == null) {
            list.add(service);
            res = blcm.saveServices(list);
            exceptions = res.getExceptions();
            if (exceptions != null && !exceptions.isEmpty()){
                System.out.println("Error while saving services");
                Iterator iter = exceptions.iterator();
                while (iter.hasNext()) {
                    ((Exception)iter.next()).printStackTrace(System.out);
                }
            }
        }
        
        return true;
    }
    
    // Deletes the registry objects
    private static void deleteRegistryObjects() throws Throwable { 
        ArrayList list = new ArrayList();
        
        // Remove the organizations and their services and service bindings
        list.add("OReilly & Associates, Inc");
        list.add("Keyboard Edge Limited");
        list.add("Amazon.com");
        list.add("Another Organization"); // Added by PostalAddress example
        BulkResponse res = bqm.findOrganizations(null, list, null, null, null, null);
        list.clear();
        Collection coll = res.getCollection();
        if (!coll.isEmpty()) {            
            Iterator iter = coll.iterator();
            while (iter.hasNext()) {
                Organization org = (Organization)iter.next();
                list.add(org.getKey());
                
                // Delete associations 
                res = bqm.findAssociations(null, org.getKey().getId(), null, null);
                Iterator aIter = res.getCollection().iterator();
                if (!res.getCollection().isEmpty()) {
                    ArrayList aList = new ArrayList();
                    while (aIter.hasNext()) {
                        Object o = aIter.next();
                        if (o instanceof Association) {
                            aList.add(((Association)o).getKey());
                        }
                    }
                    if (!aList.isEmpty()) {
                        blcm.deleteAssociations(aList);
                    }
                }                
                
                // Get all of the services for this organization
                // and delete them.
                coll = org.getServices();
                if (!coll.isEmpty()) {
                    ArrayList serviceList = new ArrayList();
                    Iterator sIter = coll.iterator();
                    while (sIter.hasNext()) {
                        Service svc = (Service)sIter.next();
                        serviceList.add(svc.getKey());
                        
                        // Delete the bindings for this service
                        coll = svc.getServiceBindings();
                        if (!coll.isEmpty()) {
                            ArrayList bindingList = new ArrayList();
                            Iterator bIter = coll.iterator();
                            while (bIter.hasNext()) {
                                bindingList.add(((ServiceBinding)bIter.next()).getKey());
                            }
                            blcm.deleteServiceBindings(bindingList);
                        }
                    }
                    blcm.deleteServices(serviceList);                    
                }              
            }
            blcm.deleteOrganizations(list);
            list.clear();
        }

        // Remove the Concept created for the Amazon WSDL specification
        list.add("AmazonWSDL");
        res = bqm.findConcepts(null, list, null, null, null);
        list.clear();
        coll = res.getCollection();
        if (!coll.isEmpty()) {            
            Iterator iter = coll.iterator();
            while (iter.hasNext()) {
                Concept cpt = (Concept)iter.next();
                list.add(cpt.getKey());
            }
            blcm.deleteConcepts(list);
            list.clear();
        }
    }
    
    // Installs a user-defined enumeration 
    private static void installCustomEnumeration(boolean isUddi) throws JAXRException {
        if (bqm.findClassificationSchemeByName(null, "TestEnum") == null) {
            ClassificationScheme scheme = blcm.createClassificationScheme("TestEnum", "Custom Enumeration");
            if (!isUddi) {
                scheme.setValueType(ClassificationScheme.VALUE_TYPE_UNIQUE);
            }
            ArrayList list = new ArrayList();
            
            // Only install the Concepts if not UDDI.
            // For UDDI, the scheme is defined in a local file.
            if (!isUddi) {
                list.add(blcm.createConcept(scheme, "Value 1", "1"));
                list.add(blcm.createConcept(scheme, "Value 2", "2"));
                list.add(blcm.createConcept(scheme, "Value 3", "3"));
                list.add(blcm.createConcept(scheme, "Value 4", "4"));
                scheme.addChildConcepts(list);
                blcm.saveConcepts(list);
                list.clear();
            }
            
            // Save the ClassificationScheme
            list.add(scheme);
            blcm.saveClassificationSchemes(list);
        }        
    }
    
    // Removes the user-defined enumeration
    private static void deleteCustomEnumeration(boolean isUddi) throws JAXRException {
        ClassificationScheme scheme = bqm.findClassificationSchemeByName(null, "TestEnum");
        if (scheme != null) {
            ArrayList list = new ArrayList();
            Iterator iter;
            Collection coll;
            BulkResponse res;
            
            if (!isUddi) {
                coll = scheme.getDescendantConcepts();
                iter = coll.iterator();
                while (iter.hasNext()) {
                    list.add(((Concept)iter.next()).getKey());
                }
                res = blcm.deleteConcepts(list);
                coll = res.getExceptions();
                if (coll != null) {
                    iter = coll.iterator();
                    while (iter.hasNext()) {
                        System.out.println(iter.next());
                    }
                }
                list.clear();
            }
            
            list.add(scheme.getKey());
            res = blcm.deleteClassificationSchemes(list); 
            coll = res.getExceptions();
            if (coll != null) {
                iter = coll.iterator();
                while (iter.hasNext()) {
                    System.out.println(iter.next());
                }
            }
        }
    }
    
    private static void usage() {
        System.out.println("Usage:\tRegistrySetup -uddi username password queryURL uppdateURL install|delete");
        System.out.println("Usage:\tRegistrySetup -ebxml keystore alias storepwd keypwd queryURL uppdateURL install|delete");        
        System.exit(1);
    }
}