LdapUserTester.java 13.6 KB
Newer Older
Gaston Dombiak's avatar
Gaston Dombiak committed
1 2 3 4 5
/**
 * $RCSfile$
 * $Revision: $
 * $Date: $
 *
6
 * Copyright (C) 2005-2008 Jive Software. All rights reserved.
Gaston Dombiak's avatar
Gaston Dombiak committed
7 8
 *
 * This software is published under the terms of the GNU Public License (GPL),
9 10
 * a copy of which is included in this distribution, or a commercial license
 * agreement with Jive.
Gaston Dombiak's avatar
Gaston Dombiak committed
11 12 13 14 15
 */

package org.jivesoftware.admin;

import org.jivesoftware.util.Log;
16
import org.jivesoftware.util.Base64;
17
import org.jivesoftware.openfire.ldap.LdapManager;
Gaston Dombiak's avatar
Gaston Dombiak committed
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
import org.xmpp.packet.JID;

import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.*;
import javax.naming.ldap.Control;
import javax.naming.ldap.LdapContext;
import javax.naming.ldap.SortControl;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.*;

/**
 * Class that assists during the testing of the user-ldap mapping.
 *
 * @author Gaston Dombiak
 */
public class LdapUserTester {

    /**
     * Constants to access user properties
     */
    public static final String NAME = "Name";
    public static final String EMAIL = "Email";
    public static final String FULL_NAME = "FullName";
    public static final String NICKNAME = "Nickname";
    public static final String BIRTHDAY = "Birthday";
45
    public static final String PHOTO = "Photo";
Gaston Dombiak's avatar
Gaston Dombiak committed
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
    public static final String HOME_STREET = "HomeStreet";
    public static final String HOME_CITY = "HomeCity";
    public static final String HOME_STATE = "HomeState";
    public static final String HOME_ZIP = "HomeZip";
    public static final String HOME_COUNTRY = "HomeCountry";
    public static final String HOME_PHONE = "HomePhone";
    public static final String HOME_MOBILE = "HomeMobile";
    public static final String HOME_FAX = "HomeFax";
    public static final String HOME_PAGER = "HomePager";
    public static final String BUSINESS_STREET = "BusinessStreet";
    public static final String BUSINESS_CITY = "BusinessCity";
    public static final String BUSINESS_STATE = "BusinessState";
    public static final String BUSINESS_ZIP = "BusinessZip";
    public static final String BUSINESS_COUNTRY = "BusinessCountry";
    public static final String BUSINESS_JOB_TITLE = "BusinessJobTitle";
    public static final String BUSINESS_DEPARTMENT = "BusinessDepartment";
    public static final String BUSINESS_PHONE = "BusinessPhone";
    public static final String BUSINESS_MOBILE = "BusinessMobile";
    public static final String BUSINESS_FAX = "BusinessFax";
    public static final String BUSINESS_PAGER = "BusinessPager";

    private LdapManager manager;
    private LdapUserProfile profile;

    public LdapUserTester(LdapManager manager, LdapUserProfile profile) {
        this.manager = manager;
        this.profile = profile;
    }

    /**
     * Returns a list of usernames with a sample of the users found in LDAP.
     *
     * @param maxSample the max size of the sample to return.
     * @return a list of usernames with a sample of the users found in LDAP.
     * @throws NamingException if something goes wrong....
     */
    public List<String> getSample(int maxSample) throws NamingException {
        List<String> usernames = new ArrayList<String>();
        LdapContext ctx = null;

        try {
            ctx = manager.getContext();

            // Sort on username field.
            Control[] searchControl;
            try {
                searchControl = new Control[]{
                        new SortControl(new String[]{manager.getUsernameField()}, Control.NONCRITICAL)
                };
            } catch (IOException e) {
                Log.error(e);
                return Collections.emptyList();
            }
            ctx.setRequestControls(searchControl);

            // Search for the dn based on the username.
            SearchControls searchControls = new SearchControls();
            // See if recursive searching is enabled. Otherwise, only search one level.
            if (manager.isSubTreeSearch()) {
                searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            } else {
                searchControls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
            }
            searchControls.setReturningAttributes(new String[]{manager.getUsernameField()});
            // Limit results to those we'll need to process
            searchControls.setCountLimit(maxSample);
            String filter = MessageFormat.format(manager.getSearchFilter(), "*");
            NamingEnumeration answer = ctx.search("", filter, searchControls);

            while (answer.hasMoreElements()) {
                // Get the next userID.
                String username = (String) ((SearchResult) answer.next()).getAttributes().get(
                        manager.getUsernameField()).get();
                // Escape username and add to results.
                usernames.add(JID.escapeNode(username));
            }
            // Close the enumeration.
            answer.close();
        } finally {
            try {
                if (ctx != null) {
                    ctx.setRequestControls(null);
                    ctx.close();
                }
            }
            catch (Exception ignored) {
                // Ignore.
            }
        }
        return usernames;
    }

