Example usage for javax.naming NamingEnumeration hasMore

List of usage examples for javax.naming NamingEnumeration hasMore

Introduction

In this page you can find the example usage for javax.naming NamingEnumeration hasMore.

Prototype

public boolean hasMore() throws NamingException;

Source Link

Document

Determines whether there are any more elements in the enumeration.

Usage

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

protected Organisation convertLdapOrganizationToOrganisation(
        NamingEnumeration<SearchResult> pOrganizationResult, NamingEnumeration<SearchResult> pPrivilegesResult)
        throws ExecutionException, NameNotFoundException {
    Organisation vOrganisation = null;/*from  w  w w . j  ava  2 s . c o  m*/
    try {
        if ((pOrganizationResult != null) && pOrganizationResult.hasMore()) {

            SearchResult sr = pOrganizationResult.next();
            vOrganisation = convertSearchResultToOrganization(sr);
            // -- Organization privileges:
            vOrganisation = this.convertLdapGroupsToOrganizationPrivileges(vOrganisation, pPrivilegesResult);
        }
    } catch (NameNotFoundException ex) {
        LOG.log(Level.SEVERE, null, ex);
        throw ex;
    } catch (NamingException ne) {
        LOG.log(Level.SEVERE, null, ne);
        throw new ExecutionException(ne.getMessage(), ne.getCause());
    } finally {
        // -- releases this context's resources immediately, instead of waiting for the garbage collector
        if (pOrganizationResult != null) {
            try {
                pOrganizationResult.close();
            } catch (NamingException ex) {
            }
        }
    }
    return vOrganisation;
}

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

/**
 * Obtain the properties for the user associated with the given uid using the
 * configured user properties query string.
 *
 * @param uid the user id of the user for whom its user properties are required.
 * @return the hash map containing user properties as name/value pairs.
 * @throws NamingException LDAP error obtaining user properties.
 *///from   w w w .  j a  v  a  2s .  c o  m
protected HashMap selectUserProperties(String uid) throws NamingException {
    HashMap userPropertiesResultSet = new HashMap();

    InitialLdapContext ctx = createLdapInitialContext();

    BasicAttributes matchAttrs = new BasicAttributes(true);

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

    matchAttrs.put(principalUidAttrName, uid);

    String userPropertiesQueryString = getUserPropertiesQueryString();
    HashMap userPropertiesQueryMap = parseQueryString(userPropertiesQueryString);

    Iterator i = userPropertiesQueryMap.keySet().iterator();
    List propertiesAttrList = new ArrayList();
    while (i.hasNext()) {
        String o = (String) i.next();
        propertiesAttrList.add(o);
    }

    String[] propertiesAttr = (String[]) propertiesAttrList.toArray(new String[propertiesAttrList.size()]);

    try {

        // This gives more control over search behavior :
        NamingEnumeration answer = ctx.search(usersCtxDN, "(&(" + principalUidAttrName + "=" + uid + "))",
                getSearchControls());

        while (answer.hasMore()) {
            SearchResult sr = (SearchResult) answer.next();
            Attributes attrs = sr.getAttributes();

            for (int j = 0; j < propertiesAttr.length; j++) {

                Attribute attribute = attrs.get(propertiesAttr[j]);

                if (attribute == null) {
                    logger.warn("Invalid user property attribute '" + propertiesAttr[j] + "'");
                    continue;
                }

                Object propertyObject = attrs.get(propertiesAttr[j]).get();

                if (propertyObject == null) {
                    logger.warn("Found a 'null' value for user property '" + propertiesAttr[j] + "'");
                    continue;
                }

                String propertyValue = propertyObject.toString();
                String propertyName = (String) userPropertiesQueryMap.get(propertiesAttr[j]);

                userPropertiesResultSet.put(propertyName, propertyValue);

                if (logger.isDebugEnabled())
                    logger.debug(
                            "Found user property '" + propertyName + "' with value '" + propertyValue + "'");
            }

        }
    } catch (NamingException e) {
        if (logger.isDebugEnabled())
            logger.debug("Failed to locate user", e);
    } finally {
        // Close the context to release the connection
        ctx.close();
    }

    return userPropertiesResultSet;
}

