Example usage for javax.naming.directory Attributes get

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

Introduction

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

Prototype

Attribute get(String attrID);

Source Link

Document

Retrieves the attribute with the given attribute id from the attribute set.

Usage

From source file:org.sipfoundry.sipxconfig.bulk.ldap.LdapRowInserter.java

@Override
protected RowResult checkRowData(SearchResult sr) {
    Attributes attrs = sr.getAttributes();
    String idAttrName = m_attrMap.getIdentityAttributeName();
    if (attrs.get(idAttrName) == null) {
        return new RowResult(RowStatus.FAILURE);
    }//from  w ww .j  a v  a  2s . c o  m
    RowStatus status = RowStatus.SUCCESS;
    try {
        String userName = m_userMapper.getUserName(attrs);
        // check username
        if (!UserValidationUtils.isValidUserName(userName)
                || (m_importedUserNames != null && m_importedUserNames.contains(userName))) {
            return new RowResult(RowStatus.FAILURE);
        }
        Set<String> aliases = m_userMapper.getAliasesSet(attrs);
        if (aliases != null) {
            Set<String> aliasesToRemove = new TreeSet<String>();
            for (String alias : aliases) {
                if (StringUtils.equals(userName, alias)
                        || m_coreContext.isAliasInUseForOthers(alias, userName)) {
                    aliasesToRemove.add(alias);
                    status = RowStatus.WARNING_ALIAS_COLLISION;
                }
            }
            if (!aliasesToRemove.isEmpty()) {
                aliases.removeAll(aliasesToRemove);
            }
        }
        m_aliases = aliases;
    } catch (Exception e) {
        return new RowResult(RowStatus.FAILURE);
    }
    return new RowResult(status);
}

From source file:org.webterm.core.plugin.authentication.LdapAuthentication.java

/**
 * Attribute reader/*from   w  w  w.ja v  a  2s . com*/
 * 
 * @param username User name
 * @return Attribute password associated with the login.
 */
public Attribute fetch(final String username) {
    Attribute pwd = null; // NOPMD - init
    if (StringUtils.isNotBlank(username)) {
        try {
            final DirContext obj = (DirContext) this.ldapContext
                    .lookup(this.attrUser + "=" + username + "," + this.baseDn); //$NON-NLS-1$ //$NON-NLS-2$
            final Attributes attributes = obj.getAttributes(ConstString.EMPTY);
            pwd = attributes.get(this.attrPwd);
        } catch (Exception ex) {
            LOG.error(ex, ex);
        }
    }
    return pwd;
}

From source file:org.apache.zeppelin.rest.GetUserList.java

/**
 * function to extract users from Zeppelin LdapRealm
 *//*from w w w . j av  a 2  s.c  o m*/
public List<String> getUserList(LdapRealm r, String searchText) {
    List<String> userList = new ArrayList<>();
    if (LOG.isDebugEnabled()) {
        LOG.debug("SearchText: " + searchText);
    }
    String userAttribute = r.getUserSearchAttributeName();
    String userSearchRealm = r.getUserSearchBase();
    String userObjectClass = r.getUserObjectClass();
    JndiLdapContextFactory CF = (JndiLdapContextFactory) r.getContextFactory();
    try {
        LdapContext ctx = CF.getSystemLdapContext();
        SearchControls constraints = new SearchControls();
        constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String[] attrIDs = { userAttribute };
        constraints.setReturningAttributes(attrIDs);
        NamingEnumeration result = ctx.search(userSearchRealm,
                "(&(objectclass=" + userObjectClass + ")(" + userAttribute + "=" + searchText + "))",
                constraints);
        while (result.hasMore()) {
            Attributes attrs = ((SearchResult) result.next()).getAttributes();
            if (attrs.get(userAttribute) != null) {
                String currentUser;
                if (r.getUserLowerCase()) {
                    LOG.debug("userLowerCase true");
                    currentUser = ((String) attrs.get(userAttribute).get()).toLowerCase();
                } else {
                    LOG.debug("userLowerCase false");
                    currentUser = (String) attrs.get(userAttribute).get();
                }
                if (LOG.isDebugEnabled()) {
                    LOG.debug("CurrentUser: " + currentUser);
                }
                userList.add(currentUser.trim());
            }
        }
    } catch (Exception e) {
        LOG.error("Error retrieving User list from Ldap Realm", e);
    }
    return userList;
}

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);/*from   w w  w.  jav a 2  s .  co  m*/
    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:org.sonar.plugins.activedirectory.server.ApacheDS.java

