KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > winstone > realm > FileRealm


1 /*
2  * Copyright 2003-2006 Rick Knowles <winstone-devel at lists sourceforge net>
3  * Distributed under the terms of either:
4  * - the common development and distribution license (CDDL), v1.0; or
5  * - the GNU Lesser General Public License, v2.1 or later
6  */

7 package winstone.realm;
8
9 import java.io.File JavaDoc;
10 import java.io.FileInputStream JavaDoc;
11 import java.io.InputStream JavaDoc;
12 import java.util.ArrayList JavaDoc;
13 import java.util.Arrays JavaDoc;
14 import java.util.Hashtable JavaDoc;
15 import java.util.List JavaDoc;
16 import java.util.Map JavaDoc;
17 import java.util.Set JavaDoc;
18 import java.util.StringTokenizer JavaDoc;
19
20 import javax.xml.parsers.DocumentBuilder JavaDoc;
21 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
22
23 import org.w3c.dom.Document JavaDoc;
24 import org.w3c.dom.Node JavaDoc;
25
26 import winstone.AuthenticationPrincipal;
27 import winstone.AuthenticationRealm;
28 import winstone.Logger;
29 import winstone.WinstoneException;
30 import winstone.WinstoneResourceBundle;
31
32 /**
33  * @author rickk
34  * @version $Id: FileRealm.java,v 1.4 2006/08/30 04:07:52 rickknowles Exp $
35  */

36 public class FileRealm implements AuthenticationRealm {
37     private static final WinstoneResourceBundle REALM_RESOURCES = new WinstoneResourceBundle("winstone.realm.LocalStrings");
38     
39     final String JavaDoc FILE_NAME_ARGUMENT = "fileRealm.configFile";
40     final String JavaDoc DEFAULT_FILE_NAME = "users.xml";
41     final String JavaDoc ELEM_USER = "user";
42     final String JavaDoc ATT_USERNAME = "username";
43     final String JavaDoc ATT_PASSWORD = "password";
44     final String JavaDoc ATT_ROLELIST = "roles";
45     private Map JavaDoc passwords;
46     private Map JavaDoc roles;
47
48     /**
49      * Constructor - this sets up an authentication realm, using the file
50      * supplied on the command line as a source of userNames/passwords/roles.
51      */

52     public FileRealm(Set JavaDoc rolesAllowed, Map JavaDoc args) {
53         this.passwords = new Hashtable JavaDoc();
54         this.roles = new Hashtable JavaDoc();
55
56         // Get the filename and parse the xml doc
57
String JavaDoc realmFileName = args.get(FILE_NAME_ARGUMENT) == null ? DEFAULT_FILE_NAME
58                 : (String JavaDoc) args.get(FILE_NAME_ARGUMENT);
59         File JavaDoc realmFile = new File JavaDoc(realmFileName);
60         if (!realmFile.exists())
61             throw new WinstoneException(REALM_RESOURCES.getString(
62                     "FileRealm.FileNotFound", realmFile.getPath()));
63         try {
64             InputStream JavaDoc inFile = new FileInputStream JavaDoc(realmFile);
65             Document JavaDoc doc = this.parseStreamToXML(inFile);
66             inFile.close();
67             Node JavaDoc rootElm = doc.getDocumentElement();
68             for (int n = 0; n < rootElm.getChildNodes().getLength(); n++) {
69                 Node JavaDoc child = rootElm.getChildNodes().item(n);
70
71                 if ((child.getNodeType() == Node.ELEMENT_NODE)
72                         && (child.getNodeName().equals(ELEM_USER))) {
73                     String JavaDoc userName = null;
74                     String JavaDoc password = null;
75                     String JavaDoc roleList = null;
76                     // Loop through for attributes
77
for (int j = 0; j < child.getAttributes().getLength(); j++) {
78                         Node JavaDoc thisAtt = child.getAttributes().item(j);
79                         if (thisAtt.getNodeName().equals(ATT_USERNAME))
80                             userName = thisAtt.getNodeValue();
81                         else if (thisAtt.getNodeName().equals(ATT_PASSWORD))
82                             password = thisAtt.getNodeValue();
83                         else if (thisAtt.getNodeName().equals(ATT_ROLELIST))
84                             roleList = thisAtt.getNodeValue();
85                     }
86
87                     if ((userName == null) || (password == null)
88                             || (roleList == null))
89                         Logger.log(Logger.FULL_DEBUG, REALM_RESOURCES,
90                                 "FileRealm.SkippingUser", userName);
91                     else {
92                         // Parse the role list into an array and sort it
93
StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(roleList, ",");
94                         List JavaDoc rl = new ArrayList JavaDoc();
95                         for (; st.hasMoreTokens();) {
96                             String JavaDoc currentRole = st.nextToken();
97                             if (rolesAllowed.contains(currentRole))
98                                 rl.add(currentRole);
99                         }
100                         Object JavaDoc roleArray[] = rl.toArray();
101                         Arrays.sort(roleArray);
102                         this.passwords.put(userName, password);
103                         this.roles.put(userName, Arrays.asList(roleArray));
104                     }
105                 }
106             }
107             Logger.log(Logger.DEBUG, REALM_RESOURCES, "FileRealm.Initialised",
108                     "" + this.passwords.size());
109         } catch (java.io.IOException JavaDoc err) {
110             throw new WinstoneException(REALM_RESOURCES
111                     .getString("FileRealm.ErrorLoading"), err);
112         }
113     }
114
115     /**
116      * Get a parsed XML DOM from the given inputstream. Used to process the
117      * web.xml application deployment descriptors.
118      */

119     private Document JavaDoc parseStreamToXML(InputStream JavaDoc in) {
120         try {
121             // Use JAXP to create a document builder
122
DocumentBuilderFactory JavaDoc factory = DocumentBuilderFactory.newInstance();
123             factory.setExpandEntityReferences(false);
124             factory.setValidating(false);
125             factory.setNamespaceAware(false);
126             factory.setIgnoringComments(true);
127             factory.setCoalescing(true);
128             factory.setIgnoringElementContentWhitespace(true);
129             DocumentBuilder JavaDoc builder = factory.newDocumentBuilder();
130             return builder.parse(in);
131         } catch (Throwable JavaDoc errParser) {
132             throw new WinstoneException(REALM_RESOURCES
133                     .getString("FileRealm.XMLParseError"), errParser);
134         }
135     }
136
137     /**
138      * Authenticate the user - do we know them ? Return a principal once we know
139      * them
140      */

141     public AuthenticationPrincipal authenticateByUsernamePassword(
142             String JavaDoc userName, String JavaDoc password) {
143         if ((userName == null) || (password == null))
144             return null;
145
146         String JavaDoc realPassword = (String JavaDoc) this.passwords.get(userName);
147         if (realPassword == null)
148             return null;
149         else if (!realPassword.equals(password))
150             return null;
151         else
152             return new AuthenticationPrincipal(userName, password,
153                     (List JavaDoc) this.roles.get(userName));
154     }
155
156     /**
157      * Retrieve an authenticated user
158      */

159     public AuthenticationPrincipal retrieveUser(String JavaDoc userName) {
160         return new AuthenticationPrincipal(userName, (String JavaDoc) this.passwords
161                 .get(userName), (List JavaDoc) this.roles.get(userName));
162     }
163 }
164
Popular Tags