From source file:org.apache.zeppelin.realm.LdapRealm.java

boolean isUserMemberOfDynamicGroup(LdapName userLdapDn, String memberUrl,
        final LdapContextFactory ldapContextFactory) throws NamingException {
    // ldap://host:port/dn?attributes?scope?filter?extensions
    if (memberUrl == null) {
        return false;
    }// w w  w  . ja  va 2s .  co  m
    String[] tokens = memberUrl.split("\\?");
    if (tokens.length < 4) {
        return false;
    }

    String searchBaseString = tokens[0].substring(tokens[0].lastIndexOf("/") + 1);
    String searchScope = tokens[2];
    String searchFilter = tokens[3];

    LdapName searchBaseDn = new LdapName(searchBaseString);

    // do scope test
    if (searchScope.equalsIgnoreCase("base")) {
        log.debug("DynamicGroup SearchScope base");
        return false;
    }
    if (!userLdapDn.toString().endsWith(searchBaseDn.toString())) {
        return false;
    }
    if (searchScope.equalsIgnoreCase("one") && (userLdapDn.size() != searchBaseDn.size() - 1)) {
        log.debug("DynamicGroup SearchScope one");
        return false;
    }
    // search for the filter, substituting base with userDn
    // search for base_dn=userDn, scope=base, filter=filter
    LdapContext systemLdapCtx = null;
    systemLdapCtx = ldapContextFactory.getSystemLdapContext();
    boolean member = false;
    NamingEnumeration<SearchResult> searchResultEnum = null;
    try {
        searchResultEnum = systemLdapCtx.search(userLdapDn, searchFilter,
                searchScope.equalsIgnoreCase("sub") ? SUBTREE_SCOPE : ONELEVEL_SCOPE);
        if (searchResultEnum.hasMore()) {
            return true;
        }
    } finally {
        try {
            if (searchResultEnum != null) {
                searchResultEnum.close();
            }
        } finally {
            LdapUtils.closeContext(systemLdapCtx);
        }
    }
    return member;
}

From source file:org.infoscoop.account.ldap.LDAPAccountManager.java

public IAccount getUser(String uid) throws NamingException {

    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    NamingEnumeration searchResultEnum;
    Map filters = new HashMap();

    String uidAttrName = "uid";
    if (this.propAttrMap.containsKey("user_id")) {
        try {/*from w ww. ja v a 2s  .c o m*/
            uidAttrName = (String) this.propAttrMap.get("user_id");
        } catch (Exception ex) {
            //ignore
        }
    }
    if (uid != null && !"".equals(uid))
        filters.put(uidAttrName, uid);

    DirContext context = null;
    try {
        context = this.initContext();
        searchResultEnum = context.search(userBase, buildFilterByUid(filters), searchControls);
        //roop of retrieval result

        while (searchResultEnum.hasMore()) {
            SearchResult searchResult = (SearchResult) searchResultEnum.next();

            String dn = searchResult.getName() + "," + userBase;
            LDAPAccount user = createLDAPUser(dn, searchResult.getAttributes());
            setGroup(context, user);

            return user;
        }

        return null;
    } finally {
        if (context != null)
            context.close();
    }
}

From source file:com.dtolabs.rundeck.jetty.jaas.JettyCachingLdapLoginModule.java

