Example usage for javax.naming.directory Attribute add

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

Introduction

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

Prototype

boolean add(Object attrVal);

Source Link

Document

Adds a new value to the attribute.

Usage

From source file:org.tolven.ldapmgr.LDAPMgrPlugin.java

protected void updateSuffix(DirContext dirContext) {
    String ldapSuffix = getLDAPSuffix();
    NamingEnumeration<SearchResult> namingEnum = null;
    try {/*  w  w  w  .j  a va2 s.co m*/
        try {
            String dn = ldapSuffix;
            Attributes attributes = new BasicAttributes();
            Attribute objclass = new BasicAttribute("objectclass");
            objclass.add("organization");
            objclass.add("dcObject");
            attributes.put(objclass);
            attributes.put("dc", "tolven");
            attributes.put("o", "myOrg");
            dirContext.createSubcontext(dn, attributes);
            logger.info("Executed a createSubContext LDAP schema for " + ldapSuffix);
        } catch (NamingException ex) {
            //For some reason the search can fail, when the suffix is available, and when not available
            // The only certainty is to attempt to create it for now
        }
    } finally {
        if (namingEnum != null) {
            try {
                namingEnum.close();
            } catch (NamingException ex) {
                throw new RuntimeException("Could not close the naming enumeration for the ldap suffix schema",
                        ex);
            }
        }
    }
}

From source file:org.wso2.carbon.user.core.tenant.CommonHybridLDAPTenantManager.java

@Deprecated
protected String createAdminEntry(String dnOfUserContext, Tenant tenant, DirContext initialDirContext)
        throws UserStoreException {
    String userDN = null;/*ww w.  jav  a 2 s . c  om*/
    DirContext organizationalUsersContext = null;
    try {
        //get connection to tenant's user context
        organizationalUsersContext = (DirContext) initialDirContext.lookup(dnOfUserContext);
        Attributes userAttributes = new BasicAttributes(true);

        //create person object class attribute
        Attribute objClass = new BasicAttribute(LDAPConstants.OBJECT_CLASS_NAME);
        objClass.add(realmConfig.getUserStoreProperty(LDAPConstants.USER_ENTRY_OBJECT_CLASS));
        if (UserCoreUtil.isKdcEnabled(realmConfig)) {
            // Add Kerberos specific object classes
            objClass.add("krb5principal");
            objClass.add("krb5kdcentry");
            objClass.add("subschema");

            String principal = tenant.getAdminName() + UserCoreConstants.PRINCIPAL_USERNAME_SEPARATOR
                    + tenant.getDomain() + UserCoreConstants.TENANT_DOMAIN_COMBINER + getRealmName();
            Attribute kerberosPrincipalName = new BasicAttribute("krb5PrincipalName");
            kerberosPrincipalName.add(principal);

            Attribute keyVersionNumber = new BasicAttribute("krb5KeyVersionNumber");
            keyVersionNumber.add("0");

            userAttributes.put(kerberosPrincipalName);
            userAttributes.put(keyVersionNumber);
        }
        userAttributes.put(objClass);

        //create user password attribute
        Attribute password = new BasicAttribute(USER_PASSWORD_ATTRIBUTE_NAME);
        String passwordHashMethod = realmConfig.getUserStoreProperty(LDAPConstants.PASSWORD_HASH_METHOD);
        String passwordToStore = UserCoreUtil.getPasswordToStore(tenant.getAdminPassword(), passwordHashMethod,
                isKDCEnabled());
        password.add(passwordToStore);
        userAttributes.put(password);

        //create mail attribute
        Attribute adminEmail = new BasicAttribute(EMAIL_ATTRIBUTE_NAME);
        adminEmail.add(tenant.getEmail());
        userAttributes.put(adminEmail);

        //create compulsory attribute: sn-last name
        Attribute lastName = new BasicAttribute(SN_ATTRIBUTE_NAME);
        lastName.add(tenant.getAdminLastName());
        userAttributes.put(lastName);

        //read user name attribute in user-mgt.xml
        String userNameAttribute = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_ATTRIBUTE);

        //if user name attribute is not cn, add it to attribute list
        if (!(CN_ATTRIBUTE_NAME.equals(userNameAttribute))) {
            Attribute firstName = new BasicAttribute(CN_ATTRIBUTE_NAME);
            firstName.add(tenant.getAdminFirstName());
            userAttributes.put(firstName);
        }
        String userRDN = userNameAttribute + "=" + tenant.getAdminName();
        organizationalUsersContext.bind(userRDN, null, userAttributes);
        userDN = userRDN + "," + dnOfUserContext;
        //return (userRDN + dnOfUserContext);
    } catch (NamingException e) {
        String errorMsg = "Error occurred while creating Admin entry";
        if (logger.isDebugEnabled()) {
            logger.debug(errorMsg, e);
        }
        throw new UserStoreException(errorMsg, e);
    } finally {
        closeContext(organizationalUsersContext);
    }

    return userDN;
}

