KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > sf > jguard > ext > authentication > manager > XmlAuthenticationManager


1 /*
2 jGuard is a security framework based on top of jaas (java authentication and authorization security).
3 it is written for web applications, to resolve simply, access control problems.
4 version $Name$
5 http://sourceforge.net/projects/jguard/
6
7 Copyright (C) 2004 Charles GAY
8
9 This library is free software; you can redistribute it and/or
10 modify it under the terms of the GNU Lesser General Public
11 License as published by the Free Software Foundation; either
12 version 2.1 of the License, or (at your option) any later version.
13
14 This library is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 Lesser General Public License for more details.
18
19 You should have received a copy of the GNU Lesser General Public
20 License along with this library; if not, write to the Free Software
21 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22
23
24 jGuard project home page:
25 http://sourceforge.net/projects/jguard/
26
27 */

28 package net.sf.jguard.ext.authentication.manager;
29
30 import java.io.FileWriter JavaDoc;
31 import java.io.IOException JavaDoc;
32 import java.io.OutputStream JavaDoc;
33 import java.security.Principal JavaDoc;
34 import java.util.Collection JavaDoc;
35 import java.util.HashMap JavaDoc;
36 import java.util.HashSet JavaDoc;
37 import java.util.Iterator JavaDoc;
38 import java.util.List JavaDoc;
39 import java.util.Map JavaDoc;
40 import java.util.Set JavaDoc;
41 import java.util.logging.Level JavaDoc;
42 import java.util.logging.Logger JavaDoc;
43
44 import javax.security.auth.Subject JavaDoc;
45
46 import net.sf.jguard.core.CoreConstants;
47 import net.sf.jguard.core.authentication.credentials.JGuardCredential;
48 import net.sf.jguard.core.principals.RolePrincipal;
49 import net.sf.jguard.ext.SecurityConstants;
50 import net.sf.jguard.ext.authentication.AuthenticationException;
51 import net.sf.jguard.ext.registration.SubjectTemplate;
52 import net.sf.jguard.ext.util.XMLUtils;
53
54 import org.dom4j.Attribute;
55 import org.dom4j.Document;
56 import org.dom4j.Element;
57 import org.dom4j.io.HTMLWriter;
58 import org.dom4j.io.OutputFormat;
59 import org.dom4j.io.XMLWriter;
60
61 /**
62  * AuthenticationManager implementation which persists in an XML repository file.
63  * @author <a HREF="mailto:diabolo512@users.sourceforge.net">Charles Gay</a>
64  * @author <a HREF="mailto:tandilero@users.sourceforge.net">Maximiliano Batelli</a>
65  *
66  */

