Source Code Cross Referenced for UsersLDAPRepository.java in  » Web-Mail » james-2.3.1 » org » apache » james » userrepository » 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 » Web Mail » james 2.3.1 » org.apache.james.userrepository 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


001:        /****************************************************************
002:         * Licensed to the Apache Software Foundation (ASF) under one   *
003:         * or more contributor license agreements.  See the NOTICE file *
004:         * distributed with this work for additional information        *
005:         * regarding copyright ownership.  The ASF licenses this file   *
006:         * to you under the Apache License, Version 2.0 (the            *
007:         * "License"); you may not use this file except in compliance   *
008:         * with the License.  You may obtain a copy of the License at   *
009:         *                                                              *
010:         *   http://www.apache.org/licenses/LICENSE-2.0                 *
011:         *                                                              *
012:         * Unless required by applicable law or agreed to in writing,   *
013:         * software distributed under the License is distributed on an  *
014:         * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY       *
015:         * KIND, either express or implied.  See the License for the    *
016:         * specific language governing permissions and limitations      *
017:         * under the License.                                           *
018:         ****************************************************************/package org.apache.james.userrepository;
019:
020:        import org.apache.avalon.framework.activity.Initializable;
021:        import org.apache.avalon.framework.configuration.Configurable;
022:        import org.apache.avalon.framework.configuration.Configuration;
023:        import org.apache.avalon.framework.configuration.ConfigurationException;
024:        import org.apache.avalon.framework.context.Context;
025:        import org.apache.avalon.framework.context.ContextException;
026:        import org.apache.avalon.framework.context.Contextualizable;
027:        import org.apache.avalon.framework.logger.AbstractLogEnabled;
028:        import org.apache.avalon.framework.service.ServiceManager;
029:        import org.apache.avalon.framework.service.Serviceable;
030:        import org.apache.james.Constants;
031:        import org.apache.james.services.User;
032:        import org.apache.james.services.UsersRepository;
033:
034:        import javax.naming.AuthenticationException;
035:        import javax.naming.NamingEnumeration;
036:        import javax.naming.NamingException;
037:        import javax.naming.directory.Attribute;
038:        import javax.naming.directory.Attributes;
039:        import javax.naming.directory.BasicAttribute;
040:        import javax.naming.directory.BasicAttributes;
041:        import javax.naming.directory.DirContext;
042:        import javax.naming.directory.InitialDirContext;
043:        import javax.naming.directory.ModificationItem;
044:        import javax.naming.directory.SearchControls;
045:        import javax.naming.directory.SearchResult;
046:
047:        import java.util.ArrayList;
048:        import java.util.Hashtable;
049:        import java.util.Iterator;
050:        import java.util.List;
051:
052:        /**
053:         * Implementation of a Repository to store users.
054:         *
055:         * This clas is a dummy for the proposal!
056:         *
057:         * @version This is $Revision: 494012 $
058:         */
059:        public class UsersLDAPRepository extends AbstractLogEnabled implements 
060:                UsersRepository, Serviceable, Configurable, Contextualizable,
061:                Initializable {
062:
063:            private DirContext ctx;
064:
065:            private String LDAPHost;
066:            private String rootNodeDN;
067:            private String rootURL;
068:            private String serverRDN;
069:            private String baseNodeDN;
070:            private String baseURL;
071:            private String mailAddressAttr;
072:            private String identAttr;
073:            private String authType;
074:            private String principal;
075:            private String password;
076:            private String usersDomain;
077:            private String membersAttr;
078:            private boolean manageGroupAttr;
079:            private String groupAttr;
080:            private boolean managePasswordAttr;
081:            private String passwordAttr;
082:
083:            /**
084:             * @see org.apache.avalon.framework.context.Contextualizable#contextualize(Context)
085:             */
086:            public void contextualize(Context context) throws ContextException {
087:                usersDomain = (String) context.get(Constants.DEFAULT_DOMAIN);
088:            }
089:
090:            /**
091:             * @see org.apache.avalon.framework.service.Serviceable#service(org.apache.avalon.framework.service.ServiceManager)
092:             */
093:            public void service(ServiceManager compMgr) {
094:                // this.comp = compMgr;
095:            }
096:
097:            /**
098:             * @see org.apache.avalon.framework.configuration.Configurable#configure(Configuration)
099:             */
100:            public void configure(Configuration conf)
101:                    throws ConfigurationException {
102:
103:                LDAPHost = conf.getChild("LDAPServer").getValue();
104:                rootNodeDN = conf.getChild("LDAPRoot").getValue();
105:                serverRDN = conf.getChild("ThisServerRDN").getValue();
106:                mailAddressAttr = conf.getChild("MailAddressAttribute")
107:                        .getValue();
108:                identAttr = conf.getChild("IdentityAttribute").getValue();
109:                authType = conf.getChild("AuthenticationType").getValue();
110:                principal = conf.getChild("Principal").getValue();
111:                password = conf.getChild("Password").getValue();
112:
113:                membersAttr = conf.getChild("MembersAttribute").getValue();
114:                manageGroupAttr = conf.getChild("ManageGroupAttribute")
115:                        .getValueAsBoolean(false);
116:                groupAttr = conf.getChild("GroupAttribute").getValue();
117:                managePasswordAttr = conf.getChild("ManagePasswordAttribute")
118:                        .getValueAsBoolean(false);
119:                passwordAttr = conf.getChild("PasswordAttribute").getValue();
120:            }
121:
122:            public void setServerRoot() {
123:                StringBuffer serverRootBuffer = new StringBuffer(128).append(
124:                        serverRDN).append(", ").append(rootNodeDN);
125:                this .setBase(serverRootBuffer.toString());
126:            }
127:
128:            public void setBase(String base) {
129:                baseNodeDN = base;
130:            }
131:
132:            /**
133:             * @see org.apache.avalon.framework.activity.Initializable#initialize()
134:             */
135:            public void initialize() throws Exception {
136:                //setServerRoot();
137:                StringBuffer urlBuffer = new StringBuffer(128).append(LDAPHost)
138:                        .append("/");
139:                rootURL = urlBuffer.toString() + rootNodeDN;
140:                baseURL = urlBuffer.toString() + baseNodeDN;
141:
142:                getLogger().info("Creating initial context from " + baseURL);
143:                //System.out.println("Creating initial context from " + baseURL);
144:
145:                Hashtable env = new Hashtable();
146:                env.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY,
147:                        "com.sun.jndi.ldap.LdapCtxFactory");
148:                env.put(javax.naming.Context.PROVIDER_URL, baseURL);
149:
150:                try {
151:                    ctx = new InitialDirContext(env); // Could throw a NamingExcpetion
152:                } catch (Exception e) {
153:                    getLogger().error("Exception creating InitialDirContext: ",
154:                            e);
155:                }
156:
157:                getLogger().info("Initial context initialized from " + baseURL);
158:            }
159:
160:            public String getChildDestination(String childName) {
161:
162:                String destination = null;
163:                String filter = "cn=" + childName;
164:                SearchControls ctls = new SearchControls();
165:
166:                try {
167:
168:                    NamingEnumeration result = ctx.search("", filter, ctls);
169:
170:                    if (result.hasMore()) {
171:                        StringBuffer destinationBuffer = new StringBuffer(128)
172:                                .append("cn=").append(childName).append(", ")
173:                                .append(baseNodeDN);
174:                        destination = destinationBuffer.toString();
175:                        getLogger().info(
176:                                "Pre-exisisting LDAP node: " + destination);
177:                    } else {
178:                        Attributes attrs = new BasicAttributes(true);
179:                        Attribute objclass = new BasicAttribute("objectclass");
180:                        objclass.add("top");
181:                        objclass.add("rfc822MailGroup");
182:                        attrs.put(objclass);
183:                        Attribute cname = new BasicAttribute("cn");
184:                        cname.add(childName);
185:                        attrs.put(cname);
186:                        Attribute owner = new BasicAttribute("owner");
187:                        owner.add("JAMES-unassigned");
188:                        attrs.put(owner);
189:
190:                        ctx.addToEnvironment(
191:                                javax.naming.Context.SECURITY_AUTHENTICATION,
192:                                authType);
193:                        ctx.addToEnvironment(
194:                                javax.naming.Context.SECURITY_PRINCIPAL,
195:                                principal);
196:                        ctx.addToEnvironment(
197:                                javax.naming.Context.SECURITY_CREDENTIALS,
198:                                password);
199:
200:                        ctx.createSubcontext("cn=" + childName, attrs);
201:                        ctx.addToEnvironment(
202:                                javax.naming.Context.SECURITY_AUTHENTICATION,
203:                                "none");
204:
205:                        StringBuffer destinationBuffer = new StringBuffer(128)
206:                                .append("cn=").append(childName).append(", ")
207:                                .append(baseNodeDN);
208:                        destination = destinationBuffer.toString();
209:                        getLogger().info(
210:                                "Created new LDAP node: " + destination);
211:                    }
212:                } catch (NamingException e) {
213:                    getLogger().error(
214:                            "Problem with child nodes " + e.getMessage(), e);
215:                }
216:
217:                return destination;
218:            }
219:
220:            /**
221:             * List users in repository.
222:             *
223:             * @return Iterator over a collection of Strings, each being one user in the repository.
224:             */
225:            public Iterator list() {
226:
227:                List result = new ArrayList();
228:                // String filter = mailAddressAttr + "=*";
229:                String[] attrIDs = { membersAttr };
230:
231:                try {
232:                    Attribute members = ctx.getAttributes("", attrIDs).get(
233:                            membersAttr);
234:                    if (members != null) {
235:                        NamingEnumeration enumeration = members.getAll();
236:                        while (enumeration.hasMore()) {
237:                            result.add(enumeration.next());
238:                        }
239:                    }
240:                } catch (NamingException e) {
241:                    getLogger().error("Problem listing mailboxes. " + e);
242:
243:                }
244:                return result.iterator();
245:            }
246:
247:            // Methods from interface UsersRepository --------------------------
248:
249:            /**
250:             * Update the repository with the specified user object.  Unsupported for
251:             * this user repository type.
252:             *
253:             * @return false
254:             */
255:            public boolean addUser(User user) {
256:                return false;
257:            }
258:
259:            public User getUserByName(String name) {
260:                return new DefaultUser("dummy", "dummy");
261:            }
262:
263:            public User getUserByNameCaseInsensitive(String name) {
264:                return getUserByName(name);
265:            }
266:
267:            public boolean containsCaseInsensitive(String name) {
268:                return contains(name);
269:            }
270:
271:            // TODO: This is in violation of the contract for the interface.
272:            //       Should only return null if the user doesn't exist.  Otherwise
273:            //       this should return a consistent string representation of the name
274:            public String getRealName(String name) {
275:                return null;
276:            }
277:
278:            public boolean updateUser(User user) {
279:                return false;
280:            }
281:
282:            /**
283:             * Adds userName to the MemberAttribute (specified in conf.xml) of this
284:             * node.
285:             * If ManageGroupAttribute (conf.xml) is TRUE then calls addGroupToUser.
286:             */
287:            public synchronized void addUser(String userName, Object attributes) {
288:
289:                String[] attrIDs = { membersAttr };
290:
291:                // First, add username to mailGroup at baseNode
292:
293:                try {
294:                    Attribute members = ctx.getAttributes("", attrIDs).get(
295:                            membersAttr);
296:
297:                    if (members != null && members.contains(userName)) {//user already here
298:                        StringBuffer infoBuffer = new StringBuffer(64).append(
299:                                "Found ").append(userName).append(
300:                                " already in mailGroup. ");
301:                        getLogger().info(infoBuffer.toString());
302:                        //System.out.println(infoBuffer.toString());
303:
304:                    } else {
305:                        ctx.addToEnvironment(
306:                                javax.naming.Context.SECURITY_AUTHENTICATION,
307:                                authType);
308:                        ctx.addToEnvironment(
309:                                javax.naming.Context.SECURITY_PRINCIPAL,
310:                                principal);
311:                        ctx.addToEnvironment(
312:                                javax.naming.Context.SECURITY_CREDENTIALS,
313:                                password);
314:
315:                        ModificationItem[] mods = new ModificationItem[1];
316:                        mods[0] = new ModificationItem(
317:                                DirContext.ADD_ATTRIBUTE, new BasicAttribute(
318:                                        membersAttr, userName));
319:
320:                        ctx.modifyAttributes("", mods);
321:
322:                        ctx.addToEnvironment(
323:                                javax.naming.Context.SECURITY_AUTHENTICATION,
324:                                "none");
325:                        StringBuffer infoBuffer = new StringBuffer(128).append(
326:                                userName).append(" added to mailGroup ")
327:                                .append(baseNodeDN);
328:                        getLogger().info(infoBuffer.toString());
329:                        //System.out.println(infoBuffer.toString());
330:                    }
331:                } catch (NamingException e) {
332:                    StringBuffer exceptionBuffer = new StringBuffer(256)
333:                            .append("Problem adding user ").append(userName)
334:                            .append(" to: ").append(baseNodeDN).append(e);
335:                    getLogger().error(exceptionBuffer.toString());
336:                }
337:
338:                // Add attributes to user objects, if necessary
339:
340:                if (manageGroupAttr) {
341:                    addGroupToUser(userName);
342:                }
343:
344:                //        if (managePasswordAttr) {
345:                //            String userPassword = (String) attributes; // Not yet implemented
346:                //        }
347:            }
348:
349:            /**
350:             * @see org.apache.james.services.UsersRepository#addUser(java.lang.String, java.lang.String)
351:             */
352:            public boolean addUser(String username, String password) {
353:                if (!contains(username)) {
354:                    addUser(username, password);
355:                    return contains(username);
356:                } else {
357:                    return false;
358:                }
359:            }
360:
361:            private void addGroupToUser(String userName) {
362:                String[] attrIDs = { membersAttr };
363:
364:                Hashtable env = new Hashtable();
365:                env.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY,
366:                        "com.sun.jndi.ldap.LdapCtxFactory");
367:                env.put(javax.naming.Context.PROVIDER_URL, rootURL);
368:
369:                DirContext rootCtx = null;
370:                try {
371:                    rootCtx = new InitialDirContext(env);
372:
373:                    String[] returnAttrs = { groupAttr };
374:                    SearchControls ctls = new SearchControls();
375:                    ctls.setReturningAttributes(attrIDs);
376:                    ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
377:                    StringBuffer filterBuffer = new StringBuffer(128).append(
378:                            mailAddressAttr).append("=").append(userName)
379:                            .append("@").append(usersDomain);
380:                    String filter = filterBuffer.toString();
381:
382:                    NamingEnumeration enumeration = rootCtx.search("", filter,
383:                            ctls);
384:
385:                    if (enumeration.hasMore()) { // ie User is in Directory
386:                        SearchResult newSr = (SearchResult) enumeration.next();
387:                        String userDN = newSr.getName();
388:                        Attribute servers = rootCtx.getAttributes(userDN,
389:                                returnAttrs).get(groupAttr);
390:
391:                        if (servers != null && servers.contains(baseNodeDN)) {//server already registered for user
392:                            getLogger().info(
393:                                    baseNodeDN + " already in user's Groups. ");
394:                            //System.out.println(baseNodeDN + " already in user's Groups. ");
395:
396:                        } else {
397:
398:                            rootCtx
399:                                    .addToEnvironment(
400:                                            javax.naming.Context.SECURITY_AUTHENTICATION,
401:                                            authType);
402:                            rootCtx.addToEnvironment(
403:                                    javax.naming.Context.SECURITY_PRINCIPAL,
404:                                    principal);
405:                            rootCtx.addToEnvironment(
406:                                    javax.naming.Context.SECURITY_CREDENTIALS,
407:                                    password);
408:
409:                            rootCtx.modifyAttributes(userDN,
410:                                    DirContext.ADD_ATTRIBUTE,
411:                                    new BasicAttributes(groupAttr, baseNodeDN,
412:                                            true));
413:
414:                            rootCtx
415:                                    .addToEnvironment(
416:                                            javax.naming.Context.SECURITY_AUTHENTICATION,
417:                                            "none");
418:                            getLogger().info(
419:                                    baseNodeDN + " added to user's groups ");
420:                            //System.out.println(baseNodeDN + " added to users' groups ");
421:
422:                        }
423:
424:                    } else {
425:                        StringBuffer infoBuffer = new StringBuffer(64).append(
426:                                "User ").append(userName).append(
427:                                " not in directory.");
428:                        getLogger().info(infoBuffer.toString());
429:                        // System.out.println(infoBuffer.toString());
430:
431:                    }
432:                } catch (NamingException e) {
433:                    getLogger().error(
434:                            "Problem adding group to user " + userName);
435:                    //System.out.println("Problem adding group to user " + userName);
436:                    //System.out.println(e.getMessage());
437:                    //e.printStackTrace();
438:                } finally {
439:                    closeDirContext(rootCtx);
440:                }
441:            }
442:
443:            public synchronized void removeUser(String userName) {
444:                String[] attrIDs = { membersAttr };
445:
446:                try {
447:                    Attribute members = ctx.getAttributes("", attrIDs).get(
448:                            membersAttr);
449:                    if (members == null) {
450:                        System.out
451:                                .println("UsersLDAPRepository - Null list attribute.");
452:
453:                    } else if (!members.contains(userName)) {//user not here
454:                        getLogger()
455:                                .info(userName + " missing from mailGroup. ");
456:                        //System.out.println(userName + " missing from mailGroup. ");
457:
458:                    } else {
459:                        // First, remove username from mailGroup at baseNode
460:
461:                        ctx.addToEnvironment(
462:                                javax.naming.Context.SECURITY_AUTHENTICATION,
463:                                authType);
464:                        ctx.addToEnvironment(
465:                                javax.naming.Context.SECURITY_PRINCIPAL,
466:                                principal);
467:                        ctx.addToEnvironment(
468:                                javax.naming.Context.SECURITY_CREDENTIALS,
469:                                password);
470:
471:                        ModificationItem[] mods = new ModificationItem[1];
472:                        mods[0] = new ModificationItem(
473:                                DirContext.REMOVE_ATTRIBUTE,
474:                                new BasicAttribute(membersAttr, userName));
475:
476:                        ctx.modifyAttributes("", mods);
477:
478:                        ctx.addToEnvironment(
479:                                javax.naming.Context.SECURITY_AUTHENTICATION,
480:                                "none");
481:                        getLogger()
482:                                .info(userName + " removed from mailGroup. ");
483:                        //System.out.println(userName + " removed from mailGroup. ");
484:                    }
485:                } catch (NamingException e) {
486:                    StringBuffer exceptionBuffer = new StringBuffer(256)
487:                            .append("Problem removing user ").append(userName)
488:                            .append(": ").append(e);
489:                    getLogger().error(exceptionBuffer.toString());
490:                    //System.out.println("Problem removing user " + userName);
491:                    //System.out.println(e.getMessage());
492:                    //e.printStackTrace();
493:                }
494:                if (manageGroupAttr) {
495:                    removeGroupFromUser(userName);
496:                }
497:
498:                if (managePasswordAttr) {
499:                    // not yet implemented
500:                }
501:
502:            }
503:
504:            public void removeGroupFromUser(String userName) {
505:
506:                Hashtable env = new Hashtable();
507:                env.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY,
508:                        "com.sun.jndi.ldap.LdapCtxFactory");
509:                env.put(javax.naming.Context.PROVIDER_URL, rootURL);
510:
511:                DirContext rootCtx = null;
512:                try {
513:                    rootCtx = new InitialDirContext(env);
514:
515:                    // Find directory entry
516:                    String[] returnAttrs = { groupAttr };
517:                    SearchControls ctls = new SearchControls();
518:                    ctls.setReturningAttributes(returnAttrs);
519:                    ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
520:                    StringBuffer filterBuffer = new StringBuffer(128).append(
521:                            mailAddressAttr).append("=").append(userName)
522:                            .append("@").append(usersDomain);
523:                    String filter = filterBuffer.toString();
524:
525:                    NamingEnumeration enumeration = rootCtx.search("", filter,
526:                            ctls);
527:
528:                    if (enumeration.hasMore()) { // ie User is in Directory
529:                        SearchResult newSr = (SearchResult) enumeration.next();
530:                        String userDN = newSr.getName();
531:
532:                        System.out.println("Found user entry: " + userDN);
533:
534:                        Attribute servers = rootCtx.getAttributes(userDN,
535:                                returnAttrs).get(groupAttr);
536:                        if (servers == null) { //should not happen
537:                            getLogger().info(
538:                                    "GroupAttribute missing from user: "
539:                                            + userName);
540:                            // System.out.println("GroupAttribute missing from user: " + userName );
541:
542:                        } else if (!servers.contains(baseNodeDN)) {//server not registered for user
543:                            getLogger().info(
544:                                    baseNodeDN
545:                                            + " missing from users' Groups. ");
546:                            //System.out.println(baseNodeDN + " missing from users' Groups. ");
547:
548:                        } else {
549:
550:                            rootCtx
551:                                    .addToEnvironment(
552:                                            javax.naming.Context.SECURITY_AUTHENTICATION,
553:                                            authType);
554:                            rootCtx.addToEnvironment(
555:                                    javax.naming.Context.SECURITY_PRINCIPAL,
556:                                    principal);
557:                            rootCtx.addToEnvironment(
558:                                    javax.naming.Context.SECURITY_CREDENTIALS,
559:                                    password);
560:
561:                            ModificationItem[] mods = new ModificationItem[1];
562:                            mods[0] = new ModificationItem(
563:                                    DirContext.REMOVE_ATTRIBUTE,
564:                                    new BasicAttribute(groupAttr, baseNodeDN));
565:
566:                            rootCtx.modifyAttributes(userDN, mods);
567:
568:                            //rootCtx.modifyAttributes(userDN, DirContext.REPLACE_ATTRIBUTE, changes);
569:
570:                            rootCtx
571:                                    .addToEnvironment(
572:                                            javax.naming.Context.SECURITY_AUTHENTICATION,
573:                                            "none");
574:                            getLogger()
575:                                    .info(
576:                                            baseNodeDN
577:                                                    + " removed from users' groups ");
578:                            //System.out.println(baseNodeDN + " removed from users' groups ");
579:
580:                        }
581:
582:                    } else {
583:                        StringBuffer infoBuffer = new StringBuffer(64).append(
584:                                "User ").append(userName).append(
585:                                " not in directory.");
586:                        getLogger().info(infoBuffer.toString());
587:                        //System.out.println(infoBuffer.toString());
588:
589:                    }
590:                } catch (NamingException e) {
591:                    StringBuffer exceptionBuffer = new StringBuffer(256)
592:                            .append("Problem removing user ").append(userName)
593:                            .append(e);
594:                    getLogger().error(exceptionBuffer.toString());
595:                    //System.out.println("Problem removing user " + userName);
596:                    //System.out.println(e.getMessage());
597:                    //e.printStackTrace();
598:                } finally {
599:                    closeDirContext(rootCtx);
600:                    rootCtx = null;
601:                }
602:            }
603:
604:            public boolean contains(String name) {
605:                boolean found = false;
606:                String[] attrIDs = { membersAttr };
607:
608:                try {
609:                    Attribute members = ctx.getAttributes("", attrIDs).get(
610:                            membersAttr);
611:                    if (members != null && members.contains(name)) {
612:                        found = true;
613:                        StringBuffer infoBuffer = new StringBuffer(64).append(
614:                                "Found ").append(name)
615:                                .append(" in mailGroup. ");
616:                        getLogger().info(infoBuffer.toString());
617:                        //System.out.println(infoBuffer.toString());
618:                    }
619:                } catch (NamingException e) {
620:                    StringBuffer exceptionBuffer = new StringBuffer(256)
621:                            .append("Problem finding user ").append(name)
622:                            .append(" : ").append(e);
623:                    getLogger().error(exceptionBuffer.toString());
624:                    //System.out.println(exceptionBuffer.toString());
625:                }
626:                return found;
627:            }
628:
629:            public boolean test(String name, String testPassword) {
630:                boolean result = false;
631:                boolean foundFlag = false;
632:                String userDN = null;
633:
634:                try {
635:                    String[] returnAttrs = { identAttr, passwordAttr };
636:                    SearchControls ctls = new SearchControls();
637:                    ctls.setReturningAttributes(returnAttrs);
638:                    ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
639:                    StringBuffer filterBuffer = new StringBuffer(128).append(
640:                            mailAddressAttr).append("=").append(name).append(
641:                            "@").append(usersDomain);
642:                    String filter = filterBuffer.toString();
643:
644:                    Hashtable env = new Hashtable();
645:                    env.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY,
646:                            "com.sun.jndi.ldap.LdapCtxFactory");
647:                    env.put(javax.naming.Context.PROVIDER_URL, rootURL);
648:                    DirContext rootCtx = null;
649:
650:                    try {
651:                        rootCtx = new InitialDirContext(env);
652:
653:                        NamingEnumeration enumeration = rootCtx.search("",
654:                                filter, ctls);
655:                        if (enumeration.hasMore()) { // ie User is in Directory
656:                            SearchResult sr = (SearchResult) enumeration.next();
657:                            String userRDN = sr.getName();
658:                            StringBuffer userDNBuffer = new StringBuffer(128)
659:                                    .append(userRDN).append(", ").append(
660:                                            rootNodeDN);
661:                            userDN = userDNBuffer.toString();
662:                            foundFlag = true;
663:                            //System.out.println("UserDN is : " + userDN);
664:                        }
665:                    } finally {
666:                        closeDirContext(rootCtx);
667:                    }
668:                } catch (Exception e) {
669:                    StringBuffer exceptionBuffer = new StringBuffer(256)
670:                            .append("Problem finding user ").append(name)
671:                            .append(" for password test.").append(e);
672:                    getLogger().error(exceptionBuffer.toString());
673:                    //e.getMessage();
674:                    //e.printStackTrace();
675:                }
676:
677:                if (foundFlag) { // ie User is in Directory
678:                    Hashtable env2 = new Hashtable();
679:                    env2.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY,
680:                            "com.sun.jndi.ldap.LdapCtxFactory");
681:                    env2.put(javax.naming.Context.PROVIDER_URL, rootURL);
682:                    env2.put(javax.naming.Context.SECURITY_AUTHENTICATION,
683:                            "simple");
684:                    env2.put(javax.naming.Context.SECURITY_PRINCIPAL, userDN);
685:                    env2.put(javax.naming.Context.SECURITY_CREDENTIALS,
686:                            testPassword);
687:                    //System.out.println("Creating initial context from " + baseURL);
688:
689:                    DirContext testCtx = null;
690:                    try {
691:                        testCtx = new InitialDirContext(env2);
692:                        result = true;
693:
694:                    } catch (AuthenticationException ae) {
695:                        result = false;
696:                        StringBuffer exceptionBuffer = new StringBuffer(256)
697:                                .append(
698:                                        "Attempt to authenticate with incorrect password for ")
699:                                .append(name).append(" : ").append(ae);
700:                        getLogger().error(exceptionBuffer.toString());
701:                        //System.out.println(exceptionBuffer.toString());
702:                        //System.out.println(ae.getMessage());
703:                        //ae.printStackTrace();
704:                    } catch (Exception e) {
705:                        StringBuffer exceptionBuffer = new StringBuffer(256)
706:                                .append("Problem checking password for ")
707:                                .append(name).append(" : ").append(e);
708:                        getLogger().error(exceptionBuffer.toString());
709:                        //System.out.println(exceptionBuffer.toString());
710:                        //System.out.println(e.getMessage());
711:                        //e.printStackTrace();
712:                    } finally {
713:                        closeDirContext(testCtx);
714:                    }
715:                }
716:                return result;
717:
718:            }
719:
720:            public int countUsers() {
721:
722:                String[] attrIDs = { membersAttr };
723:                int result = -1;
724:
725:                try {
726:                    Attribute members = ctx.getAttributes("", attrIDs).get(
727:                            membersAttr);
728:                    if (members != null) {
729:                        result = members.size();
730:                    } else {
731:                        result = 0;
732:                    }
733:                } catch (NamingException e) {
734:                    getLogger().error("Problem counting users: " + e);
735:                    //System.out.println("Problem counting users. ");
736:                }
737:                return result;
738:            }
739:
740:            public String getDomains() {
741:                return usersDomain;
742:            }
743:
744:            /**
745:             * Disposes of all open directory contexts
746:             *
747:             * @throws Exception if an error is encountered during shutdown
748:             */
749:            public void dispose() throws Exception {
750:                closeDirContext(ctx);
751:                ctx = null;
752:            }
753:
754:            private void closeDirContext(DirContext ctx) {
755:                try {
756:                    if (ctx != null) {
757:                        ctx.close();
758:                    }
759:                } catch (NamingException ne) {
760:                    getLogger()
761:                            .warn(
762:                                    "UsersLDAPRepository: Unexpected exception encountered while closing directory context: "
763:                                            + ne);
764:                }
765:            }
766:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.