Example usage for javax.naming.directory Attribute get

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

Introduction

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

Prototype

Object get() throws NamingException;

Source Link

Document

Retrieves one of this attribute's values.

Usage

From source file:org.olat.ldap.LDAPLoginManagerImpl.java

/**
 * Creates User in OLAT and ads user to LDAP securityGroup Required Attributes have to be checked before this method.
 * /*from w w w  .j  av a  2s  .  co  m*/
 * @param userAttributes Set of LDAP Attribute of User to be created
 */
@SuppressWarnings("unchecked")
public void createAndPersistUser(final Attributes userAttributes) {
    // Get and Check Config
    final String[] reqAttrs = LDAPLoginModule.checkReqAttr(userAttributes);
    if (reqAttrs != null) {
        logWarn("Can not create and persist user, the following attributes are missing::"
                + ArrayUtils.toString(reqAttrs), null);
        return;
    }

    final String uid = getAttributeValue(userAttributes
            .get(LDAPLoginModule.mapOlatPropertyToLdapAttribute(LDAPConstants.LDAP_USER_IDENTIFYER)));
    final String email = getAttributeValue(
            userAttributes.get(LDAPLoginModule.mapOlatPropertyToLdapAttribute(UserConstants.EMAIL)));
    // Lookup user
    if (securityManager.findIdentityByName(uid) != null) {
        logError("Can't create user with username='" + uid + "', does already exist in OLAT database", null);
        return;
    }
    if (!MailHelper.isValidEmailAddress(email)) {
        // needed to prevent possibly an AssertException in findIdentityByEmail breaking the sync!
        logError("Cannot try to lookup user " + uid + " by email with an invalid email::" + email, null);
        return;
    }
    if (userManager.findIdentityByEmail(email) != null) {
        logError("Can't create user with email='" + email + "', does already exist in OLAT database", null);
        return;
    }

    // Create User (first and lastname is added in next step)
    final User user = userManager.createUser(null, null, email);
    // Set User Property's (Iterates over Attributes and gets OLAT Property out
    // of olatexconfig.xml)
    final NamingEnumeration<Attribute> neAttr = (NamingEnumeration<Attribute>) userAttributes.getAll();
    try {
        while (neAttr.hasMore()) {
            final Attribute attr = neAttr.next();
            final String olatProperty = mapLdapAttributeToOlatProperty(attr.getID());
            if (attr.get() != uid) {
                final String ldapValue = getAttributeValue(attr);
                if (olatProperty == null || ldapValue == null) {
                    continue;
                }
                user.setProperty(olatProperty, ldapValue);
            }
        }
        // Add static user properties from the configuration
        final Map<String, String> staticProperties = LDAPLoginModule.getStaticUserProperties();
        if (staticProperties != null && staticProperties.size() > 0) {
            for (final Entry<String, String> staticProperty : staticProperties.entrySet()) {
                user.setProperty(staticProperty.getKey(), staticProperty.getValue());
            }
        }
    } catch (final NamingException e) {
        logError("NamingException when trying to create and persist LDAP user with username::" + uid, e);
        return;
    } catch (final Exception e) {
        // catch any exception here to properly log error
        logError("Unknown exception when trying to create and persist LDAP user with username::" + uid, e);
        return;
    }

    // Create Identity
    final Identity identity = securityManager.createAndPersistIdentityAndUser(uid, user,
            LDAPAuthenticationController.PROVIDER_LDAP, uid, null);
    // Add to SecurityGroup LDAP
    SecurityGroup secGroup = securityManager.findSecurityGroupByName(LDAPConstants.SECURITY_GROUP_LDAP);
    securityManager.addIdentityToSecurityGroup(identity, secGroup);
    // Add to SecurityGroup OLATUSERS
    secGroup = securityManager.findSecurityGroupByName(Constants.GROUP_OLATUSERS);
    securityManager.addIdentityToSecurityGroup(identity, secGroup);
    logInfo("Created LDAP user username::" + uid);

}

From source file:de.fiz.ddb.aas.utils.LDAPEngineUtilityOrganisation.java