@SuppressWarnings("unchecked")
private List getUserRolesByDn(DirContext dirContext, String userDn, String username)
        throws LoginException, NamingException {
    List<String> roleList = new ArrayList<String>();

    if (dirContext == null || _roleBaseDn == null
            || (_roleMemberAttribute == null && _roleUsernameMemberAttribute == null)
            || _roleObjectClass == null) {
        LOG.warn(/*from w  ww.  j a  v  a 2 s. com*/
                "JettyCachingLdapLoginModule: No user roles found: roleBaseDn, roleObjectClass and roleMemberAttribute or roleUsernameMemberAttribute must be specified.");
        addSupplementalRoles(roleList);
        return roleList;
    }

    String[] attrIDs = { _roleNameAttribute };
    SearchControls ctls = new SearchControls();
    ctls.setReturningAttributes(attrIDs);
    ctls.setDerefLinkFlag(true);
    ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    String filter = OBJECT_CLASS_FILTER;
    final NamingEnumeration results;

    if (null != _roleUsernameMemberAttribute) {
        Object[] filterArguments = { _roleObjectClass, _roleUsernameMemberAttribute, username };
        results = dirContext.search(_roleBaseDn, filter, filterArguments, ctls);
    } else {
        Object[] filterArguments = { _roleObjectClass, _roleMemberAttribute, userDn };
        results = dirContext.search(_roleBaseDn, filter, filterArguments, ctls);
    }

    while (results.hasMoreElements()) {
        SearchResult result = (SearchResult) results.nextElement();

        Attributes attributes = result.getAttributes();

        if (attributes == null) {
            continue;
        }

        Attribute roleAttribute = attributes.get(_roleNameAttribute);

        if (roleAttribute == null) {
            continue;
        }

        NamingEnumeration roles = roleAttribute.getAll();
        while (roles.hasMore()) {
            if (_rolePrefix != null && !"".equalsIgnoreCase(_rolePrefix)) {
                String role = (String) roles.next();
                roleList.add(role.replace(_rolePrefix, ""));
            } else {
                roleList.add((String) roles.next());
            }
        }
    }

    addSupplementalRoles(roleList);

    if (_nestedGroups) {
        roleList = getNestedRoles(dirContext, roleList);
    }

    if (roleList.size() < 1) {
        LOG.warn("JettyCachingLdapLoginModule: User '" + username
                + "' has no role membership; role query configuration may be incorrect");
    } else {
        debug("JettyCachingLdapLoginModule: User '" + username + "' has roles: " + roleList);
    }

    return roleList;
}

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

public List<String> getGroupsMember(String group, DirContext context) throws MappingException {

    NamingEnumeration<SearchResult> namingEnumeration = null;
    try {//  w  ww  .  j  av a 2s.c om

        SearchControls searchControls = new SearchControls();

        searchControls.setDerefLinkFlag(true);
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        String filter = "objectClass=" + getLdapGroupClass();

        namingEnumeration = context.search("cn=" + group + "," + getGroupsDn(), filter, searchControls);

        List<String> allMembers = new ArrayList<String>();

        while (namingEnumeration.hasMore()) {
            SearchResult searchResult = namingEnumeration.next();

            Attribute uniqueMemberAttr = searchResult.getAttributes().get(getLdapGroupMember());

            if (uniqueMemberAttr != null) {
                NamingEnumeration<String> allMembersEnum = (NamingEnumeration<String>) uniqueMemberAttr
                        .getAll();
                while (allMembersEnum.hasMore()) {
                    String userName = allMembersEnum.next();
                    // uid=blabla we only want bla bla
                    userName = StringUtils.substringAfter(userName, "=");
                    userName = StringUtils.substringBefore(userName, ",");
                    log.debug("found userName for group {}: '{}", group, userName);

                    allMembers.add(userName);
                }
                close(allMembersEnum);
            }

        }

        return allMembers;
    } catch (LdapException e) {
        throw new MappingException(e.getMessage(), e);
    } catch (NamingException e) {
        throw new MappingException(e.getMessage(), e);
    }

    finally {
        close(namingEnumeration);
    }
}

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

/**
 * Fetch the Ldap user attributes to be used as credentials.
 *
 * @param uid the user id for whom credentials are required
 * @return the hash map containing user credentials as name/value pairs
 * @throws NamingException LDAP error obtaining user credentials.
 *//*from   w w  w . jav  a  2 s .  c  o m*/
