KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jboss > security > plugins > JaasSecurityManagerService


1 /*
2  * JBoss, Home of Professional Open Source
3  *
4  * Distributable under LGPL license.
5  * See terms of license at gnu.org.
6  */

7
8 package org.jboss.security.plugins;
9
10 import java.lang.reflect.Constructor JavaDoc;
11 import java.lang.reflect.InvocationHandler JavaDoc;
12 import java.lang.reflect.Method JavaDoc;
13 import java.lang.reflect.Proxy JavaDoc;
14 import java.security.Principal JavaDoc;
15 import java.util.Enumeration JavaDoc;
16 import java.util.Hashtable JavaDoc;
17 import java.util.Set JavaDoc;
18 import java.util.List JavaDoc;
19 import java.beans.PropertyEditorManager JavaDoc;
20
21 import javax.management.MBeanServer JavaDoc;
22 import javax.naming.CommunicationException JavaDoc;
23 import javax.naming.Context JavaDoc;
24 import javax.naming.InitialContext JavaDoc;
25 import javax.naming.Name JavaDoc;
26 import javax.naming.NameClassPair JavaDoc;
27 import javax.naming.NameParser JavaDoc;
28 import javax.naming.NamingEnumeration JavaDoc;
29 import javax.naming.NamingException JavaDoc;
30 import javax.naming.OperationNotSupportedException JavaDoc;
31 import javax.naming.RefAddr JavaDoc;
32 import javax.naming.Reference JavaDoc;
33 import javax.naming.StringRefAddr JavaDoc;
34 import javax.naming.spi.ObjectFactory JavaDoc;
35 import javax.security.auth.callback.CallbackHandler JavaDoc;
36 import javax.security.auth.Subject JavaDoc;
37 import javax.security.jacc.PolicyContext JavaDoc;
38
39 import org.jboss.logging.Logger;
40 import org.jboss.security.AuthenticationManager;
41 import org.jboss.security.SecurityAssociation;
42 import org.jboss.security.SecurityProxyFactory;
43 import org.jboss.security.SecurityDomain;
44 import org.jboss.security.jacc.SubjectPolicyContextHandler;
45 import org.jboss.security.propertyeditor.PrincipalEditor;
46 import org.jboss.security.propertyeditor.SecurityDomainEditor;
47 import org.jboss.system.ServiceMBeanSupport;
48 import org.jboss.util.CachePolicy;
49 import org.jboss.util.TimedCachePolicy;
50
51 /**
52  * This is a JMX service which manages JAAS based SecurityManagers.
53  * JAAS SecurityManagers are responsible for validating credentials
54  * associated with principals. The service defaults to the
55  * org.jboss.security.plugins.JaasSecurityManager implementation but
56  * this can be changed via the securityManagerClass property.
57  *
58  * @see JaasSecurityManager
59  * @see org.jboss.security.SubjectSecurityManager
60  *
61  * @author <a HREF="on@ibis.odessa.ua">Oleg Nitz</a>
62  * @author <a HREF="rickard@telkel.com">Rickard Oberg</a>
63  * @author <a HREF="mailto:Scott.Stark@jboss.org">Scott Stark</a>
64  * @version $Revision: 1.27.2.8 $
65  */

