Example usage for javax.naming.directory BasicAttributes BasicAttributes

List of usage examples for javax.naming.directory BasicAttributes BasicAttributes

Introduction

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

Prototype

public BasicAttributes() 

Source Link

Document

Constructs a new instance of Attributes.

Usage

From source file:com.funambol.LDAP.dao.impl.ContactDAO.java

/**
 * Convert a <i>Contact</i> into a LDAP inetOrgPerson set of attributes.
 * This method is used in from Client to Server
 * /*  w w w  . j a  va2 s.c  o m*/
 * @param contact
 *            contact to transform into Attributes
 * @return Attributes representation of the contact
 */
public Attributes createEntry(Contact contact) {

    if (logger.isTraceEnabled())
        logger.trace("Working on contact:" + contact.getUid());

    Attributes attributeSet = new BasicAttributes();
    Attribute objClass = new BasicAttribute("objectClass");
    if (logger.isDebugEnabled())
        logger.debug("Ok let's add objectclass");

    objClass.add("inetOrgPerson");
    objClass.add("person");

    attributeSet.put(objClass);
    try {

        if (contact.getUid() == null) {
            contact.setUid(createUniqueId(contact));
            logger.info("UID is now: " + contact.getUid());
        }

        // Split contact object into sub-objects
        Name name = contact.getName();
        PersonalDetail personal = contact.getPersonalDetail();
        BusinessDetail business = contact.getBusinessDetail();

        List phones = personal.getPhones();
        List businessPhones = business.getPhones();

        List mails = personal.getEmails();
        List note = contact.getNotes();

        // personal address
        Address addr = personal.getAddress();

        // if displayname doesn't exist and the firstname and the lastname
        // are not both defined, this will result in a NullPointerException
        // I don't want to support any other ways of doing this right now.
        // a solution could be to use an UID for the rdn
        if (name != null) {

            if (propertyCheck(name.getLastName())) {
                attributeSet.put(new BasicAttribute("sn", name.getLastName().getPropertyValueAsString()));
            } else {
                attributeSet.put(new BasicAttribute("sn", ""));
            }

            if (propertyCheck(name.getFirstName())) {
                attributeSet
                        .put(new BasicAttribute("givenName", name.getFirstName().getPropertyValueAsString()));
            } else {
                attributeSet.put(new BasicAttribute("givenName", ""));
            }

            attributeSet.put(new BasicAttribute("cn", name.getFirstName().getPropertyValueAsString() + " "
                    + name.getLastName().getPropertyValueAsString()));
        }

        // Company name
        if (business != null && propertyCheck(business.getCompany())) {
            attributeSet.put(new BasicAttribute("o", business.getCompany().getPropertyValueAsString()));
        }

        // Adding phones
        if (phones != null && !phones.isEmpty()) {

            Iterator iter2 = phones.iterator();
            while (iter2.hasNext()) {
                Phone phone = (Phone) iter2.next();

                // if empty, no need to check type
                if (!propertyCheck(phone))
                    continue;

                // Home phones
                if (phone.getPhoneType().equals("HomeTelephoneNumber")) {
                    attributeSet.put(new BasicAttribute("homePhone", phone.getPropertyValueAsString()));
                }

                // MobilePhones
                if (phone.getPhoneType().equals("MobileTelephoneNumber"))
                    attributeSet.put(new BasicAttribute("mobile", phone.getPropertyValueAsString()));

            }
        }

        // Adding business phones
        if (businessPhones != null && !businessPhones.isEmpty()) {

            Iterator iter2 = businessPhones.iterator();
            while (iter2.hasNext()) {
                Phone phone = (Phone) iter2.next();

                // if empty, no need to check type
                if (!propertyCheck(phone))
                    continue;

                // Business phones
                if (phone.getPhoneType().equals("BusinessTelephoneNumber")) {
                    attributeSet.put(new BasicAttribute("telephoneNumber", phone.getPropertyValueAsString()));
                }
                // Fax
                if (phone.getPhoneType().equals("BusinessFaxNumber")) {
                    attributeSet.put(
                            new BasicAttribute("facsimiletelephonenumber", phone.getPropertyValueAsString()));
                }
            }
        }

        if (mails != null && !mails.isEmpty()) {

            Iterator iter1 = mails.iterator();

            // For each email address, add it
            while (iter1.hasNext()) {
                Email mail = (Email) iter1.next();
                if (propertyCheck(mail))
                    attributeSet.put(new BasicAttribute("mail", mail.getPropertyValueAsString()));
            }
        }

        // Address
        if (addr != null) {
            if (propertyCheck(personal.getAddress().getPostalCode()))
                attributeSet.put(new BasicAttribute("postalCode",
                        personal.getAddress().getPostalCode().getPropertyValueAsString()));

            if (propertyCheck(personal.getAddress().getStreet()))
                attributeSet.put(new BasicAttribute("postalAddress",
                        personal.getAddress().getStreet().getPropertyValueAsString()));

            if (propertyCheck(personal.getAddress().getCity()))
                attributeSet.put(
                        new BasicAttribute("l", personal.getAddress().getCity().getPropertyValueAsString()));
        }

        // Notes
        if (note != null && !note.isEmpty()) {
            Iterator note1 = note.iterator();
            while (note1.hasNext()) {
                Note nota = (Note) note1.next();
                if (propertyCheck(nota))
                    attributeSet.put(new BasicAttribute("description", nota.getPropertyValueAsString()));
            }
        }

        logger.info("Resulting LDAPAttributeSet is:");

        NamingEnumeration<String> ids = attributeSet.getIDs();

        while (ids.hasMoreElements()) {
            String attrID = ids.nextElement();
            logger.info(attrID + ": " + ((String) attributeSet.get(attrID).get()));

        }

        // Create the LDAPEntry with dn and attributes
        // THE DN is the DisplayName
        return attributeSet;

    } catch (Exception e) {
        logger.warn("Unable to create LDAPEntry from Contact: " + e.toString(), e);
        return null;
    }
}

