package org.astrogrid.ogsa.gcache;

import java.net.URL;
import java.util.GregorianCalendar;
import org.gridforum.ogsi.Factory;
import org.gridforum.ogsi.LocatorType;
import org.gridforum.ogsi.OGSIServiceLocator;
import org.globus.ogsa.utils.GridServiceFactory;
import org.globus.ogsa.wsdl.GSR;


/**
 * Exercises an Gcache service by creating and instance and storing
 * a datum in that instance.
 */
public class StoreClientS {

  public static void main (String[] args) throws Exception {

    if (args.length != 2) {
      System.err.println("Usage: java org.astrogrid.ogsa.gcache.StoreClient "
                         + "<factory-URL> <datum>");
      return;
    }

    try {
      StoreClientS.store(args[0], args[1]);
    }
    catch (Exception e) {
      System.err.println(e);
    }
  }


  private static void store (String url, String datum) throws Exception {
    System.out.println("Client: service factory: " + url);

    // Get access to the factory port.  Use the GridServiceFactory
    // wrapper to the port to simplify the interface of the
    // createService method.
    OGSIServiceLocator factoryLocator = new OGSIServiceLocator();
    Factory factory = factoryLocator.getFactoryPort(new URL(url));
    GridServiceFactory gridFactory = new GridServiceFactory(factory);

    // Set up authenticated access: make credentials available in
    // calls to the factory.
    SecurityHelper.configureSecureCall(factory);

    // Create a service instance with a 10-minute timeout.
    GregorianCalendar timeout = new GregorianCalendar();
    timeout.add(GregorianCalendar.MINUTE, 10);
    System.out.println("About to create a service instance.");
    LocatorType instanceLocator = gridFactory.createService(timeout);
    GSR reference = GSR.newInstance(instanceLocator);
    String location = reference.getHandle().toString();
    System.out.println("GSH of new service is " + location);
    System.out.println("Termination Time is "
                       + gridFactory.getTerminationTime().getAfter().toString()
                      );
    // Find the application port.
    GcacheGridLocator portLocator = new GcacheGridLocator();
    GcachePortType port = portLocator.getGcachePortType(instanceLocator);

    // Set up authenticated access: make credentials available in
    // calls to the service.
    SecurityHelper.configureSecureCall(port);

    // Invoke the port.
    System.out.println("About to call store().");
    port.store(datum);
    System.out.println("Stored: " + datum);
    System.out.println("The test finished without exceptions.");
  }
}
