/////////////////////////////////////////////////////////////////////////
//
// © Institute for Software Science, University of Vienna, 2004
//
// Copyright in this software belongs to Institute for Software Science, 
// University of Vienna, Nordbergstrasse 15/C/3, 1090 Vienna, Austria
//
// This software may not be used, sold, licensed, transferred, copied
// or reproduced in whole or in part in any manner or form or in or
// on any media by any person other than in accordance with the terms
// of the Licence Agreement supplied with the software, or otherwise
// without the prior written consent of the copyright owners.
//
// This software is distributed WITHOUT ANY WARRANTY, without even the
// implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE, except where stated in the Licence Agreement supplied with
// the software.
//
//	Created By :		Rainer Schmidt
//	Created Date :		2004/08/15
//	Created for Project:	GEMSS
//
////////////////////////////////////////////////////////////////////////
//
// Dependencies: None
//
/////////////////////////////////////////////////////////////////////////
//
//	Last commit info:	$Author: gerry $
//					$Date: 2004/08/09 15:30:05 $
//					$Revision: 1.2 $
//
/////////////////////////////////////////////////////////////////////////

package at.ac.univie.iss.proxies.qos.examples;

/**
 * Example 2/3
 * This example shows discovery and job handling. The registries defined in
 * config/registry.endpoints.config are queried against service attributes.
 * One service is then selected and a job is executed.
 * ------------------
 * JobHandling    [+] 
 * QoSNegotiation [-]
 * Discovery      [+]
 */

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.io.*;
import java.util.*;
import java.text.*;

import eu.gemss.GEMSS;
import eu.gemss.GridException;
import eu.gemss.components.ComponentManager;  
import eu.gemss.components.transport.GEMSSTransportAndMessaging; 

import eu.gemss.components.discovery.Attribute;
import eu.gemss.components.discovery.Discovery;
import eu.gemss.components.discovery.ServiceDescription;
import eu.gemss.components.discovery.DiscoveryGridException;
import eu.gemss.components.discovery.RegistryGridException;
import eu.gemss.components.ServiceRequest;
import eu.gemss.components.proxies.GEMSSProxyRequest;
import eu.gemss.components.proxies.GEMSSProxy;

import at.ac.univie.iss.proxies.qos.util.PropertiesHandler;
import at.ac.univie.iss.descriptors.qos.RequestDescriptor;
import at.ac.univie.iss.descriptors.qos.RequestDescriptorImpl;
import at.ac.univie.iss.descriptors.qos.QoSDescriptor;
import at.ac.univie.iss.descriptors.qos.QoSDescriptorImpl;


public class DiscoveryExample extends JobHandlingExample {
    
    private static Logger logger = Logger.getLogger(DiscoveryExample.class.getName());
    
    //registry service attributes
    String[] registryProperty = { "HelloWorld", "ServiceCategory" };

       
    public DiscoveryExample() {
        super();
    }   
    
    public static void main(String[] args) {
        DiscoveryExample discoveryExample = new DiscoveryExample();

        logger.log(Level.INFO, "Running discovery.");
        String[] serviceURI = discoveryExample.runDiscovery();

        if (serviceURI.length == 0) {
            
            logger.log(Level.WARNING, "No services found in registry!");
            System.exit(0);
        }

        logger.log(Level.INFO, "Running job handling.");
        discoveryExample.runJobHandling(System.currentTimeMillis()+"-myName", serviceURI[0]);
    }     
   
    final public String[] runDiscovery() {
        
        List services = null;
        
        try {
            // name-value pairs for service lookup 
            Attribute[] regAttributes = new Attribute[1];

            regAttributes[0] = new Attribute();
            regAttributes[0].setValue(registryProperty[0]);
            regAttributes[0].setName(registryProperty[1]);
    
    		// retrieving discovery component
            Discovery discovery = (Discovery) cm.getInstance("eu.gemss.components.discovery.Discovery");

			// querying registries
            services = discovery.discoverServices(regAttributes); 
            
            Iterator iter = services.iterator();
            
            // printing the List of ServiceDescriptions
            while (iter.hasNext()) {
                ServiceDescription serviceDsc = (ServiceDescription) iter.next();
                doLog(serviceDsc);
            }
            
            if (services == null || services.size() < 1) {
                logger.log(Level.WARNING, "No matching services found in registry!");
                System.exit(0);
            }
            
        } catch (DiscoveryGridException de) {
            logger.log(Level.SEVERE, "An error occured!", de);
        } catch (RegistryGridException re) {
            logger.log(Level.SEVERE, "An error occured!", re);
        }
        
        String[] listOfURIs = new String[services.size()];
        for (int count = 0; count < listOfURIs.length; count++) {
                    
            //return the wsdl endpoint of the first service in the list
            ServiceDescription serviceDsc = (ServiceDescription )services.get(count);
            listOfURIs[count] = serviceDsc.getWsdlEndpoint();
        }
        return listOfURIs;
    }

    
    private void doLog(Object o) {
        if (o instanceof ServiceDescription) {
            ServiceDescription serviceDsc = (ServiceDescription) o;
            Attribute[] attrList = serviceDsc.getAttributes();

            StringBuffer buf = new StringBuffer();
            buf.append("- Registry service description:\n");
            buf.append("  WSDL: " + serviceDsc.getWsdlEndpoint() + "\n");
            if (attrList != null) {     
                for (int i = 0; i < attrList.length; i++) {
                    buf.append("  Attribute [" + attrList[i].getName() + ", " + attrList[i].getValue() + "]\n");
                }
            }
            logger.log(Level.INFO, buf.toString());
        } 
    }
}