66 public class JaasSecurityManagerService
67    extends ServiceMBeanSupport
68    implements JaasSecurityManagerServiceMBean
69 {
70    private static final String JavaDoc SECURITY_MGR_PATH = "java:/jaas";
71    private static final String JavaDoc DEFAULT_CACHE_POLICY_PATH = "java:/timedCacheFactory";
72    /** The log4j interface */
73    private static Logger log;
74    /** The class that provides the security manager implementation */
75    private static String JavaDoc securityMgrClassName = "org.jboss.security.plugins.JaasSecurityManager";
76    /** The loaded securityMgrClassName */
77    private static Class JavaDoc securityMgrClass;
78    /** The JAAS CallbackHandler interface implementation to use */
79    private static String JavaDoc callbackHandlerClassName = "org.jboss.security.auth.callback.SecurityAssociationHandler";
80    private static Class JavaDoc callbackHandlerClass = org.jboss.security.auth.callback.SecurityAssociationHandler.class;
81
82    /** The location of the security credential cache policy. This is first treated
83     as a ObjectFactory location that is capable of returning CachePolicy instances
84     on a per security domain basis by appending a '/security-domain-name' string
85     to this name when looking up the CachePolicy for a domain. If this fails then
86     the location is treated as a single CachePolicy for all security domains.
87     */

88    private static String JavaDoc cacheJndiName = DEFAULT_CACHE_POLICY_PATH;
89    private static int defaultCacheTimeout = 30*60;
90    private static int defaultCacheResolution = 60;
91    /** The class that provides the SecurityProxyFactory implementation */
92    private static String JavaDoc securityProxyFactoryClassName = "org.jboss.security.SubjectSecurityProxyFactory";
93    private static Class JavaDoc securityProxyFactoryClass = org.jboss.security.SubjectSecurityProxyFactory.class;
94    /** A mapping from security domain name to a SecurityDomainContext object */
95    private static Hashtable JavaDoc securityDomainCtxMap = new Hashtable JavaDoc();
96    private static NameParser JavaDoc parser;
97    private static MBeanServer JavaDoc server;
98
99    /** The default unauthenticated principal */
100    private static String JavaDoc defaultUnauthenticatedPrincipal = "Unauthenticated Principal";
101
102    static
103    {
104       // Get a log interface, required for some statics below
105
// can not use instance field inherited from ServiceMBeanSupport
106
log = Logger.getLogger(JaasSecurityManagerService.class);
107
108    }
109
110    /** The constructor does nothing as the security manager is created
111     on each lookup into java:/jaas/xxx. This is also why all variables
112     in this class are static.
113     */

114    public JaasSecurityManagerService()
115    {
116    }
117
118    public String JavaDoc getSecurityManagerClassName()
119    {
120       return securityMgrClassName;
121    }
122    public void setSecurityManagerClassName(String JavaDoc className)
123       throws ClassNotFoundException JavaDoc, ClassCastException JavaDoc
124    {
125       securityMgrClassName = className;
126       ClassLoader JavaDoc loader = Thread.currentThread().getContextClassLoader();
127       securityMgrClass = loader.loadClass(securityMgrClassName);
128       if( AuthenticationManager.class.isAssignableFrom(securityMgrClass) == false )
129          throw new ClassCastException JavaDoc(securityMgrClass+" does not implement "+AuthenticationManager.class);
130    }
131    public String JavaDoc getSecurityProxyFactoryClassName()
132    {
133       return securityProxyFactoryClassName;
134    }
135    public void setSecurityProxyFactoryClassName(String JavaDoc className)
136       throws ClassNotFoundException JavaDoc
137    {
138       securityProxyFactoryClassName = className;
139       ClassLoader JavaDoc loader = Thread.currentThread().getContextClassLoader();
140       securityProxyFactoryClass = loader.loadClass(securityProxyFactoryClassName);
141    }
142
143    /** Get the default CallbackHandler implementation class name
144     *
145     * @return The fully qualified classname of the
146     */

147    public String JavaDoc getCallbackHandlerClassName()
148    {
149       return JaasSecurityManagerService.callbackHandlerClassName;
150    }
151    /** Set the default CallbackHandler implementation class name
152     * @see javax.security.auth.callback.CallbackHandler
153     */

154    public void setCallbackHandlerClassName(String JavaDoc className)
155       throws ClassNotFoundException JavaDoc
156    {
157       callbackHandlerClassName = className;
158       ClassLoader JavaDoc loader = Thread.currentThread().getContextClassLoader();
159       callbackHandlerClass = loader.loadClass(callbackHandlerClassName);
160    }
161
162    /** Get the jndi name under which the authentication cache policy is found
163     */

164    public String JavaDoc getAuthenticationCacheJndiName()
165    {
166       return cacheJndiName;
167    }
168    /** Set the jndi name under which the authentication cache policy is found
169     */

170    public void setAuthenticationCacheJndiName(String JavaDoc jndiName)
171    {
172       cacheJndiName = jndiName;
173    }
174    /** Get the default timed cache policy timeout.
175     @return the default cache timeout in seconds.
176     */

177    public int getDefaultCacheTimeout()
178    {
179       return defaultCacheTimeout;
180    }
181    /** Set the default timed cache policy timeout. This has no affect if the
182     AuthenticationCacheJndiName has been changed from the default value.
183     @param timeoutInSecs - the cache timeout in seconds.
184     */

185    public void setDefaultCacheTimeout(int timeoutInSecs)
186    {
187       defaultCacheTimeout = timeoutInSecs;
188    }
189    /** Get the default timed cache policy resolution.
190     */

191    public int getDefaultCacheResolution()
192    {
193       return defaultCacheResolution;
194    }
195    /** Set the default timed cache policy resolution. This has no affect if the
196     AuthenticationCacheJndiName has been changed from the default value.
197     @param resInSecs - resolution of timeouts in seconds.
198     */

199    public void setDefaultCacheResolution(int resInSecs)
200    {
201       defaultCacheResolution = resInSecs;
202    }
203
204    /** Set the indicated security domain cache timeout. This only has an
205     effect if the security domain is using the default jboss TimedCachePolicy
206     implementation.
207      
208     @param securityDomain the name of the security domain cache
209     @param timeoutInSecs - the cache timeout in seconds.
210     @param resInSecs - resolution of timeouts in seconds.
211     */

212    public void setCacheTimeout(String JavaDoc securityDomain, int timeoutInSecs, int resInSecs)
213    {
214       CachePolicy cache = getCachePolicy(securityDomain);
215       if( cache != null && cache instanceof TimedCachePolicy )
216       {
217          TimedCachePolicy tcp = (TimedCachePolicy) cache;
218          synchronized( tcp )
219          {
220             tcp.setDefaultLifetime(timeoutInSecs);
221             tcp.setResolution(resInSecs);
222          }
223       }
224       else
225       {
226          log.warn("Failed to find cache policy for securityDomain='"
227             + securityDomain + "'");
228       }
229    }
230
231    /** flush the cache policy for the indicated security domain if one exists.
232     * @param securityDomain the name of the security domain cache
233     */

234    public void flushAuthenticationCache(String JavaDoc securityDomain)
235    {
236       CachePolicy cache = getCachePolicy(securityDomain);
237       if( cache != null )
238       {
239          cache.flush();
240       }
241       else
242       {
243          log.warn("Failed to find cache policy for securityDomain='"
244             + securityDomain + "'");
245       }
246    }
247
248    /** Flush a principal's authentication cache entry associated with the
249     * given securityDomain.
250     *
251     * @param securityDomain the name of the security domain cache
252     * @param user the principal of the user to flush
253     */

254    public void flushAuthenticationCache(String JavaDoc securityDomain, Principal JavaDoc user)
255    {
256       CachePolicy cache = getCachePolicy(securityDomain);
257       if( cache != null )
258       {
259          cache.remove(user);
260       }
261       else
262       {
263          log.warn("Failed to find cache policy for securityDomain='"
264             + securityDomain + "'");
265       }
266    }
267
268    /** Return the active principals in the indicated security domain auth cache.
269     * @param securityDomain the name of the security to lookup the cache for
270     * @return List<Principal> of active keys found in the auth cache if
271     * the cache exists and is accessible, null otherwise.
272     */

273    public List JavaDoc getAuthenticationCachePrincipals(String JavaDoc securityDomain)
274    {
275       CachePolicy cache = getCachePolicy(securityDomain);
276       List JavaDoc validPrincipals = null;
277       if( cache instanceof TimedCachePolicy )
278       {
279          TimedCachePolicy tcache = (TimedCachePolicy) cache;
280          validPrincipals = tcache.getValidKeys();
281       }
282       return validPrincipals;
283    }
284
285 // Begin SecurityManagerMBean interface methods
286
public boolean isValid(String JavaDoc securityDomain, Principal JavaDoc principal, Object JavaDoc credential)
287    {
288       boolean isValid = false;
289       try
290       {
291          SecurityDomainContext sdc = lookupSecurityDomain(securityDomain);
292          isValid = sdc.getSecurityManager().isValid(principal, credential, null);
293       }
294       catch(NamingException JavaDoc e)
295       {
296          log.debug("isValid("+securityDomain+") failed", e);
297       }
298       return isValid;
299    }
300
301    public Principal JavaDoc getPrincipal(String JavaDoc securityDomain, Principal JavaDoc principal)
302    {
303       Principal JavaDoc realmPrincipal = null;
304       try
305       {
306          SecurityDomainContext sdc = lookupSecurityDomain(securityDomain);
307          realmPrincipal = sdc.getRealmMapping().getPrincipal(principal);
308       }
309       catch(NamingException JavaDoc e)
310       {
311          log.debug("getPrincipal("+securityDomain+") failed", e);
312       }
313       return realmPrincipal;
314    }
315
316     public boolean doesUserHaveRole(String JavaDoc securityDomain, Principal JavaDoc principal,
317        Object JavaDoc credential, Set JavaDoc roles)
318     {
319        boolean doesUserHaveRole = false;
320        try
321        {
322           SecurityDomainContext sdc = lookupSecurityDomain(securityDomain);
323           // Must first validate the user
324
Subject JavaDoc subject = new Subject JavaDoc();
325           sdc.getSecurityManager().isValid(principal, credential, subject);
326           // Now can query if the authenticated Subject has the role
327
SubjectActions.pushSubjectContext(principal, credential, subject);
328           doesUserHaveRole = sdc.getRealmMapping().doesUserHaveRole(principal, roles);
329           SubjectActions.popSubjectContext();
330        }
331        catch(NamingException JavaDoc e)
332        {
333           log.debug("doesUserHaveRole("+securityDomain+") failed", e);
334        }
335        return doesUserHaveRole;
336     }
337
338     public Set JavaDoc getUserRoles(String JavaDoc securityDomain, Principal JavaDoc principal, Object JavaDoc credential)
339     {
340        Set JavaDoc userRoles = null;
341        try
342        {
343           SecurityDomainContext sdc = lookupSecurityDomain(securityDomain);
344           // Must first validate the user
345
sdc.getSecurityManager().isValid(principal, credential, null);
346           // Now can query if the authenticated Subject has the role
347
userRoles = sdc.getRealmMapping().getUserRoles(principal);
348        }
349        catch(NamingException JavaDoc e)
350        {
351           log.debug("getUserRoles("+securityDomain+") failed", e);
352        }
353        return userRoles;
354     }
355 // End SecurityManagerMBean interface methods
356

357    protected void startService() throws Exception JavaDoc
358    {
359       // use thread-local principal and credential propagation
360
SecurityAssociation.setServer();
361
362       // Register the default active Subject PolicyContextHandler
363
SubjectPolicyContextHandler handler = new SubjectPolicyContextHandler();
364       PolicyContext.registerHandler(SubjectPolicyContextHandler.SUBJECT_CONTEXT_KEY,
365          handler, true);
366
367       Context JavaDoc ctx = new InitialContext JavaDoc();
368       parser = ctx.getNameParser("");
369
370       /* Create a mapping from the java:/jaas context to a SecurityDomainObjectFactory
371        so that any lookup against java:/jaas/domain returns an instance of our
372        security manager class.
373       */

374       RefAddr JavaDoc refAddr = new StringRefAddr JavaDoc("nns", "JSM");
375       String JavaDoc factoryName = SecurityDomainObjectFactory.class.getName();
376       Reference JavaDoc ref = new Reference JavaDoc("javax.naming.Context", refAddr, factoryName, null);
377       ctx.rebind(SECURITY_MGR_PATH, ref);
378       log.debug("securityMgrCtxPath="+SECURITY_MGR_PATH);
379
380       refAddr = new StringRefAddr JavaDoc("nns", "JSMCachePolicy");
381       factoryName = DefaultCacheObjectFactory.class.getName();
382       ref = new Reference JavaDoc("javax.naming.Context", refAddr, factoryName, null);
383       ctx.rebind(DEFAULT_CACHE_POLICY_PATH, ref);
384       log.debug("cachePolicyCtxPath="+cacheJndiName);
385
386       // Bind the default SecurityProxyFactory instance under java:/SecurityProxyFactory
387
SecurityProxyFactory proxyFactory = (SecurityProxyFactory) securityProxyFactoryClass.newInstance();
388       ctx.bind("java:/SecurityProxyFactory", proxyFactory);
389       log.debug("SecurityProxyFactory="+proxyFactory);
390
391       // Register the Principal property editor
392
PropertyEditorManager.registerEditor(Principal JavaDoc.class, PrincipalEditor.class);
393       PropertyEditorManager.registerEditor(SecurityDomain.class, SecurityDomainEditor.class);
394    }
395
396    protected void stopService() throws Exception JavaDoc
397    {
398       InitialContext JavaDoc ic = new InitialContext JavaDoc();
399       
400       try
401       {
402          ic.unbind(SECURITY_MGR_PATH);
403       }
404       catch(CommunicationException JavaDoc e)
405       {
406          // Do nothing, the naming services is already stopped
407
}
408       finally
409       {
410          ic.close();
411       }
412    }
413
414    /** Register a SecurityDomain implmentation
415     */

416    public void registerSecurityDomain(String JavaDoc securityDomain, SecurityDomain instance)
417    {
418       log.debug("Added "+securityDomain+", "+instance+" to map");
419       CachePolicy authCache = lookupCachePolicy(securityDomain);
420       SecurityDomainContext sdc = new SecurityDomainContext(instance, authCache);
421       securityDomainCtxMap.put(securityDomain, sdc);
422       // See if the security mgr supports an externalized cache policy
423
setSecurityDomainCache(instance, authCache);
424    }
425
426    /** Access the CachePolicy for the securityDomain.
427     * @param securityDomain the name of the security domain
428     * @return The CachePolicy if found, null otherwise.
429     */

430    private static CachePolicy getCachePolicy(String JavaDoc securityDomain)
431    {
432       if( securityDomain.startsWith(SECURITY_MGR_PATH) )
433          securityDomain = securityDomain.substring(SECURITY_MGR_PATH.length()+1);
434       CachePolicy cache = null;
435       try
436       {
437          SecurityDomainContext sdc = lookupSecurityDomain(securityDomain);
438          if( sdc != null )
439             cache = sdc.getAuthenticationCache();
440       }
441       catch(NamingException JavaDoc e)
442       {
443          log.debug("getCachePolicy("+securityDomain+") failure", e);
444       }
445       return cache;
446    }
447
448    /** Lookup the authentication CachePolicy object for a security domain. This
449     method first treats the cacheJndiName as a ObjectFactory location that is
450     capable of returning CachePolicy instances on a per security domain basis
451     by appending a '/security-domain-name' string to the cacheJndiName when
452     looking up the CachePolicy for a domain. If this fails then the cacheJndiName
453     location is treated as a single CachePolicy for all security domains.
454     */

455    private static CachePolicy lookupCachePolicy(String JavaDoc securityDomain)
456    {
457       CachePolicy authCache = null;
458       String JavaDoc domainCachePath = cacheJndiName + '/' + securityDomain;
459       try
460       {
461          InitialContext JavaDoc iniCtx = new InitialContext JavaDoc();
462          authCache = (CachePolicy) iniCtx.lookup(domainCachePath);
463       }
464       catch(Exception JavaDoc e)
465       {
466          // Failed, treat the cacheJndiName name as a global CachePolicy binding
467
try
468          {
469             InitialContext JavaDoc iniCtx = new InitialContext JavaDoc();
470             authCache = (CachePolicy) iniCtx.lookup(cacheJndiName);
471          }
472          catch(Exception JavaDoc e2)
473          {
474             log.warn("Failed to locate auth CachePolicy at: "+cacheJndiName
475                + " for securityDomain="+securityDomain);
476          }
477       }
478       return authCache;
479    }
480
481    /** Use reflection to attempt to set the authentication cache on the
482     * securityMgr argument.
483     * @param securityMgr the security manager
484     * @param cachePolicy the cache policy implementation
485     */

486    private static void setSecurityDomainCache(AuthenticationManager securityMgr,
487       CachePolicy cachePolicy)
488    {
489       try
490       {
491          Class JavaDoc[] setCachePolicyTypes = {CachePolicy.class};
492          Method JavaDoc m = securityMgrClass.getMethod("setCachePolicy", setCachePolicyTypes);
493          Object JavaDoc[] setCachePolicyArgs = {cachePolicy};
494          m.invoke(securityMgr, setCachePolicyArgs);
495          log.debug("setCachePolicy, c="+setCachePolicyArgs[0]);
496       }
497       catch(Exception JavaDoc e2)
498       { // No cache policy support, this is ok
499
log.debug("setCachePolicy failed", e2);
500       }
501    }
502
503    /** Lookup or create the SecurityDomainContext for securityDomain.
504     * @param securityDomain
505     * @return
506     * @throws NamingException
507     */

508    private static SecurityDomainContext lookupSecurityDomain(String JavaDoc securityDomain)
509          throws NamingException JavaDoc
510    {
511       SecurityDomainContext securityDomainCtx = (SecurityDomainContext) securityDomainCtxMap.get(securityDomain);
512       if( securityDomainCtx == null )
513       {
514          securityDomainCtx = newSecurityDomainCtx(securityDomain);
515          securityDomainCtxMap.put(securityDomain, securityDomainCtx);
516          log.debug("Added "+securityDomain+", "+securityDomainCtx+" to map");
517       }
518       return securityDomainCtx;
519    }
520
521    /** Create a new SecurityDomainContext for securityDomain.
522     * @param securityDomain
523     * @return
524     * @throws NamingException
525     */

526    private static SecurityDomainContext newSecurityDomainCtx(String JavaDoc securityDomain)
527       throws NamingException JavaDoc
528    {
529       SecurityDomainContext sdc = null;
530       try
531       {
532          // Create instance of securityMgrClass
533
Class JavaDoc[] parameterTypes = {String JavaDoc.class, CallbackHandler JavaDoc.class};
534          Constructor JavaDoc ctor = securityMgrClass.getConstructor(parameterTypes);
535          CallbackHandler JavaDoc handler = (CallbackHandler JavaDoc) callbackHandlerClass.newInstance();
536          Object JavaDoc[] args = {securityDomain, handler};
537          AuthenticationManager securityMgr = (AuthenticationManager) ctor.newInstance(args);
538          log.debug("Created securityMgr="+securityMgr);
539          CachePolicy cachePolicy = lookupCachePolicy(securityDomain);
540          sdc = new SecurityDomainContext(securityMgr, cachePolicy);
541          // See if the security mgr supports an externalized cache policy
542
setSecurityDomainCache(securityMgr, cachePolicy);
543       }
544       catch(Exception JavaDoc e2)
545       {
546          log.error("Failed to create sec mgr", e2);
547          throw new NamingException JavaDoc("Failed to create sec mgr:"+e2.getMessage());
548       }
549       return sdc;
550    }
551
552    /**
553     * Get the default unauthenticated principal.
554     * @return The principal name
555     */

556    public String JavaDoc getDefaultUnauthenticatedPrincipal()
557    {
558       return defaultUnauthenticatedPrincipal;
559    }
560
561    /**
562     * Set the default unauthenticated principal.
563     * @param principal The principal name
564     */

565    public void setDefaultUnauthenticatedPrincipal(String JavaDoc principal)
566    {
567       defaultUnauthenticatedPrincipal = principal;
568    }
569
570    // java:/jaas context ObjectFactory implementation
571

572    public static class SecurityDomainObjectFactory
573       implements InvocationHandler JavaDoc, ObjectFactory JavaDoc
574    {
575       /** Object factory implementation. This method returns a Context proxy
576        that is only able to handle a lookup operation for an atomic name of
577        a security domain.
578       */

579       public Object JavaDoc getObjectInstance(Object JavaDoc obj, Name JavaDoc name, Context JavaDoc nameCtx,
580          Hashtable JavaDoc environment)
581          throws Exception JavaDoc
582       {
583          ClassLoader JavaDoc loader = SubjectActions.getContextClassLoader();
584          Class JavaDoc[] interfaces = {Context JavaDoc.class};
585          Context JavaDoc ctx = (Context JavaDoc) Proxy.newProxyInstance(loader, interfaces, this);
586          return ctx;
587       }
588
589
590       /** This is the InvocationHandler callback for the Context interface that
591        was created by out getObjectInstance() method. We handle the java:/jaas/domain
592        level operations here.
593        */

594       public Object JavaDoc invoke(Object JavaDoc obj, Method JavaDoc method, Object JavaDoc[] args) throws Throwable JavaDoc
595       {
596          String JavaDoc methodName = method.getName();
597          if( methodName.equals("toString") == true )
598             return SECURITY_MGR_PATH + " Context proxy";
599          if( methodName.equals("list") == true )
600             return new DomainEnumeration(securityDomainCtxMap.keys(), securityDomainCtxMap);
601
602          if( methodName.equals("lookup") == false )
603             throw new OperationNotSupportedException JavaDoc("Only lookup is supported, op="+method);
604          String JavaDoc securityDomain = null;
605          Name JavaDoc name = null;
606          if( args[0] instanceof String JavaDoc )
607             name = parser.parse((String JavaDoc) args[0]);
608          else
609            name = (Name JavaDoc)args[0];
610          securityDomain = name.get(0);
611          SecurityDomainContext securityDomainCtx = lookupSecurityDomain(securityDomain);
612          Object JavaDoc binding = securityDomainCtx.getSecurityManager();
613          // Look for requests against the security domain context
614
if( name.size() == 2 )
615          {
616             String JavaDoc request = name.get(1);
617             binding = securityDomainCtx.lookup(request);
618          }
619          return binding;
620       }
621    }
622    static class DomainEnumeration implements NamingEnumeration JavaDoc
623    {
624       Enumeration JavaDoc domains;
625       Hashtable JavaDoc ctxMap;
626       DomainEnumeration(Enumeration JavaDoc domains, Hashtable JavaDoc ctxMap)
627       {
628          this.domains = domains;
629          this.ctxMap = ctxMap;
630       }
631
632       public void close()
633       {
634       }
635       public boolean hasMoreElements()
636       {
637          return domains.hasMoreElements();
638       }
639       public boolean hasMore()
640       {
641          return domains.hasMoreElements();
642       }
643       public Object JavaDoc next()
644       {
645          String JavaDoc name = (String JavaDoc) domains.nextElement();
646          Object JavaDoc value = ctxMap.get(name);
647          String JavaDoc className = value.getClass().getName();
648          NameClassPair JavaDoc pair = new NameClassPair JavaDoc(name, className);
649          return pair;
650       }
651       public Object JavaDoc nextElement()
652       {
653          return domains.nextElement();
654       }
655    }
656
657    /** java:/timedCacheFactory ObjectFactory implementation
658     */

659    public static class DefaultCacheObjectFactory implements InvocationHandler JavaDoc, ObjectFactory JavaDoc
660    {
661       /** Object factory implementation. This method returns a Context proxy
662        that is only able to handle a lookup operation for an atomic name of
663        a security domain.
664       */

665       public Object JavaDoc getObjectInstance(Object JavaDoc obj, Name JavaDoc name, Context JavaDoc nameCtx, Hashtable JavaDoc environment)
666          throws Exception JavaDoc
667       {
668          ClassLoader JavaDoc loader = Thread.currentThread().getContextClassLoader();
669          Class JavaDoc[] interfaces = {Context JavaDoc.class};
670          Context JavaDoc ctx = (Context JavaDoc) Proxy.newProxyInstance(loader, interfaces, this);
671          return ctx;
672       }
673       /** This is the InvocationHandler callback for the Context interface that
674        was created by out getObjectInstance() method. All this does is create
675        a new TimedCache instance.
676        */

677       public Object JavaDoc invoke(Object JavaDoc obj, Method JavaDoc method, Object JavaDoc[] args) throws Throwable JavaDoc
678       {
679          TimedCachePolicy cachePolicy = new TimedCachePolicy(defaultCacheTimeout,
680             true, defaultCacheResolution);
681          cachePolicy.create();
682          cachePolicy.start();
683          return cachePolicy;
684       }
685    }
686 }
687
Popular Tags