/////////////////////////////////////////////////////////////////////////
//
// © University of Southampton IT Innovation Centre, 2008
//
// Copyright in this library belongs to the University of Southampton
// University Road, Highfield, Southampton, UK, SO17 1BJ
//
// 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 :			Mark McArdle
//	Created Date :			2008-02-28
//	Created for Project :		CRISP
//
/////////////////////////////////////////////////////////////////////////
//
//  Dependencies : none
//
/////////////////////////////////////////////////////////////////////////
//
//	Last commit info :  $Author: mm $
//						  $Date: 2008-05-21 11:49:38 +0100 (Wed, 21 May 2008) $
//						  $Revision: 9565 $
//
/////////////////////////////////////////////////////////////////////////
package uk.ac.soton.itinnovation.grid.client.tutorial;

import java.io.File;
import uk.ac.soton.itinnovation.grid.client.proxy.ProxyFactory;
import java.net.URL;

import javax.activation.DataHandler;
import org.apache.axis.message.addressing.EndpointReferenceType;

import uk.ac.soton.ecs.iam.grid.comms.client.DataConversation;
import uk.ac.soton.ecs.iam.grid.comms.client.JobConversation;
import uk.ac.soton.ecs.iam.grid.comms.client.RemoteJobService;
import uk.ac.soton.itinnovation.grid.comms.sla.SLAResource;
import uk.ac.soton.itinnovation.grid.service.types.JobStatus;
import uk.ac.soton.itinnovation.grid.service.types.jsdl.JobDescription;
import uk.ac.soton.itinnovation.grid.types.ConversationID;

public class SLAManagedJobs {
	
	
	/** Job Service Endpoint */
	private static String JOB_SERVICE_ENDPOINT = null;
	/** SLA Service Endpoint */
	private static String SLA_RESOURCE_ENDPOINT = null;
	
	/** The application to execute, identified by its URI */
	private static final String APPLICATION = "http://it-innovation.soton.ac.uk/grid/imagemagick/paint";
	
	/** The input file to upload to the job */
	private static final String INPUT_FILE = "input.png";
	
	/** The ouptut file to download the results to */
	private static final String OUTPUT_FILE = "output.jpg";

	public SLAManagedJobs(String jobservice,String slaresource){
		JOB_SERVICE_ENDPOINT = jobservice;
		SLA_RESOURCE_ENDPOINT = slaresource;
	}
	
	public static void main(String[] args) throws Exception {
		
		/* Create a TutorialHelpers object and get a ProxyFactory
		 * object from it
		 */
		TutorialHelpers helpers = new TutorialHelpers();
		ProxyFactory proxyFactory = helpers.getFactory();
		
		/* Create a Proxy to the Job Service
		 */ 
		RemoteJobService jobService = proxyFactory.createProxy(ConversationID.getEPR(JOB_SERVICE_ENDPOINT), RemoteJobService.class);

		/* Use the JobHelpers class to create a JSDL job description
		 * using the defaults for this type of job
		 */
		JobDescription jsdl = JobHelpers.getJobDescription("Job 1",jobService.getApplicationMetadataDetailed(APPLICATION));

		/* Create the EndpointReferenceType Object that refers to an SLA
		 * Normally this will be of the form
		 * https://host:8443/gria-service-provider-mgt/services/SLAService#40894e10-1932c13d-0119-c3de5974-3518
		 * Set the type of the resource to an SLA
		 */
		EndpointReferenceType slaEPR = ConversationID.getEPR(SLA_RESOURCE_ENDPOINT);
		ConversationID.setResourceType(slaEPR, SLAResource.SLA_RESOURCE_TYPE);

		/* In the DefaultInvocationEngine the Federation Selector
		 * searches through the registry for SLA'a in order to match 
		 * policies returned by managed services.
		 * We must add the SLA to the registry to that the Federation
		 * Selector can choose it
		 */
		helpers.getRegistry().registerResource(slaEPR);

		/* Make a remote call to the Job Service to create a job resource
		 * using the JSDL we have created
		 */
		JobConversation jobConv = jobService.createJobJSDL(jsdl.toXML());
	
		/* Get Proxy to the inputs and outputs of the 
		 * job as DataConversation objectss.
		 */
		DataConversation[] inputs = jobConv.getInputs();
		DataConversation[] outputs = jobConv.getOutputs();
	
		/* Upload an input image to the input data stager
		 */
		URL url = SLAManagedJobs.class.getClassLoader().getResource(INPUT_FILE);
		inputs[0].save(new DataHandler(url));
		
		/* Tell the Job Service to start the job
		 */
		jobConv.submitJobJSDL();

		/* Poll the job status until it is done
		 */
		while(jobConv.stillActive()) {
			System.out.print(".");
			Thread.sleep(5000);
		}

		/* Check to see if the job completed sucessfully
		 */ 
		JobStatus jobStatus = jobConv.checkJob();
		if(jobStatus.getExitStatus() != 0) {
			// handle the failure
			throw new RuntimeException("Job failed. Here is the log:\n" +
					jobStatus.getLogText());
		}

		/* Read the result of the job from the output stager and save 
		 * it to a disk.
		 */
		outputs[0].read(new File(OUTPUT_FILE));

		/* Clean up resources at the service by destroying the job
		 */
		jobConv.destroy();
	}
}
