KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > security > auth > realm > Realm


1 /*
2  * The contents of this file are subject to the terms
3  * of the Common Development and Distribution License
4  * (the License). You may not use this file except in
5  * compliance with the License.
6  *
7  * You can obtain a copy of the license at
8  * https://glassfish.dev.java.net/public/CDDLv1.0.html or
9  * glassfish/bootstrap/legal/CDDLv1.0.txt.
10  * See the License for the specific language governing
11  * permissions and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL
14  * Header Notice in each file and include the License file
15  * at glassfish/bootstrap/legal/CDDLv1.0.txt.
16  * If applicable, add the following below the CDDL Header,
17  * with the fields enclosed by brackets [] replaced by
18  * you own identifying information:
19  * "Portions Copyrighted [year] [name of copyright owner]"
20  *
21  * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
22  */

23 package com.sun.enterprise.security.auth.realm;
24
25 import java.io.*;
26 import java.util.*;
27 import java.util.logging.*;
28 import java.security.Principal JavaDoc;
29 import java.security.acl.Group JavaDoc;
30 import com.sun.logging.*;
31 import com.sun.enterprise.*;
32 import com.sun.enterprise.util.*;
33 import com.sun.enterprise.security.auth.realm.IASRealm;
34
35
36 /**
37  * javadoc
38  *
39  * @see java.security.Principal
40  *
41  * @author Harish Prabandham
42  * @author Harpreet Singh
43  * @author Jyri Virkki
44  * @author Shing Wai Chan
45  *
46  */