public Set<OIDs> getAllSubOrgIds(boolean pLicensedOrgs, OIDs pOIDs, int pScopy, AasPrincipal pPerformer)
        throws ExecutionException {
    Set<OIDs> vSetOIDs = new HashSet<OIDs>();
    NamingEnumeration<SearchResult> searchResults = null;
    try {//w w w . j  a  v  a2s.  c  om
        searchResults = getAllSubOrgs(pLicensedOrgs, pOIDs, pScopy,
                new String[] { Constants.ldap_ddbOrg_Id, Constants.ldap_ddbOrg_PID, "+" }, pPerformer);
        SearchResult sr;
        Attribute attr;
        while (searchResults.hasMore()) {
            sr = searchResults.next();
            if ((attr = sr.getAttributes().get(Constants.ldap_ddb_EntryDN)) != null) {
                vSetOIDs.add(new OIDs(String.valueOf(attr.get()),
                        (attr = sr.getAttributes().get(Constants.ldap_ddbOrg_PID)) != null
                                ? String.valueOf(attr.get())
                                : null));
            } else {
                throw new ExecutionException("entryDN = null : OIDs = " + pOIDs, null);
            }
        }
    } catch (IllegalAccessException ex) {
        LOG.log(Level.SEVERE, "Connection-Error", ex);
        throw new ExecutionException(ex.getMessage(), ex.getCause());
    } catch (NamingException ne) {
        LOG.log(Level.SEVERE, "NamingException", ne);
        throw new ExecutionException(ne.getMessage(), ne.getCause());
    } finally {
        if (searchResults != null) {
            try {
                searchResults.close();
                searchResults = null;
            } catch (NamingException ex) {
            }
        }
    }
    return vSetOIDs;
}

From source file:org.apache.nifi.ldap.tenants.LdapUserGroupProvider.java

private String getGroupName(final DirContextOperations ctx) {
    final String name;

    if (useDnForGroupName) {
        name = ctx.getDn().toString();/*from ww w.j a v  a  2  s  . c om*/
    } else {
        final Attribute attributeName = ctx.getAttributes().get(groupNameAttribute);
        if (attributeName == null) {
            throw new AuthorizationAccessException(
                    "Group identity attribute [" + groupNameAttribute + "] does not exist.");
        }

        try {
            name = (String) attributeName.get();
        } catch (NamingException e) {
            throw new AuthorizationAccessException(
                    "Error while retrieving group name attribute [" + groupNameAttribute + "].");
        }
    }

    return name;
}

From source file:org.apache.nifi.ldap.tenants.LdapUserGroupProvider.java

private String getUserIdentity(final DirContextOperations ctx) {
    final String identity;

    if (useDnForUserIdentity) {
        identity = ctx.getDn().toString();
    } else {/*from w w  w .  j a  v  a 2s  .co m*/
        final Attribute attributeName = ctx.getAttributes().get(userIdentityAttribute);
        if (attributeName == null) {
            throw new AuthorizationAccessException(
                    "User identity attribute [" + userIdentityAttribute + "] does not exist.");
        }

        try {
            identity = (String) attributeName.get();
        } catch (NamingException e) {
            throw new AuthorizationAccessException(
                    "Error while retrieving user name attribute [" + userIdentityAttribute + "].");
        }
    }

    return IdentityMappingUtil.mapIdentity(identity, identityMappings);
}

From source file:com.alfaariss.oa.engine.attribute.gather.processor.jndi.JNDIGatherer.java

/**
 * Gathers attributes from JNDI storage to the supplied attributes object.
 * @see com.alfaariss.oa.engine.core.attribute.gather.processor.IProcessor#process(java.lang.String, com.alfaariss.oa.api.attribute.IAttributes)
 *//*w ww . ja  v a  2s.co  m*/
