Example usage for javax.naming.directory BasicAttribute add

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

Introduction

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

Prototype

public boolean add(Object attrVal) 

Source Link

Document

Adds a new value to this attribute.

Usage

From source file:edu.kit.scc.ldap.LdapPosixUserDao.java

/**
 * Inserts a new POSIX user into the LDAP directory.
 * //from  ww w.ja va 2  s. c o m
 * @param posixUser the {@link PosixUser} to insert
 * @return the {@link PosixUser} inserted
 */
public PosixUser insertUser(PosixUser posixUser) {
    if (posixUser.commonName == null || posixUser.gidNumber == null || posixUser.homeDirectory == null
            || posixUser.surName == null || posixUser.uid == null || posixUser.uidNumber == null) {
        log.warn("PosixUser has missing mandatory attributes");
        return null;
    }

    BasicAttribute personBasicAttribute = new BasicAttribute("objectclass");
    personBasicAttribute.add("extensibleObject");
    personBasicAttribute.add("inetOrgPerson");
    personBasicAttribute.add("organizationalPerson");
    personBasicAttribute.add("person");
    personBasicAttribute.add("posixAccount");

    Attributes personAttributes = new BasicAttributes();
    personAttributes.put(personBasicAttribute);
    personAttributes.put("cn", posixUser.getCommonName());
    personAttributes.put("sn", posixUser.getSurName());
    personAttributes.put("uid", posixUser.getUid());
    personAttributes.put("uidNumber", String.valueOf(posixUser.getUidNumber()));
    personAttributes.put("gidNumber", String.valueOf(posixUser.getGidNumber()));
    personAttributes.put("homeDirectory", posixUser.getHomeDirectory());

    if (posixUser.getUniqueIdentifier() != null) {
        personAttributes.put("uniqueIdentifier", posixUser.getUniqueIdentifier());
    }
    if (posixUser.getDescription() != null) {
        personAttributes.put("description", posixUser.getDescription());
    }
    if (posixUser.getGecos() != null) {
        personAttributes.put("gecos", posixUser.getGecos());
    }
    if (posixUser.getLoginShell() != null) {
        personAttributes.put("loginShell", posixUser.getLoginShell());
    }
    if (posixUser.getUserPassword() != null) {
        personAttributes.put("userPassword", posixUser.getUserPassword());
    }
    if (posixUser.getGivenName() != null) {
        personAttributes.put("givenName", posixUser.getGivenName());
    }
    if (posixUser.getMail() != null) {
        personAttributes.put("mail", posixUser.getMail());
    }

    LdapName newUserDn = LdapUtils.emptyLdapName();
    try {
        newUserDn = new LdapName(userBase);
        newUserDn.add("uid=" + posixUser.getUid());
        log.debug("Insert {}", newUserDn.toString());
        ldapTemplate.bind(newUserDn, null, personAttributes);

        return posixUser;
    } catch (InvalidNameException ex) {
        log.error("ERROR {}", ex.toString());
        // ex.printStackTrace();
    } catch (NameAlreadyBoundException ex) {
        log.error("ERROR {}", ex.toString());
    }
    return null;
}

From source file:org.apache.archiva.redback.users.ldap.LdapUserManagerTest.java

private void assertExist(DirContext context, String dn, String attribute, String value) throws NamingException {
    SearchControls ctls = new SearchControls();

    ctls.setDerefLinkFlag(true);/*ww  w  . j ava  2s . c  om*/
    ctls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
    ctls.setReturningAttributes(new String[] { "*" });

    BasicAttributes matchingAttributes = new BasicAttributes();
    matchingAttributes.put(attribute, value);
    BasicAttribute objectClass = new BasicAttribute("objectClass");
    objectClass.add("inetOrgPerson");
    matchingAttributes.put(objectClass);

    NamingEnumeration<SearchResult> results = context.search(suffix, matchingAttributes);
    // NamingEnumeration<SearchResult> results = context.search( suffix, "(" + attribute + "=" + value + ")", ctls
    // );

    assertTrue(results.hasMoreElements());
    SearchResult result = results.nextElement();
    Attributes attrs = result.getAttributes();
    Attribute testAttr = attrs.get(attribute);
    assertEquals(value, testAttr.get());

}

From source file:edu.kit.scc.ldap.LdapPosixUserDao.java

/**
 * Updates a POSIX user in the LDAP directory.
 * /* ww  w. j  a v  a 2  s  .co m*/
 * @param posixUser the {@link PosixUser} to update
 * @return the {@link PosixUser} updated
 */
