Example usage for javax.naming.directory Attribute getID

List of usage examples for javax.naming.directory Attribute getID

Introduction

In this page you can find the example usage for javax.naming.directory Attribute getID.

Prototype

String getID();

Source Link

Document

Retrieves the id of this attribute.

Usage

From source file:de.acosix.alfresco.mtsupport.repo.auth.ldap.EnhancedLDAPUserRegistry.java

/**
 * Gets the values of a repeating attribute that may have range restriction options. If an attribute is range
 * restricted, it will appear in the attribute set with a ";range=i-j" option, where i and j indicate the start and
 * end index, and j is '*' if it is at the end.
 *
 * @param attributes/*from w  w  w . j a  va2  s . c o m*/
 *            the attributes
 * @param attributeName
 *            the attribute name
 * @return the range restricted attribute
 * @throws NamingException
 *             the naming exception
 */
protected Attribute getRangeRestrictedAttribute(final Attributes attributes, final String attributeName)
        throws NamingException {
    final Attribute unrestricted = attributes.get(attributeName);
    if (unrestricted != null) {
        return unrestricted;
    }
    final NamingEnumeration<? extends Attribute> i = attributes.getAll();
    final String searchString = attributeName.toLowerCase(Locale.ENGLISH) + ';';
    while (i.hasMore()) {
        final Attribute attribute = i.next();
        if (attribute.getID().toLowerCase(Locale.ENGLISH).startsWith(searchString)) {
            return attribute;
        }
    }
    return null;
}

From source file:org.liveSense.auth.ldap.LdapAuthenticationHandler.java

/**
 * Copy LDAP user properties to JCR User properties
 * @param ldapUser/*from  ww w .j  ava 2  s . c  om*/
 */
private void updateUserAttributes(Session session, LdapUser ldapUser, Authorizable user) {
    // Collecting attribute names
    try {
        for (Iterator e = user.getPropertyNames(); e.hasNext();) {
            user.removeProperty((String) e.next());
        }

        for (NamingEnumeration<? extends Attribute> ae = ldapUser.getAttributes().getAll(); ae.hasMore();) {
            Attribute attr = ae.next();
            log.info("Attribute: " + attr.getID());
            // multi value attribute
            if (attr.size() > 1) {
                Value[] props = new Value[attr.size()];
                int i = 0;
                for (NamingEnumeration e = attr.getAll(); e.hasMore();) {
                    Object o = e.next();
                    if (o instanceof String)
                        props[i] = session.getValueFactory().createValue((String) o);
                    i++;
                }
                user.setProperty(attr.getID(), props);
            } else {
                if (attr.get(0) instanceof String)
                    user.setProperty(attr.getID(), session.getValueFactory().createValue((String) attr.get(0)));
            }
        }
    } catch (Exception e) {
        log.error("Could not update user attributes", e);
    }

}

From source file:it.webappcommon.lib.LDAPHelper.java

/**
 * @param args//from   w  w  w . j a  v a2s.  co  m
 *            the command line arguments
 */