protected HashMap selectCredentials(String uid) throws NamingException {
    HashMap credentialResultSet = new HashMap();

    InitialLdapContext ctx = createLdapInitialContext();

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

    // BasicAttributes matchAttrs = new BasicAttributes(true);
    // matchAttrs.put(principalUidAttrName, uid);

    String credentialQueryString = getCredentialQueryString();
    HashMap credentialQueryMap = parseQueryString(credentialQueryString);

    Iterator i = credentialQueryMap.keySet().iterator();
    List credentialAttrList = new ArrayList();
    while (i.hasNext()) {
        String o = (String) i.next();
        credentialAttrList.add(o);
    }

    String[] credentialAttr = (String[]) credentialAttrList.toArray(new String[credentialAttrList.size()]);

    try {

        // NamingEnumeration answer = ctx.search(usersCtxDN, matchAttrs, credentialAttr);

        // This gives more control over search behavior :
        NamingEnumeration answer = ctx.search(usersCtxDN, "(&(" + principalUidAttrName + "=" + uid + "))",
                getSearchControls());

        while (answer.hasMore()) {
            SearchResult sr = (SearchResult) answer.next();
            Attributes attrs = sr.getAttributes();

            for (int j = 0; j < credentialAttr.length; j++) {

                Object credentialObject = attrs.get(credentialAttr[j]).get();
                String credentialName = (String) credentialQueryMap.get(credentialAttr[j]);
                String credentialValue = null;

                if (logger.isDebugEnabled())
                    logger.debug("Found user credential '" + credentialName + "' of type '"
                            + credentialObject.getClass().getName() + ""
                            + (credentialObject.getClass().isArray()
                                    ? "[" + Array.getLength(credentialObject) + "]"
                                    : "")
                            + "'");

                // if the attribute value is an array, cast it to byte[] and then convert to
                // String using proper encoding
                if (credentialObject.getClass().isArray()) {

                    try {
                        // Try to create a UTF-8 String, we use java.nio to handle errors in a better way.
                        // If the byte[] cannot be converted to UTF-8, we're using the credentialObject as is.
                        byte[] credentialData = (byte[]) credentialObject;
                        ByteBuffer in = ByteBuffer.allocate(credentialData.length);
                        in.put(credentialData);
                        in.flip();

                        Charset charset = Charset.forName("UTF-8");
                        CharsetDecoder decoder = charset.newDecoder();
                        CharBuffer charBuffer = decoder.decode(in);

                        credentialValue = charBuffer.toString();

                    } catch (CharacterCodingException e) {
                        if (logger.isDebugEnabled())
                            logger.debug("Can't convert credential value to String using UTF-8");
                    }

                } else if (credentialObject instanceof String) {
                    // The credential value must be a String ...
                    credentialValue = (String) credentialObject;

                }

                // Check what do we have ...
                if (credentialValue != null) {
                    // Remove any schema information from the credential value, like the {md5} prefix for passwords.
                    credentialValue = getSchemeFreeValue(credentialValue);
                    credentialResultSet.put(credentialName, credentialValue);
                } else {
                    // We have a binary credential, leave it as it is ... probably binary value.
                    credentialResultSet.put(credentialName, credentialObject);
                }

                if (logger.isDebugEnabled())
                    logger.debug("Found user credential '" + credentialName + "' with value '"
                            + (credentialValue != null ? credentialValue : credentialObject) + "'");
            }

        }
    } catch (NamingException e) {
        if (logger.isDebugEnabled())
            logger.debug("Failed to locate user", e);
    } finally {
        // Close the context to release the connection
        ctx.close();
    }

    return credentialResultSet;
}

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