@SuppressWarnings("unused")
private ApacheDS startKerberos() throws Exception {
    Preconditions.checkState(ldapServer.isStarted());

    kdcServer.setDirectoryService(directoryService);
    // FIXME hard-coded ports
    kdcServer.setTransports(new TcpTransport(6088), new UdpTransport(6088));
    kdcServer.setEnabled(true);//from w ww . ja va2 s .  co m
    kdcServer.setPrimaryRealm(realm);
    kdcServer.setSearchBaseDn(baseDn);
    kdcServer.setKdcPrincipal("krbtgt/" + realm + "@" + baseDn);
    kdcServer.start();

    // -------------------------------------------------------------------
    // Enable the krb5kdc schema
    // -------------------------------------------------------------------

    Hashtable<String, Object> env = new Hashtable<String, Object>();
    env.put(DirectoryService.JNDI_KEY, directoryService);
    env.put(Context.INITIAL_CONTEXT_FACTORY, CoreContextFactory.class.getName());
    env.put(Context.PROVIDER_URL, ServerDNConstants.OU_SCHEMA_DN);
    InitialLdapContext schemaRoot = new InitialLdapContext(env, null);

    // check if krb5kdc is disabled
    Attributes krb5kdcAttrs = schemaRoot.getAttributes("cn=Krb5kdc");
    boolean isKrb5KdcDisabled = false;
    if (krb5kdcAttrs.get("m-disabled") != null) {
        isKrb5KdcDisabled = ((String) krb5kdcAttrs.get("m-disabled").get()).equalsIgnoreCase("TRUE");
    }

    // if krb5kdc is disabled then enable it
    if (isKrb5KdcDisabled) {
        Attribute disabled = new BasicAttribute("m-disabled");
        ModificationItem[] mods = new ModificationItem[] {
                new ModificationItem(DirContext.REMOVE_ATTRIBUTE, disabled) };
        schemaRoot.modifyAttributes("cn=Krb5kdc", mods);
    }
    return this;
}

From source file:org.jasig.portlet.blackboardvcportlet.service.impl.LdapUserServiceImplTest.java

@Test
public void testFindUserWithMapper() {
    when(ldapOperations.search(eq(""), eq("(&(objectclass=person)(uid=ID))"), any(AttributesMapper.class)))
            .thenAnswer(new Answer<Object>() {
                @Override/*from   w w  w.  j a  va 2s .co  m*/
                public Object answer(InvocationOnMock invocation) throws Throwable {
                    final Object[] args = invocation.getArguments();
                    final AttributesMapper mapper = (AttributesMapper) args[2];

                    final Attributes attributes = mock(Attributes.class);

                    final Attribute uidAttr = mock(Attribute.class);
                    when(uidAttr.get()).thenReturn("jdoe");

                    when(attributes.get("uid")).thenReturn(uidAttr);

                    return ImmutableList.of(mapper.mapFromAttributes(attributes));
                }
            });

    final BasicUser user = ldapUserServiceImpl.findUser("ID");

    final BasicUserImpl expected = new BasicUserImpl("jdoe", null, null);

    assertEquals(expected, user);
    assertEquals(expected.getEmail(), user.getEmail());
    assertEquals(expected.getDisplayName(), user.getDisplayName());
    assertEquals(expected.getAdditionalEmails(), user.getAdditionalEmails());
}

From source file:org.javlo.external.agitos.dkim.DKIMUtil.java

public boolean checkDNSForPublickey(String signingDomain, String selector) throws DKIMSignerException {

    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
    String recordname = selector + "._domainkey." + signingDomain;
    String value = null;/*from ww w  .j  a v  a  2s  .  c om*/

    try {
        DirContext dnsContext = new InitialDirContext(env);

        javax.naming.directory.Attributes attribs = dnsContext.getAttributes(recordname,
                new String[] { "TXT" });
        javax.naming.directory.Attribute txtrecord = attribs.get("txt");

        if (txtrecord == null) {
            throw new DKIMSignerException("There is no TXT record available for " + recordname);
        }

        // "v=DKIM1; g=*; k=rsa; p=MIGfMA0G ..."
        value = (String) txtrecord.get();

    } catch (NamingException ne) {
        throw new DKIMSignerException("Selector lookup failed", ne);
    }

    if (value == null) {
        throw new DKIMSignerException("Value of RR " + recordname + " couldn't be retrieved");
    }

    // try to read public key from RR
    String[] tags = value.split(";");
    for (String tag : tags) {
        tag = tag.trim();
        if (tag.startsWith("p=")) {

            try {
                KeyFactory keyFactory = KeyFactory.getInstance("RSA");

                // decode public key, FSTODO: convert to DER format
                PKCS8EncodedKeySpec pubSpec = new PKCS8EncodedKeySpec(tag.substring(2).getBytes());
                RSAPrivateKey pubKey = (RSAPrivateKey) keyFactory.generatePublic(pubSpec);
            } catch (NoSuchAlgorithmException nsae) {
                throw new DKIMSignerException("RSA algorithm not found by JVM");
            } catch (InvalidKeySpecException ikse) {
                throw new DKIMSignerException(
                        "The public key " + tag + " in RR " + recordname + " couldn't be decoded.");
            }

            // FSTODO: create test signature with privKey and test validation with pubKey to check on a valid key pair

            return true;
        }
    }

    throw new DKIMSignerException("No public key available in " + recordname);
}