// public static void main(String[] args) {
private List<UserInfo> search(String filter) throws NamingException {
    DirContext ctx = null;
    SearchControls ctls = null;
    Properties env = new Properties();
    List<UserInfo> res = new ArrayList<UserInfo>();
    boolean trovatiRisultati = false;

    env.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT);

    env.put(Context.PROVIDER_URL, "ldap://" + server + ":" + port);

    env.put(Context.SECURITY_AUTHENTICATION, "simple");

    if (org.apache.commons.lang3.StringUtils.isEmpty(loginDomain)) {
        env.put(Context.SECURITY_PRINCIPAL, loginUserName);
    } else {
        env.put(Context.SECURITY_PRINCIPAL, loginDomain + "\\" + loginUserName);
    }
    env.put(Context.SECURITY_CREDENTIALS, loginPassword);

    try {
        ctx = new InitialDirContext(env);

        ctls = new SearchControls();
        ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        // String filter = "";
        // // filter = "(&(objectClass=inetOrgPerson)(objectClass=person))";
        // filter = FILTER_USERS_ACTIVE;

        // Tutti i membri di un gruppo
        // (objectCategory=user)(memberOf=CN=QA Users,OU=Help
        // Desk,DC=dpetri,DC=net)

        // ESEMPI
        // http://www.petri.co.il/ldap_search_samples_for_windows_2003_and_exchange.htm

        // Account disabled
        // (UserAccountControl:1.2.840.113556.1.4.803:=2)

        NamingEnumeration<SearchResult> answer = ctx.search(areaWhereSearch, filter, ctls);

        UserInfo userInfo = null;
        while (answer.hasMoreElements()) {
            trovatiRisultati = true;

            SearchResult a = answer.nextElement();
            // logger.debug(a.getNameInNamespace());

            Attributes result = a.getAttributes();

            if (result == null) {
                // System.out.print("Attributi non presenti");
            } else {
                NamingEnumeration<? extends Attribute> attributi = result.getAll();

                userInfo = new UserInfo();
                while (attributi.hasMoreElements()) {
                    Attribute att = attributi.nextElement();
                    // logger.debug(att.getID());

                    String value = "";
                    // for (NamingEnumeration vals = att.getAll();
                    // vals.hasMoreElements(); logger.debug("\t" +
                    // vals.nextElement()))
                    // ;
                    NamingEnumeration<?> vals = att.getAll();
                    while (vals.hasMoreElements()) {
                        Object val = vals.nextElement();

                        // logger.debug("\t" + val);
                        value = (value.isEmpty()) ? value + val.toString() : value + ";" + val.toString();
                    }

                    if (att.getID().equalsIgnoreCase(FIELD_ACCOUNT_NAME)) {
                        // userInfo.setFIELD_ACCOUNT_NAME(value);
                        userInfo.setAccount(value);
                    } else if (att.getID().equalsIgnoreCase(FIELD_COGNOME)) {
                        // userInfo.setFIELD_COGNOME(value);
                        userInfo.setCognome(value);
                    } else if (att.getID().equalsIgnoreCase(FIELD_EMAIL)) {
                        // userInfo.setFIELD_EMAIL(value);
                        userInfo.setEmail(value);
                    } else if (att.getID().equalsIgnoreCase(FIELD_GROUPS)) {
                        // userInfo.setFIELD_GROUPS(value);
                        userInfo.setGruppi(value);
                    } else if (att.getID().equalsIgnoreCase(FIELD_NOME)) {
                        // userInfo.setFIELD_NOME(value);
                        userInfo.setNome(value);
                    } else if (att.getID().equalsIgnoreCase(FIELD_NOME_COMPLETO)) {
                        // userInfo.setFIELD_NOME_COMPLETO(value);
                        userInfo.setNomeCompleto(value);
                    } else if (att.getID().equalsIgnoreCase(FIELD_NOME_VISUALIZZATO)) {
                        // userInfo.setFIELD_NOME_VISUALIZZATO(value);
                        // userInfo.setNome(value);
                    } else if (att.getID().equalsIgnoreCase(FIELD_TEL)) {
                        // userInfo.setFIELD_TEL(value);
                        userInfo.setTel(value);
                    } else if (att.getID().equalsIgnoreCase(FIELD_UFFICIO)) {
                        // userInfo.setFIELD_UFFICIO(value);
                        userInfo.setUfficio(value);
                    }
                    // res.put(att.getID(), value);
                }

                // Attribute attr = result.get("cn");
                // if (attr != null) {
                // logger.debug("cn:");
                // for (NamingEnumeration vals = attr.getAll();
                // vals.hasMoreElements(); logger.debug("\t" +
                // vals.nextElement()));
                // }
                //
                // attr = result.get("sn");
                // if (attr != null) {
                // logger.debug("sn:");
                // for (NamingEnumeration vals = attr.getAll();
                // vals.hasMoreElements(); logger.debug("\t" +
                // vals.nextElement()));
                // }
                //
                // attr = result.get("mail");
                // if (attr != null) {
                // logger.debug("mail:");
                // for (NamingEnumeration vals = attr.getAll();
                // vals.hasMoreElements(); logger.debug("\t" +
                // vals.nextElement()));
                // }
                //
                // // attr = result.get("uid");
                // // if (attr != null) {
                // // logger.debug("uid:");
                // // for (NamingEnumeration vals = attr.getAll();
                // vals.hasMoreElements(); logger.debug("\t" +
                // vals.nextElement()));
                // // }
                // //
                // // attr = result.get("userPassword");
                // // if (attr != null) {
                // // logger.debug("userPassword:");
                // // for (NamingEnumeration vals = attr.getAll();
                // vals.hasMoreElements(); logger.debug("\t" +
                // vals.nextElement()));
                // // }

                if (userInfo != null) {
                    res.add(userInfo);
                }
            }
        }
    } catch (NamingException ne) {
        // ne.printStackTrace();
        logger.error(ne);
        throw ne;
    } finally {
        try {
            if (ctx != null) {
                ctx.close();
            }
        } catch (Exception e) {
        }
    }

    // Azzero l'hash map
    if (!trovatiRisultati) {
        res = null;
    }

    return res;
}

From source file:org.springframework.ldap.core.DirContextAdapter.java