protected Organisation convertLdapGroupsToOrganizationPrivileges(Organisation pOrg,
        NamingEnumeration<SearchResult> pPrivilegesResult) throws ExecutionException {
    try {//from www  .ja  va2 s.co  m
        if (pPrivilegesResult != null) {
            PrivilegeEnum p;
            SearchResult sr;
            String vCnPrivileg;
            // construct privileges
            while (pPrivilegesResult.hasMore()) {
                sr = pPrivilegesResult.next();
                vCnPrivileg = (String) sr.getAttributes().get(Constants.ldap_ddbPrivilege_Cn).get();
                p = this.mapToPrivilege(sr.getAttributes(), Constants.ldap_ddbPrivilege_Cn);
                if (p != null) {
                    pOrg.addPrivileges(p);
                } else {
                    LOG.log(Level.WARNING,
                            "Die Organisation ''{0}'' verfgt ber einen nicht existierende Privileg: ''{1}''!",
                            new Object[] { pOrg.getId(), vCnPrivileg });
                }
            }
            // -- releases this context's resources immediately, instead of waiting for the garbage collector
            pPrivilegesResult.close();
        }
    } catch (NamingException ne) {
        LOG.log(Level.SEVERE, null, ne);
        throw new ExecutionException(ne.getMessage(), ne.getCause());
    } finally {
        // -- releases this context's resources immediately, instead of waiting for the garbage collector
        if (pPrivilegesResult != null) {
            try {
                pPrivilegesResult.close();
            } catch (NamingException ex) {
            }
        }
    }
    return pOrg;
}

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

