/*
 * Copyright (c) 2000, 2001, 2002 The University of Utah and the Flux Group.
 * All rights reserved.
 *
 * Permission to use, copy, modify, and distribute this file
 * for any purpose with or without restriction is hereby granted.
 */
import edu.utah.janosvm.sys.Team;
import edu.utah.janosvm.sys.TeamHandle;
import edu.utah.janosvm.sys.Exportable;
import edu.utah.janosvm.sys.PersistentExport;
import edu.utah.janosvm.sys.DeadTeamException;

import edu.utah.janosvm.resources.NameSpaceResource;

public class HelloBackEnd
    /*
     * Subclass from Exportable since we're exporting objects of this
     * class.  We could have just constructed an Exportable object and
     * HelloBackEnd object separately, but this is more convenient.
     */
    extends Exportable
    /*
     * HelloBackEnd objects should live even when there is noone using
     * them, so make the class an implementation of PersistentExport.
     */
    implements PersistentExport
{
    
    /*
     * The only interface we're exporting to the client class.
     */
    public void sayHelloTo(String name)
    {
	Team team = Team.current();
	/* Build the message within the calling team */
	final String msg =
	    "Client " +
	    team.getName() +
	    " says `Hello " +
	    name +
	    "'";

	/*
	 * Visit the kernel since we want to lock an object owned
	 * by it, `this'.
	 */
	try
	{
	    TeamHandle kernel = team.getKernelTeam();
	    
	    kernel.switchTo();
	    {
		/* Serialize any output */
		synchronized(this)
		{
		    System.out.println(msg);
		}
	    }
	    kernel.returnFrom();
	}
	catch(DeadTeamException dte)
	{
	    /* We're probably dead */
	}
	catch(Throwable th)
	{
	    /* There was an exception thrown by the visit code */
	    System.err.print(th);
	}
    }
	
    public static void main(String args[])
	throws Exception
    {
	NameSpaceResource.exportClassGroup("tutorial-hello");
	    
	/* Create an object for export */
	HelloBackEnd be = new HelloBackEnd();

	/*
	 * Call the exportObject method and export our object
	 * with the name `HelloServer'.
	 */
	Team.current().exportObject("HelloServer", be);
    }
	
}