From source file:org.archone.ad.domain.LdapActions.java

@RPCAction(name = "user.add", required = { "userId" })
@SecuredMethod(constraints = "administrator.by_domain")
public HashMap<String, Object> addUser(OperationContext opContext) throws NamingException {
    String userId = (String) opContext.getParams().get("userId");

    UserDn userDn = nameHelper.newUserDnFromId(userId);
    DomainDn domainDn = nameHelper.newDomainDnFromDomain(userDn.getDomain());

    DirContextAdapter userDirContext = (DirContextAdapter) SecurityUtils.getSubject().getPrincipal();

    Attributes attrs = new BasicAttributes();
    BasicAttribute ocattr = new BasicAttribute("objectclass");
    for (String objectClassName : ldapConfiguration.getUserObjectClassList()) {
        ocattr.add(objectClassName);//from w w w . jav  a 2s  .  co  m
    }
    attrs.put(ocattr);

    for (DisplayAttribute displayAttribute : displayAttributeHelper.getApiNameIndexedAttrDef().values()) {
        Object attrValue = opContext.getParams().get(displayAttribute.getApiName());

        if (attrValue != null) {
            BasicAttribute attr = new BasicAttribute(displayAttribute.getLdapName());

            if (attrValue instanceof List) {
                for (Object attrOneValue : (List) attrValue) {
                    attr.add(attrOneValue);
                }
            } else {
                attr.add(attrValue);
            }

            attrs.put(attr);

        } else if (displayAttribute.isMustHave()) {
            throw new RuntimeException(displayAttribute.getApiName() + " is required!");
        }

    }

    userDirContext.bind(userDn, null, attrs);

    HashMap<String, Object> response = new HashMap<String, Object>();

    response.put("success", true);

    return response;
}

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

