//
//  FirstSample.java
//  
//
//  Created by Gemstone on 2005/06/06.
//

//
// A small sample program to connect to the default Facets
// repository, create a session and save an object away
//
package com.gemstone.examples;

import com.gemstone.persistence.collections.*;
import com.gemstone.persistence.*;
import com.gemstone.persistence.naming.*;
import javax.naming.*;
import javax.jdo.*;

public class FirstSample 
	{
	//
	// the main methods that will get called when we
	// run thhis classes from the command line
	//
	public static void main(String args[])
		{
		(new FirstSample(args)).run();
		}
	//
	// the constructor that is called that will allow
	// us to access any command line arguments
	//
	public FirstSample(String args[])
		{
		// in this case do nothing
		}
	//
	// run the sample code
	//
	public void run()
		{
		SessionFactory		aSessionFactory = null;
		GsSession			aSession = null;
		Context				aContext;
		Integer				anInt;
		//
		// retrieve the SessionFactory instance
		//
		try
			{
			aSessionFactory = SessionFactory.getInstance();
			}
		catch (Exception exception)
			{
			System.err.println("unable to access SessionFactory instance");
			exception.printStackTrace();
			System.exit(5);
			}
		//
		// now get a session
		//
		try
			{
			aSession = aSessionFactory.getSession();
			System.out.println("sucessfully retrieved a session");
			}
		catch (Exception exception)
			{
			exception.printStackTrace();
			System.exit(5);
			}
		//
		// now retrieve the default name space and bind an object
		//
		try
			{
			aContext = aSession.getInitialContext();
			//
			// ask the session to begin a transaction
			//
			aSession.begin();
			System.out.println("successfully started a transaction");
			aContext.bind("sample object 1",new Integer(111));
			aSession.commit();
			System.out.println("successfully bound 'sample object 1' to an Integer");
			System.out.println("aborting session to refresh session view");
			aSession.abort();
			anInt = (Integer)aContext.lookup("sample object 1");
			System.out.println("found the bound object");
			}
		catch (NameAlreadyBoundException nabException)
			{
			System.out.println("the name 'sample object 1' is already in use");
			}
		catch (NamingException namingException)
			{
			System.err.println("unexpected naming exception when binding the sample object");
			namingException.printStackTrace();
			}
		catch (GsTransactionInProgressException eipException)
			{
			System.err.println("there is already a transaction in progress");
			eipException.printStackTrace();
			}
		finally
			{
			aSession.abort();
			aSession.close();
			}
		}
	}