    /**
     * Returns a list of attributes and their LDAP values found in LDAP for the specified username.
     *
     * @param username the username of the user to get his attributes from LDAP.
     * @return a list of attributes and their LDAP values found in LDAP for the specified username.
     */
    public Map<String, String> getAttributes(String username) {
        Map<String, String> userAttributes = new HashMap<String, String>();
        // Un-escape username.
        username = JID.unescapeNode(username);
        DirContext ctx = null;
        try {
            String userDN = manager.findUserDN(username);
            // Build list of attributes to load from LDAP
            Map<String, PropertyMapping> ldapMappings = getLdapAttributes();
            Set<String> fields = new HashSet<String>();
            for (PropertyMapping mapping : ldapMappings.values()) {
                fields.addAll(mapping.getFields());
            }
            fields.add(manager.getUsernameField());
            // Load records
            ctx = manager.getContext(manager.getUsersBaseDN(username));
            Attributes attrs = ctx.getAttributes(userDN, fields.toArray(new String[]{}));
            // Build answer
            for (Map.Entry<String, PropertyMapping> entry : ldapMappings.entrySet()) {
                String attribute = entry.getKey();
                PropertyMapping mapping = entry.getValue();
                String value = mapping.getDisplayFormat();
                for (String field : mapping.getFields()) {
                    Attribute ldapField = attrs.get(field);
                    if (ldapField != null) {
169 170 171 172 173 174 175 176
                        String answer;
                        Object ob = ldapField.get();
                        if (ob instanceof String) {
                            answer = (String) ob;
                        } else {
                            answer = Base64.encodeBytes((byte[]) ob);
                        }
                        value = value.replace("{" + field + "}", answer);
Gaston Dombiak's avatar
Gaston Dombiak committed
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
                    }
                }
                userAttributes.put(attribute, value);
            }
        }
        catch (Exception e) {
            Log.error(e);
            // TODO something else?
        }
        finally {
            try {
                if (ctx != null) {
                    ctx.close();
                }
            }
            catch (Exception ignored) {
                // Ignore.
            }
        }
        return userAttributes;
    }