public void process(String sUserId, IAttributes oAttributes) throws AttributeException {
    DirContext oDirContext = null;
    NamingEnumeration oNamingEnumeration = null;
    try {
        try {
            oDirContext = new InitialDirContext(_htJNDIEnvironment);
        } catch (NamingException e) {
            _logger.error("Could not create the connection: " + _htJNDIEnvironment);
            throw new AttributeException(SystemErrors.ERROR_RESOURCE_CONNECT, e);
        }

        SearchControls oScope = new SearchControls();
        oScope.setSearchScope(SearchControls.SUBTREE_SCOPE);
        if (_listGather.size() > 0) {
            String[] saAttributes = _listGather.toArray(new String[0]);
            oScope.setReturningAttributes(saAttributes);
        }

        String searchFilter = resolveSearchQuery(sUserId);
        try {
            oNamingEnumeration = oDirContext.search(_sDNBase, searchFilter, oScope);
        } catch (InvalidSearchFilterException e) {
            StringBuffer sbFailed = new StringBuffer("Wrong filter: ");
            sbFailed.append(searchFilter);
            sbFailed.append(" while searching for attributes for id: ");
            sbFailed.append(sUserId);
            _logger.error(sbFailed.toString(), e);
            throw new AttributeException(SystemErrors.ERROR_RESOURCE_RETRIEVE, e);
        } catch (NamingException e) {
            _logger.debug("User unknown: " + sUserId);
            return;
        }

        if (oNamingEnumeration.hasMore()) {
            SearchResult oSearchResult = (SearchResult) oNamingEnumeration.next();
            Attributes oSearchedAttributes = oSearchResult.getAttributes();
            NamingEnumeration neAttributes = oSearchedAttributes.getAll();
            while (neAttributes.hasMore()) {
                Attribute oAttribute = (Attribute) neAttributes.next();
                String sAttributeName = oAttribute.getID();
                String sMappedName = _htMapper.get(sAttributeName);
                if (sMappedName != null)
                    sAttributeName = sMappedName;

                if (oAttribute.size() > 1) {
                    Vector<Object> vValue = new Vector<Object>();
                    NamingEnumeration neAttribute = oAttribute.getAll();
                    while (neAttribute.hasMore())
                        vValue.add(neAttribute.next());

                    oAttributes.put(sAttributeName, vValue);
                } else {
                    Object oValue = oAttribute.get();
                    if (oValue == null)
                        oValue = "";
                    oAttributes.put(sAttributeName, oValue);
                }
            }
        }
    } catch (AttributeException e) {
        throw e;
    } catch (NamingException e) {
        _logger.debug("Failed to fetch attributes for user: " + sUserId, e);
    } catch (Exception e) {
        _logger.fatal("Could not retrieve fields for user with id: " + sUserId, e);
        throw new AttributeException(SystemErrors.ERROR_INTERNAL);
    } finally {
        if (oNamingEnumeration != null) {
            try {
                oNamingEnumeration.close();
            } catch (Exception e) {
                _logger.error("Could not close Naming Enumeration after searching for user with id: " + sUserId,
                        e);
            }
        }
        if (oDirContext != null) {
            try {
                oDirContext.close();
            } catch (NamingException e) {
                _logger.error("Could not close Dir Context after searching for user with id: " + sUserId, e);
            }
        }
    }
}

From source file:org.apache.nifi.ldap.tenants.LdapUserGroupProvider.java

private String getReferencedUserValue(final DirContextOperations ctx) {
    final String referencedUserValue;

    if (StringUtils.isBlank(groupMemberReferencedUserAttribute)) {
        referencedUserValue = ctx.getDn().toString();
    } else {/*  ww w  .  j  a v a  2 s.com*/
        final Attribute attributeName = ctx.getAttributes().get(groupMemberReferencedUserAttribute);
        if (attributeName == null) {
            throw new AuthorizationAccessException("Referenced user value attribute ["
                    + groupMemberReferencedUserAttribute + "] does not exist.");
        }

        try {
            referencedUserValue = (String) attributeName.get();
        } catch (NamingException e) {
            throw new AuthorizationAccessException("Error while retrieving reference user value attribute ["
                    + groupMemberReferencedUserAttribute + "].");
        }
    }

    return referencedUserValue;
}

From source file:org.apache.nifi.ldap.tenants.LdapUserGroupProvider.java

private String getReferencedGroupValue(final DirContextOperations ctx) {
    final String referencedGroupValue;

    if (StringUtils.isBlank(userGroupReferencedGroupAttribute)) {
        referencedGroupValue = ctx.getDn().toString();
    } else {/* w w w.  jav  a  2  s.  co  m*/
        final Attribute attributeName = ctx.getAttributes().get(userGroupReferencedGroupAttribute);
        if (attributeName == null) {
            throw new AuthorizationAccessException("Referenced group value attribute ["
                    + userGroupReferencedGroupAttribute + "] does not exist.");
        }

        try {
            referencedGroupValue = (String) attributeName.get();
        } catch (NamingException e) {
            throw new AuthorizationAccessException("Error while retrieving referenced group value attribute ["
                    + userGroupReferencedGroupAttribute + "].");
        }
    }

    return referencedGroupValue;
}

From source file:org.atricore.idbus.idojos.ldapidentitystore.LDAPIdentityStore.java

/**
 * Fetches the supplied user./*from w  w w . j a v a  2  s  . c  o m*/
 *
 * @param attrValue the user id
 * @return the user id for the supplied uid
 * @throws NamingException LDAP error obtaining user information.
 */