/**
 * @see java.lang.Object#toString()//from www  .  j a  v  a2 s .  c o m
 */
public String toString() {
    StringBuffer buf = new StringBuffer();
    buf.append(getClass().getName());
    buf.append(":");
    if (dn != null) {
        buf.append(" dn=" + dn);
    }
    buf.append(" {");

    try {
        for (NamingEnumeration i = originalAttrs.getAll(); i.hasMore();) {
            Attribute attribute = (Attribute) i.next();
            if (attribute.size() == 1) {
                buf.append(attribute.getID());
                buf.append('=');
                buf.append(attribute.get());
            } else {
                for (int j = 0; j < attribute.size(); j++) {
                    if (j > 0) {
                        buf.append(", ");
                    }
                    buf.append(attribute.getID());
                    buf.append('[');
                    buf.append(j);
                    buf.append("]=");
                    buf.append(attribute.get(j));
                }
            }

            if (i.hasMore()) {
                buf.append(", ");
            }
        }
    } catch (NamingException e) {
        log.warn("Error in toString()");
    }
    buf.append('}');

    return buf.toString();
}

From source file:org.springframework.ldap.core.DirContextAdapter.java

/**
 * Collect all modifications for the changed attribute. If no changes have
 * been made, return immediately. If modifications have been made, and the
 * original size as well as the updated size of the attribute is 1, replace
 * the attribute. If the size of the updated attribute is 0, remove the
 * attribute. Otherwise, the attribute is a multi-value attribute; if it's
 * an ordered one it should be replaced in its entirety to preserve the new
 * ordering, if not all modifications to the original value (removals and
 * additions) will be collected individually.
 * /* ww w . j a  va2  s. c o m*/
 * @param changedAttr the value of the changed attribute.
 * @param modificationList the list in which to add the modifications.
 * @throws NamingException if thrown by called Attribute methods.
 */
private void collectModifications(Attribute changedAttr, List modificationList) throws NamingException {
    Attribute currentAttribute = originalAttrs.get(changedAttr.getID());

    if (changedAttr.equals(currentAttribute)) {
        // No changes
        return;
    } else if (currentAttribute != null && currentAttribute.size() == 1 && changedAttr.size() == 1) {
        // Replace single-vale attribute.
        modificationList.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE, changedAttr));
    } else if (changedAttr.size() == 0 && currentAttribute != null) {
        // Attribute has been removed.
        modificationList.add(new ModificationItem(DirContext.REMOVE_ATTRIBUTE, changedAttr));
    } else if ((currentAttribute == null || currentAttribute.size() == 0) && changedAttr.size() > 0) {
        // Attribute has been added.
        modificationList.add(new ModificationItem(DirContext.ADD_ATTRIBUTE, changedAttr));
    } else if (changedAttr.size() > 0 && changedAttr.isOrdered()) {
        // This is a multivalue attribute and it is ordered - the original
        // value should be replaced with the new values so that the ordering
        // is preserved.
        modificationList.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE, changedAttr));
    } else if (changedAttr.size() > 0) {
        // Change of multivalue Attribute. Collect additions and removals
        // individually.
        List myModifications = new LinkedList();
        collectModifications(currentAttribute, changedAttr, myModifications);

        if (myModifications.isEmpty()) {
            // This means that the attributes are not equal, but the
            // actual values are the same - thus the order must have
            // changed. This should result in a REPLACE_ATTRIBUTE operation.
            myModifications.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE, changedAttr));
        }

        modificationList.addAll(myModifications);
    }
}

From source file:org.olat.ldap.manager.LDAPLoginManagerImpl.java

/**
 * Checks if LDAP properties are different then OLAT properties of a User. If
 * they are different a Map (OlatPropertyName,LDAPValue) is returned.
 * /*  ww  w.  j  a v  a2s. c om*/
 * @param attributes Set of LDAP Attribute of Identity
 * @param identity Identity to compare
 * 
 * @return Map(OlatPropertyName,LDAPValue) of properties Identity, where
 *         property has changed. NULL is returned it no attributes have to be synced
 */
