Source Code Cross Referenced for PortalLDAPUtil.java in  » Portal » liferay-portal-4.4.2 » com » liferay » portal » security » ldap » 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 » Portal » liferay portal 4.4.2 » com.liferay.portal.security.ldap 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


001:        /**
002:         * Copyright (c) 2000-2008 Liferay, Inc. All rights reserved.
003:         *
004:         * Permission is hereby granted, free of charge, to any person obtaining a copy
005:         * of this software and associated documentation files (the "Software"), to deal
006:         * in the Software without restriction, including without limitation the rights
007:         * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
008:         * copies of the Software, and to permit persons to whom the Software is
009:         * furnished to do so, subject to the following conditions:
010:         *
011:         * The above copyright notice and this permission notice shall be included in
012:         * all copies or substantial portions of the Software.
013:         *
014:         * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
015:         * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
016:         * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
017:         * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
018:         * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
019:         * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
020:         * SOFTWARE.
021:         */package com.liferay.portal.security.ldap;
022:
023:        import com.liferay.portal.NoSuchUserException;
024:        import com.liferay.portal.NoSuchUserGroupException;
025:        import com.liferay.portal.PortalException;
026:        import com.liferay.portal.SystemException;
027:        import com.liferay.portal.kernel.log.Log;
028:        import com.liferay.portal.kernel.log.LogFactoryUtil;
029:        import com.liferay.portal.kernel.log.LogUtil;
030:        import com.liferay.portal.kernel.util.CalendarFactoryUtil;
031:        import com.liferay.portal.kernel.util.PropertiesUtil;
032:        import com.liferay.portal.kernel.util.StringMaker;
033:        import com.liferay.portal.kernel.util.StringPool;
034:        import com.liferay.portal.kernel.util.StringUtil;
035:        import com.liferay.portal.kernel.util.Validator;
036:        import com.liferay.portal.model.Company;
037:        import com.liferay.portal.model.Contact;
038:        import com.liferay.portal.model.User;
039:        import com.liferay.portal.model.UserGroup;
040:        import com.liferay.portal.model.impl.CompanyImpl;
041:        import com.liferay.portal.service.CompanyLocalServiceUtil;
042:        import com.liferay.portal.service.UserGroupLocalServiceUtil;
043:        import com.liferay.portal.service.UserLocalServiceUtil;
044:        import com.liferay.portal.util.PrefsPropsUtil;
045:        import com.liferay.portal.util.PropsUtil;
046:        import com.liferay.portal.util.PropsValues;
047:        import com.liferay.util.ldap.LDAPUtil;
048:        import com.liferay.util.ldap.Modifications;
049:
050:        import java.text.DateFormat;
051:        import java.text.ParseException;
052:        import java.text.SimpleDateFormat;
053:
054:        import java.util.Calendar;
055:        import java.util.Date;
056:        import java.util.List;
057:        import java.util.Locale;
058:        import java.util.Properties;
059:
060:        import javax.naming.Binding;
061:        import javax.naming.Context;
062:        import javax.naming.NameNotFoundException;
063:        import javax.naming.NamingEnumeration;
064:        import javax.naming.directory.Attribute;
065:        import javax.naming.directory.Attributes;
066:        import javax.naming.directory.ModificationItem;
067:        import javax.naming.directory.SearchControls;
068:        import javax.naming.directory.SearchResult;
069:        import javax.naming.ldap.InitialLdapContext;
070:        import javax.naming.ldap.LdapContext;
071:
072:        /**
073:         * <a href="PortalLDAPUtil.java.html"><b><i>View Source</i></b></a>
074:         *
075:         * @author Michael Young
076:         * @author Brian Wing Shun Chan
077:         * @author Jerry Niu
078:         * @author Scott Lee
079:         * @author Hervé Ménage
080:         *
081:         */
082:        public class PortalLDAPUtil {
083:
084:            public static final String IMPORT_BY_USER = "user";
085:
086:            public static final String IMPORT_BY_GROUP = "group";
087:
088:            public static void exportToLDAP(Contact contact) throws Exception {
089:                long companyId = contact.getCompanyId();
090:
091:                if (!isAuthEnabled(companyId) || !isExportEnabled(companyId)) {
092:                    return;
093:                }
094:
095:                LdapContext ctx = getContext(companyId);
096:
097:                if (ctx == null) {
098:                    return;
099:                }
100:
101:                User user = UserLocalServiceUtil.getUserByContactId(contact
102:                        .getContactId());
103:
104:                Properties userMappings = getUserMappings(companyId);
105:                Binding binding = getUser(contact.getCompanyId(), user
106:                        .getScreenName());
107:                String name = StringPool.BLANK;
108:
109:                if (binding == null) {
110:
111:                    // Generate full DN based on user DN
112:
113:                    StringMaker sm = new StringMaker();
114:
115:                    sm.append(userMappings.getProperty("screenName"));
116:                    sm.append(StringPool.EQUAL);
117:                    sm.append(user.getScreenName());
118:                    sm.append(StringPool.COMMA);
119:                    sm.append(getUsersDN(companyId));
120:
121:                    name = sm.toString();
122:
123:                    // Create new user in LDAP
124:
125:                    LDAPUser ldapUser = (LDAPUser) Class.forName(
126:                            PropsValues.LDAP_USER_IMPL).newInstance();
127:
128:                    ldapUser.setUser(user);
129:
130:                    ctx.bind(name, ldapUser);
131:                } else {
132:
133:                    // Modify existing LDAP user record
134:
135:                    name = getNameInNamespace(companyId, binding);
136:
137:                    Modifications mods = Modifications.getInstance();
138:
139:                    mods.addItem(userMappings.getProperty("firstName"), contact
140:                            .getFirstName());
141:                    mods.addItem(userMappings.getProperty("lastName"), contact
142:                            .getLastName());
143:
144:                    ModificationItem[] modItems = mods.getItems();
145:
146:                    ctx.modifyAttributes(name, modItems);
147:                }
148:
149:                ctx.close();
150:            }
151:
152:            public static void exportToLDAP(User user) throws Exception {
153:                long companyId = user.getCompanyId();
154:
155:                if (!isAuthEnabled(companyId) || !isExportEnabled(companyId)) {
156:                    return;
157:                }
158:
159:                LdapContext ctx = getContext(companyId);
160:
161:                if (ctx == null) {
162:                    return;
163:                }
164:
165:                Properties userMappings = getUserMappings(companyId);
166:                Binding binding = getUser(user.getCompanyId(), user
167:                        .getScreenName());
168:                String name = StringPool.BLANK;
169:
170:                if (binding == null) {
171:
172:                    // Generate full DN based on user DN
173:
174:                    StringMaker sm = new StringMaker();
175:
176:                    sm.append(userMappings.getProperty("screenName"));
177:                    sm.append(StringPool.EQUAL);
178:                    sm.append(user.getScreenName());
179:                    sm.append(StringPool.COMMA);
180:                    sm.append(getUsersDN(companyId));
181:
182:                    name = sm.toString();
183:
184:                    // Create new user in LDAP
185:
186:                    LDAPUser ldapUser = (LDAPUser) Class.forName(
187:                            PropsValues.LDAP_USER_IMPL).newInstance();
188:
189:                    ldapUser.setUser(user);
190:
191:                    ctx.bind(name, ldapUser);
192:                } else {
193:
194:                    // Modify existing LDAP user record
195:
196:                    name = getNameInNamespace(companyId, binding);
197:
198:                    Modifications mods = Modifications.getInstance();
199:
200:                    if (user.isPasswordModified()
201:                            && Validator.isNotNull(user
202:                                    .getPasswordUnencrypted())) {
203:
204:                        mods.addItem(userMappings.getProperty("password"), user
205:                                .getPasswordUnencrypted());
206:                    }
207:
208:                    mods.addItem(userMappings.getProperty("emailAddress"), user
209:                            .getEmailAddress());
210:
211:                    ModificationItem[] modItems = mods.getItems();
212:
213:                    ctx.modifyAttributes(name, modItems);
214:                }
215:
216:                ctx.close();
217:            }
218:
219:            public static Attributes getAttributes(LdapContext ctx,
220:                    String fullDistinguishedName) throws Exception {
221:
222:                String[] attrIds = { "creatorsName", "createTimestamp",
223:                        "modifiersName", "modifyTimestamp" };
224:
225:                Attributes attrs = ctx.getAttributes(fullDistinguishedName);
226:
227:                NamingEnumeration enu = ctx.getAttributes(
228:                        fullDistinguishedName, attrIds).getAll();
229:
230:                while (enu.hasMore()) {
231:                    attrs.put((Attribute) enu.next());
232:                }
233:
234:                return attrs;
235:            }
236:
237:            public static String getAuthSearchFilter(long companyId,
238:                    String emailAddress, String screenName, String userId)
239:                    throws PortalException, SystemException {
240:
241:                String filter = PrefsPropsUtil.getString(companyId,
242:                        PropsUtil.LDAP_AUTH_SEARCH_FILTER);
243:
244:                if (_log.isDebugEnabled()) {
245:                    _log.debug("Search filter before transformation " + filter);
246:                }
247:
248:                filter = StringUtil.replace(filter, new String[] {
249:                        "@company_id@", "@email_address@", "@screen_name@",
250:                        "@user_id@" }, new String[] {
251:                        String.valueOf(companyId), emailAddress, screenName,
252:                        userId });
253:
254:                if (_log.isDebugEnabled()) {
255:                    _log.debug("Search filter after transformation " + filter);
256:                }
257:
258:                return filter;
259:            }
260:
261:            public static LdapContext getContext(long companyId)
262:                    throws Exception {
263:                String baseProviderURL = PrefsPropsUtil.getString(companyId,
264:                        PropsUtil.LDAP_BASE_PROVIDER_URL);
265:                String pricipal = PrefsPropsUtil.getString(companyId,
266:                        PropsUtil.LDAP_SECURITY_PRINCIPAL);
267:                String credentials = PrefsPropsUtil.getString(companyId,
268:                        PropsUtil.LDAP_SECURITY_CREDENTIALS);
269:
270:                return getContext(companyId, baseProviderURL, pricipal,
271:                        credentials);
272:            }
273:
274:            public static LdapContext getContext(long companyId,
275:                    String providerURL, String pricipal, String credentials)
276:                    throws Exception {
277:
278:                Properties env = new Properties();
279:
280:                env.put(Context.INITIAL_CONTEXT_FACTORY, PrefsPropsUtil
281:                        .getString(companyId, PropsUtil.LDAP_FACTORY_INITIAL));
282:                env.put(Context.PROVIDER_URL, providerURL);
283:                env.put(Context.SECURITY_PRINCIPAL, pricipal);
284:                env.put(Context.SECURITY_CREDENTIALS, credentials);
285:
286:                LogUtil.debug(_log, env);
287:
288:                LdapContext ctx = null;
289:
290:                try {
291:                    ctx = new InitialLdapContext(env, null);
292:                } catch (Exception e) {
293:                    if (_log.isWarnEnabled()) {
294:                        _log.warn("Failed to bind to the LDAP server");
295:                    }
296:
297:                    if (_log.isDebugEnabled()) {
298:                        _log.debug(e);
299:                    }
300:                }
301:
302:                return ctx;
303:            }
304:
305:            public static Properties getGroupMappings(long companyId)
306:                    throws Exception {
307:
308:                Properties groupMappings = PropertiesUtil.load(PrefsPropsUtil
309:                        .getString(companyId, PropsUtil.LDAP_GROUP_MAPPINGS));
310:
311:                LogUtil.debug(_log, groupMappings);
312:
313:                return groupMappings;
314:            }
315:
316:            public static NamingEnumeration getGroups(long companyId,
317:                    LdapContext ctx, int maxResults) throws Exception {
318:
319:                String baseDN = PrefsPropsUtil.getString(companyId,
320:                        PropsUtil.LDAP_BASE_DN);
321:                String groupFilter = PrefsPropsUtil.getString(companyId,
322:                        PropsUtil.LDAP_IMPORT_GROUP_SEARCH_FILTER);
323:
324:                return getGroups(companyId, ctx, maxResults, baseDN,
325:                        groupFilter);
326:            }
327:
328:            public static NamingEnumeration getGroups(long companyId,
329:                    LdapContext ctx, int maxResults, String baseDN,
330:                    String groupFilter) throws Exception {
331:
332:                SearchControls cons = new SearchControls(
333:                        SearchControls.SUBTREE_SCOPE, maxResults, 0, null,
334:                        false, false);
335:
336:                return ctx.search(baseDN, groupFilter, cons);
337:            }
338:
339:            public static String getNameInNamespace(long companyId,
340:                    Binding binding) throws Exception {
341:
342:                String baseDN = PrefsPropsUtil.getString(companyId,
343:                        PropsUtil.LDAP_BASE_DN);
344:
345:                if (Validator.isNull(baseDN)) {
346:                    return binding.getName();
347:                } else {
348:                    StringMaker sm = new StringMaker();
349:
350:                    sm.append(binding.getName());
351:                    sm.append(StringPool.COMMA);
352:                    sm.append(baseDN);
353:
354:                    return sm.toString();
355:                }
356:            }
357:
358:            public static Binding getUser(long companyId, String screenName)
359:                    throws Exception {
360:
361:                LdapContext ctx = getContext(companyId);
362:
363:                if (ctx == null) {
364:                    return null;
365:                }
366:
367:                String baseDN = PrefsPropsUtil.getString(companyId,
368:                        PropsUtil.LDAP_BASE_DN);
369:
370:                Properties userMappings = getUserMappings(companyId);
371:
372:                StringMaker filter = new StringMaker();
373:
374:                filter.append(StringPool.OPEN_PARENTHESIS);
375:                filter.append(userMappings.getProperty("screenName"));
376:                filter.append(StringPool.EQUAL);
377:                filter.append(screenName);
378:                filter.append(StringPool.CLOSE_PARENTHESIS);
379:
380:                SearchControls cons = new SearchControls(
381:                        SearchControls.SUBTREE_SCOPE, 1, 0, null, false, false);
382:
383:                NamingEnumeration enu = ctx.search(baseDN, filter.toString(),
384:                        cons);
385:
386:                ctx.close();
387:
388:                if (enu.hasMore()) {
389:                    Binding binding = (Binding) enu.next();
390:
391:                    return binding;
392:                } else {
393:                    return null;
394:                }
395:            }
396:
397:            public static Properties getUserMappings(long companyId)
398:                    throws Exception {
399:                Properties userMappings = PropertiesUtil.load(PrefsPropsUtil
400:                        .getString(companyId, PropsUtil.LDAP_USER_MAPPINGS));
401:
402:                LogUtil.debug(_log, userMappings);
403:
404:                return userMappings;
405:            }
406:
407:            public static NamingEnumeration getUsers(long companyId,
408:                    LdapContext ctx, int maxResults) throws Exception {
409:
410:                String baseDN = PrefsPropsUtil.getString(companyId,
411:                        PropsUtil.LDAP_BASE_DN);
412:                String userFilter = PrefsPropsUtil.getString(companyId,
413:                        PropsUtil.LDAP_IMPORT_USER_SEARCH_FILTER);
414:
415:                return getUsers(companyId, ctx, maxResults, baseDN, userFilter);
416:            }
417:
418:            public static NamingEnumeration getUsers(long companyId,
419:                    LdapContext ctx, int maxResults, String baseDN,
420:                    String userFilter) throws Exception {
421:
422:                SearchControls cons = new SearchControls(
423:                        SearchControls.SUBTREE_SCOPE, maxResults, 0, null,
424:                        false, false);
425:
426:                return ctx.search(baseDN, userFilter, cons);
427:            }
428:
429:            public static String getUsersDN(long companyId) throws Exception {
430:                return PrefsPropsUtil.getString(companyId,
431:                        PropsUtil.LDAP_USERS_DN);
432:            }
433:
434:            public static boolean hasUser(long companyId, String screenName)
435:                    throws Exception {
436:
437:                if (getUser(companyId, screenName) != null) {
438:                    return true;
439:                } else {
440:                    return false;
441:                }
442:            }
443:
444:            public static void importFromLDAP() throws Exception {
445:                List companies = CompanyLocalServiceUtil.getCompanies();
446:
447:                for (int i = 0; i < companies.size(); i++) {
448:                    Company company = (Company) companies.get(i);
449:
450:                    importFromLDAP(company.getCompanyId());
451:                }
452:            }
453:
454:            public static void importFromLDAP(long companyId) throws Exception {
455:                if (!isImportEnabled(companyId)) {
456:                    return;
457:                }
458:
459:                LdapContext ctx = getContext(companyId);
460:
461:                if (ctx == null) {
462:                    return;
463:                }
464:
465:                try {
466:                    String importMethod = PrefsPropsUtil.getString(companyId,
467:                            PropsUtil.LDAP_IMPORT_METHOD);
468:
469:                    if (importMethod.equals(IMPORT_BY_USER)) {
470:                        NamingEnumeration enu = getUsers(companyId, ctx, 0);
471:
472:                        // Loop through all LDAP users
473:
474:                        while (enu.hasMore()) {
475:                            SearchResult result = (SearchResult) enu.next();
476:
477:                            Attributes attrs = getAttributes(ctx,
478:                                    getNameInNamespace(companyId, result));
479:
480:                            importLDAPUser(companyId, ctx, attrs,
481:                                    StringPool.BLANK, true);
482:                        }
483:                    } else if (importMethod.equals(IMPORT_BY_GROUP)) {
484:                        NamingEnumeration enu = getGroups(companyId, ctx, 0);
485:
486:                        // Loop through all LDAP groups
487:
488:                        while (enu.hasMore()) {
489:                            SearchResult result = (SearchResult) enu.next();
490:
491:                            Attributes attrs = getAttributes(ctx,
492:                                    getNameInNamespace(companyId, result));
493:
494:                            importLDAPGroup(companyId, ctx, attrs, true);
495:                        }
496:                    }
497:                } catch (Exception e) {
498:                    _log.error("Error importing LDAP users and groups", e);
499:                } finally {
500:                    if (ctx != null) {
501:                        ctx.close();
502:                    }
503:                }
504:            }
505:
506:            public static UserGroup importLDAPGroup(long companyId,
507:                    LdapContext ctx, Attributes attrs,
508:                    boolean importGroupMembership) throws Exception {
509:
510:                AttributesTransformer attrsTransformer = AttributesTransformerFactory
511:                        .getInstance();
512:
513:                attrs = attrsTransformer.transformGroup(attrs);
514:
515:                Properties groupMappings = getGroupMappings(companyId);
516:
517:                LogUtil.debug(_log, groupMappings);
518:
519:                String groupName = LDAPUtil.getAttributeValue(attrs,
520:                        groupMappings.getProperty("groupName")).toLowerCase();
521:                String description = LDAPUtil.getAttributeValue(attrs,
522:                        groupMappings.getProperty("description"));
523:
524:                // Get or create user group
525:
526:                UserGroup userGroup = null;
527:
528:                try {
529:                    userGroup = UserGroupLocalServiceUtil.getUserGroup(
530:                            companyId, groupName);
531:
532:                    UserGroupLocalServiceUtil.updateUserGroup(companyId,
533:                            userGroup.getUserGroupId(), groupName, description);
534:                } catch (NoSuchUserGroupException nsuge) {
535:                    if (_log.isDebugEnabled()) {
536:                        _log.debug("Adding user group to portal " + groupName);
537:                    }
538:
539:                    long defaultUserId = UserLocalServiceUtil
540:                            .getDefaultUserId(companyId);
541:
542:                    try {
543:                        userGroup = UserGroupLocalServiceUtil.addUserGroup(
544:                                defaultUserId, companyId, groupName,
545:                                description);
546:                    } catch (Exception e) {
547:                        if (_log.isWarnEnabled()) {
548:                            _log.warn("Could not create user group "
549:                                    + groupName);
550:                        }
551:
552:                        if (_log.isDebugEnabled()) {
553:                            _log.debug(e, e);
554:                        }
555:                    }
556:                }
557:
558:                // Import users and membership
559:
560:                if (importGroupMembership && (userGroup != null)) {
561:                    Attribute attr = attrs.get(groupMappings
562:                            .getProperty("user"));
563:
564:                    if (attr != null) {
565:                        _importUsersAndMembershipFromLDAPGroup(companyId, ctx,
566:                                userGroup.getUserGroupId(), attr);
567:                    }
568:                }
569:
570:                return userGroup;
571:            }
572:
573:            public static User importLDAPUser(long companyId, LdapContext ctx,
574:                    Attributes attrs, String password,
575:                    boolean importGroupMembership) throws Exception {
576:
577:                AttributesTransformer attrsTransformer = AttributesTransformerFactory
578:                        .getInstance();
579:
580:                attrs = attrsTransformer.transformUser(attrs);
581:
582:                Properties userMappings = getUserMappings(companyId);
583:
584:                LogUtil.debug(_log, userMappings);
585:
586:                User defaultUser = UserLocalServiceUtil
587:                        .getDefaultUser(companyId);
588:
589:                boolean autoPassword = false;
590:                boolean updatePassword = true;
591:
592:                if (password.equals(StringPool.BLANK)) {
593:                    autoPassword = true;
594:                    updatePassword = false;
595:                }
596:
597:                long creatorUserId = 0;
598:                boolean passwordReset = false;
599:                boolean autoScreenName = false;
600:                String screenName = LDAPUtil.getAttributeValue(attrs,
601:                        userMappings.getProperty("screenName")).toLowerCase();
602:                String emailAddress = LDAPUtil.getAttributeValue(attrs,
603:                        userMappings.getProperty("emailAddress"));
604:                Locale locale = defaultUser.getLocale();
605:                String firstName = LDAPUtil.getAttributeValue(attrs,
606:                        userMappings.getProperty("firstName"));
607:                String middleName = LDAPUtil.getAttributeValue(attrs,
608:                        userMappings.getProperty("middleName"));
609:                String lastName = LDAPUtil.getAttributeValue(attrs,
610:                        userMappings.getProperty("lastName"));
611:
612:                if (Validator.isNull(firstName) || Validator.isNull(lastName)) {
613:                    String fullName = LDAPUtil.getAttributeValue(attrs,
614:                            userMappings.getProperty("fullName"));
615:
616:                    String[] names = LDAPUtil.splitFullName(fullName);
617:
618:                    firstName = names[0];
619:                    middleName = names[1];
620:                    lastName = names[2];
621:                }
622:
623:                int prefixId = 0;
624:                int suffixId = 0;
625:                boolean male = true;
626:                int birthdayMonth = Calendar.JANUARY;
627:                int birthdayDay = 1;
628:                int birthdayYear = 1970;
629:                String jobTitle = LDAPUtil.getAttributeValue(attrs,
630:                        userMappings.getProperty("jobTitle"));
631:                long[] organizationIds = new long[0];
632:                boolean sendEmail = false;
633:
634:                if (_log.isDebugEnabled()) {
635:                    _log.debug("Screen name " + screenName
636:                            + " and email address " + emailAddress);
637:                }
638:
639:                if (Validator.isNull(screenName)
640:                        || Validator.isNull(emailAddress)) {
641:                    if (_log.isWarnEnabled()) {
642:                        _log
643:                                .warn("Cannot add user because screen name and email address "
644:                                        + "are required");
645:                    }
646:
647:                    return null;
648:                }
649:
650:                User user = null;
651:
652:                try {
653:
654:                    // Find corresponding portal user
655:
656:                    String authType = PrefsPropsUtil.getString(companyId,
657:                            PropsUtil.COMPANY_SECURITY_AUTH_TYPE,
658:                            PropsValues.COMPANY_SECURITY_AUTH_TYPE);
659:
660:                    if (authType.equals(CompanyImpl.AUTH_TYPE_SN)) {
661:                        user = UserLocalServiceUtil.getUserByScreenName(
662:                                companyId, screenName);
663:                    } else {
664:                        user = UserLocalServiceUtil.getUserByEmailAddress(
665:                                companyId, emailAddress);
666:                    }
667:
668:                    // Skip if is default user
669:
670:                    if (user.isDefaultUser()) {
671:                        return user;
672:                    }
673:
674:                    // Skip import if user fields has been already synced and if
675:                    // import is part of a scheduled import
676:
677:                    Date ldapUserModifiedDate = null;
678:
679:                    String modifiedDate = LDAPUtil.getAttributeValue(attrs,
680:                            "modifyTimestamp");
681:
682:                    try {
683:                        DateFormat dateFormat = new SimpleDateFormat(
684:                                "yyyyMMddHHmmss");
685:
686:                        ldapUserModifiedDate = dateFormat.parse(modifiedDate);
687:
688:                        if (ldapUserModifiedDate.equals(user.getModifiedDate())
689:                                && autoPassword) {
690:
691:                            if (_log.isDebugEnabled()) {
692:                                _log
693:                                        .debug("User is already syncronized, skipping user "
694:                                                + user.getEmailAddress());
695:                            }
696:
697:                            return user;
698:                        }
699:                    } catch (ParseException pe) {
700:                        if (_log.isDebugEnabled()) {
701:                            _log.debug("Unable to parse LDAP modify timestamp "
702:                                    + modifiedDate);
703:                        }
704:
705:                        _log.debug(pe, pe);
706:                    }
707:
708:                    Contact contact = user.getContact();
709:
710:                    Calendar birthdayCal = CalendarFactoryUtil.getCalendar();
711:
712:                    birthdayCal.setTime(contact.getBirthday());
713:
714:                    birthdayMonth = birthdayCal.get(Calendar.MONTH);
715:                    birthdayDay = birthdayCal.get(Calendar.DATE);
716:                    birthdayYear = birthdayCal.get(Calendar.YEAR);
717:
718:                    // User exists so update user information
719:
720:                    if (updatePassword) {
721:                        user = UserLocalServiceUtil.updatePassword(user
722:                                .getUserId(), password, password,
723:                                passwordReset, true);
724:                    }
725:
726:                    user = UserLocalServiceUtil.updateUser(user.getUserId(),
727:                            password, user.isPasswordReset(), screenName,
728:                            emailAddress, user.getLanguageId(), user
729:                                    .getTimeZoneId(), user.getGreeting(), user
730:                                    .getComments(), firstName, middleName,
731:                            lastName, contact.getPrefixId(), contact
732:                                    .getSuffixId(), contact.getMale(),
733:                            birthdayMonth, birthdayDay, birthdayYear, contact
734:                                    .getSmsSn(), contact.getAimSn(), contact
735:                                    .getIcqSn(), contact.getJabberSn(), contact
736:                                    .getMsnSn(), contact.getSkypeSn(), contact
737:                                    .getYmSn(), jobTitle, user
738:                                    .getOrganizationIds());
739:
740:                    if (ldapUserModifiedDate != null) {
741:                        UserLocalServiceUtil.updateModifiedDate(user
742:                                .getUserId(), ldapUserModifiedDate);
743:                    }
744:                } catch (NoSuchUserException nsue) {
745:
746:                    // User does not exist so create
747:
748:                }
749:
750:                if (user == null) {
751:                    try {
752:                        if (_log.isDebugEnabled()) {
753:                            _log.debug("Adding user to portal " + emailAddress);
754:                        }
755:
756:                        user = UserLocalServiceUtil.addUser(creatorUserId,
757:                                companyId, autoPassword, password, password,
758:                                autoScreenName, screenName, emailAddress,
759:                                locale, firstName, middleName, lastName,
760:                                prefixId, suffixId, male, birthdayMonth,
761:                                birthdayDay, birthdayYear, jobTitle,
762:                                organizationIds, sendEmail);
763:                    } catch (Exception e) {
764:                        _log.error("Problem adding user with screen name "
765:                                + screenName + " and email address "
766:                                + emailAddress, e);
767:                    }
768:                }
769:
770:                // Import user groups and membership
771:
772:                if (importGroupMembership && (user != null)) {
773:                    String userMappingsGroup = userMappings
774:                            .getProperty("group");
775:
776:                    if (userMappingsGroup != null) {
777:                        Attribute attr = attrs.get(userMappingsGroup);
778:
779:                        if (attr != null) {
780:                            _importGroupsAndMembershipFromLDAPUser(companyId,
781:                                    ctx, user.getUserId(), attr);
782:                        }
783:                    }
784:                }
785:
786:                return user;
787:            }
788:
789:            public static boolean isAuthEnabled(long companyId)
790:                    throws PortalException, SystemException {
791:
792:                if (PrefsPropsUtil.getBoolean(companyId,
793:                        PropsUtil.LDAP_AUTH_ENABLED,
794:                        PropsValues.LDAP_AUTH_ENABLED)) {
795:
796:                    return true;
797:                } else {
798:                    return false;
799:                }
800:            }
801:
802:            public static boolean isExportEnabled(long companyId)
803:                    throws PortalException, SystemException {
804:
805:                if (PrefsPropsUtil.getBoolean(companyId,
806:                        PropsUtil.LDAP_EXPORT_ENABLED,
807:                        PropsValues.LDAP_EXPORT_ENABLED)) {
808:
809:                    return true;
810:                } else {
811:                    return false;
812:                }
813:            }
814:
815:            public static boolean isImportEnabled(long companyId)
816:                    throws PortalException, SystemException {
817:
818:                if (PrefsPropsUtil.getBoolean(companyId,
819:                        PropsUtil.LDAP_IMPORT_ENABLED,
820:                        PropsValues.LDAP_IMPORT_ENABLED)) {
821:
822:                    return true;
823:                } else {
824:                    return false;
825:                }
826:            }
827:
828:            public static boolean isImportOnStartup(long companyId)
829:                    throws PortalException, SystemException {
830:
831:                if (PrefsPropsUtil.getBoolean(companyId,
832:                        PropsUtil.LDAP_IMPORT_ON_STARTUP)) {
833:
834:                    return true;
835:                } else {
836:                    return false;
837:                }
838:            }
839:
840:            public static boolean isNtlmEnabled(long companyId)
841:                    throws PortalException, SystemException {
842:
843:                if (!isAuthEnabled(companyId)) {
844:                    return false;
845:                }
846:
847:                if (PrefsPropsUtil.getBoolean(companyId,
848:                        PropsUtil.NTLM_AUTH_ENABLED)) {
849:                    return true;
850:                } else {
851:                    return false;
852:                }
853:            }
854:
855:            public static boolean isPasswordPolicyEnabled(long companyId)
856:                    throws PortalException, SystemException {
857:
858:                if (PrefsPropsUtil.getBoolean(companyId,
859:                        PropsUtil.LDAP_PASSWORD_POLICY_ENABLED,
860:                        PropsValues.LDAP_PASSWORD_POLICY_ENABLED)) {
861:
862:                    return true;
863:                } else {
864:                    return false;
865:                }
866:            }
867:
868:            private static void _importGroupsAndMembershipFromLDAPUser(
869:                    long companyId, LdapContext ctx, long userId, Attribute attr)
870:                    throws Exception {
871:
872:                // Remove all user group membership from user
873:
874:                UserGroupLocalServiceUtil.clearUserUserGroups(userId);
875:
876:                for (int i = 0; i < attr.size(); i++) {
877:
878:                    // Find group in LDAP
879:
880:                    String fullGroupDN = (String) attr.get(i);
881:
882:                    Attributes groupAttrs = null;
883:
884:                    try {
885:                        groupAttrs = getAttributes(ctx, fullGroupDN);
886:                    } catch (NameNotFoundException nnfe) {
887:                        _log.error("LDAP group not found with fullGroupDN "
888:                                + fullGroupDN);
889:
890:                        _log.error(nnfe, nnfe);
891:
892:                        continue;
893:                    }
894:
895:                    UserGroup userGroup = importLDAPGroup(companyId, ctx,
896:                            groupAttrs, false);
897:
898:                    // Add user to user group
899:
900:                    if (userGroup != null) {
901:                        if (_log.isDebugEnabled()) {
902:                            _log.debug("Adding " + userId + " to group "
903:                                    + userGroup.getUserGroupId());
904:                        }
905:
906:                        UserLocalServiceUtil.addUserGroupUsers(userGroup
907:                                .getUserGroupId(), new long[] { userId });
908:                    }
909:                }
910:            }
911:
912:            private static void _importUsersAndMembershipFromLDAPGroup(
913:                    long companyId, LdapContext ctx, long userGroupId,
914:                    Attribute attr) throws Exception {
915:
916:                // Remove all user membership from user group
917:
918:                UserLocalServiceUtil.clearUserGroupUsers(userGroupId);
919:
920:                for (int i = 0; i < attr.size(); i++) {
921:
922:                    // Find user in LDAP
923:
924:                    String fullUserDN = (String) attr.get(i);
925:
926:                    Attributes userAttrs = null;
927:
928:                    try {
929:                        userAttrs = getAttributes(ctx, fullUserDN);
930:                    } catch (NameNotFoundException nnfe) {
931:                        _log.error("LDAP user not found with fullUserDN "
932:                                + fullUserDN);
933:
934:                        _log.error(nnfe, nnfe);
935:
936:                        continue;
937:                    }
938:
939:                    User user = importLDAPUser(companyId, ctx, userAttrs,
940:                            StringPool.BLANK, false);
941:
942:                    // Add user to user group
943:
944:                    if (user != null) {
945:                        if (_log.isDebugEnabled()) {
946:                            _log.debug("Adding " + user.getUserId()
947:                                    + " to group " + userGroupId);
948:                        }
949:
950:                        UserLocalServiceUtil.addUserGroupUsers(userGroupId,
951:                                new long[] { user.getUserId() });
952:                    }
953:                }
954:            }
955:
956:            private static Log _log = LogFactoryUtil
957:                    .getLog(PortalLDAPUtil.class);
958:
959:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.