Example usage for javax.naming.directory BasicAttribute BasicAttribute

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

Introduction

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

Prototype

public BasicAttribute(String id, boolean ordered) 

Source Link

Document

Constructs a new instance of a possibly ordered attribute with no value.

Usage

From source file:hsa.awp.common.naming.DirectoryTest.java

/**
 * Properties that must be set./*  w ww.  j  av a 2s.  com*/
 *
 * @throws Exception If something went wrong with Attributes
 */

@Test
public void testGetUserProperties() throws Exception {

    for (Attributes curAttrs : adapter.getUsers().values()) {
        Properties curProps = directory.getUserProperties((String) curAttrs.get("uid").get());
        // here we have to fix the semester field - ldap has a field like
        // 0079$8 but directory maps to 8
        // TODO refactor ldap abstraction to externalize field processing
        String curSemesterString = (String) curAttrs.get("term").get();
        curAttrs.put(new BasicAttribute("term", curSemesterString.split("\\$")[1]));
        assertTrue(isEqual(curAttrs, curProps));
    }
}

From source file:py.una.pol.karaku.security.KarakuUserService.java

private List<KarakuPermission> loadAuthoritiesByDn(String uid) {

    List<KarakuPermission> listaRoles = new ArrayList<KarakuPermission>();

    try {//  w  w w  .  ja v a  2  s . co  m
        DirContext ctx = getInitialDirContext(propertiesUtil.get(LDAP_ADMIN_KEY),
                propertiesUtil.get(LDAP_ADMIN_PASS_KEY));
        Attributes matchAttrs = new BasicAttributes(true);
        matchAttrs.put(new BasicAttribute("member", getRealUsername(uid)));
        NamingEnumeration<SearchResult> answer = ctx.search("ou=permissions", matchAttrs);

        while (answer.hasMore()) {
            SearchResult searchResult = answer.next();
            Attributes attributes = searchResult.getAttributes();
            Attribute attr = attributes.get("cn");
            String rol = (String) attr.get();
            KarakuPermission grantedAuthority = new KarakuPermission(rol);
            listaRoles.add(grantedAuthority);
        }

        return listaRoles;
    } catch (NamingException e) {
        LOG.warn("Can't create Ldap Context", e);
        return Collections.emptyList();
    }
}

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

public void updateRdn(LdapName rootDn, RdnType type, String rdnValue) {
    DirContext ctx = null;//from   w w w .  j  a  v a  2 s .c o  m

    try {
        ctx = contextFactory.createContext(rootDn.toString());

        ModificationItem[] modifications = new ModificationItem[1];

        Attribute attribute = new BasicAttribute(type.toString(), rdnValue);

        modifications[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, attribute);

        ctx.modifyAttributes("", modifications);

    }

    catch (NamingException e) {
        throw new RuntimeException(type.toString() + "=" + rdnValue + "," + rootDn.toString(), e);
    }

    finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (NamingException e) {
                log.debug(e);
            }
        }
    }
}

From source file:org.jamwiki.ldap.LdapUserHandler.java

/**
 *
 *//*from  w w w . ja  v a2s .  c  o  m*/
public WikiUserInfo lookupWikiUserInfo(String username) throws Exception {
    InitialDirContext ctx = null;
    try {
        ctx = getContext(Environment.getValue(Environment.PROP_LDAP_LOGIN),
                Encryption.getEncryptedProperty(Environment.PROP_LDAP_PASSWORD, null));
        BasicAttributes matchAttrs = new BasicAttributes(true);
        matchAttrs.put(new BasicAttribute(Environment.getValue(Environment.PROP_LDAP_FIELD_USERID), username));
        NamingEnumeration answer = ctx.search(Environment.getValue(Environment.PROP_LDAP_CONTEXT), matchAttrs,
                SEARCH_ATTRIBUTES);
        return (!answer.hasMore()) ? null : this.initWikiUserInfo(answer);
    } finally {
        try {
            ctx.close();
        } catch (Exception e) {
        }
    }
}

From source file:org.apache.karaf.jaas.modules.ldap.LdapCacheTest.java