protected void updateRootDN(DirContext dirContext, SearchControls controls) {
    String ldapRootDN = getRootDN();
    NamingEnumeration<SearchResult> namingEnum = null;
    try {/*from ww w . jav  a2  s . c  o  m*/
        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:org.wso2.carbon.connector.integration.test.ldap.LdapConnectorIntegrationTest.java

public void createSampleEntity() throws Exception {

    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

    env.put(Context.PROVIDER_URL, providerUrl);
    env.put(Context.SECURITY_PRINCIPAL, securityPrincipal);
    env.put(Context.SECURITY_CREDENTIALS, securityCredentials);

    DirContext ctx = new InitialDirContext(env);
    Attributes entry = new BasicAttributes();
    Attribute obClassAttr = new BasicAttribute("objectClass");
    obClassAttr.add("inetOrgPerson");
    entry.put(obClassAttr);//from   w ww  .  j  a va  2 s . co m

    Attribute mailAttr = new BasicAttribute("mail");
    mailAttr.add(testUserId + "@wso2.com");
    entry.put(mailAttr);

    Attribute passAttr = new BasicAttribute("userPassword");
    passAttr.add("12345");
    entry.put(passAttr);

    Attribute snAttr = new BasicAttribute("sn");
    snAttr.add("dim");
    entry.put(snAttr);

    Attribute cnAttr = new BasicAttribute("cn");
    cnAttr.add("dim");
    entry.put(cnAttr);

    String dn = "uid=" + testUserId + "," + userBase;

    ctx.createSubcontext(dn, entry);
}

From source file:CreateJavaSchema.java

/**
 * Inserts attribute definitions from RFC 2713 into the schema.
 *
 * This method maps the LDAP schema definitions in RFC 2713 onto the
 * proprietary attributes required by the Active Directory schema.
 *
 * The resulting attribute definitions are identical to those of RFC 2713.
 *///from   w  ww . j  a va  2  s.c o m
protected void insertADAttributes(DirContext rootCtx, DirContext schemaCtx) throws NamingException {

    System.out.println("  [inserting new attribute definitions ...]");

    String dn = schemaCtx.getNameInNamespace();
    String attrID;

    attrID = new String("javaClassName");
    Attributes attrs1 = new BasicAttributes();

    attrs1.put(new BasicAttribute("adminDescription", attrID));
    attrs1.put(new BasicAttribute("attributeID", "1.3.6.1.4.1.42.2.27.4.1.6"));
    attrs1.put(new BasicAttribute("attributeSyntax", "2.5.5.12"));
    attrs1.put(new BasicAttribute("cn", attrID));
    attrs1.put(
            new BasicAttribute("description", "Fully qualified name of distinguished Java class or interface"));
    attrs1.put(new BasicAttribute("distinguishedName", "CN=" + attrID + "," + dn));
    attrs1.put(new BasicAttribute("isSingleValued", "TRUE"));
    attrs1.put(new BasicAttribute("lDAPDisplayName", attrID));
    attrs1.put(new BasicAttribute("name", attrID));
    attrs1.put(new BasicAttribute("objectCategory", "CN=Attribute-Schema," + dn));
    attrs1.put(new BasicAttribute("objectClass", "attributeSchema"));
    attrs1.put(new BasicAttribute("oMSyntax", "64"));
    attrs1.put(new BasicAttribute("searchFlags", "0"));
    attrs1.put(new BasicAttribute("systemOnly", "FALSE"));

    schemaCtx.createSubcontext("cn=" + attrID, attrs1);
    System.out.println("    [" + attrID + "]");

    attrID = new String("javaCodeBase");
    Attributes attrs2 = new BasicAttributes();

    attrs2.put(new BasicAttribute("adminDescription", attrID));
    attrs2.put(new BasicAttribute("attributeID", "1.3.6.1.4.1.42.2.27.4.1.7"));
    attrs2.put(new BasicAttribute("attributeSyntax", "2.5.5.5"));
    attrs2.put(new BasicAttribute("cn", attrID));
    attrs2.put(new BasicAttribute("description", "URL(s) specifying the location of class definition"));
    attrs2.put(new BasicAttribute("distinguishedName", "CN=" + attrID + "," + dn));
    attrs2.put(new BasicAttribute("isSingleValued", "FALSE"));
    attrs2.put(new BasicAttribute("lDAPDisplayName", attrID));
    attrs2.put(new BasicAttribute("name", attrID));
    attrs2.put(new BasicAttribute("objectCategory", "CN=Attribute-Schema," + dn));
    attrs2.put(new BasicAttribute("objectClass", "attributeSchema"));
    attrs2.put(new BasicAttribute("oMSyntax", "22"));
    attrs2.put(new BasicAttribute("searchFlags", "0"));
    attrs2.put(new BasicAttribute("systemOnly", "FALSE"));

    schemaCtx.createSubcontext("cn=" + attrID, attrs2);
    System.out.println("    [" + attrID + "]");

    attrID = new String("javaSerializedData");
    Attributes attrs3 = new BasicAttributes();

    attrs3.put(new BasicAttribute("adminDescription", attrID));
    attrs3.put(new BasicAttribute("attributeID", "1.3.6.1.4.1.42.2.27.4.1.8"));
    attrs3.put(new BasicAttribute("attributeSyntax", "2.5.5.10"));
    attrs3.put(new BasicAttribute("cn", attrID));
    attrs3.put(new BasicAttribute("description", "Serialized form of a Java object"));
    attrs3.put(new BasicAttribute("distinguishedName", "CN=" + attrID + "," + dn));
    attrs3.put(new BasicAttribute("isSingleValued", "TRUE"));
    attrs3.put(new BasicAttribute("lDAPDisplayName", attrID));
    attrs3.put(new BasicAttribute("name", attrID));
    attrs3.put(new BasicAttribute("objectCategory", "CN=Attribute-Schema," + dn));
    attrs3.put(new BasicAttribute("objectClass", "attributeSchema"));
    attrs3.put(new BasicAttribute("oMSyntax", "4"));
    attrs3.put(new BasicAttribute("searchFlags", "0"));
    attrs3.put(new BasicAttribute("systemOnly", "FALSE"));

    schemaCtx.createSubcontext("cn=" + attrID, attrs3);
    System.out.println("    [" + attrID + "]");

    attrID = new String("javaFactory");
    Attributes attrs4 = new BasicAttributes();

    attrs4.put(new BasicAttribute("adminDescription", attrID));
    attrs4.put(new BasicAttribute("attributeID", "1.3.6.1.4.1.42.2.27.4.1.10"));
    attrs4.put(new BasicAttribute("attributeSyntax", "2.5.5.12"));
    attrs4.put(new BasicAttribute("cn", attrID));
    attrs4.put(new BasicAttribute("description", "Fully qualified Java class name of a JNDI object factory"));
    attrs4.put(new BasicAttribute("distinguishedName", "CN=" + attrID + "," + dn));
    attrs4.put(new BasicAttribute("isSingleValued", "TRUE"));
    attrs4.put(new BasicAttribute("lDAPDisplayName", attrID));
    attrs4.put(new BasicAttribute("name", attrID));
    attrs4.put(new BasicAttribute("objectCategory", "CN=Attribute-Schema," + dn));
    attrs4.put(new BasicAttribute("objectClass", "attributeSchema"));
    attrs4.put(new BasicAttribute("oMSyntax", "64"));
    attrs4.put(new BasicAttribute("searchFlags", "0"));
    attrs4.put(new BasicAttribute("systemOnly", "FALSE"));

    schemaCtx.createSubcontext("cn=" + attrID, attrs4);
    System.out.println("    [" + attrID + "]");

    attrID = new String("javaReferenceAddress");
    Attributes attrs5 = new BasicAttributes();

    attrs5.put(new BasicAttribute("adminDescription", attrID));
    attrs5.put(new BasicAttribute("attributeID", "1.3.6.1.4.1.42.2.27.4.1.11"));
    attrs5.put(new BasicAttribute("attributeSyntax", "2.5.5.12"));
    attrs5.put(new BasicAttribute("cn", attrID));
    attrs5.put(new BasicAttribute("description", "Addresses associated with a JNDI Reference"));
    attrs5.put(new BasicAttribute("distinguishedName", "CN=" + attrID + "," + dn));
    attrs5.put(new BasicAttribute("isSingleValued", "FALSE"));
    attrs5.put(new BasicAttribute("lDAPDisplayName", attrID));
    attrs5.put(new BasicAttribute("name", attrID));
    attrs5.put(new BasicAttribute("objectCategory", "CN=Attribute-Schema," + dn));
    attrs5.put(new BasicAttribute("objectClass", "attributeSchema"));
    attrs5.put(new BasicAttribute("oMSyntax", "64"));
    attrs5.put(new BasicAttribute("searchFlags", "0"));
    attrs5.put(new BasicAttribute("systemOnly", "FALSE"));

    schemaCtx.createSubcontext("cn=" + attrID, attrs5);
    System.out.println("    [" + attrID + "]");

    attrID = new String("javaDoc");
    Attributes attrs6 = new BasicAttributes();

    attrs6.put(new BasicAttribute("adminDescription", attrID));
    attrs6.put(new BasicAttribute("attributeID", "1.3.6.1.4.1.42.2.27.4.1.12"));
    attrs6.put(new BasicAttribute("attributeSyntax", "2.5.5.5"));
    attrs6.put(new BasicAttribute("cn", attrID));
    attrs6.put(new BasicAttribute("description", "The Java documentation for the class"));
    attrs6.put(new BasicAttribute("distinguishedName", "CN=" + attrID + "," + dn));
    attrs6.put(new BasicAttribute("isSingleValued", "FALSE"));
    attrs6.put(new BasicAttribute("lDAPDisplayName", attrID));
    attrs6.put(new BasicAttribute("name", attrID));
    attrs6.put(new BasicAttribute("objectCategory", "CN=Attribute-Schema," + dn));
    attrs6.put(new BasicAttribute("objectClass", "attributeSchema"));
    attrs6.put(new BasicAttribute("oMSyntax", "22"));
    attrs6.put(new BasicAttribute("searchFlags", "0"));
    attrs6.put(new BasicAttribute("systemOnly", "FALSE"));

    schemaCtx.createSubcontext("cn=" + attrID, attrs6);
    System.out.println("    [" + attrID + "]");

    attrID = new String("javaClassNames");
    Attributes attrs7 = new BasicAttributes();

    attrs7.put(new BasicAttribute("adminDescription", attrID));
    attrs7.put(new BasicAttribute("attributeID", "1.3.6.1.4.1.42.2.27.4.1.13"));
    attrs7.put(new BasicAttribute("attributeSyntax", "2.5.5.12"));
    attrs7.put(new BasicAttribute("cn", attrID));
    attrs7.put(new BasicAttribute("description", "Fully qualified Java class or interface name"));
    attrs7.put(new BasicAttribute("distinguishedName", "CN=" + attrID + "," + dn));
    attrs7.put(new BasicAttribute("isSingleValued", "FALSE"));
    attrs7.put(new BasicAttribute("lDAPDisplayName", attrID));
    attrs7.put(new BasicAttribute("name", attrID));
    attrs7.put(new BasicAttribute("objectCategory", "CN=Attribute-Schema," + dn));
    attrs7.put(new BasicAttribute("objectClass", "attributeSchema"));
    attrs7.put(new BasicAttribute("oMSyntax", "64"));
    attrs7.put(new BasicAttribute("searchFlags", "0"));
    attrs7.put(new BasicAttribute("systemOnly", "FALSE"));

    schemaCtx.createSubcontext("cn=" + attrID, attrs7);
    System.out.println("    [" + attrID + "]");

    flushADSchemaMods(rootCtx); // finally
}

From source file:org.archone.ad.domain.LdapActions.java

@RPCAction(name = "group.add", required = { "groupId" })
@SecuredMethod(constraints = "administrator.by_domain")
public HashMap<String, Object> addGroup(OperationContext opContext) throws NamingException {
    String groupId = (String) opContext.getParams().get("groupId");

    GroupDn groupDn = nameHelper.newGroupDnFromId(groupId);
    DomainDn domainDn = nameHelper.newDomainDnFromDomain(groupDn.getDomain());

    DirContextAdapter userDirContext = (DirContextAdapter) SecurityUtils.getSubject().getPrincipal();

    Attributes attrs = new BasicAttributes();
    BasicAttribute ocattr = new BasicAttribute("objectclass");
    for (String objectClassName : ldapConfiguration.getGroupObjectClassList()) {
        ocattr.add(objectClassName);//w  ww.ja va  2 s  . co  m
    }
    attrs.put(ocattr);

    String description = (String) opContext.getParams().get("description");
    if (description != null && !description.isEmpty()) {
        BasicAttribute descattr = new BasicAttribute("description");
        descattr.add(description);
        attrs.put(descattr);
    }

    userDirContext.bind(groupDn, null, attrs);

    HashMap<String, Object> response = new HashMap<String, Object>();

    response.put("success", true);

    return response;
}

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 ww w .j  a  v a 2s  .c  o 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:it.infn.ct.security.utilities.LDAPUtils.java

public static boolean registerUser(LDAPUser lus, UserRequest userReq, String OrgDN, String OrgUDN) {
    boolean registration = false;
    DirContext ctx = null;/*from   www.  jav  a 2  s .c om*/
    try {
        ctx = getAuthContext(lus.getUsername(), lus.getPassword());

        Attributes attrsBag = new BasicAttributes();

        Attribute oc = new BasicAttribute("objectClass");
        oc.add("inetOrgPerson");
        oc.add("organizationalPerson");
        oc.add("person");
        oc.add("top");
        attrsBag.put(oc);

        Attribute sn = new BasicAttribute("sn", userReq.getSurname());
        attrsBag.put(sn);

        Attribute cn = new BasicAttribute("cn", userReq.getUsername());
        attrsBag.put(cn);

        Attribute dispName = new BasicAttribute("displayName", userReq.getUsername());
        attrsBag.put(dispName);

        Attribute uPass = new BasicAttribute("userPassword", userReq.getPassword());
        attrsBag.put(uPass);

        Attribute regAdd = new BasicAttribute("registeredAddress", userReq.getPreferredMail());
        attrsBag.put(regAdd);

        if (userReq.getTitle() != null && !userReq.getTitle().isEmpty()) {
            Attribute title = new BasicAttribute("title", userReq.getTitle());
            attrsBag.put(title);
        }

        Attribute gName = new BasicAttribute("givenName", userReq.getGivenname());
        attrsBag.put(gName);

        Attribute inits = new BasicAttribute("initials", userReq.getGivenname().substring(0, 1).toUpperCase()
                + userReq.getSurname().substring(0, 1).toUpperCase());
        attrsBag.put(inits);

        Attribute mails = new BasicAttribute("mail");
        mails.add(userReq.getPreferredMail());
        for (String adMail : userReq.getAdditionalMails().split("[,\\s;]"))
            if (!adMail.isEmpty())
                mails.add(adMail.trim());
        attrsBag.put(mails);

        Attribute org = new BasicAttribute("o", OrgDN);
        attrsBag.put(org);

        if (OrgUDN != null && !OrgUDN.isEmpty()) {
            Attribute orgU = new BasicAttribute("ou", OrgUDN);
            attrsBag.put(orgU);
        }

        ResourceBundle rb = ResourceBundle.getBundle("ldap");
        ctx.createSubcontext("cn=" + userReq.getUsername() + "," + rb.getString("peopleRoot"), attrsBag);

        ModificationItem[] modItems = new ModificationItem[1];
        modItems[0] = new ModificationItem(DirContext.ADD_ATTRIBUTE, new BasicAttribute("uniqueMember",
                "cn=" + userReq.getUsername() + "," + rb.getString("peopleRoot")));

        ctx.modifyAttributes(rb.getString("usersGroup"), modItems);

        registration = true;
    } catch (NameNotFoundException ex) {
        _log.error(ex);
    } catch (NamingException e) {
        _log.error(e);
    } finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (Exception e) {
                // Never mind this.
            }
        }
    }

    return registration;
}