67 public class XmlAuthenticationManager extends AbstractAuthenticationManager implements AuthenticationManager{
68
69     public static final String JavaDoc GENERIC_PRINCIPALS = "genericPrincipals";
70
71     private static final String JavaDoc PUBLIC_OPTIONAL_CREDENTIALS = "publicOptionalCredentials";
72     private static final String JavaDoc PRIVATE_OPTIONAL_CREDENTIALS = "privateOptionalCredentials";
73     private static final String JavaDoc PUBLIC_REQUIRED_CREDENTIALS = "publicRequiredCredentials";
74     private static final String JavaDoc CRED_TEMPLATE_ID = "credTemplateId";
75     private static final String JavaDoc PRIVATE_REQUIRED_CREDENTIALS = "privateRequiredCredentials";
76     private static final String JavaDoc USER_TEMPLATE = "userTemplate";
77     private static final String JavaDoc VALUE = "value";
78     private static final String JavaDoc ID = "id";
79     private static final String JavaDoc CREDENTIAL = "credential";
80     private static final String JavaDoc PRINCIPAL_REF = "principalRef";
81     private static final String JavaDoc PRINCIPALS_REF = "principalsRef";
82     private static final String JavaDoc PUBLIC_CREDENTIALS = "publicCredentials";
83     private static final String JavaDoc IDENTITY = "identity";
84     private static final String JavaDoc PRIVATE_CREDENTIALS = "privateCredentials";
85     private static final String JavaDoc USER = "user";
86     private static final String JavaDoc USERS = "users";
87     private static final String JavaDoc APPLICATION_NAME = "applicationName";
88     private static final String JavaDoc CLASS = "class";
89     private static final String JavaDoc NAME = "name";
90     private static final String JavaDoc ACTIVE = "active";
91     private static final String JavaDoc DEFINITION = "definition";
92     private static final String JavaDoc PRINCIPAL = "principal";
93     private static final String JavaDoc PRINCIPALS = "principals";
94     /** Logger for this class */
95     private static final Logger JavaDoc logger = Logger.getLogger(XmlAuthenticationManager.class.getName());
96     private Document document = null;
97     private Element root = null;
98     private String JavaDoc fileLocation = null;
99
100     //link principals applicationName#name(as keys) and principals objects from multiple applications
101
private Map JavaDoc principals;
102     //principals from multiple applications
103
private Set JavaDoc principalsSet;
104     private Set JavaDoc users;
105
106     public XmlAuthenticationManager(){
107         super();
108         users = new HashSet JavaDoc();
109         principalsSet = new HashSet JavaDoc();
110         principals = new HashMap JavaDoc();
111     }
112
113
114     /**
115      * persist principal in the XML repository.
116      * @param principal to persist
117      * @see net.sf.jguard.ext.authentication.manager.AuthenticationManager#createPrincipal(net.sf.jguard.core.principals.RolePrincipal)
118      */

119     protected void persistPrincipal(Principal JavaDoc principal) throws AuthenticationException {
120         Element principals = root.element(XmlAuthenticationManager.PRINCIPALS);
121         Element newPrincipal = principals.addElement(XmlAuthenticationManager.PRINCIPAL);
122         Element principalName = newPrincipal.addElement(XmlAuthenticationManager.NAME);
123         principalName.setText(principal.getName());
124
125         Element principalClass = newPrincipal.addElement(XmlAuthenticationManager.CLASS);
126         principalClass.setText(principal.getClass().getName());
127
128         Element applicationName = newPrincipal.addElement(XmlAuthenticationManager.APPLICATION_NAME);
129         if(principal instanceof RolePrincipal){
130           applicationName.setText(((RolePrincipal)principal).getApplicationName());
131         }
132          try {
133             XMLUtils.write(fileLocation,document);
134         } catch (IOException JavaDoc e) {
135             logger.severe(e.getMessage());
136             throw new AuthenticationException(e.getMessage());
137     }
138     }
139
140
141     /**
142      * initialise the DAO by reading the XML file, and converting it in objects.
143      * @see net.sf.jguard.ext.authentication.manager.AuthenticationManager#init(java.util.Map)
144      */

145     public void init(Map JavaDoc options) {
146
147         applicationName= (String JavaDoc)options.get(CoreConstants.APPLICATION_NAME);
148
149         debug = Boolean.valueOf((String JavaDoc)options.get("debug")).booleanValue();
150         fileLocation = (String JavaDoc)options.get(SecurityConstants.AUTHENTICATION_XML_FILE_LOCATION);
151
152         if(fileLocation==null){
153             logger.severe(" parameter '"+SecurityConstants.AUTHENTICATION_XML_FILE_LOCATION+"' which is null must be specified in the authentication configuration ");
154         }
155         if(debug){
156             if (logger.isLoggable(Level.FINEST)) {
157                 logger.finest("initAuthenticationDAO() - fileLocation="+ fileLocation);
158             }
159         }
160
161         document = XMLUtils.read(fileLocation);
162         root = document.getRootElement();
163         initPrincipals(root);
164         try {
165             super.subjectTemplate = getSubjectTemplate(AbstractAuthenticationManager.DEFAULT);
166         } catch (AuthenticationException e) {
167             logger.info(" no SubjectTemplate are defined ");
168         }
169         users = initUsers(root);
170
171     }
172
173     /**
174      * update user's informations in the XML repository file.
175      * @see net.sf.jguard.ext.authentication.manager.AuthenticationManager#updateUser(JGuardCredential, javax.security.auth.Subject)
176      */

177     protected void updateUserImpl(JGuardCredential identityCred, Subject JavaDoc user) throws AuthenticationException {
178         logger.finest("update user - identityCred ="+identityCred);
179         Element userElement = findUser(identityCred);
180         if(userElement!=null){
181             deleteUserFromMemory(identityCred);
182             root.element(XmlAuthenticationManager.USERS).elements(XmlAuthenticationManager.USER).remove(userElement);
183             try {
184                    XMLUtils.write(fileLocation,document);
185             } catch (IOException JavaDoc e) {
186                    logger.log(Level.SEVERE, "removeUser(Subject)", e);
187                    throw new AuthenticationException(e.getMessage());
188             }
189             persistUser(user);
190         }
191     }
192
193     /**
194      * remove user from users repository stored in memory.
195      * @param user to remove
196      * @throws AuthenticationException
197      */

198     private void deleteUserFromMemory(Subject JavaDoc user) throws AuthenticationException{
199         deleteUserFromMemory(extractIdentityCredentialFromUser(user));
200     }
201
202     /**
203      * remove user from users repository stored in memory.
204      * @param identityCred 'identity' credential from the user to remove.
205      * @throws AuthenticationException
206      */

207     private void deleteUserFromMemory(JGuardCredential identityCred) throws AuthenticationException{
208         Iterator JavaDoc itUsers= users.iterator();
209         while(itUsers.hasNext()){
210             Subject JavaDoc user = (Subject JavaDoc)itUsers.next();
211             JGuardCredential credFromUser = extractIdentityCredentialFromUser(user);
212             if(identityCred.equals(credFromUser)){
213                 itUsers.remove();
214                 logger.finest("user with identityCred:"+identityCred.getId()+" ="+identityCred.getValue()+" removed ");
215                 break;
216             }
217         }
218     }
219     
220     /**
221      * remove the user from the XML repository.
222      * @param user to remove
223      * @throws AuthenticationException
224      * @see net.sf.jguard.ext.authentication.manager.AuthenticationManager#deleteUser(javax.security.auth.Subject)
225      */

226     public void deleteUser(Subject JavaDoc user) throws AuthenticationException {
227         if(user!= null){
228             deleteUserFromMemory(user);
229
230             Element userElement = findUser(user);
231             if(userElement!= null){
232                root.element(XmlAuthenticationManager.USERS).elements(XmlAuthenticationManager.USER).remove(userElement);
233                try {
234                    XMLUtils.write(fileLocation,document);
235                } catch (IOException JavaDoc e) {
236                    logger.log(Level.SEVERE, "removeUser(Subject)", e);
237                    throw new AuthenticationException(e.getMessage());
238                }
239
240             }
241         }
242     }
243
244     /**
245      * find the DOM4J Element corresponding to this Subject, null otherwise.
246      * @param user subject we are looking for in the XML repository file.
247      * @return Element corresponding to the found user, null if not found.
248      * @throws AuthenticationException
249      */

250     private Element findUser(Subject JavaDoc user)throws AuthenticationException{
251
252         JGuardCredential identityCred = extractIdentityCredentialFromUser(user);
253
254         return findUser(identityCred);
255     }
256
257
258     /**
259      * return the DOM4J element which match with the identityCredential provided.
260      * @param identityCred
261      * @return null if no user is found, an Element if user found
262      */

263     private Element findUser(JGuardCredential identityCred) {
264         logger.finest("try to find user with identityCredential="+identityCred);
265         Element usersElement = root.element(XmlAuthenticationManager.USERS);
266         List JavaDoc usersElementlist = usersElement.elements(XmlAuthenticationManager.USER);
267         Iterator JavaDoc itUsersList = usersElementlist.iterator();
268         while(itUsersList.hasNext()){
269
270             Element userElement = (Element)itUsersList.next();
271             Element privateCredentialsElement = userElement.element(XmlAuthenticationManager.PRIVATE_CREDENTIALS);
272             Element elt = (Element)privateCredentialsElement.selectSingleNode("./credential[id='"+identityCred.getId()+"' and value='"+identityCred.getValue()+"']");
273             if(elt!=null){
274                 logger.finest("user "+userElement+"has been found");
275                 return userElement;
276             }
277
278
279             Element publicCredentialsElement = userElement.element(XmlAuthenticationManager.PUBLIC_CREDENTIALS);
280             Element elt2 = (Element)publicCredentialsElement.selectSingleNode("./credential[id='"+identityCred.getId()+"' and value='"+identityCred.getValue()+"']");
281             if(elt2!=null){
282                 logger.finest("user "+userElement+"has been found");
283                 return userElement;
284             }
285         }
286         //no user has been found
287
logger.finest("no user has been found");
288         return null;
289     }
290
291     /**
292      * initialize principals.
293      * @param root dom4j element
294      */

295     private void initPrincipals(Element root){
296         Element principalsElement = root.element(XmlAuthenticationManager.PRINCIPALS);
297         List JavaDoc principalsList = principalsElement.elements(XmlAuthenticationManager.PRINCIPAL);
298         Iterator JavaDoc itPrincipalsList = principalsList.iterator();
299
300         while(itPrincipalsList.hasNext()){
301             Element principalElement = (Element)itPrincipalsList.next();
302             RolePrincipal principal = new RolePrincipal();
303             principal.setLocalName(principalElement.element(XmlAuthenticationManager.NAME).getStringValue());
304             Element applicationNameElement = principalElement.element(XmlAuthenticationManager.APPLICATION_NAME);
305             principal.setApplicationName(applicationNameElement.getStringValue());
306             principals.put(principal.getName(),principal);
307             principalsSet.add(principal);
308             if(principal.getApplicationName().equals(applicationName)){
309                 localPrincipalsSet.add(principal);
310                 localPrincipals.put(principal.getName(),principal);
311             }
312         }
313
314
315     }
316
317     /**
318      * initialize users.
319      * @param root dom4j element
320      * @return users Set
321      */

322     private Set JavaDoc initUsers(Element root){
323         Element usersElement = root.element(XmlAuthenticationManager.USERS);
324         List JavaDoc usersList = usersElement.elements(XmlAuthenticationManager.USER);
325         Iterator JavaDoc itUsersList = usersList.iterator();
326
327         while(itUsersList.hasNext()){
328             Element userElement = (Element)itUsersList.next();
329
330             Set JavaDoc userPrincipals = new HashSet JavaDoc();
331             Set JavaDoc privateCredentials = new HashSet JavaDoc();
332             Set JavaDoc publicCredentials = new HashSet JavaDoc();
333             Element privateCredentialsElement = userElement.element(XmlAuthenticationManager.PRIVATE_CREDENTIALS);
334             Element publicCredentialsElement = userElement.element(XmlAuthenticationManager.PUBLIC_CREDENTIALS);
335             List JavaDoc privCredentialsList = privateCredentialsElement.elements(XmlAuthenticationManager.CREDENTIAL);
336             Iterator JavaDoc itPrivCred = privCredentialsList.iterator();
337             while(itPrivCred.hasNext()){
338                 Element privateCredentialElement = (Element)itPrivCred.next();
339                 JGuardCredential privateCredential = new JGuardCredential();
340                 String JavaDoc id = privateCredentialElement.element(XmlAuthenticationManager.ID).getStringValue();
341                 String JavaDoc value = privateCredentialElement.element(XmlAuthenticationManager.VALUE).getStringValue();
342                 privateCredential.setId(id);
343                 privateCredential.setValue(value);
344                 privateCredentials.add(privateCredential);
345             }
346
347             List JavaDoc pubCredentialsList = publicCredentialsElement.elements(XmlAuthenticationManager.CREDENTIAL);
348             Iterator JavaDoc itPubCred = pubCredentialsList.iterator();
349             while(itPubCred.hasNext()){
350
351                 Element publicCredentialElement = (Element)itPubCred.next();
352                 JGuardCredential publicCredential = new JGuardCredential();
353                 String JavaDoc id = publicCredentialElement.element(XmlAuthenticationManager.ID).getStringValue();
354                 String JavaDoc value = publicCredentialElement.element(XmlAuthenticationManager.VALUE).getStringValue();
355                 publicCredential.setId(id);
356                 publicCredential.setValue(value);
357                 publicCredentials.add(publicCredential);
358             }
359
360             Element principalsRefElement = userElement.element(XmlAuthenticationManager.PRINCIPALS_REF);
361             List JavaDoc userPrincipalsRefElement = principalsRefElement.elements(XmlAuthenticationManager.PRINCIPAL_REF);
362             Iterator JavaDoc itUserPrincipals = userPrincipalsRefElement.iterator();
363             while(itUserPrincipals.hasNext()){
364                 Element principalElement = (Element)itUserPrincipals.next();
365                 String JavaDoc principalName = principalElement.attributeValue(XmlAuthenticationManager.NAME);
366                 String JavaDoc principalApplicationName = principalElement.attributeValue(XmlAuthenticationManager.APPLICATION_NAME);
367                 //if the applicationName is not set, the current applicationName is implied
368
if(principalApplicationName==null){
369                     principalApplicationName = super.applicationName;
370                 }
371                 String JavaDoc definition = principalElement.attributeValue(XmlAuthenticationManager.DEFINITION);
372                 String JavaDoc active = principalElement.attributeValue(XmlAuthenticationManager.ACTIVE);
373                 
374                 RolePrincipal principal = new RolePrincipal();
375                 principal.setLocalName(principalName);
376                 principal.setApplicationName(principalApplicationName);
377                 principal.setDefinition(definition);
378                 if("true".equalsIgnoreCase(active))
379                     principal.setActive(true);
380                 else
381                     principal.setActive(false);
382                 
383                 userPrincipals.add(principal);
384             }
385             
386
387             //subject is not in read-only mode
388
Subject JavaDoc user = new Subject JavaDoc(false,userPrincipals,publicCredentials,privateCredentials);
389             
390             users.add(user);
391         }
392
393         return users;
394     }
395
396     /**
397      * construct from configuration file the subjectTemplate.
398      * @return Subject template built
399      * @throws AuthenticationException
400      */

401     public SubjectTemplate getSubjectTemplate(String JavaDoc name) throws AuthenticationException{
402         List JavaDoc stList= root.selectNodes("//userTemplate[name=\""+name+"\"]");
403         if(stList ==null ||stList.size()!=1){
404             logger.severe("SubjectTemplates found : "+stList);
405             throw new AuthenticationException("subjecttemplate intitled "+name+" is not unique ");
406         }
407         Element subjectTemplateElement = (Element)stList.get(0);
408         SubjectTemplate st = buildSubjectTemplateFromElement(subjectTemplateElement,name);
409         return st;
410     }
411
412
413     private SubjectTemplate buildSubjectTemplateFromElement(Element userTemplate,String JavaDoc name) {
414         Element privateRequiredCredentials = userTemplate.element(XmlAuthenticationManager.PRIVATE_REQUIRED_CREDENTIALS);
415         List JavaDoc privReqCreds = privateRequiredCredentials.elements(XmlAuthenticationManager.CRED_TEMPLATE_ID);
416         Set JavaDoc privReqCreds2 = getJGuardCredentialList(privReqCreds);
417         Element publicRequiredCredentials = userTemplate.element(XmlAuthenticationManager.PUBLIC_REQUIRED_CREDENTIALS);
418         List JavaDoc pubReqCreds = publicRequiredCredentials.elements(XmlAuthenticationManager.CRED_TEMPLATE_ID);
419         Set JavaDoc pubReqCreds2 = getJGuardCredentialList(pubReqCreds);
420         Element privateOptionalCredentials = userTemplate.element(XmlAuthenticationManager.PRIVATE_OPTIONAL_CREDENTIALS);
421         List JavaDoc privOptCreds = privateOptionalCredentials.elements(XmlAuthenticationManager.CRED_TEMPLATE_ID);
422         Set JavaDoc privOptCreds2 = getJGuardCredentialList(privOptCreds);
423         Element publicOptionalCredentials = userTemplate.element(XmlAuthenticationManager.PUBLIC_OPTIONAL_CREDENTIALS);
424         List JavaDoc pubOptCreds = publicOptionalCredentials.elements(XmlAuthenticationManager.CRED_TEMPLATE_ID);
425         Set JavaDoc pubOptCreds2 = getJGuardCredentialList(pubOptCreds);
426         SubjectTemplate st = new SubjectTemplate();
427         st.setPrivateRequiredCredentials(privReqCreds2);
428         st.setPublicRequiredCredentials(pubReqCreds2);
429         st.setPrivateOptionalCredentials(privOptCreds2);
430         st.setPublicOptionalCredentials(pubOptCreds2);
431
432         List JavaDoc genericPrincipalElements = userTemplate.element(XmlAuthenticationManager.GENERIC_PRINCIPALS).elements(XmlAuthenticationManager.PRINCIPAL_REF);
433         Set JavaDoc genPpals = getGenericPrincipals(genericPrincipalElements);
434         st.setPrincipals(genPpals);
435         st.setName(name);
436         return st;
437     }
438
439
440
441     private Set JavaDoc getGenericPrincipals(List JavaDoc genericPrincipalElements){
442         Set JavaDoc genericPpals = new HashSet JavaDoc();
443         Iterator JavaDoc principalsIterator = genericPrincipalElements.iterator();
444         while(principalsIterator.hasNext()){
445             Element ppalElement = (Element)principalsIterator.next();
446             Principal JavaDoc ppal = (Principal JavaDoc)principals.get(applicationName+"#"+ppalElement.attribute("name").getData());
447             if(ppal!=null){
448                 genericPpals.add(ppal);
449             }
450         }
451
452         return genericPpals;
453     }
454     /**
455      * transform a list of DOM4J elements into a Set of JGuardCredentials.
456      * @param credTemplateIdElements list of DOM4J elements
457      * @return Set of jGuardCredentials
458      */

459     private Set JavaDoc getJGuardCredentialList(List JavaDoc credTemplateIdElements){
460         Iterator JavaDoc it = credTemplateIdElements.iterator();
461         Set JavaDoc jguardCredlist = new HashSet JavaDoc();
462         while(it.hasNext()){
463             Element credElement = (Element)it.next();
464             JGuardCredential jcred = new JGuardCredential();
465             Attribute identity = credElement.attribute(XmlAuthenticationManager.IDENTITY);
466             if(identity!=null && identity.getText().equals("true")){
467                 jcred.setIdentity(true);
468             }
469             String JavaDoc id = credElement.getStringValue();
470
471             jcred.setId(id);
472             jguardCredlist.add(jcred);
473         }
474         return jguardCredlist;
475     }
476
477     /**
478      * persist user into the XML repository file.
479      * @param user
480      * @throws AuthenticationException
481      */

482     protected void persistUser(Subject JavaDoc user) throws AuthenticationException {
483         Element xmlUsers = root.element(XmlAuthenticationManager.USERS);
484         Element newUser = xmlUsers.addElement(XmlAuthenticationManager.USER);
485         Element privateCredentials = newUser.addElement(XmlAuthenticationManager.PRIVATE_CREDENTIALS);
486         Set JavaDoc privCredentialsSet = user.getPrivateCredentials(JGuardCredential.class);
487         persistCredentialsSet(privCredentialsSet,privateCredentials);
488
489         Element publicCredentials = newUser.addElement(XmlAuthenticationManager.PUBLIC_CREDENTIALS);
490         Set JavaDoc pubCredentials = user.getPublicCredentials(JGuardCredential.class);
491         persistCredentialsSet(pubCredentials,publicCredentials);
492
493         Element ppals = newUser.addElement(XmlAuthenticationManager.PRINCIPALS_REF);
494         Set JavaDoc principals = user.getPrincipals();
495         persistPrincipalRefs(principals,ppals);
496         try {
497             XMLUtils.write(fileLocation,document);
498             //add the user to the in-memory users repository
499
this.users.add(user);
500         } catch (IOException JavaDoc e) {
501             logger.log(Level.SEVERE, "persistUser(Subject)", e);
502             throw new AuthenticationException(e.getMessage());
503         }
504     }
505
506     /**
507      * persist principals into the XML repository file.
508      * @param principals
509      * @param ppals
510      */

511     private void persistPrincipalRefs(Set JavaDoc principals, Element ppals) {
512         
513         Iterator JavaDoc itPrincipals = principals.iterator();
514         while(itPrincipals.hasNext()){
515             Principal JavaDoc ppal = (Principal JavaDoc)itPrincipals.next();
516             if(ppal instanceof RolePrincipal) {
517                 RolePrincipal jppal = (RolePrincipal)ppal;
518                 Element principal = ppals.addElement(XmlAuthenticationManager.PRINCIPAL_REF);
519                 principal.addAttribute(XmlAuthenticationManager.NAME, jppal.getLocalName());
520                 principal.addAttribute(XmlAuthenticationManager.APPLICATION_NAME, jppal.getApplicationName());
521                 principal.addAttribute(XmlAuthenticationManager.DEFINITION, jppal.getDefinition());
522                 principal.addAttribute(XmlAuthenticationManager.ACTIVE, jppal.isActive()==true?"true":"false");
523             }
524         }
525
526     }
527
528     /**
529      * persist a jGuardCredential set into the XML subset corresponding to the
530      * credentialsSetElement.
531      * @param credentials
532      * @param credentialsSetElement
533      */

534     private void persistCredentialsSet(Set JavaDoc credentials,Element credentialsSetElement){
535         Iterator JavaDoc itPubCredentials = credentials.iterator();
536         while(itPubCredentials.hasNext()){
537             JGuardCredential jcred2 = (JGuardCredential)itPubCredentials.next();
538             Element credential = credentialsSetElement.addElement(XmlAuthenticationManager.CREDENTIAL);
539             Element id = credential.addElement(XmlAuthenticationManager.ID);
540             id.setText(jcred2.getId());
541             Element value = credential.addElement(XmlAuthenticationManager.VALUE);
542             value.setText(jcred2.getValue().toString());
543         }
544
545     }
546
547
548     /**
549      * define and persist the SubjectTemplate for registration.
550      * @param template
551      */

552     public void persistSubjectTemplate(SubjectTemplate template) {
553          Element subjectTemplateElement = root.element(XmlAuthenticationManager.USER_TEMPLATE);
554          Element privateRequiredCredentials = subjectTemplateElement.element(XmlAuthenticationManager.PRIVATE_REQUIRED_CREDENTIALS);
555          Iterator JavaDoc privReqCredIt = template.getPrivateRequiredCredentials().iterator();
556          while(privReqCredIt.hasNext()){
557              JGuardCredential cred = (JGuardCredential)privReqCredIt.next();
558              Element cred1 = privateRequiredCredentials.addElement(XmlAuthenticationManager.CRED_TEMPLATE_ID);
559              cred1.setText(cred.getId());
560          }
561
562          Element publicRequiredCredentials = subjectTemplateElement.element(XmlAuthenticationManager.PUBLIC_REQUIRED_CREDENTIALS);
563          Iterator JavaDoc pubReqCredIt = template.getPublicRequiredCredentials().iterator();
564          while(pubReqCredIt.hasNext()){
565              JGuardCredential cred = (JGuardCredential)pubReqCredIt.next();
566              Element cred1 = publicRequiredCredentials.addElement(XmlAuthenticationManager.CRED_TEMPLATE_ID);
567              cred1.setText(cred.getId());
568          }
569
570          Element privateOptionalCredentials = subjectTemplateElement.element(XmlAuthenticationManager.PRIVATE_OPTIONAL_CREDENTIALS);
571          Iterator JavaDoc privOptCredIt = template.getPrivateOptionalCredentials().iterator();
572          while(privOptCredIt.hasNext()){
573              JGuardCredential cred = (JGuardCredential)privOptCredIt.next();
574              Element cred1 = privateOptionalCredentials.addElement(XmlAuthenticationManager.CRED_TEMPLATE_ID);
575              cred1.setText(cred.getId());
576          }
577
578
579          Element publicOptionalCredentials = subjectTemplateElement.element(XmlAuthenticationManager.PUBLIC_OPTIONAL_CREDENTIALS);
580          Iterator JavaDoc pubOptCredIt = template.getPublicOptionalCredentials().iterator();
581          while(pubOptCredIt.hasNext()){
582              JGuardCredential cred = (JGuardCredential)pubOptCredIt.next();
583              Element cred1 = publicOptionalCredentials.addElement(XmlAuthenticationManager.CRED_TEMPLATE_ID);
584              cred1.setText(cred.getId());
585          }
586     }
587
588     /**
589      * @return <i>true</i> if there is no principals and no permissions.
590      * <i>false</i> otherwise.
591      */

592     public boolean isEmpty() {
593         List JavaDoc principalsList = root.selectNodes("//principal");
594         List JavaDoc users = root.selectNodes("//users");
595         if(!principalsList.isEmpty()&&!users.isEmpty()){
596             return false;
597         }
598         return true;
599
600     }
601
602
603
604
605     public Set JavaDoc getAllPrincipalsSet(){
606         return principalsSet;
607     }
608
609
610
611
612     /**
613      * search the users which matches credentials criterions.
614      * @param credentials crierions used to grab the users
615      * @return users found
616      */

617     public Set JavaDoc findUsers(Collection JavaDoc credentials){
618         Set JavaDoc usersFound = new HashSet JavaDoc();
619         Iterator JavaDoc it = users.iterator();
620         while(it.hasNext()){
621             Subject JavaDoc user = (Subject JavaDoc)it.next();
622             Iterator JavaDoc itCred = credentials.iterator();
623             boolean userFound = true;
624             while(itCred.hasNext()){
625                 JGuardCredential jcred = (JGuardCredential)itCred.next();
626                 if(user.getPrivateCredentials().contains(jcred)||
627                    user.getPublicCredentials().contains(jcred)){
628                   continue;
629                 }else{
630                      userFound = false;
631                 }
632             }
633
634             if(userFound==true){
635                 usersFound.add(user);
636             }
637         }
638         return usersFound;
639     }
640
641     public Set JavaDoc getUsers() {
642         return users;
643     }
644
645
646     public void updatePrincipal(String JavaDoc oldPrincipalName, Principal JavaDoc principal) {
647         Principal JavaDoc oldPal = (Principal JavaDoc)principals.remove(oldPrincipalName);
648         principalsSet.remove(oldPal);
649         principals.put(principal.getName(),principal);
650         principalsSet.add(principal);
651
652         try {
653             XMLUtils.write(fileLocation,document);
654         } catch (IOException JavaDoc e) {
655             logger.log(Level.SEVERE, "updateRole(String, RolePrincipal)", e);
656         }
657
658     }
659
660
661     public boolean deletePrincipal(Principal JavaDoc principal) throws AuthenticationException {
662         Principal JavaDoc ppalReference = (Principal JavaDoc)principals.remove(principal.getName());
663         if(ppalReference==null){
664             return false;
665         }
666         principalsSet.remove(ppalReference);
667         Element principalsElement = root.element("principals");
668         Element principalElement = (Element)principalsElement.selectSingleNode("//principal[name='"+principal.getName()+"']");
669         principalsElement.remove(principalElement);
670         if(ppalReference.getClass().equals(RolePrincipal.class)){
671           //delete all the references of this principal
672
XMLUtils.deletePrincipalRefs(root,(RolePrincipal)ppalReference);
673         }
674         try {
675             XMLUtils.write(fileLocation,document);
676         } catch (IOException JavaDoc e) {
677             logger.log(Level.SEVERE, "deletePrincipal(String)", e);
678             throw new AuthenticationException(e.getMessage());
679         }
680         return true;
681
682     }
683
684     
685     public String JavaDoc exportAsXMLString(){
686         return document.asXML();
687     }
688     
689     public void writeAsXML(OutputStream JavaDoc outputStream, String JavaDoc encodingScheme) throws IOException JavaDoc {
690        OutputFormat outformat = OutputFormat.createPrettyPrint();
691        outformat.setEncoding(encodingScheme);
692        XMLWriter writer = new XMLWriter(outputStream, outformat);
693        writer.write(this.document);
694        writer.flush();
695     }
696
697
698     
699     public void writeAsHTML(OutputStream JavaDoc outputStream) throws IOException JavaDoc{
700          HTMLWriter writer = new HTMLWriter(outputStream,OutputFormat.createPrettyPrint());
701          writer.write(this.document);
702          writer.flush();
703     }
704
705
706     public void exportAsXMLFile(String JavaDoc fileName) throws IOException JavaDoc {
707         XMLWriter xmlWriter = new XMLWriter(new FileWriter JavaDoc(fileName), OutputFormat.createPrettyPrint());
708         xmlWriter.write(document);
709         xmlWriter.close();
710     }
711 }
712
Popular Tags