From source file:org.tolven.ldapmgr.LDAPMgrPlugin.java

protected void updateGroups(DirContext dirContext, SearchControls controls) {
    String ldapSuffix = getLDAPSuffix();
    String ldapGroups = getLDAPGroups();
    NamingEnumeration<SearchResult> namingEnum = null;
    try {/*from  ww  w . ja v a 2  s. c  om*/
        boolean schemaExists = false;
        try {
            namingEnum = dirContext.search(ldapSuffix, ldapGroups, controls);
            schemaExists = namingEnum.hasMore();
        } catch (NamingException ex) {
            throw new RuntimeException("Could find groups schema", ex);
        }
        if (schemaExists) {
            logger.info("LDAP schema for " + ldapGroups + " already exists");
        } else {
            String dn = ldapGroups + "," + ldapSuffix;
            Attributes attributes = new BasicAttributes();
            Attribute objclass = new BasicAttribute("objectclass");
            objclass.add("organizationalUnit");
            attributes.put(objclass);
            attributes.put(ldapGroups.substring(0, ldapGroups.indexOf("=")),
                    ldapGroups.substring(ldapGroups.indexOf("=") + 1));
            try {
                dirContext.createSubcontext(dn, attributes);
            } catch (NamingException ex) {
                throw new RuntimeException("Could not create groups schema", ex);
            }
            logger.info("Created LDAP schema for " + ldapGroups);
        }
    } finally {
        if (namingEnum != null) {
            try {
                namingEnum.close();
            } catch (NamingException ex) {
                throw new RuntimeException("Could not close the naming enumeration for the ldap groups schema",
                        ex);
            }
        }
    }
}

From source file:org.tolven.ldapmgr.LDAPMgrPlugin.java

protected void updatePeople(DirContext dirContext, SearchControls controls) {
    String ldapSuffix = getLDAPSuffix();
    String ldapPeople = getLDAPPeople();
    NamingEnumeration<SearchResult> namingEnum = null;
    try {// w ww .j  a  v a 2 s  .c o m
        boolean schemaExists = false;
        try {
            namingEnum = dirContext.search(ldapSuffix, ldapPeople, controls);
            schemaExists = namingEnum.hasMore();
        } catch (NamingException ex) {
            throw new RuntimeException("Could find people schema", ex);
        }
        if (schemaExists) {
            logger.info("LDAP schema for " + ldapPeople + " already exists");
        } else {
            String dn = ldapPeople + "," + ldapSuffix;
            Attributes attributes = new BasicAttributes();
            Attribute objclass = new BasicAttribute("objectclass");
            objclass.add("organizationalUnit");
            attributes.put(objclass);
            attributes.put(ldapPeople.substring(0, ldapPeople.indexOf("=")),
                    ldapPeople.substring(ldapPeople.indexOf("=") + 1));
            try {
                dirContext.createSubcontext(dn, attributes);
            } catch (NamingException ex) {
                throw new RuntimeException("Could not create people schema", ex);
            }
            logger.info("Created LDAP schema for " + ldapPeople);
        }
    } finally {
        if (namingEnum != null) {
            try {
                namingEnum.close();
            } catch (NamingException ex) {
                throw new RuntimeException("Could not close the naming enumeration for the ldap people schema",
                        ex);
            }
        }
    }
}

From source file:org.tolven.ldapmgr.LDAPMgrPlugin.java

protected void updateUser(String user, String encryptedPassword, DirContext dirContext,
        SearchControls controls) {
    NamingEnumeration<SearchResult> namingEnum = null;
    try {/*from  w w w.  j  a  va 2s  .co  m*/
        String ldapPeople = getLDAPPeople();
        String ldapSuffix = getLDAPSuffix();
        boolean schemaExists = false;
        try {
            namingEnum = dirContext.search(ldapPeople + "," + ldapSuffix, "uid=" + user, controls);
            schemaExists = namingEnum.hasMore();
        } catch (NamingException ex) {
            throw new RuntimeException("Could find schema for: " + user, ex);
        }
        if (schemaExists) {
            logger.info("LDAP schema for user " + user + " already exists");
        } else {
            String dn = "uid=" + user + "," + ldapPeople + "," + ldapSuffix;
            Attributes attributes = new BasicAttributes();
            Attribute objclass = new BasicAttribute("objectclass");
            objclass.add("inetOrgPerson");
            attributes.put(objclass);
            attributes.put("uid", user);
            attributes.put("sn", user);
            attributes.put("cn", user);
            attributes.put("userPassword", encryptedPassword);
            try {
                dirContext.createSubcontext(dn, attributes);
            } catch (NamingException ex) {
                throw new RuntimeException("Could not create schema for: " + user, ex);
            }
            logger.info("Created LDAP schema for " + user);
        }
    } finally {
        if (namingEnum != null) {
            try {
                namingEnum.close();
            } catch (NamingException ex) {
                throw new RuntimeException(
                        "Could not close the naming enumeration for the ldap schema: " + user, ex);
            }
        }
    }
}