protected Organisation convertSearchResultToOrganization(final SearchResult sr)
        throws ExecutionException, NameNotFoundException {
    if (sr == null) {
        throw new ExecutionException("SearchResult sr == NULL", new NullPointerException());
    }//  w ww  . ja  v  a 2s .c o  m
    Organisation vOrganisation = null;
    try {
        Attributes attributes = sr.getAttributes();

        Attribute attr;
        String vStr;
        String vOrgName = ((attr = attributes.get(Constants.ldap_ddbOrg_Id)) != null
                ? String.valueOf(attr.get())
                : null);
        String vName = sr.getName();
        String vNameInNamespace = sr.getNameInNamespace();
        // --- EntryDN
        String vEntryDN = ((attr = attributes.get(Constants.ldap_ddb_EntryDN)) != null
                ? String.valueOf(attr.get())
                : "");

        int idx;
        // -- Parent node detections:
        String vParent = null;
        //vParent = sr.getName();
        //LOG.log(Level.INFO, "getNameInNamespace() = '" + sr.getNameInNamespace() + "'");
        //LOG.log(Level.INFO, "getName() = '" + sr.getName() + "'");
        // -- getNameInNamespace() = 'o=99900711,o=00008125,o=00050350,ou=Organizations,dc=de'
        // -- getName() = 'o=99900711,o=00008125,o=00050350'

        //sr.getName(): 'o=00000116', 
        //sr.getNameInNamespace(): 'o=00000116,o=00050350,ou=Organizations,dc=de', 
        //vOrgEntryDN: 'o=00000116,o=00050350,ou=Organizations,dc=de'            
        vParent = sr.getNameInNamespace();
        if ((idx = vParent.indexOf(",ou=")) >= 0) {
            vParent = vParent.substring(0, idx);
        }
        vParent = vParent.replaceAll(Constants.ldap_ddbOrg_Id + "=", "");
        // -- 99900711,00008125,00050350'
        String[] vParents = vParent.split(",");

        if (vParents.length >= 2) {
            vParent = vParents[1];
        } else {
            vParent = null;
        }

        LOG.log(Level.INFO,
                "convertLdapOrganizationToOrganisation: o: '" + vOrgName + "', vParent: '" + vParent
                        + "', sr.getName(): '" + vName + "', sr.getNameInNamespace(): '" + vNameInNamespace
                        + "', vOrgEntryDN: '" + vEntryDN + "', sr.isRelative(): '" + sr.isRelative() + "'");
        /*
         * if ( (vOrgName != null)&&(!vOrgName.isEmpty()) ) { vOrganisation = new Organisation(vOrgName,
         * vDescription, vParent);
         */
        if ((vEntryDN != null) && (!vEntryDN.isEmpty())) {
            vOrganisation = new Organisation(vEntryDN,
                    (attr = sr.getAttributes().get(Constants.ldap_ddbOrg_PID)) != null
                            ? String.valueOf(attr.get())
                            : null);
            // Public-ID: (s.o.)
            // vOrganisation.setOrgPID( (attr = attributes.get(ddbOrg_PID)) != null ? String.valueOf(attr.get()) :
            // "");
            // Parent (s.o.)
            vOrganisation.setOrgParent(vParent);

            // Kurzbeschreibung der Einrichtung
            vOrganisation.setDescription((attr = attributes.get(Constants.ldap_ddbOrg_Description)) != null
                    ? String.valueOf(attr.get())
                    : null);

            // -- Rechtsform
            try {
                vOrganisation.setBusinessCategory(
                        (attr = attributes.get(Constants.ldap_ddbOrg_BusinessCategory)) != null
                                ? ConstEnumOrgSector.valueOf(String.valueOf(attr.get()))
                                : null);
            } catch (IllegalArgumentException ex) {
                LOG.log(Level.WARNING, "Organisation-Sector-Error: {0}", ex.getMessage());
                vOrganisation.setStatus(null);
            }

            // -- Sub-Sectors:
            if ((attr = attributes.get(Constants.ldap_ddbOrg_SubBusinessCategory)) != null) {
                ConstEnumOrgSubSector vSubSector;
                NamingEnumeration<?> allSubSectors = attr.getAll();
                while (allSubSectors.hasMore()) {
                    try {
                        vSubSector = ConstEnumOrgSubSector.valueOf((String) allSubSectors.next());
                        vOrganisation.addSubSectors(vSubSector);
                    } catch (IllegalArgumentException ex) {
                        LOG.log(Level.WARNING, "Organisation-SubSector-Error: {0}", ex.getMessage());
                    }
                }
            }

            // -- Funding Agency
            vOrganisation.setFundingAgency((attr = attributes.get(Constants.ldap_ddbOrg_FundingAgency)) != null
                    ? String.valueOf(attr.get())
                    : null);

            // Name der Einrichtung
            vOrganisation.setDisplayName((attr = attributes.get(Constants.ldap_ddbOrg_DisplayName)) != null
                    ? String.valueOf(attr.get())
                    : "");

            // E-Mail
            vOrganisation.setEmail(
                    (attr = attributes.get(Constants.ldap_ddbOrg_Email)) != null ? String.valueOf(attr.get())
                            : null);
            // Telefonnummer
            vOrganisation.setTel((attr = attributes.get(Constants.ldap_ddbOrg_TelephoneNumber)) != null
                    ? String.valueOf(attr.get())
                    : null);
            // -- FAX
            vOrganisation.setFax((attr = attributes.get(Constants.ldap_ddbOrg_FaxNumber)) != null
                    ? String.valueOf(attr.get())
                    : null);

            // -- PLZ
            vOrganisation.getAddress()
                    .setPostalCode((attr = attributes.get(Constants.ldap_ddbOrg_PostalCode)) != null
                            ? String.valueOf(attr.get())
                            : "");

            // -- City/Ortsname [l, localityName]
            if ((attr = attributes.get(Constants.ldap_ddbOrg_LocalityName)) != null) {
                vOrganisation.getAddress().setLocalityName(String.valueOf(attr.get()));
            } else if ((attr = attributes.get("l")) != null) {
                vOrganisation.getAddress().setLocalityName(String.valueOf(attr.get()));
            }

            // -- HouseIdentifier
            vOrganisation.getAddress()
                    .setHouseIdentifier((attr = attributes.get(Constants.ldap_ddbOrg_HouseIdentifier)) != null
                            ? String.valueOf(attr.get())
                            : "");
            // -- Strasse
            vOrganisation.getAddress()
                    .setStreet((attr = attributes.get(Constants.ldap_ddbOrg_Street)) != null
                            ? String.valueOf(attr.get())
                            : "");

            // -- Bundesland [stateOrProvinceName, st]
            if ((attr = attributes.get(Constants.ldap_ddbOrg_StateOrProvinceName)) != null) {
                vOrganisation.getAddress().setStateOrProvinceName(String.valueOf(attr.get()));
            } else if ((attr = attributes.get("st")) != null) {
                vOrganisation.getAddress().setStateOrProvinceName(String.valueOf(attr.get()));
            }

            // -- Land [countryName, c]
            if ((attr = attributes.get(Constants.ldap_ddbOrg_CountryName)) != null) {
                vOrganisation.getAddress().setCountryName(String.valueOf(attr.get()));
            }
            // -- AddressSuplement
            vOrganisation.getAddress()
                    .setAddressSuplement((attr = attributes.get(Constants.ldap_ddbOrg_AddressSuplement)) != null
                            ? String.valueOf(attr.get())
                            : "");

            // -- Geokoordinaten
            try {
                vOrganisation.getAddress()
                        .setLatitude((attr = attributes.get(Constants.ldap_ddbOrg_GeoLatitude)) != null
                                ? Double.valueOf(String.valueOf(attr.get()))
                                : 0.0);
            } catch (NumberFormatException ex) {
                LOG.log(Level.WARNING, "GeoLatitude-Error: {0}", ex.getMessage());
            }
            try {
                vOrganisation.getAddress()
                        .setLongitude((attr = attributes.get(Constants.ldap_ddbOrg_GeoLongitude)) != null
                                ? Double.valueOf(String.valueOf(attr.get()))
                                : 0.0);
            } catch (NumberFormatException ex) {
                LOG.log(Level.WARNING, "GeoLongitude-Error: {0}", ex.getMessage());
            }
            vOrganisation.getAddress().setLocationDisplayName(
                    (attr = attributes.get(Constants.ldap_ddbOrg_LocationDisplayName)) != null
                            ? String.valueOf(attr.get())
                            : null);

            vOrganisation.setAbbreviation((attr = attributes.get(Constants.ldap_ddbOrg_Abbreviation)) != null
                    ? String.valueOf(attr.get())
                    : null);

            vOrganisation.setLegalStatus((attr = attributes.get(Constants.ldap_ddbOrg_LegalStatus)) != null
                    ? String.valueOf(attr.get())
                    : null);

            if ((attr = attributes.get(Constants.ldap_ddbOrg_URL)) != null) {
                NamingEnumeration<?> allURLs = attr.getAll();
                while (allURLs.hasMore()) {
                    vOrganisation.addURLs((String) allURLs.next());
                }
            }

            vOrganisation.setLogo(
                    (attr = attributes.get(Constants.ldap_ddbOrg_Logo)) != null ? String.valueOf(attr.get())
                            : null);

            // -- org-Status:
            //vOrganisation.setStatus((attr = attributes.get(Constants.ldap_ddbOrg_Status)) != null ? String
            //  .valueOf(attr.get()) : "");
            try {
                vOrganisation.setStatus((attr = attributes.get(Constants.ldap_ddbOrg_Status)) != null
                        ? ConstEnumOrgStatus.valueOf(String.valueOf(attr.get()))
                        : ConstEnumOrgStatus.pending);
            } catch (IllegalArgumentException ex) {
                LOG.log(Level.WARNING, "Organisation-Status-Error: {0}", ex.getMessage());
                vOrganisation.setStatus(null);
            }

            vOrganisation.setCreatedBy((attr = attributes.get(Constants.ldap_ddb_CreatorsName)) != null
                    ? String.valueOf(attr.get())
                    : "");

            try { // createTimestamp-Error: For input string: "20120620142810Z"
                  // 1340205676692 - 20120620152116Z - 2012-06-20-15-21-16Z
                  // vOrganisation.setCreated( (attr = attributes.get(ddbOrg_CreateTimestamp)) != null ?
                  // Long.valueOf(String.valueOf(attr.get())) : Long.valueOf(-1));
                if ((attr = attributes.get(Constants.ldap_ddb_CreateTimestamp)) != null) {
                    vStr = String.valueOf(attr.get());
                    vOrganisation.setCreated(convertLdapDateToLong(vStr));
                }
            } catch (NumberFormatException ex) {
                LOG.log(Level.WARNING, "createTimestamp-Error: {0}", ex.getMessage());
            }

            vOrganisation.setModifiedBy((attr = attributes.get(Constants.ldap_ddb_ModifiersName)) != null
                    ? String.valueOf(attr.get())
                    : "");
            try { // modifyTimestamp-Error: For input string: "20120620142810Z"
                  // vOrganisation.setModified( (attr = attributes.get(ddbOrg_ModifyTimestamp)) != null ?
                  // Long.valueOf(String.valueOf(attr.get())) : Long.valueOf(-1));
                if ((attr = attributes.get(Constants.ldap_ddb_ModifyTimestamp)) != null) {
                    vStr = String.valueOf(attr.get());
                    vOrganisation.setModified(convertLdapDateToLong(vStr));
                }
            } catch (NumberFormatException ex) {
                LOG.log(Level.WARNING, "modifyTimestamp-Error: {0}", ex.getMessage());
            }

            if ((attr = attributes.get(Constants.ldap_ddbOrg_Properties)) != null
                    && attributes.get(Constants.ldap_ddbOrg_Properties).get() != null) {
                vOrganisation.setProperties(serializer.deserialize((String) attr.get()));
            }

        } else {
            throw new NameNotFoundException();
        }
    } catch (IllegalAccessException ex) {
        LOG.log(Level.SEVERE, null, ex);
        throw new ExecutionException(ex.getMessage(), ex.getCause());
    } catch (NameNotFoundException ex) {
        LOG.log(Level.SEVERE, null, ex);
        throw ex;
    } catch (NamingException ne) {
        LOG.log(Level.SEVERE, null, ne);
        throw new ExecutionException(ne.getMessage(), ne.getCause());
    }
    return vOrganisation;
}