public PosixUser updateUser(PosixUser posixUser) {
    BasicAttribute personBasicAttribute = new BasicAttribute("objectclass");
    personBasicAttribute.add("extensibleObject");
    personBasicAttribute.add("inetOrgPerson");
    personBasicAttribute.add("organizationalPerson");
    personBasicAttribute.add("person");
    personBasicAttribute.add("posixAccount");

    Attributes personAttributes = new BasicAttributes();
    personAttributes.put(personBasicAttribute);

    if (posixUser.getCommonName() != null) {
        personAttributes.put("cn", posixUser.getCommonName());
    }
    if (posixUser.getSurName() != null) {
        personAttributes.put("sn", posixUser.getSurName());
    }
    if (posixUser.getUid() != null) {
        personAttributes.put("uid", posixUser.getUid());
    }
    if (posixUser.getUidNumber() != null) {
        personAttributes.put("uidNumber", String.valueOf(posixUser.getUidNumber()));
    }
    if (posixUser.getGidNumber() != null) {
        personAttributes.put("gidNumber", String.valueOf(posixUser.getGidNumber()));
    }
    if (posixUser.getHomeDirectory() != null) {
        personAttributes.put("homeDirectory", posixUser.getHomeDirectory());
    }
    if (posixUser.getUniqueIdentifier() != null) {
        personAttributes.put("uniqueIdentifier", posixUser.getUniqueIdentifier());
    }
    if (posixUser.getDescription() != null) {
        personAttributes.put("description", posixUser.getDescription());
    }
    if (posixUser.getGecos() != null) {
        personAttributes.put("gecos", posixUser.getGecos());
    }
    if (posixUser.getLoginShell() != null) {
        personAttributes.put("loginShell", posixUser.getLoginShell());
    }
    if (posixUser.getUserPassword() != null) {
        personAttributes.put("userPassword", posixUser.getUserPassword());
    }
    if (posixUser.getGivenName() != null) {
        personAttributes.put("givenName", posixUser.getGivenName());
    }
    if (posixUser.getMail() != null) {
        personAttributes.put("mail", posixUser.getMail());
    }

    LdapName userDn = LdapUtils.emptyLdapName();
    try {
        userDn = new LdapName(userBase);
        userDn.add("uid=" + posixUser.getUid());
        log.debug("Update {}", userDn.toString());
        ldapTemplate.rebind(userDn, null, personAttributes);

        return posixUser;
    } catch (InvalidNameException ex) {
        log.error("ERROR {}", ex.toString());
        // ex.printStackTrace();
    }
    return null;
}

From source file:org.springframework.ldap.demo.dao.PersonDaoImpl.java

private Attributes getAttributesToBind(Person person) {
    Attributes attrs = new BasicAttributes();
    BasicAttribute ocattr = new BasicAttribute("objectclass");
    ocattr.add("top");
    ocattr.add("person");
    attrs.put(ocattr);//from w  ww  .  j a v a  2 s.co  m
    attrs.put("cn", person.getFullName());
    attrs.put("sn", person.getLastName());
    attrs.put("description", person.getDescription());
    attrs.put("telephoneNumber", person.getPhone());
    return attrs;
}

From source file:org.apache.archiva.redback.common.ldap.role.TestLdapRoleMapper.java

private void bindUserObject(DirContext context, String cn, String dn) throws Exception {
    Attributes attributes = new BasicAttributes(true);
    BasicAttribute objectClass = new BasicAttribute("objectClass");
    objectClass.add("top");
    objectClass.add("inetOrgPerson");
    objectClass.add("person");
    objectClass.add("organizationalperson");
    attributes.put(objectClass);//ww  w.  j ava  2  s . c o  m
    attributes.put("cn", cn);
    attributes.put("sn", "foo");
    attributes.put("mail", cn + "@apache.org");
    attributes.put("userPassword", passwordEncoder.encodePassword("foo"));
    attributes.put("givenName", "foo");
    context.createSubcontext(dn, attributes);
}

From source file:org.apache.archiva.redback.common.ldap.role.TestLdapRoleMapper.java

private void createGroup(DirContext context, String groupName, String dn, List<String> users) throws Exception {

    Attributes attributes = new BasicAttributes(true);
    BasicAttribute objectClass = new BasicAttribute("objectClass");
    objectClass.add("top");
    objectClass.add("groupOfUniqueNames");
    attributes.put(objectClass);//from  w w w .j a  va  2  s .  c o m
    attributes.put("cn", groupName);
    BasicAttribute basicAttribute = new BasicAttribute("uniquemember");
    for (String user : users) {
        basicAttribute.add("uid=" + user + "," + suffix);// dc=archiva,dc=apache,dc=org" );
    }

    attributes.put(basicAttribute);
    context.createSubcontext(dn, attributes);
}