@SuppressWarnings("unchecked")
public Map<String, String> prepareUserPropertyForSync(Attributes attributes, Identity identity) {
    Map<String, String> olatPropertyMap = new HashMap<String, String>();
    User user = identity.getUser();
    NamingEnumeration<Attribute> neAttrs = (NamingEnumeration<Attribute>) attributes.getAll();
    try {
        while (neAttrs.hasMore()) {
            Attribute attr = neAttrs.next();
            String olatProperty = mapLdapAttributeToOlatProperty(attr.getID());
            if (olatProperty == null) {
                continue;
            }
            String ldapValue = getAttributeValue(attr);
            String olatValue = user.getProperty(olatProperty, null);
            if (olatValue == null) {
                // new property or user ID (will always be null, pseudo property)
                olatPropertyMap.put(olatProperty, ldapValue);
            } else {
                if (ldapValue.compareTo(olatValue) != 0) {
                    olatPropertyMap.put(olatProperty, ldapValue);
                }
            }
        }
        if (olatPropertyMap.size() == 1 && olatPropertyMap.get(LDAPConstants.LDAP_USER_IDENTIFYER) != null) {
            log.debug("propertymap for identity " + identity.getName()
                    + " contains only userID, NOTHING TO SYNC!");
            return null;
        } else {
            log.debug("propertymap for identity " + identity.getName() + " contains " + olatPropertyMap.size()
                    + " items (" + olatPropertyMap.keySet() + ") to be synced later on");
            return olatPropertyMap;
        }

    } catch (NamingException e) {
        log.error("NamingException when trying to prepare user properties for LDAP sync", e);
        return null;
    }
}

From source file:org.lsc.jndi.JndiServices.java

/**
 * Return the LDAP schema.//w w  w .j  a v a 2  s  .co m
 *
 * @param attrsToReturn
 *                list of attribute names to return (or null for all
 *                'standard' attributes)
 * @return the map of name => attribute
 * @throws NamingException
 *                 thrown if something goes wrong (bad
 */
@SuppressWarnings("unchecked")
public Map<String, List<String>> getSchema(final String[] attrsToReturn) throws NamingException {
    Map<String, List<String>> attrsResult = new HashMap<String, List<String>>();

    // connect to directory
    Hashtable<String, String> props = (Hashtable<String, String>) ctx.getEnvironment();
    String baseUrl = (String) props.get(Context.PROVIDER_URL);
    baseUrl = baseUrl.substring(0, baseUrl.lastIndexOf('/'));
    props.put(Context.PROVIDER_URL, baseUrl);
    DirContext schemaCtx = new InitialLdapContext(props, null);

    // find schema entry
    SearchControls sc = new SearchControls();
    sc.setSearchScope(SearchControls.OBJECT_SCOPE);
    sc.setReturningAttributes(new String[] { "subschemaSubentry" });

    NamingEnumeration<SearchResult> schemaDnSR = schemaCtx.search("", "(objectclass=*)", sc);

    SearchResult sr = null;
    Attribute subschemaSubentry = null;
    String subschemaSubentryDN = null;

    if (schemaDnSR.hasMore()) {
        sr = schemaDnSR.next();
    }
    if (sr != null) {
        subschemaSubentry = sr.getAttributes().get("subschemaSubentry");
    }
    if (subschemaSubentry != null && subschemaSubentry.size() > 0) {
        subschemaSubentryDN = (String) subschemaSubentry.get();
    }

    if (subschemaSubentryDN != null) {
        // get schema attributes from subschemaSubentryDN
        Attributes schemaAttrs = schemaCtx.getAttributes(subschemaSubentryDN,
                attrsToReturn != null ? attrsToReturn : new String[] { "*", "+" });

        if (schemaAttrs != null) {
            for (String attr : attrsToReturn) {
                Attribute schemaAttr = schemaAttrs.get(attr);
                if (schemaAttr != null) {
                    attrsResult.put(schemaAttr.getID(), (List<String>) Collections.list(schemaAttr.getAll()));
                }
            }
        }
    }

    return attrsResult;
}

From source file:org.olat.ldap.manager.LDAPLoginManagerImpl.java

/**
 * Creates User in OLAT and ads user to LDAP securityGroup Required Attributes
 * have to be checked before this method.
 * //  www . ja va  2s  .com
 * @param userAttributes Set of LDAP Attribute of User to be created
 */
