/*
 * @(#)SecurityUtil.java
 *
 * Copyright 2000-2002 by Oracle Corporation,
 * 500 Oracle Parkway, Redwood Shores, California, 94065, U.S.A.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information
 * of Oracle Corporation.
 */

package oracle.jbo.common.ampool;

import java.lang.reflect.Method;
import java.security.Principal;

/**
 * <b>Internal:</b> <em>Applications should not use this class.</em>
 * <p>
 */
public class SecurityUtil
{
   private static final String GET_REALM_METHOD = "getRealm";
   private static final String GET_NAME_METHOD = "getName";
   private static final String REALM_INTF = "Realm";

   public static Class getInterface(Class cls, String name)
   {
      try
      {
         Class[] intfs = cls.getInterfaces();
         for (int i = 0; i < intfs.length; i++)
         {
            if (intfs[i].getName().endsWith(name))
            {
               return intfs[i];
            }
         }
      }
      catch (Exception e)
      {
         e.printStackTrace();
      }
      return null;
   }

   public static Method getMethod(Class cls, String name)
   {
      Method mthd = null;

      try
      {
         mthd = cls.getMethod(name, null);
      }
      catch (Exception e2)
      {
      }
      return mthd;
   }

   public static String getRealmName(Principal p)
   {
      String realmName = null;

      try
      {
          Object realm = null;
          Method realmMethod = SecurityUtil.getMethod(p.getClass(), GET_REALM_METHOD);
          if (realmMethod != null)
          {
             realm = realmMethod.invoke(p, null);
          }

          if (realm != null)
          {
             Class cls = SecurityUtil.getInterface(realm.getClass(), REALM_INTF);
             if (cls != null)
             {
                Method mthd = SecurityUtil.getMethod(cls, GET_NAME_METHOD);
                if (mthd != null)
                {
                   realmName = (String) mthd.invoke(realm, null);
                }
             }
          }
      }
      catch (Exception e1)
      {                        
         e1.printStackTrace();
      }

      return realmName;
   }
}
