// EntityClientSample.java

// Sample program showing entity bean usage.
// 

import javax.naming.*;
import javax.ejb.*;
import javax.rmi.*;
import java.util.*;
import props.*;

public class EntityClientSample {
    
    static public void main( String[] args )
    {
        checkArgs( args );
        try {
            // Obtain the EJB home
            Properties env = new Properties();
            env.put( "java.naming.factory.initial",
                "desisoft.ejb.client.JRMPFactory" );
            env.put( "desisoft.ejb.nameServer1",
                "localhost:2050" );
            Context ctx = new InitialContext( env );
            PropsHome home = (PropsHome) PortableRemoteObject.narrow(
                                            ctx.lookup( "Props" ), PropsHome.class );
            
            Props bean;
            if ( doGet ) {
                try {
                    bean = home.findByPrimaryKey( prop );
                    System.out.println( prop + ": " + bean.getValue());
                } catch (FinderException notFound) {
                    System.out.println( "Property \"" + prop + "\" was not found" );
                }
            } else {
                try {
                    bean = home.create( prop, value );
                } catch (DuplicateKeyException exists) {
                    bean = home.findByPrimaryKey( prop );
                }
                bean.setValue( value );
                System.out.println( "Set value of \"" + prop + "\" to \"" + value + "\"" );
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    static void usage()
    {
        System.out.println( "Usage: java EntityClientSample put <prop-name> <value>" );
        System.out.println( "       java EntityClientSample get <prop-name>" );
        System.exit( 0 );
    }

    static void checkArgs( String[] args )
    {
        if ( args.length < 2 )
            usage();
        prop = args[1];
        if ( args[0].equalsIgnoreCase( "get" )) {
            if ( args.length > 2 )
                usage();
            doGet = true;
        } else if ( args[0].equalsIgnoreCase( "put" )) {
            if ( args.length != 3 )
                usage();
             doGet = false;
             value = args[2];
        } else
            usage();
    }
        
    static boolean doGet = false;
    static String prop = null;
    static String value = null;
   
}