    private Map<String, PropertyMapping> getLdapAttributes() {
        Map<String, PropertyMapping> map = new HashMap<String, PropertyMapping>();

        if (profile.getName() != null && profile.getName().trim().length() > 0) {
            map.put(NAME, new PropertyMapping(profile.getName()));
        }
        if (profile.getEmail() != null && profile.getEmail().trim().length() > 0) {
            map.put(EMAIL, new PropertyMapping(profile.getEmail()));
        }
        if (profile.getFullName() != null && profile.getFullName().trim().length() > 0) {
            map.put(FULL_NAME, new PropertyMapping(profile.getFullName()));
        }
        if (profile.getNickname() != null && profile.getNickname().trim().length() > 0) {
            map.put(NICKNAME, new PropertyMapping(profile.getNickname()));
        }
        if (profile.getBirthday() != null && profile.getBirthday().trim().length() > 0) {
            map.put(BIRTHDAY, new PropertyMapping(profile.getBirthday()));
        }
217 218 219
        if (profile.getPhoto() != null && profile.getPhoto().trim().length() > 0) {
            map.put(PHOTO, new PropertyMapping(profile.getPhoto()));
        }
Gaston Dombiak's avatar
Gaston Dombiak committed
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
        if (profile.getHomeStreet() != null && profile.getHomeStreet().trim().length() > 0) {
            map.put(HOME_STREET, new PropertyMapping(profile.getHomeStreet()));
        }
        if (profile.getHomeCity() != null && profile.getHomeCity().trim().length() > 0) {
            map.put(HOME_CITY, new PropertyMapping(profile.getHomeCity()));
        }
        if (profile.getHomeState() != null && profile.getHomeState().trim().length() > 0) {
            map.put(HOME_STATE, new PropertyMapping(profile.getHomeState()));
        }
        if (profile.getHomeZip() != null && profile.getHomeZip().trim().length() > 0) {
            map.put(HOME_ZIP, new PropertyMapping(profile.getHomeZip()));
        }
        if (profile.getHomeCountry() != null && profile.getHomeCountry().trim().length() > 0) {
            map.put(HOME_COUNTRY, new PropertyMapping(profile.getHomeCountry()));
        }
        if (profile.getHomePhone() != null && profile.getHomePhone().trim().length() > 0) {
            map.put(HOME_PHONE, new PropertyMapping(profile.getHomePhone()));
        }
        if (profile.getHomeMobile() != null && profile.getHomeMobile().trim().length() > 0) {
            map.put(HOME_MOBILE, new PropertyMapping(profile.getHomeMobile()));
        }
        if (profile.getHomeFax() != null && profile.getHomeFax().trim().length() > 0) {
            map.put(HOME_FAX, new PropertyMapping(profile.getHomeFax()));
        }
        if (profile.getHomePager() != null && profile.getHomePager().trim().length() > 0) {
            map.put(HOME_PAGER, new PropertyMapping(profile.getHomePager()));
        }
        if (profile.getBusinessStreet() != null && profile.getBusinessStreet().trim().length() > 0) {
            map.put(BUSINESS_STREET, new PropertyMapping(profile.getBusinessStreet()));
        }
        if (profile.getBusinessCity() != null && profile.getBusinessCity().trim().length() > 0) {
            map.put(BUSINESS_CITY, new PropertyMapping(profile.getBusinessCity()));
        }
        if (profile.getBusinessState() != null && profile.getBusinessState().trim().length() > 0) {
            map.put(BUSINESS_STATE, new PropertyMapping(profile.getBusinessState()));
        }
        if (profile.getBusinessZip() != null && profile.getBusinessZip().trim().length() > 0) {
            map.put(BUSINESS_ZIP, new PropertyMapping(profile.getBusinessZip()));
        }
        if (profile.getBusinessCountry() != null && profile.getBusinessCountry().trim().length() > 0) {
            map.put(BUSINESS_COUNTRY, new PropertyMapping(profile.getBusinessCountry()));
        }
        if (profile.getBusinessJobTitle() != null && profile.getBusinessJobTitle().trim().length() > 0) {
            map.put(BUSINESS_JOB_TITLE, new PropertyMapping(profile.getBusinessJobTitle()));
        }
        if (profile.getBusinessDepartment() != null && profile.getBusinessDepartment().trim().length() > 0) {
            map.put(BUSINESS_DEPARTMENT, new PropertyMapping(profile.getBusinessDepartment()));
        }
        if (profile.getBusinessPhone() != null && profile.getBusinessPhone().trim().length() > 0) {
            map.put(BUSINESS_PHONE, new PropertyMapping(profile.getBusinessPhone()));
        }
        if (profile.getBusinessMobile() != null && profile.getBusinessMobile().trim().length() > 0) {
            map.put(BUSINESS_MOBILE, new PropertyMapping(profile.getBusinessMobile()));
        }
        if (profile.getBusinessFax() != null && profile.getBusinessFax().trim().length() > 0) {
            map.put(BUSINESS_FAX, new PropertyMapping(profile.getBusinessFax()));
        }
        if (profile.getBusinessPager() != null && profile.getBusinessPager().trim().length() > 0) {
            map.put(BUSINESS_PAGER, new PropertyMapping(profile.getBusinessPager()));
        }

        return map;
    }

    private static class PropertyMapping {
        /**
         * Format how user property is going to appear (e.g. {firstname}, {lastname}
         */
        private String displayFormat;
        /**
         * LDAP fields that compose the user property
         */
        private Collection<String> fields = new ArrayList<String>();


        public PropertyMapping(String displayFormat) {
            this.displayFormat = displayFormat;

298 299 300
            StringTokenizer st = new StringTokenizer(displayFormat.trim(), ", //{}");
            while (st.hasMoreTokens()) {
                fields.add(st.nextToken().replaceFirst("(\\{)([\\d\\D&&[^}]]+)(})", "$2"));
Gaston Dombiak's avatar
Gaston Dombiak committed
301 302 303 304 305 306 307 308 309 310 311 312
            }
        }

        public String getDisplayFormat() {
            return displayFormat;
        }

        public Collection<String> getFields() {
            return fields;
        }
    }
}