@Test
public void testAdminLogin() throws Exception {
    Properties options = ldapLoginModuleOptions();
    LDAPLoginModule module = new LDAPLoginModule();
    CallbackHandler cb = new CallbackHandler() {
        public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
            for (Callback cb : callbacks) {
                if (cb instanceof NameCallback) {
                    ((NameCallback) cb).setName("admin");
                } else if (cb instanceof PasswordCallback) {
                    ((PasswordCallback) cb).setPassword("admin123".toCharArray());
                }/*from   w  w w.  j  a va 2s  . c  om*/
            }
        }
    };
    Subject subject = new Subject();
    module.initialize(subject, cb, null, options);

    assertEquals("Precondition", 0, subject.getPrincipals().size());
    assertTrue(module.login());
    assertTrue(module.commit());

    assertEquals(2, subject.getPrincipals().size());

    boolean foundUser = false;
    boolean foundRole = false;
    for (Principal pr : subject.getPrincipals()) {
        if (pr instanceof UserPrincipal) {
            assertEquals("admin", pr.getName());
            foundUser = true;
        } else if (pr instanceof RolePrincipal) {
            assertEquals("admin", pr.getName());
            foundRole = true;
        }
    }
    assertTrue(foundUser);
    assertTrue(foundRole);

    assertTrue(module.logout());
    assertEquals("Principals should be gone as the user has logged out", 0, subject.getPrincipals().size());

    DirContext context = new LDAPCache(new LDAPOptions(options)).open();

    // Make "admin" user a member of a new "another" group

    //        dn: cn=admin,ou=groups,dc=example,dc=com
    //        objectClass: top
    //        objectClass: groupOfNames
    //        cn: admin
    //        member: cn=admin,ou=people,dc=example,dc=com
    Attributes entry = new BasicAttributes();
    entry.put(new BasicAttribute("cn", "another"));
    Attribute oc = new BasicAttribute("objectClass");
    oc.add("top");
    oc.add("groupOfNames");
    entry.put(oc);
    Attribute mb = new BasicAttribute("member");
    mb.add("cn=admin,ou=people,dc=example,dc=com");
    entry.put(mb);
    context.createSubcontext("cn=another,ou=groups,dc=example,dc=com", entry);

    Thread.sleep(100);

    module = new LDAPLoginModule();
    subject = new Subject();
    module.initialize(subject, cb, null, options);
    assertEquals("Precondition", 0, subject.getPrincipals().size());
    assertTrue(module.login());
    assertTrue(module.commit());
    assertEquals("Postcondition", 3, subject.getPrincipals().size());
}

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

@Override
public void updateUser(LdapUser user, Map<RdnType, String> newData) {
    Preconditions.checkNotNull(newData);
    Preconditions.checkNotNull(user.getTenantId());
    Preconditions.checkNotNull(user.getUserId());
    Preconditions.checkArgument(user.getTenantId().trim().length() > 0);
    Preconditions.checkArgument(user.getUserId().trim().length() > 0);
    Preconditions.checkArgument(newData.size() > 0);

    try {/*w w w  . j  a va 2s.c om*/
        ModificationItem[] modifications = new ModificationItem[newData.size()];

        int i = 0;

        for (RdnType attributeName : newData.keySet()) {
            /* if (attributeName.equals(RdnType.UID))
            throw new RuntimeException("Cannot change uid.");*/

            modifications[i] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
                    new BasicAttribute(attributeName.toString(), newData.get(attributeName)));

            i++;
        }

        LdapName rootDn = namingFactory.createUsersDn(user.getTenantId());
        Rdn userRdn = NamingFactory.createRdn(RdnType.UID, user.getUserId());
        LdapName subContextName = NamingFactory.createName(userRdn);

        ldapDao.updateSubContext(rootDn, subContextName, modifications);
    } catch (Exception e) {
        log.error(e);
        throw new java.lang.RuntimeException(e);
    }
}

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

/**
 * @param rootDn//from  ww  w  . j a  va 2 s . c om
 * @param type
 * @param rdnValue
 */