From source file:org.mule.transport.ldap.util.DSManager.java

/**
 * Imports the LDIF entries packaged with the Eve JNDI provider jar into the
 * newly created system partition to prime it up for operation. Note that
 * only ou=system entries will be added - entries for other partitions
 * cannot be imported and will blow chunks.
 * /*from  w ww .j a va2s . c o m*/
 * @throws NamingException
 *             if there are problems reading the ldif file and adding those
 *             entries to the system partition
 */
protected void importLdif(final InputStream in) throws NamingException {
    if (in == null) {
        throw new NullPointerException("in must not be null");
    }

    try {
        final Iterator<LdifEntry> iterator = new LdifReader(in).iterator();

        while (iterator.hasNext()) {
            final LdifEntry entry = iterator.next();

            final LdapDN dn = new LdapDN(entry.getDn());
            // dn.remove(0);
            // dn.remove(0);

            final Attributes attr = new BasicAttributes();

            final Iterator<EntryAttribute> iea = entry.getEntry().iterator();

            for (; iea.hasNext();) {
                final EntryAttribute ea = iea.next();

                attr.put(ea.getId(), ea.get().get());

                logger.debug("id " + ea.getId() + "//" + ea.get().get());
                logger.debug("size:" + ea.size());
            }

            logger.debug(" for dn:" + dn);

            root.createSubcontext(dn, attr);
        }
    } catch (final Exception e) {
        final String msg = "failed while trying to parse system ldif file";
        final NamingException ne = new LdapConfigurationException(msg);
        ne.setRootCause(e);
        throw ne;
    }
}

