Source Code Cross Referenced for XmlAuthenticationManager.java in  » Authentication-Authorization » jguard » net » sf » jguard » ext » authentication » manager » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » Authentication Authorization » jguard » net.sf.jguard.ext.authentication.manager 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


001:        /*
002:        jGuard is a security framework based on top of jaas (java authentication and authorization security).
003:        it is written for web applications, to resolve simply, access control problems.
004:        version $Name$
005:        http://sourceforge.net/projects/jguard/
006:
007:        Copyright (C) 2004  Charles GAY
008:
009:        This library is free software; you can redistribute it and/or
010:        modify it under the terms of the GNU Lesser General Public
011:        License as published by the Free Software Foundation; either
012:        version 2.1 of the License, or (at your option) any later version.
013:
014:        This library is distributed in the hope that it will be useful,
015:        but WITHOUT ANY WARRANTY; without even the implied warranty of
016:        MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
017:        Lesser General Public License for more details.
018:
019:        You should have received a copy of the GNU Lesser General Public
020:        License along with this library; if not, write to the Free Software
021:        Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
022:
023:
024:        jGuard project home page:
025:        http://sourceforge.net/projects/jguard/
026:
027:         */
028:        package net.sf.jguard.ext.authentication.manager;
029:
030:        import java.io.FileWriter;
031:        import java.io.IOException;
032:        import java.io.OutputStream;
033:        import java.security.Principal;
034:        import java.util.Collection;
035:        import java.util.HashMap;
036:        import java.util.HashSet;
037:        import java.util.Iterator;
038:        import java.util.List;
039:        import java.util.Map;
040:        import java.util.Set;
041:        import java.util.logging.Level;
042:        import java.util.logging.Logger;
043:
044:        import javax.security.auth.Subject;
045:
046:        import net.sf.jguard.core.CoreConstants;
047:        import net.sf.jguard.core.authentication.credentials.JGuardCredential;
048:        import net.sf.jguard.core.principals.RolePrincipal;
049:        import net.sf.jguard.ext.SecurityConstants;
050:        import net.sf.jguard.ext.authentication.AuthenticationException;
051:        import net.sf.jguard.ext.registration.SubjectTemplate;
052:        import net.sf.jguard.ext.util.XMLUtils;
053:
054:        import org.dom4j.Attribute;
055:        import org.dom4j.Document;
056:        import org.dom4j.Element;
057:        import org.dom4j.io.HTMLWriter;
058:        import org.dom4j.io.OutputFormat;
059:        import org.dom4j.io.XMLWriter;
060:
061:        /**
062:         * AuthenticationManager implementation which persists in an XML repository file.
063:         * @author <a href="mailto:diabolo512@users.sourceforge.net">Charles Gay</a>
064:         * @author <a href="mailto:tandilero@users.sourceforge.net">Maximiliano Batelli</a>
065:         *
066:         */
067:        public class XmlAuthenticationManager extends
068:                AbstractAuthenticationManager implements  AuthenticationManager {
069:
070:            public static final String GENERIC_PRINCIPALS = "genericPrincipals";
071:
072:            private static final String PUBLIC_OPTIONAL_CREDENTIALS = "publicOptionalCredentials";
073:            private static final String PRIVATE_OPTIONAL_CREDENTIALS = "privateOptionalCredentials";
074:            private static final String PUBLIC_REQUIRED_CREDENTIALS = "publicRequiredCredentials";
075:            private static final String CRED_TEMPLATE_ID = "credTemplateId";
076:            private static final String PRIVATE_REQUIRED_CREDENTIALS = "privateRequiredCredentials";
077:            private static final String USER_TEMPLATE = "userTemplate";
078:            private static final String VALUE = "value";
079:            private static final String ID = "id";
080:            private static final String CREDENTIAL = "credential";
081:            private static final String PRINCIPAL_REF = "principalRef";
082:            private static final String PRINCIPALS_REF = "principalsRef";
083:            private static final String PUBLIC_CREDENTIALS = "publicCredentials";
084:            private static final String IDENTITY = "identity";
085:            private static final String PRIVATE_CREDENTIALS = "privateCredentials";
086:            private static final String USER = "user";
087:            private static final String USERS = "users";
088:            private static final String APPLICATION_NAME = "applicationName";
089:            private static final String CLASS = "class";
090:            private static final String NAME = "name";
091:            private static final String ACTIVE = "active";
092:            private static final String DEFINITION = "definition";
093:            private static final String PRINCIPAL = "principal";
094:            private static final String PRINCIPALS = "principals";
095:            /** Logger for this class */
096:            private static final Logger logger = Logger
097:                    .getLogger(XmlAuthenticationManager.class.getName());
098:            private Document document = null;
099:            private Element root = null;
100:            private String fileLocation = null;
101:
102:            //link principals applicationName#name(as keys) and principals objects from multiple applications
103:            private Map principals;
104:            //principals from multiple applications
105:            private Set principalsSet;
106:            private Set users;
107:
108:            public XmlAuthenticationManager() {
109:                super ();
110:                users = new HashSet();
111:                principalsSet = new HashSet();
112:                principals = new HashMap();
113:            }
114:
115:            /**
116:             * persist principal in the XML repository.
117:             * @param principal to persist
118:             * @see net.sf.jguard.ext.authentication.manager.AuthenticationManager#createPrincipal(net.sf.jguard.core.principals.RolePrincipal)
119:             */
120:            protected void persistPrincipal(Principal principal)
121:                    throws AuthenticationException {
122:                Element principals = root
123:                        .element(XmlAuthenticationManager.PRINCIPALS);
124:                Element newPrincipal = principals
125:                        .addElement(XmlAuthenticationManager.PRINCIPAL);
126:                Element principalName = newPrincipal
127:                        .addElement(XmlAuthenticationManager.NAME);
128:                principalName.setText(principal.getName());
129:
130:                Element principalClass = newPrincipal
131:                        .addElement(XmlAuthenticationManager.CLASS);
132:                principalClass.setText(principal.getClass().getName());
133:
134:                Element applicationName = newPrincipal
135:                        .addElement(XmlAuthenticationManager.APPLICATION_NAME);
136:                if (principal instanceof  RolePrincipal) {
137:                    applicationName.setText(((RolePrincipal) principal)
138:                            .getApplicationName());
139:                }
140:                try {
141:                    XMLUtils.write(fileLocation, document);
142:                } catch (IOException e) {
143:                    logger.severe(e.getMessage());
144:                    throw new AuthenticationException(e.getMessage());
145:                }
146:            }
147:
148:            /**
149:             * initialise the DAO by reading the XML file, and converting it in objects.
150:             * @see net.sf.jguard.ext.authentication.manager.AuthenticationManager#init(java.util.Map)
151:             */
152:            public void init(Map options) {
153:
154:                applicationName = (String) options
155:                        .get(CoreConstants.APPLICATION_NAME);
156:
157:                debug = Boolean.valueOf((String) options.get("debug"))
158:                        .booleanValue();
159:                fileLocation = (String) options
160:                        .get(SecurityConstants.AUTHENTICATION_XML_FILE_LOCATION);
161:
162:                if (fileLocation == null) {
163:                    logger
164:                            .severe(" parameter '"
165:                                    + SecurityConstants.AUTHENTICATION_XML_FILE_LOCATION
166:                                    + "' which is null must be specified in the authentication configuration ");
167:                }
168:                if (debug) {
169:                    if (logger.isLoggable(Level.FINEST)) {
170:                        logger.finest("initAuthenticationDAO() - fileLocation="
171:                                + fileLocation);
172:                    }
173:                }
174:
175:                document = XMLUtils.read(fileLocation);
176:                root = document.getRootElement();
177:                initPrincipals(root);
178:                try {
179:                    super .subjectTemplate = getSubjectTemplate(AbstractAuthenticationManager.DEFAULT);
180:                } catch (AuthenticationException e) {
181:                    logger.info(" no SubjectTemplate are defined ");
182:                }
183:                users = initUsers(root);
184:
185:            }
186:
187:            /**
188:             * update user's informations in the XML repository file.
189:             * @see net.sf.jguard.ext.authentication.manager.AuthenticationManager#updateUser(JGuardCredential, javax.security.auth.Subject)
190:             */
191:            protected void updateUserImpl(JGuardCredential identityCred,
192:                    Subject user) throws AuthenticationException {
193:                logger.finest("update user - identityCred =" + identityCred);
194:                Element userElement = findUser(identityCred);
195:                if (userElement != null) {
196:                    deleteUserFromMemory(identityCred);
197:                    root.element(XmlAuthenticationManager.USERS).elements(
198:                            XmlAuthenticationManager.USER).remove(userElement);
199:                    try {
200:                        XMLUtils.write(fileLocation, document);
201:                    } catch (IOException e) {
202:                        logger.log(Level.SEVERE, "removeUser(Subject)", e);
203:                        throw new AuthenticationException(e.getMessage());
204:                    }
205:                    persistUser(user);
206:                }
207:            }
208:
209:            /**
210:             * remove user from users repository stored in memory.
211:             * @param user to remove
212:             * @throws AuthenticationException
213:             */
214:            private void deleteUserFromMemory(Subject user)
215:                    throws AuthenticationException {
216:                deleteUserFromMemory(extractIdentityCredentialFromUser(user));
217:            }
218:
219:            /**
220:             * remove user from users repository stored in memory.
221:             * @param identityCred 'identity' credential from the user to remove.
222:             * @throws AuthenticationException
223:             */
224:            private void deleteUserFromMemory(JGuardCredential identityCred)
225:                    throws AuthenticationException {
226:                Iterator itUsers = users.iterator();
227:                while (itUsers.hasNext()) {
228:                    Subject user = (Subject) itUsers.next();
229:                    JGuardCredential credFromUser = extractIdentityCredentialFromUser(user);
230:                    if (identityCred.equals(credFromUser)) {
231:                        itUsers.remove();
232:                        logger.finest("user with identityCred:"
233:                                + identityCred.getId() + " ="
234:                                + identityCred.getValue() + " removed ");
235:                        break;
236:                    }
237:                }
238:            }
239:
240:            /**
241:             * remove the user from the XML repository.
242:             * @param user to remove
243:             * @throws AuthenticationException
244:             * @see net.sf.jguard.ext.authentication.manager.AuthenticationManager#deleteUser(javax.security.auth.Subject)
245:             */
246:            public void deleteUser(Subject user) throws AuthenticationException {
247:                if (user != null) {
248:                    deleteUserFromMemory(user);
249:
250:                    Element userElement = findUser(user);
251:                    if (userElement != null) {
252:                        root.element(XmlAuthenticationManager.USERS).elements(
253:                                XmlAuthenticationManager.USER).remove(
254:                                userElement);
255:                        try {
256:                            XMLUtils.write(fileLocation, document);
257:                        } catch (IOException e) {
258:                            logger.log(Level.SEVERE, "removeUser(Subject)", e);
259:                            throw new AuthenticationException(e.getMessage());
260:                        }
261:
262:                    }
263:                }
264:            }
265:
266:            /**
267:             * find the DOM4J Element corresponding to this Subject, null otherwise.
268:             * @param user subject we are looking for in the XML repository file.
269:             * @return Element corresponding to the found user, null if not found.
270:             * @throws AuthenticationException
271:             */
272:            private Element findUser(Subject user)
273:                    throws AuthenticationException {
274:
275:                JGuardCredential identityCred = extractIdentityCredentialFromUser(user);
276:
277:                return findUser(identityCred);
278:            }
279:
280:            /**
281:             * return the DOM4J element which match with the identityCredential provided.
282:             * @param identityCred
283:             * @return null if no user is found, an Element if user found
284:             */
285:            private Element findUser(JGuardCredential identityCred) {
286:                logger.finest("try to find user with identityCredential="
287:                        + identityCred);
288:                Element usersElement = root
289:                        .element(XmlAuthenticationManager.USERS);
290:                List usersElementlist = usersElement
291:                        .elements(XmlAuthenticationManager.USER);
292:                Iterator itUsersList = usersElementlist.iterator();
293:                while (itUsersList.hasNext()) {
294:
295:                    Element userElement = (Element) itUsersList.next();
296:                    Element privateCredentialsElement = userElement
297:                            .element(XmlAuthenticationManager.PRIVATE_CREDENTIALS);
298:                    Element elt = (Element) privateCredentialsElement
299:                            .selectSingleNode("./credential[id='"
300:                                    + identityCred.getId() + "' and value='"
301:                                    + identityCred.getValue() + "']");
302:                    if (elt != null) {
303:                        logger.finest("user " + userElement + "has been found");
304:                        return userElement;
305:                    }
306:
307:                    Element publicCredentialsElement = userElement
308:                            .element(XmlAuthenticationManager.PUBLIC_CREDENTIALS);
309:                    Element elt2 = (Element) publicCredentialsElement
310:                            .selectSingleNode("./credential[id='"
311:                                    + identityCred.getId() + "' and value='"
312:                                    + identityCred.getValue() + "']");
313:                    if (elt2 != null) {
314:                        logger.finest("user " + userElement + "has been found");
315:                        return userElement;
316:                    }
317:                }
318:                //no user has been found
319:                logger.finest("no user has been found");
320:                return null;
321:            }
322:
323:            /**
324:             * initialize principals.
325:             * @param root dom4j element
326:             */
327:            private void initPrincipals(Element root) {
328:                Element principalsElement = root
329:                        .element(XmlAuthenticationManager.PRINCIPALS);
330:                List principalsList = principalsElement
331:                        .elements(XmlAuthenticationManager.PRINCIPAL);
332:                Iterator itPrincipalsList = principalsList.iterator();
333:
334:                while (itPrincipalsList.hasNext()) {
335:                    Element principalElement = (Element) itPrincipalsList
336:                            .next();
337:                    RolePrincipal principal = new RolePrincipal();
338:                    principal.setLocalName(principalElement.element(
339:                            XmlAuthenticationManager.NAME).getStringValue());
340:                    Element applicationNameElement = principalElement
341:                            .element(XmlAuthenticationManager.APPLICATION_NAME);
342:                    principal.setApplicationName(applicationNameElement
343:                            .getStringValue());
344:                    principals.put(principal.getName(), principal);
345:                    principalsSet.add(principal);
346:                    if (principal.getApplicationName().equals(applicationName)) {
347:                        localPrincipalsSet.add(principal);
348:                        localPrincipals.put(principal.getName(), principal);
349:                    }
350:                }
351:
352:            }
353:
354:            /**
355:             * initialize users.
356:             * @param root dom4j element
357:             * @return users Set
358:             */
359:            private Set initUsers(Element root) {
360:                Element usersElement = root
361:                        .element(XmlAuthenticationManager.USERS);
362:                List usersList = usersElement
363:                        .elements(XmlAuthenticationManager.USER);
364:                Iterator itUsersList = usersList.iterator();
365:
366:                while (itUsersList.hasNext()) {
367:                    Element userElement = (Element) itUsersList.next();
368:
369:                    Set userPrincipals = new HashSet();
370:                    Set privateCredentials = new HashSet();
371:                    Set publicCredentials = new HashSet();
372:                    Element privateCredentialsElement = userElement
373:                            .element(XmlAuthenticationManager.PRIVATE_CREDENTIALS);
374:                    Element publicCredentialsElement = userElement
375:                            .element(XmlAuthenticationManager.PUBLIC_CREDENTIALS);
376:                    List privCredentialsList = privateCredentialsElement
377:                            .elements(XmlAuthenticationManager.CREDENTIAL);
378:                    Iterator itPrivCred = privCredentialsList.iterator();
379:                    while (itPrivCred.hasNext()) {
380:                        Element privateCredentialElement = (Element) itPrivCred
381:                                .next();
382:                        JGuardCredential privateCredential = new JGuardCredential();
383:                        String id = privateCredentialElement.element(
384:                                XmlAuthenticationManager.ID).getStringValue();
385:                        String value = privateCredentialElement.element(
386:                                XmlAuthenticationManager.VALUE)
387:                                .getStringValue();
388:                        privateCredential.setId(id);
389:                        privateCredential.setValue(value);
390:                        privateCredentials.add(privateCredential);
391:                    }
392:
393:                    List pubCredentialsList = publicCredentialsElement
394:                            .elements(XmlAuthenticationManager.CREDENTIAL);
395:                    Iterator itPubCred = pubCredentialsList.iterator();
396:                    while (itPubCred.hasNext()) {
397:
398:                        Element publicCredentialElement = (Element) itPubCred
399:                                .next();
400:                        JGuardCredential publicCredential = new JGuardCredential();
401:                        String id = publicCredentialElement.element(
402:                                XmlAuthenticationManager.ID).getStringValue();
403:                        String value = publicCredentialElement.element(
404:                                XmlAuthenticationManager.VALUE)
405:                                .getStringValue();
406:                        publicCredential.setId(id);
407:                        publicCredential.setValue(value);
408:                        publicCredentials.add(publicCredential);
409:                    }
410:
411:                    Element principalsRefElement = userElement
412:                            .element(XmlAuthenticationManager.PRINCIPALS_REF);
413:                    List userPrincipalsRefElement = principalsRefElement
414:                            .elements(XmlAuthenticationManager.PRINCIPAL_REF);
415:                    Iterator itUserPrincipals = userPrincipalsRefElement
416:                            .iterator();
417:                    while (itUserPrincipals.hasNext()) {
418:                        Element principalElement = (Element) itUserPrincipals
419:                                .next();
420:                        String principalName = principalElement
421:                                .attributeValue(XmlAuthenticationManager.NAME);
422:                        String principalApplicationName = principalElement
423:                                .attributeValue(XmlAuthenticationManager.APPLICATION_NAME);
424:                        //if the applicationName is not set, the current applicationName is implied
425:                        if (principalApplicationName == null) {
426:                            principalApplicationName = super .applicationName;
427:                        }
428:                        String definition = principalElement
429:                                .attributeValue(XmlAuthenticationManager.DEFINITION);
430:                        String active = principalElement
431:                                .attributeValue(XmlAuthenticationManager.ACTIVE);
432:
433:                        RolePrincipal principal = new RolePrincipal();
434:                        principal.setLocalName(principalName);
435:                        principal.setApplicationName(principalApplicationName);
436:                        principal.setDefinition(definition);
437:                        if ("true".equalsIgnoreCase(active))
438:                            principal.setActive(true);
439:                        else
440:                            principal.setActive(false);
441:
442:                        userPrincipals.add(principal);
443:                    }
444:
445:                    //subject is not in read-only mode
446:                    Subject user = new Subject(false, userPrincipals,
447:                            publicCredentials, privateCredentials);
448:
449:                    users.add(user);
450:                }
451:
452:                return users;
453:            }
454:
455:            /**
456:             * construct from configuration file the subjectTemplate.
457:             * @return Subject template built
458:             * @throws AuthenticationException
459:             */
460:            public SubjectTemplate getSubjectTemplate(String name)
461:                    throws AuthenticationException {
462:                List stList = root.selectNodes("//userTemplate[name=\"" + name
463:                        + "\"]");
464:                if (stList == null || stList.size() != 1) {
465:                    logger.severe("SubjectTemplates found : " + stList);
466:                    throw new AuthenticationException(
467:                            "subjecttemplate intitled " + name
468:                                    + " is not unique ");
469:                }
470:                Element subjectTemplateElement = (Element) stList.get(0);
471:                SubjectTemplate st = buildSubjectTemplateFromElement(
472:                        subjectTemplateElement, name);
473:                return st;
474:            }
475:
476:            private SubjectTemplate buildSubjectTemplateFromElement(
477:                    Element userTemplate, String name) {
478:                Element privateRequiredCredentials = userTemplate
479:                        .element(XmlAuthenticationManager.PRIVATE_REQUIRED_CREDENTIALS);
480:                List privReqCreds = privateRequiredCredentials
481:                        .elements(XmlAuthenticationManager.CRED_TEMPLATE_ID);
482:                Set privReqCreds2 = getJGuardCredentialList(privReqCreds);
483:                Element publicRequiredCredentials = userTemplate
484:                        .element(XmlAuthenticationManager.PUBLIC_REQUIRED_CREDENTIALS);
485:                List pubReqCreds = publicRequiredCredentials
486:                        .elements(XmlAuthenticationManager.CRED_TEMPLATE_ID);
487:                Set pubReqCreds2 = getJGuardCredentialList(pubReqCreds);
488:                Element privateOptionalCredentials = userTemplate
489:                        .element(XmlAuthenticationManager.PRIVATE_OPTIONAL_CREDENTIALS);
490:                List privOptCreds = privateOptionalCredentials
491:                        .elements(XmlAuthenticationManager.CRED_TEMPLATE_ID);
492:                Set privOptCreds2 = getJGuardCredentialList(privOptCreds);
493:                Element publicOptionalCredentials = userTemplate
494:                        .element(XmlAuthenticationManager.PUBLIC_OPTIONAL_CREDENTIALS);
495:                List pubOptCreds = publicOptionalCredentials
496:                        .elements(XmlAuthenticationManager.CRED_TEMPLATE_ID);
497:                Set pubOptCreds2 = getJGuardCredentialList(pubOptCreds);
498:                SubjectTemplate st = new SubjectTemplate();
499:                st.setPrivateRequiredCredentials(privReqCreds2);
500:                st.setPublicRequiredCredentials(pubReqCreds2);
501:                st.setPrivateOptionalCredentials(privOptCreds2);
502:                st.setPublicOptionalCredentials(pubOptCreds2);
503:
504:                List genericPrincipalElements = userTemplate.element(
505:                        XmlAuthenticationManager.GENERIC_PRINCIPALS).elements(
506:                        XmlAuthenticationManager.PRINCIPAL_REF);
507:                Set genPpals = getGenericPrincipals(genericPrincipalElements);
508:                st.setPrincipals(genPpals);
509:                st.setName(name);
510:                return st;
511:            }
512:
513:            private Set getGenericPrincipals(List genericPrincipalElements) {
514:                Set genericPpals = new HashSet();
515:                Iterator principalsIterator = genericPrincipalElements
516:                        .iterator();
517:                while (principalsIterator.hasNext()) {
518:                    Element ppalElement = (Element) principalsIterator.next();
519:                    Principal ppal = (Principal) principals.get(applicationName
520:                            + "#" + ppalElement.attribute("name").getData());
521:                    if (ppal != null) {
522:                        genericPpals.add(ppal);
523:                    }
524:                }
525:
526:                return genericPpals;
527:            }
528:
529:            /**
530:             * transform a list of DOM4J elements into a Set of JGuardCredentials.
531:             * @param credTemplateIdElements list of DOM4J elements
532:             * @return Set of jGuardCredentials
533:             */
534:            private Set getJGuardCredentialList(List credTemplateIdElements) {
535:                Iterator it = credTemplateIdElements.iterator();
536:                Set jguardCredlist = new HashSet();
537:                while (it.hasNext()) {
538:                    Element credElement = (Element) it.next();
539:                    JGuardCredential jcred = new JGuardCredential();
540:                    Attribute identity = credElement
541:                            .attribute(XmlAuthenticationManager.IDENTITY);
542:                    if (identity != null && identity.getText().equals("true")) {
543:                        jcred.setIdentity(true);
544:                    }
545:                    String id = credElement.getStringValue();
546:
547:                    jcred.setId(id);
548:                    jguardCredlist.add(jcred);
549:                }
550:                return jguardCredlist;
551:            }
552:
553:            /**
554:             * persist user into the XML repository file.
555:             * @param user
556:             * @throws AuthenticationException
557:             */
558:            protected void persistUser(Subject user)
559:                    throws AuthenticationException {
560:                Element xmlUsers = root.element(XmlAuthenticationManager.USERS);
561:                Element newUser = xmlUsers
562:                        .addElement(XmlAuthenticationManager.USER);
563:                Element privateCredentials = newUser
564:                        .addElement(XmlAuthenticationManager.PRIVATE_CREDENTIALS);
565:                Set privCredentialsSet = user
566:                        .getPrivateCredentials(JGuardCredential.class);
567:                persistCredentialsSet(privCredentialsSet, privateCredentials);
568:
569:                Element publicCredentials = newUser
570:                        .addElement(XmlAuthenticationManager.PUBLIC_CREDENTIALS);
571:                Set pubCredentials = user
572:                        .getPublicCredentials(JGuardCredential.class);
573:                persistCredentialsSet(pubCredentials, publicCredentials);
574:
575:                Element ppals = newUser
576:                        .addElement(XmlAuthenticationManager.PRINCIPALS_REF);
577:                Set principals = user.getPrincipals();
578:                persistPrincipalRefs(principals, ppals);
579:                try {
580:                    XMLUtils.write(fileLocation, document);
581:                    //add the user to the in-memory users repository
582:                    this .users.add(user);
583:                } catch (IOException e) {
584:                    logger.log(Level.SEVERE, "persistUser(Subject)", e);
585:                    throw new AuthenticationException(e.getMessage());
586:                }
587:            }
588:
589:            /**
590:             * persist principals into the XML repository file.
591:             * @param principals
592:             * @param ppals
593:             */
594:            private void persistPrincipalRefs(Set principals, Element ppals) {
595:
596:                Iterator itPrincipals = principals.iterator();
597:                while (itPrincipals.hasNext()) {
598:                    Principal ppal = (Principal) itPrincipals.next();
599:                    if (ppal instanceof  RolePrincipal) {
600:                        RolePrincipal jppal = (RolePrincipal) ppal;
601:                        Element principal = ppals
602:                                .addElement(XmlAuthenticationManager.PRINCIPAL_REF);
603:                        principal.addAttribute(XmlAuthenticationManager.NAME,
604:                                jppal.getLocalName());
605:                        principal.addAttribute(
606:                                XmlAuthenticationManager.APPLICATION_NAME,
607:                                jppal.getApplicationName());
608:                        principal.addAttribute(
609:                                XmlAuthenticationManager.DEFINITION, jppal
610:                                        .getDefinition());
611:                        principal.addAttribute(XmlAuthenticationManager.ACTIVE,
612:                                jppal.isActive() == true ? "true" : "false");
613:                    }
614:                }
615:
616:            }
617:
618:            /**
619:             * persist a jGuardCredential set into the XML subset corresponding to the
620:             * credentialsSetElement.
621:             * @param credentials
622:             * @param credentialsSetElement
623:             */
624:            private void persistCredentialsSet(Set credentials,
625:                    Element credentialsSetElement) {
626:                Iterator itPubCredentials = credentials.iterator();
627:                while (itPubCredentials.hasNext()) {
628:                    JGuardCredential jcred2 = (JGuardCredential) itPubCredentials
629:                            .next();
630:                    Element credential = credentialsSetElement
631:                            .addElement(XmlAuthenticationManager.CREDENTIAL);
632:                    Element id = credential
633:                            .addElement(XmlAuthenticationManager.ID);
634:                    id.setText(jcred2.getId());
635:                    Element value = credential
636:                            .addElement(XmlAuthenticationManager.VALUE);
637:                    value.setText(jcred2.getValue().toString());
638:                }
639:
640:            }
641:
642:            /**
643:             * define and persist the SubjectTemplate for registration.
644:             * @param template
645:             */
646:            public void persistSubjectTemplate(SubjectTemplate template) {
647:                Element subjectTemplateElement = root
648:                        .element(XmlAuthenticationManager.USER_TEMPLATE);
649:                Element privateRequiredCredentials = subjectTemplateElement
650:                        .element(XmlAuthenticationManager.PRIVATE_REQUIRED_CREDENTIALS);
651:                Iterator privReqCredIt = template
652:                        .getPrivateRequiredCredentials().iterator();
653:                while (privReqCredIt.hasNext()) {
654:                    JGuardCredential cred = (JGuardCredential) privReqCredIt
655:                            .next();
656:                    Element cred1 = privateRequiredCredentials
657:                            .addElement(XmlAuthenticationManager.CRED_TEMPLATE_ID);
658:                    cred1.setText(cred.getId());
659:                }
660:
661:                Element publicRequiredCredentials = subjectTemplateElement
662:                        .element(XmlAuthenticationManager.PUBLIC_REQUIRED_CREDENTIALS);
663:                Iterator pubReqCredIt = template.getPublicRequiredCredentials()
664:                        .iterator();
665:                while (pubReqCredIt.hasNext()) {
666:                    JGuardCredential cred = (JGuardCredential) pubReqCredIt
667:                            .next();
668:                    Element cred1 = publicRequiredCredentials
669:                            .addElement(XmlAuthenticationManager.CRED_TEMPLATE_ID);
670:                    cred1.setText(cred.getId());
671:                }
672:
673:                Element privateOptionalCredentials = subjectTemplateElement
674:                        .element(XmlAuthenticationManager.PRIVATE_OPTIONAL_CREDENTIALS);
675:                Iterator privOptCredIt = template
676:                        .getPrivateOptionalCredentials().iterator();
677:                while (privOptCredIt.hasNext()) {
678:                    JGuardCredential cred = (JGuardCredential) privOptCredIt
679:                            .next();
680:                    Element cred1 = privateOptionalCredentials
681:                            .addElement(XmlAuthenticationManager.CRED_TEMPLATE_ID);
682:                    cred1.setText(cred.getId());
683:                }
684:
685:                Element publicOptionalCredentials = subjectTemplateElement
686:                        .element(XmlAuthenticationManager.PUBLIC_OPTIONAL_CREDENTIALS);
687:                Iterator pubOptCredIt = template.getPublicOptionalCredentials()
688:                        .iterator();
689:                while (pubOptCredIt.hasNext()) {
690:                    JGuardCredential cred = (JGuardCredential) pubOptCredIt
691:                            .next();
692:                    Element cred1 = publicOptionalCredentials
693:                            .addElement(XmlAuthenticationManager.CRED_TEMPLATE_ID);
694:                    cred1.setText(cred.getId());
695:                }
696:            }
697:
698:            /**
699:             * @return <i>true</i> if there is no principals and no permissions.
700:             * <i>false</i> otherwise.
701:             */
702:            public boolean isEmpty() {
703:                List principalsList = root.selectNodes("//principal");
704:                List users = root.selectNodes("//users");
705:                if (!principalsList.isEmpty() && !users.isEmpty()) {
706:                    return false;
707:                }
708:                return true;
709:
710:            }
711:
712:            public Set getAllPrincipalsSet() {
713:                return principalsSet;
714:            }
715:
716:            /**
717:             *  search the users which matches credentials criterions.
718:             * @param credentials crierions used to grab the users
719:             * @return users found
720:             */
721:            public Set findUsers(Collection credentials) {
722:                Set usersFound = new HashSet();
723:                Iterator it = users.iterator();
724:                while (it.hasNext()) {
725:                    Subject user = (Subject) it.next();
726:                    Iterator itCred = credentials.iterator();
727:                    boolean userFound = true;
728:                    while (itCred.hasNext()) {
729:                        JGuardCredential jcred = (JGuardCredential) itCred
730:                                .next();
731:                        if (user.getPrivateCredentials().contains(jcred)
732:                                || user.getPublicCredentials().contains(jcred)) {
733:                            continue;
734:                        } else {
735:                            userFound = false;
736:                        }
737:                    }
738:
739:                    if (userFound == true) {
740:                        usersFound.add(user);
741:                    }
742:                }
743:                return usersFound;
744:            }
745:
746:            public Set getUsers() {
747:                return users;
748:            }
749:
750:            public void updatePrincipal(String oldPrincipalName,
751:                    Principal principal) {
752:                Principal oldPal = (Principal) principals
753:                        .remove(oldPrincipalName);
754:                if (oldPal == null) {
755:                    logger.log(Level.WARNING, " principal " + oldPrincipalName
756:                            + " cannot be updated because it does not exists ");
757:                    return;
758:                }
759:                principalsSet.remove(oldPal);
760:                principals.put(principal.getName(), principal);
761:                principalsSet.add(principal);
762:
763:                try {
764:                    XMLUtils.write(fileLocation, document);
765:                } catch (IOException e) {
766:                    logger.log(Level.SEVERE,
767:                            "updateRole(String, RolePrincipal)", e);
768:                }
769:
770:            }
771:
772:            public boolean deletePrincipal(Principal principal)
773:                    throws AuthenticationException {
774:                Principal ppalReference = (Principal) principals
775:                        .remove(principal.getName());
776:                if (ppalReference == null) {
777:                    return false;
778:                }
779:                principalsSet.remove(ppalReference);
780:                Element principalsElement = root.element("principals");
781:                Element principalElement = (Element) principalsElement
782:                        .selectSingleNode("//principal[name='"
783:                                + principal.getName() + "']");
784:                principalsElement.remove(principalElement);
785:                if (ppalReference.getClass().equals(RolePrincipal.class)) {
786:                    //delete all the references of this principal
787:                    XMLUtils.deletePrincipalRefs(root,
788:                            (RolePrincipal) ppalReference);
789:                }
790:                try {
791:                    XMLUtils.write(fileLocation, document);
792:                } catch (IOException e) {
793:                    logger.log(Level.SEVERE, "deletePrincipal(String)", e);
794:                    throw new AuthenticationException(e.getMessage());
795:                }
796:                return true;
797:
798:            }
799:
800:            public String exportAsXMLString() {
801:                return document.asXML();
802:            }
803:
804:            public void writeAsXML(OutputStream outputStream,
805:                    String encodingScheme) throws IOException {
806:                OutputFormat outformat = OutputFormat.createPrettyPrint();
807:                outformat.setEncoding(encodingScheme);
808:                XMLWriter writer = new XMLWriter(outputStream, outformat);
809:                writer.write(this .document);
810:                writer.flush();
811:            }
812:
813:            public void writeAsHTML(OutputStream outputStream)
814:                    throws IOException {
815:                HTMLWriter writer = new HTMLWriter(outputStream, OutputFormat
816:                        .createPrettyPrint());
817:                writer.write(this .document);
818:                writer.flush();
819:            }
820:
821:            public void exportAsXMLFile(String fileName) throws IOException {
822:                XMLWriter xmlWriter = new XMLWriter(new FileWriter(fileName),
823:                        OutputFormat.createPrettyPrint());
824:                xmlWriter.write(document);
825:                xmlWriter.close();
826:            }
827:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.