Example usage for javax.naming.directory Attributes put

List of usage examples for javax.naming.directory Attributes put

Introduction

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

Prototype

Attribute put(Attribute attr);

Source Link

Document

Adds a new attribute to the attribute set.

Usage

From source file:org.swordess.ldap.util.AttrUtils.java

/**
 * Add several attributes with a same value into <tt>attrs</tt>.
 * /* w  w w. j  a  v  a 2  s .  c o m*/
 * @param attrs
 * @param ids
 *            ids of each attribute
 * @param value
 */
public static void put(Attributes attrs, String[] ids, Object value) {
    if (null == attrs) {
        return;
    }
    for (Attribute toPut : create(ids, value)) {
        attrs.put(toPut);
    }
}

From source file:org.easy.ldap.LdapDao.java

/**
 * @param rdsn/*from   w ww .j  a  v  a  2s  .  c  o  m*/
 * @return
 */
private static Attributes toAttributes(Map<RdnType, String> rdsn) {
    Attributes attributes = new BasicAttributes();

    for (RdnType attributeName : rdsn.keySet()) {
        attributes.put(new BasicAttribute(attributeName.toString(), rdsn.get(attributeName)));
    }

    return attributes;
}

From source file:org.easy.ldap.LdapDao.java

/**
 * @param user// ww  w .  ja v a  2  s.c o m
 * @return
 */
public static Attributes toAttributes(LdapUser user) {
    Attributes attributes = new BasicAttributes();

    if (user.getCommonName() != null)
        attributes.put(new BasicAttribute(RdnType.CN.toString(), user.getCommonName()));

    if (user.getGivenName() != null)
        attributes.put(new BasicAttribute(RdnType.GIVEN_NAME.toString(), user.getGivenName()));

    if (user.getSurname() != null)
        attributes.put(new BasicAttribute(RdnType.SN.toString(), user.getSurname()));

    if (user.getUserId() != null)
        attributes.put(new BasicAttribute(RdnType.UID.toString(), user.getUserId()));

    if (user.getEmail() != null)
        attributes.put(new BasicAttribute(RdnType.MAIL.toString(), user.getEmail()));

    if (user.getPassword() != null)
        attributes.put(new BasicAttribute(RdnType.PASSWORD.toString(), user.getPassword()));

    return attributes;
}

From source file:edu.lafayette.metadb.model.userman.UserManDAO.java

/**
 * Get the LDAP DN for a user.//from w  w  w  .  j a va2s  .  c o m
 * @param searchUser
 * @param searchPassword
 * @param userName
 * @return
 */
@SuppressWarnings("unchecked")
private static String getDN(String searchUser, String searchPassword, String userName) {
    // The resultant DN
    String result;

    // Set up environment for creating initial context
    Hashtable env = new Hashtable(11);
    env.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(javax.naming.Context.PROVIDER_URL, Global.LDAP_URL);

    // Use admin credencials for search// Authenticate
    env.put(javax.naming.Context.SECURITY_AUTHENTICATION, "Simple");
    env.put(javax.naming.Context.SECURITY_PRINCIPAL, searchUser);
    env.put(javax.naming.Context.SECURITY_CREDENTIALS, searchPassword);

    DirContext ctx = null;
    try {
        // Create initial context
        ctx = new InitialDirContext(env);
        //MetaDbHelper.note("Created LDAP context");

        Attributes matchAttrs = new BasicAttributes(true);
        matchAttrs.put(new BasicAttribute(Global.LDAP_ID, userName));
        //MetaDbHelper.note("Created attributes");

        // look up attributes
        try {
            //MetaDbHelper.note("Setting up query");

            SearchControls ctrls = new SearchControls();
            ctrls.setSearchScope(Global.LDAP_SCOPE);

            NamingEnumeration<SearchResult> answer = ctx.search(Global.LDAP_URL + Global.LDAP_CONTEXT,
                    "(&({0}={1}))", new Object[] { Global.LDAP_ID, userName }, ctrls);

            //MetaDbHelper.note("NamingEnumeration retrieved");

            while (answer.hasMoreElements()) {
                SearchResult sr = answer.next();
                if (StringUtils.isEmpty(Global.LDAP_CONTEXT)) {
                    result = sr.getName();
                } else {
                    result = (sr.getName() + "," + Global.LDAP_CONTEXT);
                }

                //MetaDbHelper.note("Got DN: "+result);

                return result;
            }
        } catch (NamingException e) {
            MetaDbHelper.logEvent(e);
            //MetaDbHelper.note("LDAP Error: Failed Search");
        }
    } catch (NamingException e) {
        MetaDbHelper.logEvent(e);
        //MetaDbHelper.note("LDAP Error: Failed authentication");
    } finally {
        // Close the context when we're done
        try {
            if (ctx != null)
                ctx.close();
        } catch (NamingException e) {
        }
    }
    // No DN match found
    return null;
}