From source file:org.swordess.ldap.odm.core.SessionImpl.java

private static Attributes fromTransientToAttributes(Object obj) {
    EntityMetaData metaData = EntityMetaData.get(ClassHelper.actualClass(obj));
    Attributes toSaves = new BasicAttributes();
    for (EntityPropertyMetaData propMetaData : metaData) {
        Object propValue = propMetaData.getter().get(obj);
        if (propValue == null) {
            continue;
        }//from   ww  w  .  j ava  2s .  c  o m

        // ignore empty list when create
        if (propMetaData.isMultiple() && ((List) propValue).isEmpty()) {
            continue;
        }

        Evaluator<String> evaluator = null;
        if (propMetaData.isReference()) {
            // reference property use dn as attribute value
            final EntityMetaData metaDataOfReferenceProp = EntityMetaData.get(propMetaData.getValueClass());
            evaluator = new Evaluator<String>() {
                public String eval(Object obj) {
                    Object idValue = metaDataOfReferenceProp.getIdProperty().getter().get(obj);
                    if (null == idValue) {
                        return null;
                    }
                    return DnHelper.build((String) idValue, metaDataOfReferenceProp.getManagedClass());
                }
            };
        } else {
            evaluator = createPropEvaluator(propMetaData);
        }

        if (!propMetaData.isMultiple()) {
            AttrUtils.putIfNotNull(toSaves,
                    AttrUtils.create(propMetaData.getLdapPropName(), propValue, evaluator));
        } else {
            AttrUtils.putIfNotNull(toSaves,
                    AttrUtils.create(propMetaData.getLdapPropName(), (List) propValue, evaluator));
        }
    }

    toSaves.put(AttrUtils.create("objectclass", metaData.objectClasses()));
    return toSaves;
}