From source file:org.apache.archiva.redback.common.ldap.role.TestLdapRoleMapper.java

private void assertExist(DirContext context, String dn, String attribute, String value) throws NamingException {
    SearchControls ctls = new SearchControls();

    ctls.setDerefLinkFlag(true);// w  ww . jav  a2s  . com
    ctls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
    ctls.setReturningAttributes(new String[] { "*" });

    BasicAttributes matchingAttributes = new BasicAttributes();
    matchingAttributes.put(attribute, value);
    BasicAttribute objectClass = new BasicAttribute("objectClass");
    objectClass.add("inetOrgPerson");
    matchingAttributes.put(objectClass);

    NamingEnumeration<SearchResult> results = context.search(suffix, matchingAttributes);

    assertTrue(results.hasMoreElements());
    SearchResult result = results.nextElement();
    Attributes attrs = result.getAttributes();
    Attribute testAttr = attrs.get(attribute);
    assertEquals(value, testAttr.get());

}

From source file:org.apache.archiva.redback.common.ldap.role.TestLdapRoleMapper.java

@Before
public void setUp() throws Exception {
    super.setUp();

    usersPerGroup = new HashMap<String, List<String>>(3);

    usersPerGroup.put("internal-repo-manager", Arrays.asList("admin", "user.9"));
    usersPerGroup.put("internal-repo-observer", Arrays.asList("admin", "user.7", "user.8"));
    usersPerGroup.put("archiva-admin", Arrays.asList("admin", "user.7"));

    users = new ArrayList<String>(4);
    users.add("admin");
    users.add("user.7");
    users.add("user.8");
    users.add("user.9");

    passwordEncoder = new SHA1PasswordEncoder();

    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();/*  ww w .  j  av  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);

    makeUsers();

    createGroups();

}

From source file:org.apache.archiva.redback.users.ldap.ctl.DefaultLdapController.java

private void bindUserObject(DirContext context, User user) throws NamingException {
    Attributes attributes = new BasicAttributes(true);
    BasicAttribute objectClass = new BasicAttribute("objectClass");
    objectClass.add("top");
    objectClass.add("inetOrgPerson");
    objectClass.add("person");
    objectClass.add("organizationalperson");
    attributes.put(objectClass);//from  w  w w.  j a v a 2 s. co  m
    attributes.put("cn", user.getUsername());
    attributes.put("sn", "foo");
    if (StringUtils.isNotEmpty(user.getEmail())) {
        attributes.put("mail", user.getEmail());
    }

    if (userConf.getBoolean(UserConfigurationKeys.LDAP_BIND_AUTHENTICATOR_ALLOW_EMPTY_PASSWORDS, false)
            && StringUtils.isNotEmpty(user.getPassword())) {
        attributes.put("userPassword", passwordEncoder.encodePassword(user.getPassword()));
    }
    attributes.put("givenName", "foo");
    context.createSubcontext("cn=" + user.getUsername() + "," + this.getBaseDn(), attributes);
}

From source file:de.fiz.ddb.aas.auxiliaryoperations.ThreadOrganisationCreate.java

private void createOrg() throws ExecutionException, IllegalArgumentException, AASUnauthorizedException {
    InitialLdapContext vCtx = null;

    Attributes vOrgAttributes = new BasicAttributes(true);

    BasicAttribute objectClass = new BasicAttribute("objectclass", "top");
    objectClass.add(Constants.ldap_ddbOrg_ObjectClass);
    objectClass.add("organization");

    vOrgAttributes.put(objectClass);//from   ww  w  .jav  a  2  s  .  c  o m

    // ---All this occurs only if that is not a copy in the export directory
    if (!this.isAddToLicensedOrgs()) {

        // -- When creating the status always set on Pending:
        if (!this.isIngestingOperation()) {
            this._orgObj.setStatus(ConstEnumOrgStatus.pending);
            long vTimeStamp = new Date().getTime();
            this._orgObj.setModified(vTimeStamp);
            this._orgObj.setCreated(vTimeStamp);
        }

        if (this._performer != null) {
            this._orgObj.setModifiedBy(this._performer.getUid());
            this._orgObj.setCreatedBy(this._performer.getUid());
        }

        // -- Is null, if it was isIngestingOperation or isAddToLicensedOrgs 
        //    and therefore does not need to be additionally checked
        if (_submit != null) {
            GeoAdresse vGeoAdresse;
            try {
                vGeoAdresse = _submit.get(50, TimeUnit.SECONDS);
                if (vGeoAdresse.getRequestStatus() == GeoRequestStatus.OK) {
                    this._orgObj.getAddress().setLatitude(vGeoAdresse.getLatitude());
                    this._orgObj.getAddress().setLongitude(vGeoAdresse.getLongitude());
                    this._orgObj.getAddress().setLocationDisplayName(vGeoAdresse.getLocationDisplayName());
                } else {
                    LOG.log(Level.WARNING, "GeoRequestStatus: {0}, (organization id: {1})",
                            new Object[] { vGeoAdresse.getRequestStatus(), this._orgObj.getOIDs() });
                }
            } catch (InterruptedException ex) {
                LOG.log(Level.WARNING,
                        "Geocoding request exeption for organization id: " + this._orgObj.getOIDs(), ex);
            } catch (TimeoutException ex) {
                LOG.log(Level.WARNING,
                        "Geocoding request exeption for organization id: " + this._orgObj.getOIDs(), ex);
            }
        }
    }

    // -- Conversion of parameters to LDAP attributes:
    this.convertOrganizationToLdapOrgAttrsForCreate(this._orgObj, vOrgAttributes, getPerformer());

    StringBuilder vEntryDN = (this.isAddToLicensedOrgs() ? this.getLicensedOrgsDN(this._orgObj.getOIDs())
            : this.getOrgDN(this._orgObj.getOIDs()));

    try {
        // put arbitrary (Org) Properties as JSON-String into LDAP.
        if (this._orgObj.getProperties() != null && !this._orgObj.getProperties().isEmpty()) {
            vOrgAttributes.put(new BasicAttribute(Constants.ldap_ddbOrg_Properties,
                    serializer.serialize(this._orgObj.getProperties())));
        }

        // finally bind the entry
        vCtx = LDAPConnector.getSingletonInstance().takeCtx();
        ((InitialDirContext) vCtx).bind(vEntryDN.toString(), vCtx, vOrgAttributes);

        // -- Add default privilege(s) so we can assign performer
        //    but only if that is not a copy in the export directory
        if (!this.isAddToLicensedOrgs()) {
            this._orgObj.getPrivilegesSet().add(PrivilegeEnum.ADMIN_ORG);

            // create org-privileges
            for (PrivilegeEnum p : this._orgObj.getPrivilegesSet()) {
                ThreadSinglePrivilegeCreate threadSinglePrivilegeCreate = new ThreadSinglePrivilegeCreate(p,
                        this._orgObj, this._performer);
                threadSinglePrivilegeCreate.call();
            }
            // -- Logging:
            LOG.log(Level.INFO, "One organization with DN: ''{0}'' was created.", new Object[] { vEntryDN });
        } else {
            // -- Logging:
            LOG.log(Level.INFO, "One organization with DN: ''{0}'' was copied to the export directory.",
                    new Object[] { vEntryDN });
        }
    } catch (AssertionError ex) {
        LOG.log(Level.SEVERE, null, ex);
        throw new IllegalArgumentException(ex.getMessage(), ex.getCause());
    } catch (IllegalAccessException ex) {
        LOG.log(Level.SEVERE, null, ex);
        throw new ExecutionException(ex.getMessage(), ex.getCause());
    } catch (NamingException ex) {
        // LDAP: error code 68 - ENTRY_ALREADY_EXISTS: failed for Add
        // Request
        try {
            if (vCtx != null) {
                vCtx.close();
                vCtx = null;
            }
        } catch (NamingException ex1) {
            LOG.log(Level.SEVERE, null, ex1);
        }
        try {
            vCtx = LDAPConnector.getSingletonInstance().getDirContext();
        } catch (NamingException ex1) {
            LOG.log(Level.SEVERE, null, ex1);
        } catch (IllegalAccessException ex1) {
            LOG.log(Level.SEVERE, null, ex1);
        }
        throw new IllegalArgumentException(ex.getMessage());
    } finally {
        if (vCtx != null) {
            try {
                LDAPConnector.getSingletonInstance().putCtx(vCtx);
            } catch (Exception ex) {
                LOG.log(Level.SEVERE, "Exception", ex);
            }
        }
    }

}