@Override
public Identity createAndPersistUser(Attributes userAttributes) {
    // Get and Check Config
    String[] reqAttrs = syncConfiguration.checkRequestAttributes(userAttributes);
    if (reqAttrs != null) {
        log.warn("Can not create and persist user, the following attributes are missing::"
                + ArrayUtils.toString(reqAttrs), null);
        return null;
    }

    String uid = getAttributeValue(userAttributes
            .get(syncConfiguration.getOlatPropertyToLdapAttribute(LDAPConstants.LDAP_USER_IDENTIFYER)));
    String email = getAttributeValue(
            userAttributes.get(syncConfiguration.getOlatPropertyToLdapAttribute(UserConstants.EMAIL)));
    // Lookup user
    if (securityManager.findIdentityByName(uid) != null) {
        log.error("Can't create user with username='" + uid
                + "', this username does already exist in OLAT database", null);
        return null;
    }
    if (!MailHelper.isValidEmailAddress(email)) {
        // needed to prevent possibly an AssertException in findIdentityByEmail breaking the sync!
        log.error("Cannot try to lookup user " + uid + " by email with an invalid email::" + email, null);
        return null;
    }
    if (userManager.userExist(email)) {
        log.error("Can't create user with email='" + email
                + "', a user with that email does already exist in OLAT database", null);
        return null;
    }

    // Create User (first and lastname is added in next step)
    User user = userManager.createUser(null, null, email);
    // Set User Property's (Iterates over Attributes and gets OLAT Property out
    // of olatexconfig.xml)
    NamingEnumeration<? extends Attribute> neAttr = userAttributes.getAll();
    try {
        while (neAttr.hasMore()) {
            Attribute attr = neAttr.next();
            String olatProperty = mapLdapAttributeToOlatProperty(attr.getID());
            if (!attr.getID().equalsIgnoreCase(
                    syncConfiguration.getOlatPropertyToLdapAttribute(LDAPConstants.LDAP_USER_IDENTIFYER))) {
                String ldapValue = getAttributeValue(attr);
                if (olatProperty == null || ldapValue == null)
                    continue;
                user.setProperty(olatProperty, ldapValue);
            }
        }
        // Add static user properties from the configuration
        Map<String, String> staticProperties = syncConfiguration.getStaticUserProperties();
        if (staticProperties != null && staticProperties.size() > 0) {
            for (Entry<String, String> staticProperty : staticProperties.entrySet()) {
                user.setProperty(staticProperty.getKey(), staticProperty.getValue());
            }
        }
    } catch (NamingException e) {
        log.error("NamingException when trying to create and persist LDAP user with username::" + uid, e);
        return null;
    } catch (Exception e) {
        // catch any exception here to properly log error
        log.error("Unknown exception when trying to create and persist LDAP user with username::" + uid, e);
        return null;
    }

    // Create Identity
    Identity identity = securityManager.createAndPersistIdentityAndUser(uid, null, user,
            LDAPAuthenticationController.PROVIDER_LDAP, uid);
    // Add to SecurityGroup LDAP
    SecurityGroup secGroup = securityManager.findSecurityGroupByName(LDAPConstants.SECURITY_GROUP_LDAP);
    securityManager.addIdentityToSecurityGroup(identity, secGroup);
    // Add to SecurityGroup OLATUSERS
    secGroup = securityManager.findSecurityGroupByName(Constants.GROUP_OLATUSERS);
    securityManager.addIdentityToSecurityGroup(identity, secGroup);
    log.info("Created LDAP user username::" + uid);
    return identity;
}

From source file:org.springframework.ldap.core.DirContextAdapter.java

public void update() {
    NamingEnumeration attributesEnumeration = null;

    try {//  w w  w  .ja  v a2  s. c  o  m
        attributesEnumeration = updatedAttrs.getAll();

        // find what to update
        while (attributesEnumeration.hasMore()) {
            Attribute a = (Attribute) attributesEnumeration.next();

            // if it does not exist it should be added
            if (isEmptyAttribute(a)) {
                originalAttrs.remove(a.getID());
            } else {
                // Otherwise it should be set.
                originalAttrs.put(a);
            }
        }
    } catch (NamingException e) {
        throw LdapUtils.convertLdapException(e);
    } finally {
        closeNamingEnumeration(attributesEnumeration);
    }

    // Reset the attributes to be updated
    updatedAttrs = new BasicAttributes(true);
}

From source file:org.springframework.ldap.core.DirContextAdapter.java

private void collectModifications(Attribute originalAttr, Attribute changedAttr, List modificationList)
        throws NamingException {

    Attribute originalClone = (Attribute) originalAttr.clone();
    Attribute addedValuesAttribute = new BasicAttribute(originalAttr.getID());

    for (int i = 0; i < changedAttr.size(); i++) {
        Object attributeValue = changedAttr.get(i);
        if (!originalClone.remove(attributeValue)) {
            addedValuesAttribute.add(attributeValue);
        }/*w ww . j  av a2  s . c  o  m*/
    }

    // We have now traversed and removed all values from the original that
    // were also present in the new values. The remaining values in the
    // original must be the ones that were removed.
    if (originalClone.size() > 0) {
        modificationList.add(new ModificationItem(DirContext.REMOVE_ATTRIBUTE, originalClone));
    }

    if (addedValuesAttribute.size() > 0) {
        modificationList.add(new ModificationItem(DirContext.ADD_ATTRIBUTE, addedValuesAttribute));
    }
}