/*
 * Copyright 2002 Tryllian BV and Otto Moerbeek
 * http://www.tryllian.com
 * otto@tryllian.com
 */

package net.drijf.javaone;

import java.io.File;
import java.net.URL;
import java.util.HashMap;

/**
 * Demonstrate the class loading and delegation mechanism by loading
 * a test class from a (signed) jar and executing the test methods.
 * 
 * @author Otto Moerbeek
 */
public class TestMain {

   /**
    * Do some tests.
    * @param argv the command line arguments. Usage:
    * <pre>
    * net.drijf.javaone.TestMain keystore passphrase jarfile
    * </pre>
    */
   public static void main(String[] argv) 
        throws Exception 
    {
        System.out.println();
        System.out.println("=== Running with jarfile = " + argv[2] + " ===");
        // Install our own security manager
        System.setSecurityManager(new StrictSecurityManager());

        // Construct the role mapping
        HashMap map = new HashMap();
        map.put(null, RoleImpl.NOTHING);
        map.put("root_ca1", RoleImpl.ALL);
        map.put("expired", RoleImpl.ALL);
        map.put("by_ca2", RoleImpl.ENTER);
        map.put("delegated_ca", RoleImpl.READER);
       
        // Create our own delegating policy object
        DelegatingPolicy p = new DelegatingPolicy(new File(argv[0]),
            argv[1].toCharArray(), new RoleMappingImpl(map));
 
        // Create our own class loader using a delegating policy
        DelegatingCL loader = new DelegatingCL(
            new URL[] {new URL("file:" + argv[2]) },
            TestMain.class.getClassLoader(),
            p);
        
        // Load the test class
        System.out.println("=== Trying to load class ===");
        Class cl = Class.forName("test.Test", false, loader);
        
        // Print the assigned permissions
        java.security.PermissionCollection perms =
            cl.getProtectionDomain().getPermissions();
        System.out.println("=== Code has permissions === " + perms + "===");
        
        // Construct an instance of the test and try the test methods
        TestInterface test = (TestInterface)cl.newInstance();

        System.out.println("=== Trying to read file ===");
        System.out.println("=== File contains: " 
                           + test.tryToReadFile("README") + " ===");
        System.out.println("=== Trying to create thread ===");
        test.tryToCreateThread();
        System.out.println("=== Thread created ===");

        // Now do some more nasty things
        try {
            System.out.println("=== Trying to exit VM ===");
            test.tryToExitVM();
            System.exit(0);
        }
        catch (Exception e) {
            //e.printStackTrace();a
        }
        System.out.println("=== Trying to exit VM did not work! ===");
        System.out.println("=== Trying to set security manager ===");
        System.setSecurityManager(null);
        System.out.println("=== Security manager set ===");
    }
}
