/**
 * (c) Microsoft Corporation.  All rights reserved
 */
package org.ogf.hpcbp;

import org.ggf.schemas.bes._2006._08.bes_factory.*;
import org.ggf.schemas.bes._2006._08.bes_factory.HPCBPServiceStub.*;
import java.io.*;
import org.apache.axis2.context.*;
import javax.xml.stream.*;
import org.apache.axiom.om.OMElement;

//import org.apache.log4j.*;

public class Client {
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// Set up the environment for the SSL verificaton
		System.setProperty("javax.net.ssl.trustStore",".\\castore");
		System.setProperty("javax.net.ssl.keyStorePassword","trustnoone");
		System.setProperty("javax.net.ssl.trustStoreType", "JKS");
		
		// Set up the basic log4j configuration - useful for debugging
		//BasicConfigurator.configure();
		
        if (args.length != 4)
        {
        	System.out.println("HPCBPClient [service URL] [JSDL job file] [username] [password]");
        	return;
        }
    
        String serviceUrl = args[0];
        String jsdlFileName = args[1];
        String userName = args[2];
        String password = args[3];

        System.out.println("Contacting:"+serviceUrl);
        System.out.println("Sending JSDL:"+jsdlFileName);
        
        try
        {
        	Client hpcbp = new Client(serviceUrl, userName, password);

        	EndpointReferenceType[] eprs = new EndpointReferenceType[1];

		    // Generate the HPCBP acitivty from a supplied JSDL file
        	eprs[0] = hpcbp.CreateActivity(jsdlFileName);

		    // Generate the HPCBP acitivty from Axis2 generated JSDL objects
       		eprs[1] = hpcbp.CreateActivity(Client.CreateJSDLDocument("ipconfig",null));

            if (eprs[0] == null)
            {
               System.out.println("There was a problem creating the activity on the HPCBP web service.");
               return;
            }

            ReferenceParametersType rps = eprs[0].getReferenceParameters();
            OMElement[] elements = rps.getExtraElement();
            for (int i=0;i<elements.length;i++)
            {
                System.out.println(elements[i].toString());
            }

        	GetActivityStatusResponseType[] status = null;
        	do
        	{
        		status = hpcbp.GetActivityStatuses(eprs);
        		System.out.println(status[0].getActivityStatus().getState().toString());
        	} while (status[0].getActivityStatus().getState() == ActivityStateEnumeration.Pending || status[0].getActivityStatus().getState() == ActivityStateEnumeration.Running);
        }
        catch (Exception ex)
        {
			System.out.println(ex);
        }
        
	}
	
    public static JobDefinition_Type CreateJSDLDocument(String command, String host)
    {
		// Use the get/set from the auto generated object model generated by Axis
	
		JobDefinition_Type jobDefinition = new JobDefinition_Type();
    	JobDescription_Type jobDescription= new JobDescription_Type();
    	Application_Type application = new Application_Type();
    	HPCProfileApplication_Type hpcApplication = new HPCProfileApplication_Type();
    	FileName_Type executable = new FileName_Type();
    	executable.setString("ipconfig");
    	hpcApplication.setExecutable(executable);
    	application.setHPCProfileApplication(hpcApplication);

        if (host != null)
        {
			Resources_Type resources = new Resources_Type();
    		CandidateHosts_Type hosts = new CandidateHosts_Type();
    		String [] hostname = new String[1];
    		hostname[0] = host;
    		hosts.setHostName(hostname);
    		resources.setCandidateHosts(hosts);
    		jobDescription.setResources(resources);
		}

    	jobDescription.setApplication(application);
    	jobDefinition.setJobDescription(jobDescription);

		return jobDefinition;
 	}
 

	private HPCBPServiceStub _proxy;
	
	static public String WSSUsername;
	static public String WSSPassword;
	
	public Client(String serviceURL,String username,String password) throws Exception
	{
		// Create the proxy to the HPCBP service
		String confFile = "conf" + System.getProperty("file.separator") + "axis2.xml";
		ConfigurationContext config = ConfigurationContextFactory.createConfigurationContextFromFileSystem(".", confFile);
		_proxy = new HPCBPServiceStub(config,serviceURL);
		Client.WSSUsername = username;
		Client.WSSPassword = password;
        _proxy._getServiceClient().engageModule("rampart");
	}
        
	public EndpointReferenceType CreateActivity(JobDefinition_Type jobDefinitionType) throws Exception 
	{
    	return SendCreateActivityMessage(jobDefinitionType);
	}


	public EndpointReferenceType CreateActivity(String fileName) throws Exception
	{
		XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(new FileInputStream(fileName));
		JobDefinition_Type jobDefinitionType = JobDefinition_Type.Factory.parse(reader);
		
    	return SendCreateActivityMessage(jobDefinitionType);
 	}

    private EndpointReferenceType SendCreateActivityMessage(JobDefinition_Type jobDefinitionType)
    {
    	
    	ActivityDocumentType activityDocumentType = new ActivityDocumentType();
    	activityDocumentType.setJobDefinition(jobDefinitionType);
    	CreateActivityType createActivityType = new CreateActivityType();
    	createActivityType.setActivityDocument(activityDocumentType);
    	CreateActivity activity = new CreateActivity();
    	activity.setCreateActivity(createActivityType);
    		
    	try
    	{
    		CreateActivityResponse response = _proxy.CreateActivity(activity);
    		return response.getCreateActivityResponse().getActivityIdentifier();
    	}
    	catch (Exception ex)
        {
            System.out.println(ex.toString());
            return null;
        }
    }

    public FactoryResourceAttributesDocumentType GetFactoryAttributesDocument(BasicFilterType basicFilter) throws Exception //, AdvancedFilterType advancedFilter)
    {
    	boolean returnResources = false;
    	boolean returnActivities = false;
    	
    	String xmlString = new String("<GetFactoryAttributesDocument><BasicFilter  xmlns=\"http://schemas.ogf.org/hpcp/2007/01/bp/BasicFilter\"><ActivityReferences>"+returnActivities+"</ActivityReferences><ContainedResources>"+returnResources+"</ContainedResources></BasicFilter></GetFactoryAttributesDocument>");
    	System.out.println(xmlString);
    	XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(new ByteArrayInputStream(xmlString.getBytes()));
    	GetFactoryAttributesDocumentType document = GetFactoryAttributesDocumentType.Factory.parse(reader);
    	GetFactoryAttributesDocument request = new GetFactoryAttributesDocument();
    	request.setGetFactoryAttributesDocument(document);
    	// ADD IN ADVANCED FILTER
    	GetFactoryAttributesDocumentResponse response = _proxy.GetFactoryAttributesDocument(request);
    	FactoryResourceAttributesDocumentType factory = response.getGetFactoryAttributesDocumentResponse().getFactoryResourceAttributesDocument();
    	return factory;
    }

    public GetActivityStatusResponseType[] GetActivityStatuses(EndpointReferenceType[] activityEPRs)
    {
        // Get the status of one or more activity
        try
        {
        	GetActivityStatusesType getActivityStatusesType = new GetActivityStatusesType();
        	getActivityStatusesType.setActivityIdentifier(activityEPRs);
        	GetActivityStatuses getActivityStatuses = new GetActivityStatuses();
        	getActivityStatuses.setGetActivityStatuses(getActivityStatusesType);
            GetActivityStatusesResponse response = _proxy.GetActivityStatuses(getActivityStatuses);
            return response.getGetActivityStatusesResponse().getResponse();
        }
        catch (Exception ex)
        {
            System.out.println(ex.toString());
            return null;
        }
    }

    public TerminateActivityResponseType[] TerminateActivity(EndpointReferenceType[] activityEPRs)
    {
        try
        {
        	TerminateActivitiesType terminateActivitiesType = new TerminateActivitiesType();
        	terminateActivitiesType.setActivityIdentifier(activityEPRs);
        	TerminateActivities terminateActivities = new TerminateActivities();
        	terminateActivities.setTerminateActivities(terminateActivitiesType);
        	TerminateActivitiesResponse response = _proxy.TerminateActivities(terminateActivities);
        	return response.getTerminateActivitiesResponse().getResponse();
        }
        catch (Exception ex)
        {
            System.out.println(ex.toString());
            return null;
        }
    }       
}