From source file:org.nuxeo.ecm.directory.ldap.LDAPSession.java

@SuppressWarnings("unchecked")
protected List<String> getMandatoryAttributes(Attribute objectClassesAttribute) throws DirectoryException {
    try {/*from w  w  w.jav  a2 s .co  m*/
        List<String> mandatoryAttributes = new ArrayList<String>();

        DirContext schema = dirContext.getSchema("");
        List<String> objectClasses = new ArrayList<String>();
        if (objectClassesAttribute == null) {
            // use the creation classes as reference schema for this entry
            objectClasses.addAll(Arrays.asList(getDirectory().getDescriptor().getCreationClasses()));
        } else {
            // introspec the objectClass definitions to find the mandatory
            // attributes for this entry
            NamingEnumeration<Object> values = null;
            try {
                values = (NamingEnumeration<Object>) objectClassesAttribute.getAll();
                while (values.hasMore()) {
                    objectClasses.add(values.next().toString().trim());
                }
            } catch (NamingException e) {
                throw new DirectoryException(e);
            } finally {
                if (values != null) {
                    values.close();
                }
            }
        }
        objectClasses.remove("top");
        for (String creationClass : objectClasses) {
            Attributes attributes = schema.getAttributes("ClassDefinition/" + creationClass);
            Attribute attribute = attributes.get("MUST");
            if (attribute != null) {
                NamingEnumeration<String> values = (NamingEnumeration<String>) attribute.getAll();
                try {
                    while (values.hasMore()) {
                        String value = values.next();
                        mandatoryAttributes.add(value);
                    }
                } finally {
                    values.close();
                }
            }
        }
        return mandatoryAttributes;
    } catch (NamingException e) {
        throw new DirectoryException("getMandatoryAttributes failed", e);
    }
}