From source file:info.globalbus.dkim.DKIMUtil.java

public boolean checkDNSForPublickey(String signingDomain, String selector) throws DKIMSignerException {

    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
    String recordname = selector + "._domainkey." + signingDomain;
    String value = null;//  w  w  w. j  a v a  2 s .c om

    try {
        DirContext dnsContext = new InitialDirContext(env);

        javax.naming.directory.Attributes attribs = dnsContext.getAttributes(recordname,
                new String[] { "TXT" });
        javax.naming.directory.Attribute txtrecord = attribs.get("txt");

        if (txtrecord == null) {
            throw new DKIMSignerException("There is no TXT record available for " + recordname);
        }

        // "v=DKIM1; g=*; k=rsa; p=MIGfMA0G ..."
        value = (String) txtrecord.get();

    } catch (NamingException ne) {
        throw new DKIMSignerException("Selector lookup failed", ne);
    }

    if (value == null) {
        throw new DKIMSignerException("Value of RR " + recordname + " couldn't be retrieved");
    }

    // try to read public key from RR
    String[] tags = value.split(";");
    for (String tag : tags) {
        tag = tag.trim();
        if (tag.startsWith("p=")) {

            try {
                KeyFactory keyFactory = KeyFactory.getInstance("RSA");

                // decode public key, FSTODO: convert to DER format
                PKCS8EncodedKeySpec pubSpec = new PKCS8EncodedKeySpec(tag.substring(2).getBytes());
                keyFactory.generatePublic(pubSpec);
            } catch (NoSuchAlgorithmException nsae) {
                throw new DKIMSignerException("RSA algorithm not found by JVM");
            } catch (InvalidKeySpecException ikse) {
                throw new DKIMSignerException(
                        "The public key " + tag + " in RR " + recordname + " couldn't be decoded.");
            }

            // FSTODO: create test signature with privKey and test
            // validation with pubKey to check on a valid key pair

            return true;
        }
    }

    throw new DKIMSignerException("No public key available in " + recordname);
}

From source file:com.healthcit.cacure.businessdelegates.LdapUserManager.java

public Set<UserCredentials> loadUsersByRole(RoleCode roleCode) {
    Role role = roleDao.getByRoleCode(roleCode);

    String groupFilter = createGroupFilter(roleCode);

    Set<UserCredentials> userCredentials = new HashSet<UserCredentials>();

    try {/*from w w  w  . j  a  v a2 s .c  o  m*/
        Attributes attrs = contextSource.getReadOnlyContext().getAttributes(groupFilter);
        Attribute memAttr = attrs.get(Constants.LDAP_GROUP_UNIQUE_MEMBER);

        NamingEnumeration<?> elements = memAttr.getAll();
        while (elements.hasMoreElements()) {
            DistinguishedName dn = new DistinguishedName((String) elements.nextElement());
            String userName = dn.getValue(Constants.LDAP_UID);
            DirContextOperations dir = searchForUser(userName);
            String email = dir.getStringAttribute("mail");
            UserCredentials user = getUserFromDatabase(userName);
            user.setEmail(email);
            userCredentials.add(user);
        }

    } catch (NamingException e) {
        log.error(e.getMessage());
    }

    return userCredentials;
}

From source file:org.sipfoundry.sipxconfig.bulk.ldap.UserMapper.java

/**
 * Returns single value for an attribute, even if attribute has more values...
 *
 * @param attrs collection of attributes
 * @param attr attribute name/*  w w w  . ja  v a2  s .co  m*/
 */
private String getValue(Attributes attrs, String attrName) throws NamingException {
    Attribute attribute = attrs.get(attrName);
    if (attribute == null) {
        return null;
    }
    Object value = attribute.get();
    if (value == null) {
        return null;
    }
    // some values like userPassword are returned as byte[], see XX-9328
    if (value instanceof byte[]) {
        return new String((byte[]) value);
    }
    return value.toString();
}