From source file:org.tolven.ldapmgr.LDAPMgrPlugin.java

protected void updateRootDN(DirContext dirContext, SearchControls controls) {
    String ldapRootDN = getRootDN();
    NamingEnumeration<SearchResult> namingEnum = null;
    try {//from  www .  j ava 2s. c om
        boolean schemaExists = false;
        String name = null;
        String base = null;
        try {
            int index = ldapRootDN.indexOf(",");
            if (index == -1) {
                throw new RuntimeException("Expected to find at least one comma in the rootDN");
            } else {
                name = ldapRootDN.substring(0, index);
                base = ldapRootDN.substring(index + 1);
            }
            namingEnum = dirContext.search(base, name, controls);
            schemaExists = namingEnum.hasMore();
        } catch (NamingException ex) {
            throw new RuntimeException("Could find rootDN schema", ex);
        }
        if (schemaExists) {
            logger.info("LDAP schema for " + ldapRootDN + " already exists");
        } else {
            String dn = name + "," + base;
            Attributes attributes = new BasicAttributes();
            Attribute objclass = new BasicAttribute("objectclass");
            objclass.add("organizationalRole");
            attributes.put(objclass);
            attributes.put(name.substring(0, name.indexOf("=")), name.substring(name.indexOf("=") + 1));
            try {
                dirContext.createSubcontext(dn, attributes);
            } catch (NamingException ex) {
                throw new RuntimeException("Could not create rootDN schema", ex);
            }
            logger.info("Created LDAP schema for " + ldapRootDN);
        }
    } finally {
        if (namingEnum != null) {
            try {
                namingEnum.close();
            } catch (NamingException ex) {
                throw new RuntimeException("Could not close the naming enumeration for the ldap rootDN schema",
                        ex);
            }
        }
    }
}

From source file:nl.knaw.dans.common.ldap.repo.LdapMapper.java

/**
 * Marshal an object to attributes./*  w  ww . j a v  a  2  s.c  o  m*/
 *
 * @param instance
 *        the object to be marshaled
 * @param forUpdate
 *        is this an add or update operation
 * @return the attributes derived from annotated fields and methods of the object
 * @throws MissingAttributeException
 *         if a required attribute is null or blank
 * @throws LdapMappingException
 *         wrapper for various exceptions
 */
public Attributes marshal(T instance, boolean forUpdate)
        throws MissingAttributeException, LdapMappingException {
    if (!clazz.equals(instance.getClass())) {
        throw new IllegalArgumentException(instance.getClass().getName() + " is not a " + clazz.getName());
    }
    Attributes attrs = new BasicAttributes();
    Attribute oc = new BasicAttribute("objectclass");
    for (String objectClass : getObjectClasses()) {
        oc.add(objectClass);
    }
    attrs.put(oc);

    loadAttributesFromFields(instance, attrs, forUpdate);
    loadAttributesFromMethods(instance, attrs, forUpdate);

    return attrs;
}

From source file:nl.knaw.dans.common.ldap.repo.LdapMapper.java

private void loadSingleAttribute(Attributes attrs, String attrID, Object value, boolean oneWayEncrypted,
        boolean forUpdate, String encrypted, LdapAttributeValueTranslator translator)
        throws LdapMappingException {
    if (value != null) {
        value = translator.toLdap(value);

        if (oneWayEncrypted) {
            value = encrypt(value);/*www  .  j av  a2s  .c  om*/
        } else if (ENCRYPTION_ALGORITHM.equals(encrypted)) {
            value = preparePassword(value);
        } else if (value.getClass().isEnum()) {
            value = value.toString();
        } else if (Boolean.class.equals(value.getClass())) {
            value = ((Boolean) value) ? "TRUE" : "FALSE";
        } else if (value instanceof Number) {
            value = value.toString();
        }

        Attribute attr = attrs.get(attrID);
        if (attr == null) {
            attrs.put(attrID, value);
        } else {
            attr.add(value);
        }

    } else if (!USERPASSWORD.equals(attrID) && forUpdate) {
        attrs.put(new BasicAttribute(attrID));
    }
}

From source file:edu.vt.middleware.ldap.dsml.Dsmlv1.java