public void addRdn(LdapName rootDn, RdnType type, String rdnValue) {
    DirContext ctx = null;

    try {
        ctx = contextFactory.createContext(rootDn.toString());

        ModificationItem[] modifications = new ModificationItem[1];

        Attribute attribute = new BasicAttribute(type.toString(), rdnValue);

        modifications[0] = new ModificationItem(DirContext.ADD_ATTRIBUTE, attribute);

        ctx.modifyAttributes("", modifications);

    }

    catch (NamingException e) {
        throw new RuntimeException(e);
    }

    finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (NamingException e) {
                log.debug(e);
            }
        }
    }

}

From source file:org.gbif.portal.registration.LDAPUtils.java

/**
 * Creates a user. String array contains:
 * 1) first name//from  w  w w . j  a v  a  2  s. co m
 * 2) surname
 * 3) email
 * 4) username
 * 5) password
 * 
 * @param userDetails
 * @return
 * @throws NamingException
 */
public boolean createNewUser(UserLogin userLogin) throws NamingException {
    DirContext ctx = getUserContext();
    Attributes attributes = new BasicAttributes();
    attributes.put(new BasicAttribute("sn", userLogin.getSurname()));
    attributes.put(new BasicAttribute("givenName", userLogin.getFirstName()));
    attributes.put(new BasicAttribute("cn", userLogin.getFirstName() + " " + userLogin.getSurname()));
    attributes.put(new BasicAttribute("mail", userLogin.getEmail()));
    if (userLogin.getTelephone() != null) {
        attributes.put(new BasicAttribute("telephoneNumber", userLogin.getTelephone()));
    }
    attributes.put(new BasicAttribute("userPassword", userLogin.getPassword()));
    attributes.put(new BasicAttribute("objectClass", "top"));
    attributes.put(new BasicAttribute("objectClass", "person"));
    attributes.put(new BasicAttribute("objectClass", "organizationalPerson"));
    attributes.put(new BasicAttribute("objectClass", "inetorgperson"));
    String contextName = "uid=" + userLogin.getUsername();
    String fullContextName = contextName + "," + ctx.getNameInNamespace();

    //add the user to ldap
    ctx.createSubcontext(contextName, attributes);

    //need to add user to group
    for (int i = 0; i < userGroups.length; i++) {
        DirContext groupContext = getGroupContext();
        Attributes groupAttributes = groupContext.getAttributes(userGroups[i]);
        groupAttributes.get("uniqueMember").add(fullContextName);
        groupContext.modifyAttributes(userGroups[i], DirContext.REPLACE_ATTRIBUTE, groupAttributes);
    }
    return true;
}

From source file:org.bedework.selfreg.common.DirMaintImpl.java

@Override
public void setUserPassword(final String account, final String password) throws SelfregException {
    BasicAttribute attr = new BasicAttribute("userPassword", encodedPassword(password.toCharArray()));
    ModificationItem mi = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, attr);

    ModificationItem[] mods = { mi };
    getLdir().modify(accountDn(account), mods);
}

From source file:org.apache.ftpserver.usermanager.LdapUserManager.java

/**
 * Save user.//from   w  ww .  j av  a  2s.  c  om
 */
public synchronized void save(User user) throws FtpException {
    try {
        String name = user.getName();
        String dn = getDN(name);
        BaseUser newUser = new BaseUser(user);

        // if password is not available, 
        // do not change the existing password
        User existUser = getUserByName(name);
        if ((existUser != null) && (newUser.getPassword() == null)) {
            newUser.setPassword(existUser.getPassword());
        }

        // set attributes
        Attributes attrs = new BasicAttributes(true);
        attrs.put(new BasicAttribute(CN, name));
        attrs.put(new BasicAttribute(CLASS_NAME, BaseUser.class.getName()));

        // bind object
        m_log.info("Rebinding user " + dn);
        m_adminContext.rebind(dn, newUser, attrs);
    } catch (NamingException ex) {
        m_log.error("LdapUserManager.save()", ex);
        throw new FtpException("LdapUserManager.save()", ex);
    }
}