47 public abstract class Realm implements Comparable JavaDoc {
48
49     private static LocalStringManagerImpl localStrings =
50     new LocalStringManagerImpl(Realm.class);
51
52     private static Hashtable loadedRealms = new Hashtable();
53     private String JavaDoc myName;
54
55     // Keep track of name of default realm. This is updated during startup
56
// using value from server.xml
57
private static String JavaDoc defaultRealmName="default";
58     
59     // Keep a mapping from "default" to default realm (if no such named
60
// realm is present) for the sake of all the hardcoded accesses to it.
61
// This needs to be removed as part of RI security service cleanup.
62
private final static String JavaDoc RI_DEFAULT="default";
63
64     // All realms have a set of properties from config file, consolidate.
65
private Properties ctxProps;
66
67     
68     /**
69      * Returns the name of this realm.
70      *
71      * @return realm name.
72      */

73     public final String JavaDoc getName() {
74     return myName;
75     }
76
77     
78     /**
79      * Assigns the name of this realm, and stores it in the cache
80      * of realms. Used when initializing a newly created in-memory
81      * realm object; if the realm already has a name, there is no
82      * effect.
83      *
84      * @param name name to be assigned to this realm.
85      */

86     protected final void setName(String JavaDoc name) {
87     if (myName != null) {
88         return;
89     }
90     myName = name;
91     }
92
93     
94     /**
95      * Returns the name of this realm.
96      *
97      * @return name of realm.
98      */

99     public String JavaDoc toString() {
100     return myName;
101     }
102
103     
104     /**
105      * Compares a realm to another. The comparison first considers the
106      * authentication type, so that realms supporting the same kind of
107      * user authentication are grouped together. Then it compares realm
108      * realm names. Realms compare "before" other kinds of objects (i.e.
109      * there's only a partial order defined, in the case that those other
110      * objects compare themselves "before" a realm object).
111      */

112     public int compareTo (Object JavaDoc realm) {
113     if (!(realm instanceof Realm)) {
114         return 1;
115     }
116     
117     Realm r = (Realm) realm;
118     String JavaDoc str = r.getAuthType ();
119     int temp;
120     
121     if ((temp = getAuthType ().compareTo (str)) != 0) {
122         return temp;
123     }
124
125     str = r.getName ();
126     return getName ().compareTo (str);
127     }
128
129
130     /**
131      * Instantiate a Realm with the given name and properties using the
132      * Class name given. This method is used by iAS and not RI.
133      *
134      * @param name Name of the new realm.
135      * @param className Java Class name of the realm to create.
136      * @param props Properties containing values of the Property element
137      * from server.xml
138      * @returns Reference to the new Realm. The Realm class keeps an internal
139      * list of all instantiated realms.
140      * @throws BadRealmException If the requested realm cannot be instantiated.
141      *
142      */

143     public static Realm instantiate(String JavaDoc name, String JavaDoc className,
144                                     Properties props)
145         throws BadRealmException
146     {
147         return doInstantiate(name, className, props);
148     }
149
150
151     /**
152      * Instantiate a Realm with the given name, loading properties from
153      * the given file. This method is only used by RI and is not called
154      * anywhere in iAS.
155      *
156      * @param realmName Name of the new realm.
157      * @param f File containing Properties for the new realm.
158      */

159     public static Realm instantiate(String JavaDoc realmName, File f)
160     throws NoSuchRealmException, BadRealmException, FileNotFoundException
161     {
162         if (!f.exists() || !f.isFile()) {
163             throw new FileNotFoundException ();
164         }
165         
166         if(_getInstance(realmName) != null) {
167             throw new BadRealmException(
168                 localStrings.getLocalString("realm.already_exists",
169                                             "This Realm already exists."));
170         }
171         
172         //
173
// First load the description from properties.
174
//
175
InputStream in = null;
176         Properties props = new Properties();
177         
178         try{
179             in = new FileInputStream(f);
180             props.load(in);
181             //
182
// Then instantiate and initialize, using the single mandatory
183
// property ("classname").
184
//
185
String JavaDoc classname = props.getProperty("classname");
186             assert (classname != null);
187
188             return doInstantiate(realmName, classname, props);
189         } catch (IOException e) {
190             throw new BadRealmException(e.toString());
191         } finally {
192             if (in != null) {
193                 try {
194                     in.close();
195                 } catch(Exception JavaDoc ex) {
196                 }
197             }
198         }
199     }
200
201     
202     /**
203      * Instantiates a Realm class of the given type and invokes its init()
204      *
205      */

206     private static Realm doInstantiate(String JavaDoc name, String JavaDoc className,
207                                        Properties props)
208         throws BadRealmException
209     {
210         try {
211             Class JavaDoc realmClass = Class.forName(className);
212             Object JavaDoc obj = realmClass.newInstance();
213             Realm r = (Realm) obj;
214             r.setName(name);
215             r.init(props);
216
217             loadedRealms.put(name, r);
218             return r;
219
220         } catch(Exception JavaDoc e) {
221             throw new BadRealmException(e);
222         }
223     }
224
225
226     /**
227      * Replace a Realm instance. Can be used by a Realm subclass to
228      * replace a previously initialized instance of itself. Future
229      * getInstance requests will then obtain the new instance.
230      *
231      * <P>Minimal error checking is done. The realm being replaced must
232      * already exist (instantiate() was previously called), the new
233      * instance must be fully initialized properly and it must of course
234      * be of the same class as the previous instance.
235      *
236      * @param realm The new realm instance.
237      * @param name The (previously instantiated) name for this realm.
238      *
239      */

240     protected static void updateInstance(Realm realm, String JavaDoc name)
241     {
242         Realm oldRealm = (Realm)loadedRealms.get(name);
243         if (!oldRealm.getClass().equals(realm.getClass())) {
244             // would never happen unless bug in realm subclass
245
throw new Error JavaDoc("Incompatible class "+realm.getClass()+
246                             " in replacement realm "+name);
247         }
248         realm.setName(oldRealm.getName());
249         loadedRealms.put(name, realm);
250     }
251
252     
253     /**
254      * Convenience method which returns the Realm object representing
255      * the current default realm. Equivalent to
256      * getInstance(getDefaultRealm()).
257      *
258      * @return Realm representing default realm.
259      * @exception NoSuchRealmException if default realm does not exist
260      */

261     public static Realm getDefaultInstance() throws NoSuchRealmException
262     {
263         return getInstance(defaultRealmName);
264     }
265
266     
267     /**
268      * Returns the name of the default realm.
269      *
270      * @return Default realm name.
271      *
272      */

273     public static String JavaDoc getDefaultRealm() {
274         return defaultRealmName;
275     }
276
277     
278     /**
279      * Sets the name of the default realm.
280      *
281      * @param realmName Name of realm to set as default.
282      *
283      */

284     public static void setDefaultRealm(String JavaDoc realmName) {
285         defaultRealmName = realmName;
286     }
287
288     /**
289      * Remove realm with given name from cache.
290      * @param realmName
291      * @exception NoSuchRealmException
292      */

293     static void unloadInstance(String JavaDoc realmName) throws NoSuchRealmException {
294         //make sure instance exist
295
getInstance(realmName);
296         loadedRealms.remove(realmName);
297     }
298
299
300     /**
301      * Set a realm property.
302      *
303      * @param name property name.
304      * @param value property value.
305      *
306      */

307     public void setProperty(String JavaDoc name, String JavaDoc value)
308     {
309         ctxProps.setProperty(name, value);
310     }
311
312
313     /**
314      * Get a realm property.
315      *
316      * @param name property name.
317      * @returns value.
318      *
319      */

320     public String JavaDoc getProperty(String JavaDoc name)
321     {
322         return ctxProps.getProperty(name);
323     }
324
325     /**
326      * Return properties of the realm.
327      */

328     protected Properties getProperties() {
329         return ctxProps;
330     }
331
332
333     /**
334      * Returns name of JAAS context used by this realm.
335      *
336      * <P>The JAAS context is defined in server.xml auth-realm element
337      * associated with this realm.
338      *
339      * @return String containing JAAS context name.
340      *
341      */

342     public String JavaDoc getJAASContext()
343     {
344         return ctxProps.getProperty(IASRealm.JAAS_CONTEXT_PARAM);
345     }
346     
347     
348     /**
349      * Returns the realm identified by the name which is passed
350      * as a parameter. This function knows about all the realms
351      * which exist; it is not possible to store (or create) one
352      * which is not accessible through this routine.
353      *
354      * @param name identifies the realm
355      * @return the requested realm
356      * @exception NoSuchRealmException if the realm is invalid
357      * @exception BadRealmException if realm data structures are bad
358      */

359     public static Realm getInstance(String JavaDoc name) throws NoSuchRealmException
360     {
361     Realm retval = _getInstance(name);
362
363         if (retval == null) {
364             throw new NoSuchRealmException(
365                 localStrings.getLocalString("realm.no_such_realm",
366                 name + " realm does not exist.",
367                 new Object JavaDoc[] { name }));
368         }
369      
370     return retval;
371     }
372
373     /**
374      * This is a private method for getting realm instance.
375      * If realm does not exist, then it will not return null rather than
376      * throw exception.
377      * @param name identifies the realm
378      * @return the requested realm
379      */

380     private static Realm _getInstance(String JavaDoc name) {
381     Realm retval = null;
382     retval = (Realm) loadedRealms.get (name);
383
384         // Some tools as well as numerous other locations assume that
385
// getInstance("default") always works; keep them from breaking
386
// until code can be properly cleaned up. 4628429
387

388         // Also note that for example the appcontainer will actually create
389
// a Subject always containing realm='default' so this notion
390
// needs to be fixed/handled.
391
if ( (retval == null) && (RI_DEFAULT.equals(name)) ) {
392             retval = (Realm) loadedRealms.get (defaultRealmName);
393         }
394
395         return retval;
396     }
397
398
399     /**
400      * Returns the names of accessible realms.
401      * @return set of realm names
402      */

403     public static Enumeration getRealmNames() {
404     return loadedRealms.keys();
405     }
406
407
408     /**
409      * The default constructor creates a realm which will later
410      * be initialized, either from properties or by deserializing.
411      */

412     protected Realm() {
413         ctxProps = new Properties();
414     }
415
416
417     /**
418      * Initialize a realm with some properties. This can be used
419      * when instantiating realms from their descriptions. This
420      * method may only be called a single time.
421      *
422      * @param props initialization parameters used by this realm.
423      * @exception BadRealmException if the configuration parameters
424      * identify a corrupt realm
425      * @exception NoSuchRealmException if the configuration parameters
426      * specify a realm which doesn't exist
427      */

428     protected void init(Properties props)
429         throws BadRealmException, NoSuchRealmException {
430     }
431
432
433     
434     //---[ Abstract methods ]------------------------------------------------
435

436     
437     /**
438      * Returns a short (preferably less than fifteen characters) description
439      * of the kind of authentication which is supported by this realm.
440      *
441      * @return description of the kind of authentication that is directly
442      * supported by this realm.
443      */

444     public abstract String JavaDoc getAuthType ();
445
446     /**
447      * Returns an AuthenticationHandler object which can be used to
448      * authenticate within this realm.
449      *
450      * @return An AuthenticationHandler object for this realm.
451      */

452     public abstract AuthenticationHandler getAuthenticationHandler ();
453
454     /**
455      * Returns names of all the users in this particular realm.
456      *
457      * @return enumeration of user names (strings)
458      * @exception BadRealmException if realm data structures are bad
459      */

460     public abstract Enumeration getUserNames() throws BadRealmException;
461
462     /**
463      * Returns the information recorded about a particular named user.
464      *
465      * @param name name of the user whose information is desired
466      * @return the user object
467      * @exception NoSuchUserException if the user doesn't exist
468      * @exception BadRealmException if realm data structures are bad
469      */

470     public abstract User getUser(String JavaDoc name)
471     throws NoSuchUserException, BadRealmException;
472
473     /**
474      * Returns names of all the groups in this particular realm.
475      *
476      * @return enumeration of group names (strings)
477      * @exception BadRealmException if realm data structures are bad
478      */

479     public abstract Enumeration getGroupNames()
480     throws BadRealmException;
481
482     /**
483      * Returns the name of all the groups that this user belongs to
484      * @param username name of the user in this realm whose group listing
485      * is needed.
486      * @return enumeration of group names (strings)
487      * @exception InvalidOperationException thrown if the realm does not
488      * support this operation - e.g. Certificate realm does not support this
489      * operation
490      */

491     public abstract Enumeration getGroupNames (String JavaDoc username)
492     throws InvalidOperationException, NoSuchUserException;
493     
494     /**
495      * Refreshes the realm data so that new users/groups are visible.
496      *
497      * @exception BadRealmException if realm data structures are bad
498      */

499     public abstract void refresh() throws BadRealmException;
500     
501     /**
502      * Checks if the given realm name is loaded/valid.
503      * @param String name of the realm to check.
504      * @return true if realm present, false otherwise.
505      */

506     public static boolean isValidRealm(String JavaDoc name){
507         if(name == null){
508             return false;
509         } else {
510             return loadedRealms.containsKey(name);
511         }
512     }
513 }
514
515
516
517
518
519
Popular Tags