From source file:it.infn.ct.security.utilities.LDAPUtils.java

public static boolean addOrganisation(LDAPUser lus, Organization org) {
    boolean registration = false;
    DirContext ctx = null;//ww  w .  j a va  2  s .  c  o m
    try {
        ctx = getAuthContext(lus.getUsername(), lus.getPassword());

        Attributes attrsBag = new BasicAttributes();

        Attribute oc = new BasicAttribute("objectClass");
        oc.add("organization");
        oc.add("top");
        attrsBag.put(oc);

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

        Attribute description = new BasicAttribute("description", org.getDescription());
        attrsBag.put(description);

        if (org.getReference() != null && !org.getReference().isEmpty()) {
            Attribute registeredAddr = new BasicAttribute("registeredAddress", org.getReference());
            attrsBag.put(registeredAddr);
        }

        ResourceBundle rb = ResourceBundle.getBundle("ldap");
        ctx.createSubcontext(
                "o=" + org.getKey() + ",c=" + org.getCountryCode() + "," + rb.getString("organisationsRoot"),
                attrsBag);

        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: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;// w  w  w.j a  v a2s.  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:egovframework.com.ext.ldapumt.service.impl.OrgManageLdapDAO.java

/**
 * ? ldap? .//w  w  w.j  av a  2 s  . c om
 * @param vo  vo
 * @param attr
 */
protected void insertOrgManage(LdapObject vo, BasicAttribute attr) {
    final Attributes attrs = new BasicAttributes();
    attrs.put(attr);

    introspect(vo, new Executable() {
        @Override
        public void execute(String key, Object value) {
            attrs.put(key, value);
        }
    });

    ldapTemplate.bind(vo.getDn(), null, attrs);
}

From source file:org.easy.ldap.AuthServiceImpl.java

@Override
public List<String> getAssignedRoles(LdapUser user) {
    List<String> out = null;

    String uniqueMemberDn = namingFactory.createUserDn(user.getTenantId(), user.getUserId()).toString();
    LdapName rolesDn = namingFactory.createRolesDn(user.getTenantId());
    Attributes attributes = new BasicAttributes();
    attributes.put(new BasicAttribute(RdnType.UNIQUE_MEMBER.toString(), uniqueMemberDn));

    out = ldapDao.findRdnValues(rolesDn, attributes, RdnType.CN);

    return out;/*from   w ww. j  av  a 2  s. c  o  m*/
}

From source file:py.una.pol.karaku.util.LDAPUtil.java

/**
 * Recupera los usuarios de LDAP//from  w w  w . j  a v a2 s.  co  m
 * 
 * @return Una lista con los usuarios de LDAP
 */
public List<User> getUsers() {

    List<User> users = new ArrayList<User>();

    try {
        DirContext ctx = createInitialDirContext();

        Attributes matchAttrs = new BasicAttributes(true);
        matchAttrs.put(new BasicAttribute("uid"));

        NamingEnumeration<SearchResult> answer = ctx.search("ou=users", matchAttrs);

        while (answer.hasMore()) {
            SearchResult sr = answer.next();
            String uid = sr.getName().substring(4);
            // No se retornan los usuarios especiales
            if (!uid.startsWith(LDAP_SPECIAL_USER_PREFIX) && !ListHelper.contains(EXCLUDED_USERS, uid)) {
                User user = new User();
                user.setUid(uid);
                Attributes atributos = sr.getAttributes();
                String cn = atributos.get("cn").toString().substring(4);
                user.setCn(cn);
                users.add(user);
            }
        }

    } catch (NamingException e) {
        throw new KarakuRuntimeException(e.getMessage(), e);
    }

    return users;

}

From source file:org.apache.archiva.redback.rest.services.LdapGroupMappingServiceTest.java

@Override
public void startServer() throws Exception {
    super.startServer();

    groupSuffix = apacheDs.addSimplePartition("test", new String[] { "archiva", "apache", "org" }).getSuffix();

    log.info("groupSuffix: {}", groupSuffix);

    suffix = "ou=People,dc=archiva,dc=apache,dc=org";

    log.info("DN Suffix: {}", suffix);

    apacheDs.startServer();//from  ww  w . j a  v  a 2  s. c om

    BasicAttribute objectClass = new BasicAttribute("objectClass");
    objectClass.add("top");
    objectClass.add("organizationalUnit");

    Attributes attributes = new BasicAttributes(true);
    attributes.put(objectClass);
    attributes.put("organizationalUnitName", "foo");

    apacheDs.getAdminContext().createSubcontext(suffix, attributes);

    createGroups();
}