protected String selectUser(String attrId, String attrValue) throws NamingException {
    String uidValue = null;

    InitialLdapContext ctx = createLdapInitialContext();

    String uidAttrName = this.getPrincipalUidAttributeID();
    String usersCtxDN = this.getUsersCtxDN();

    try {
        // NamingEnumeration answer = ctx.search(usersCtxDN, matchAttrs, principalAttr);
        // This gives more control over search behavior :
        NamingEnumeration answer = ctx.search(usersCtxDN, "(&(" + attrId + "=" + attrValue + "))",
                getSearchControls());

        while (answer.hasMore()) {
            SearchResult sr = (SearchResult) answer.next();
            Attributes attrs = sr.getAttributes();
            Attribute uidAttr = attrs.get(uidAttrName);

            if (uidAttr == null) {
                logger.warn("Invalid user attrValue attribute '" + uidAttrName + "'");
                continue;
            }

            uidValue = uidAttr.get().toString();

            if (uidValue != null) {
                if (logger.isDebugEnabled())
                    logger.debug(
                            "Found user '" + uidAttrName + "=" + uidValue + "' for user '" + attrValue + "'");
            } else {
                if (logger.isDebugEnabled())
                    logger.debug("User not found for user '" + attrValue + "'");
            }
        }
    } catch (NamingException e) {
        if (logger.isDebugEnabled())
            logger.debug("Failed to locate user", e);
    } finally {
        // Close the context to release the connection
        ctx.close();
    }

    return uidValue;
}

From source file:org.wso2.carbon.directory.server.manager.internal.LDAPServerStoreManager.java

public ServerPrinciple[] listServicePrinciples(String filter) throws DirectoryServerManagerException {

    ServerPrinciple[] serverNames = null;

    int maxItemLimit = Integer.parseInt(
            this.realmConfiguration.getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_MAX_USER_LIST));

    SearchControls searchCtls = new SearchControls();
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    searchCtls.setCountLimit(maxItemLimit);

    if (filter.contains("?") || filter.contains("**")) {
        log.error("Invalid search character " + filter);
        throw new DirectoryServerManagerException(
                "Invalid character sequence entered for service principle search. Please enter valid sequence.");
    }//from www . j a  v  a2 s. c om

    StringBuilder searchFilter;
    searchFilter = new StringBuilder(
            this.realmConfiguration.getUserStoreProperty(LDAPConstants.USER_NAME_LIST_FILTER));
    String searchBase = this.realmConfiguration.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE);

    StringBuilder buff = new StringBuilder();
    buff.append("(&").append(searchFilter).append("(")
            .append(LDAPServerManagerConstants.KRB5_PRINCIPAL_NAME_ATTRIBUTE).append("=").append(filter)
            .append(")").append(getServerPrincipleIncludeString()).append(")");

    String[] returnedAtts = { LDAPServerManagerConstants.KRB5_PRINCIPAL_NAME_ATTRIBUTE,
            LDAPServerManagerConstants.LDAP_COMMON_NAME };
    searchCtls.setReturningAttributes(returnedAtts);
    DirContext dirContext = null;
    try {
        dirContext = connectionSource.getContext();
        NamingEnumeration<SearchResult> answer = dirContext.search(searchBase, buff.toString(), searchCtls);
        List<ServerPrinciple> list = new ArrayList<ServerPrinciple>();
        int i = 0;
        while (answer.hasMoreElements() && i < maxItemLimit) {
            SearchResult sr = answer.next();
            if (sr.getAttributes() != null) {
                Attribute serverNameAttribute = sr.getAttributes()
                        .get(LDAPServerManagerConstants.KRB5_PRINCIPAL_NAME_ATTRIBUTE);
                Attribute serverDescription = sr.getAttributes()
                        .get(LDAPServerManagerConstants.LDAP_COMMON_NAME);
                if (serverNameAttribute != null) {

                    ServerPrinciple principle;
                    String serviceName;
                    String serverPrincipleFullName = (String) serverNameAttribute.get();

                    if (serverPrincipleFullName.toLowerCase(Locale.ENGLISH)
                            .contains(LDAPServerManagerConstants.KERBEROS_TGT)) {
                        continue;
                    }

                    if (serverPrincipleFullName.contains("@")) {
                        serviceName = serverPrincipleFullName.split("@")[0];
                    } else {
                        serviceName = serverPrincipleFullName;
                    }

                    if (serverDescription != null) {
                        principle = new ServerPrinciple(serviceName, (String) serverDescription.get());
                    } else {

                        principle = new ServerPrinciple(serviceName);
                    }

                    list.add(principle);
                    i++;
                }
            }
        }

        serverNames = list.toArray(new ServerPrinciple[list.size()]);
        Arrays.sort(serverNames);

    } catch (NamingException e) {
        log.error(e.getMessage(), e);
        throw new DirectoryServerManagerException("Unable to list service principles.", e);
    } catch (UserStoreException e) {
        log.error("Unable to retrieve LDAP connection context.", e);
        throw new DirectoryServerManagerException("Unable to list service principles.", e);
    } finally {
        try {
            JNDIUtil.closeContext(dirContext);
        } catch (UserStoreException e) {
            log.error("Unable to close directory context.", e);
        }
    }
    return serverNames;

}