/**
 * This will take a DSML <code>Element</code> containing an entry of type
 * <dsml:entry name="name"/> and convert it to a LDAP search result.
 *
 * @param  entryElement  <code>Element</code> of DSML content
 *
 * @return  <code>SearchResult</code>
 *//*from   w w  w  .j a  v a 2  s. c om*/
protected SearchResult createSearchResult(final Element entryElement) {
    String name = "";
    final Attributes entryAttributes = new BasicAttributes(true);
    SearchResult attrResults = null;

    if (entryElement != null) {

        name = entryElement.attributeValue("dn");
        if (name == null) {
            name = "";
        }

        if (entryElement.hasContent()) {

            final Iterator<?> ocIterator = entryElement.elementIterator("objectclass");
            while (ocIterator.hasNext()) {
                final Element ocElement = (Element) ocIterator.next();
                if (ocElement != null && ocElement.hasContent()) {
                    final String ocName = "objectClass";
                    final Attribute entryAttribute = new BasicAttribute(ocName);
                    final Iterator<?> valueIterator = ocElement.elementIterator("oc-value");
                    while (valueIterator.hasNext()) {
                        final Element valueElement = (Element) valueIterator.next();
                        if (valueElement != null) {
                            final String value = valueElement.getText();
                            if (value != null) {
                                entryAttribute.add(value);
                            }
                        }
                    }
                    entryAttributes.put(entryAttribute);
                }
            }

            attrResults = super.createSearchResult(entryElement);
        }
    }

    if (attrResults != null) {
        final Attributes attrs = attrResults.getAttributes();
        if (attrs != null) {
            final NamingEnumeration<? extends Attribute> ae = attrs.getAll();
            if (ae != null) {
                try {
                    while (ae.hasMore()) {
                        entryAttributes.put(ae.next());
                    }
                } catch (NamingException e) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Could not read attribute in SearchResult from parent");
                    }
                }
            }
        }
    }
    return new SearchResult(name, null, entryAttributes);
}

From source file:org.kitodo.production.ldap.LdapUser.java

private void prepareAttributes(LdapGroup ldapGroup, User user, String inUidNumber) {
    Attribute oc = new BasicAttribute("objectclass");
    StringTokenizer tokenizer = new StringTokenizer(ldapGroup.getObjectClasses(), ",");
    while (tokenizer.hasMoreTokens()) {
        oc.add(tokenizer.nextToken());
    }/*from   w w w  .  j  a v a  2s . c  om*/
    this.attributes.put(oc);

    this.attributes.put("uid", replaceVariables(ldapGroup.getUid(), user, inUidNumber));
    this.attributes.put("cn", replaceVariables(ldapGroup.getUid(), user, inUidNumber));
    this.attributes.put("displayName", replaceVariables(ldapGroup.getDisplayName(), user, inUidNumber));
    this.attributes.put("description", replaceVariables(ldapGroup.getDescription(), user, inUidNumber));
    this.attributes.put("gecos", replaceVariables(ldapGroup.getGecos(), user, inUidNumber));
    this.attributes.put("loginShell", replaceVariables(ldapGroup.getLoginShell(), user, inUidNumber));
    this.attributes.put("sn", replaceVariables(ldapGroup.getSn(), user, inUidNumber));
    this.attributes.put("homeDirectory", replaceVariables(ldapGroup.getHomeDirectory(), user, inUidNumber));

    this.attributes.put("sambaAcctFlags", replaceVariables(ldapGroup.getSambaAcctFlags(), user, inUidNumber));
    this.attributes.put("sambaLogonScript",
            replaceVariables(ldapGroup.getSambaLogonScript(), user, inUidNumber));
    this.attributes.put("sambaPrimaryGroupSID",
            replaceVariables(ldapGroup.getSambaPrimaryGroupSID(), user, inUidNumber));
    this.attributes.put("sambaSID", replaceVariables(ldapGroup.getSambaSID(), user, inUidNumber));

    this.attributes.put("sambaPwdMustChange",
            replaceVariables(ldapGroup.getSambaPwdMustChange(), user, inUidNumber));
    this.attributes.put("sambaPasswordHistory",
            replaceVariables(ldapGroup.getSambaPasswordHistory(), user, inUidNumber));
    this.attributes.put("sambaLogonHours", replaceVariables(ldapGroup.getSambaLogonHours(), user, inUidNumber));
    this.attributes.put("sambaKickoffTime",
            replaceVariables(ldapGroup.getSambaKickoffTime(), user, inUidNumber));
    this.attributes.put("sambaPwdLastSet", String.valueOf(System.currentTimeMillis() / 1000L));

    this.attributes.put("uidNumber", inUidNumber);
    this.attributes.put("gidNumber", replaceVariables(ldapGroup.getGidNumber(), user, inUidNumber));
}