Example usage for javax.naming.directory SearchResult getAttributes

List of usage examples for javax.naming.directory SearchResult getAttributes

Introduction

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

Prototype

public Attributes getAttributes() 

Source Link

Document

Retrieves the attributes in this search result.

Usage

From source file:org.lsc.jndi.JndiServices.java

/**
 * Retrieve a specific attribute from an object
 * //w w w .j a  v a  2  s . co  m
 * @param objectDn
 * @param attribute
 * @return
 * @throws LscServiceException
 */
public List<String> getAttributeValues(String objectDn, String attribute) throws LscServiceException {
    List<String> values = null;
    try {
        // Setup search
        SearchControls sc = new SearchControls();
        sc.setDerefLinkFlag(false);
        sc.setReturningAttributes(new String[] { attribute });
        sc.setSearchScope(SearchControls.OBJECT_SCOPE);
        sc.setReturningObjFlag(true);

        // Retrieve attribute values
        SearchResult res = getEntry(objectDn, "objectClass=*", sc, SearchControls.OBJECT_SCOPE);
        Attribute attr = res.getAttributes().get(attribute);
        if (attr != null) {
            values = new ArrayList<String>();
            NamingEnumeration<?> enu = attr.getAll();
            while (enu.hasMoreElements()) {
                Object val = enu.next();
                values.add(val.toString());
            }
        }
    } catch (NamingException e) {
        throw new LscServiceException(e);
    }
    return values;
}

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

/**
 * //w  ww .jav  a 2s  .  c  o m
 * Creates list of all OLAT Users which have been deleted out of the LDAP
 * directory but still exits in OLAT
 * 
 * Configuration: Required Attributes = ldapContext.xml (property=reqAttrs)
 * LDAP Base = ldapContext.xml (property=ldapBase)
 * 
 * @param syncTime The time to search in LDAP for changes since this time.
 *          SyncTime has to formatted: JJJJMMddHHmm
 * @param ctx The LDAP system connection, if NULL or closed NamingExecpiton is
 *          thrown
 * 
 * @return Returns list of Identity from the user which have been deleted in
 *         LDAP
 * 
 * @throws NamingException
 */
public List<Identity> getIdentitysDeletedInLdap(LdapContext ctx) {
    if (ctx == null)
        return null;
    // Find all LDAP Users
    String userID = syncConfiguration.getOlatPropertyToLdapAttribute(LDAPConstants.LDAP_USER_IDENTIFYER);
    String userFilter = syncConfiguration.getLdapUserFilter();
    final List<String> ldapList = new ArrayList<String>();

    ldapDao.searchInLdap(new LDAPVisitor() {
        @Override
        public void visit(SearchResult result) throws NamingException {
            Attributes attrs = result.getAttributes();
            NamingEnumeration<? extends Attribute> aEnum = attrs.getAll();
            while (aEnum.hasMore()) {
                Attribute attr = aEnum.next();
                // use lowercase username
                ldapList.add(attr.get().toString().toLowerCase());
            }
        }
    }, (userFilter == null ? "" : userFilter), new String[] { userID }, ctx);

    if (ldapList.isEmpty()) {
        log.warn("No users in LDAP found, can't create deletionList!!", null);
        return null;
    }

    // Find all User in OLAT, members of LDAPSecurityGroup
    SecurityGroup ldapGroup = securityManager.findSecurityGroupByName(LDAPConstants.SECURITY_GROUP_LDAP);
    if (ldapGroup == null) {
        log.error("Error getting users from OLAT security group '" + LDAPConstants.SECURITY_GROUP_LDAP
                + "' : group does not exist", null);
        return null;
    }

    List<Identity> identityListToDelete = new ArrayList<Identity>();
    List<Identity> olatListIdentity = securityManager.getIdentitiesOfSecurityGroup(ldapGroup);
    for (Identity ida : olatListIdentity) {
        // compare usernames with lowercase
        if (!ldapList.contains(ida.getName().toLowerCase())) {
            identityListToDelete.add(ida);
        }
    }
    return identityListToDelete;
}

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

/**
 * binding authentication check This methode of authentication works only if
 * the user branch of the DIT (ldap tree) has an ACI (acces control
 * instruction) that allow the access to any user or at least for the user
 * that logs in.//from www  .  j  a  v a  2s  . c om
 *
 * @param username
 * @param password
 * @return
 * @throws LoginException
 */
@SuppressWarnings("unchecked")
protected boolean bindingLogin(String username, Object password) throws LoginException, NamingException {
    final String cacheToken = Credential.MD5.digest(username + ":" + password.toString());
    if (_cacheDuration > 0) { // only worry about caching if there is a cacheDuration set.
        CachedUserInfo cached = USERINFOCACHE.get(cacheToken);
        if (cached != null) {
            if (System.currentTimeMillis() < cached.expires) {
                debug("Cache Hit for " + username + ".");
                userInfoCacheHits++;
                JAASUserInfo jaasUserInfo = new JAASUserInfo(cached.userInfo);
                try {
                    jaasUserInfo.fetchRoles();
                } catch (Exception ex) {
                    if (_debug) {
                        LOG.debug("Failed to fetch roles", ex);
                    }
                    throw new LoginException("Error obtaining user info.");
                }
                setCurrentUser(jaasUserInfo);
                setAuthenticated(true);
                return true;
            } else {
                LOG.info("Cache Eviction for " + username + ".");
                USERINFOCACHE.remove(cacheToken);
            }
        } else {
            debug("Cache Miss for " + username + ".");
        }
    }

    SearchResult searchResult = findUser(username);

    String userDn = searchResult.getNameInNamespace();

    LOG.info("Attempting authentication: " + userDn);
    DirContext dirContext = createBindUserDirContext(userDn, password);
    setDemographicAttributes(searchResult.getAttributes());

    // use _rootContext to find roles, if configured to doso
    if (_forceBindingLoginUseRootContextForRoles) {
        dirContext = _rootContext;
        debug("Using _rootContext for role lookup.");
    }
    List roles = getUserRolesByDn(dirContext, userDn, username);

    UserInfo userInfo = new UserInfo(username, new Password(password.toString()), roles);
    if (_cacheDuration > 0) {
        USERINFOCACHE.put(cacheToken,
                new CachedUserInfo(userInfo, System.currentTimeMillis() + _cacheDuration));
        debug("Adding " + username + " set to expire: " + System.currentTimeMillis() + _cacheDuration);
    }
    JAASUserInfo jaasUserInfo = new JAASUserInfo(userInfo);
    try {
        jaasUserInfo.fetchRoles();
    } catch (Exception ex) {
        if (_debug) {
            LOG.debug("Failed to fetch roles", ex);
        }
        throw new LoginException("Error obtaining user info.");
    }
    setCurrentUser(jaasUserInfo);
    setAuthenticated(true);
    return true;
}

From source file:org.swordess.ldap.odm.core.SessionImpl.java

@Override
public <T> List<T> search(Class<T> clazz, String filter) {
    if (null == filter) {
        return null;
    }//from w w  w  .  j a  va  2  s  . co m

    LogUtils.debug(LOG, "search " + clazz.getName() + " with filter=" + filter);

    SearchControls ctrl = new SearchControls();
    ctrl.setSearchScope(SearchControls.SUBTREE_SCOPE);
    ctrl.setReturningAttributes(EntityMetaData.getDefinedAttrNames(clazz));

    List<T> retVal = new ArrayList<T>();
    try {
        NamingEnumeration<SearchResult> results = ctx.search(EntityMetaData.get(clazz).context(), filter, ctrl);
        while (results.hasMore()) {
            try {
                SearchResult result = results.next();
                T entity = null;
                if (sessionCache.containsKey(result.getNameInNamespace())) {
                    // guarantee the reference integrity for one search result
                    entity = (T) sessionCache.get(result.getNameInNamespace());
                } else {
                    entity = fromAttributesToEntity(clazz, result.getAttributes());
                    sessionCache.put(result.getNameInNamespace(), entity);
                }
                retVal.add(entity);
            } catch (NamingException e) {
                LogUtils.error(LOG, "Unable to construct the entity", e);
            }
        }
    } catch (NamingException e) {
        throw new SessionException(e.getMessage(), e);
    }
    return retVal;
}

From source file:edu.internet2.middleware.psp.ldap.LdapSpmlTarget.java

/** {@inheritDoc} */
public void execute(LookupRequest lookupRequest, LookupResponse lookupResponse) {

    Ldap ldap = null;//from w w  w  .j a v  a2s .c  o  m
    try {
        // will not return AD Range option attrs
        // Attributes attributes = ldap.getAttributes(escapedDn, retAttrs);

        SearchFilter sf = new SearchFilter();
        sf.setFilter("objectclass=*");
        SearchControls sc = new SearchControls();
        sc.setSearchScope(SearchControls.OBJECT_SCOPE);

        // This lookup requests attributes defined for *all* objects.
        // Perhaps there should be two searches, one for the identifier
        // and a second for attributes.
        String[] retAttrs = getPSP().getNames(getId(), lookupRequest.getReturnData()).toArray(new String[] {});
        sc.setReturningAttributes(retAttrs);

        // TODO logging
        String dn = lookupRequest.getPsoID().getID();
        String escapedDn = LdapSpmlTarget.escapeForwardSlash(dn);

        ldap = ldapPool.checkOut();

        LOG.debug("Target '{}' - Searching '{}'", getId(), PSPUtil.toString(lookupRequest));
        Iterator<SearchResult> searchResults = ldap.search(escapedDn, sf, sc);
        LOG.debug("Target '{}' - Searched '{}'", getId(), PSPUtil.toString(lookupRequest));

        if (!searchResults.hasNext()) {
            fail(lookupResponse, ErrorCode.NO_SUCH_IDENTIFIER);
            return;
        }

        SearchResult result = searchResults.next();

        if (searchResults.hasNext()) {
            fail(lookupResponse, ErrorCode.CUSTOM_ERROR, "More than one result found.");
            return;
        }
        Attributes attributes = result.getAttributes();

        // return attributes in order defined by config
        OrderedLdapBeanFactory orderedLdapBeanFactory = new OrderedLdapBeanFactory();
        // sort values
        SortedLdapBeanFactory sortedLdapBeanFactory = new SortedLdapBeanFactory();

        LdapAttributes ldapAttributes = orderedLdapBeanFactory.newLdapAttributes();
        for (String retAttr : retAttrs) {
            Attribute attr = attributes.get(retAttr);
            if (attr != null) {
                LdapAttribute ldapAttribute = sortedLdapBeanFactory.newLdapAttribute();
                ldapAttribute.setAttribute(attr);
                ldapAttributes.addAttribute(ldapAttribute);
            }
        }

        LdapEntry entry = sortedLdapBeanFactory.newLdapEntry();
        entry.setDn(dn);
        entry.setLdapAttributes(ldapAttributes);

        if (this.isLogLdif()) {
            LdapResult lr = sortedLdapBeanFactory.newLdapResult();
            lr.addEntry(entry);
            LdifResultConverter lrc = new LdifResultConverter();
            LOG.info("Target '{}' - LDIF\n{}", getId(), lrc.toLdif(lr));
        }

        // build pso
        lookupResponse.setPso(getPSO(entry, lookupRequest.getReturnData()));

    } catch (NameNotFoundException e) {
        fail(lookupResponse, ErrorCode.NO_SUCH_IDENTIFIER);
    } catch (LdapPoolException e) {
        fail(lookupResponse, ErrorCode.CUSTOM_ERROR, e);
    } catch (InvalidNameException e) {
        fail(lookupResponse, ErrorCode.CUSTOM_ERROR, e);
    } catch (NamingException e) {
        fail(lookupResponse, ErrorCode.CUSTOM_ERROR, e);
    } catch (DSMLProfileException e) {
        fail(lookupResponse, ErrorCode.CUSTOM_ERROR, e);
    } catch (Spml2Exception e) {
        fail(lookupResponse, ErrorCode.CUSTOM_ERROR, e);
    } catch (PspException e) {
        fail(lookupResponse, ErrorCode.CUSTOM_ERROR, e);
    } finally {
        if (ldap != null) {
            ldapPool.checkIn(ldap);
        }
    }
}

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

/**
 * Store new links using the LDAP staticAttributeId strategy.
 *
 * @see org.nuxeo.ecm.directory.Reference#addLinks(String, List)
 *//* ww  w. j  a v a 2 s . c  om*/
@Override
public void addLinks(String sourceId, List<String> targetIds) throws DirectoryException {

    if (targetIds.isEmpty()) {
        // optim: nothing to do, return silently without further creating
        // session instances
        return;
    }

    LDAPDirectory ldapTargetDirectory = (LDAPDirectory) getTargetDirectory();
    LDAPDirectory ldapSourceDirectory = (LDAPDirectory) getSourceDirectory();
    String attributeId = getStaticAttributeId();
    if (attributeId == null) {
        if (log.isTraceEnabled()) {
            log.trace(String.format("trying to edit a non-static reference from %s in directory %s: ignoring",
                    sourceId, ldapSourceDirectory.getName()));
        }
        return;
    }
    try (LDAPSession targetSession = (LDAPSession) ldapTargetDirectory.getSession();
            LDAPSession sourceSession = (LDAPSession) ldapSourceDirectory.getSession()) {
        // fetch the entry to be able to run the security policy
        // implemented in an entry adaptor
        DocumentModel sourceEntry = sourceSession.getEntry(sourceId, false);
        if (sourceEntry == null) {
            throw new DirectoryException(String.format("could not add links from unexisting %s in directory %s",
                    sourceId, ldapSourceDirectory.getName()));
        }
        if (!BaseSession.isReadOnlyEntry(sourceEntry)) {
            SearchResult ldapEntry = sourceSession.getLdapEntry(sourceId);

            String sourceDn = ldapEntry.getNameInNamespace();
            Attribute storedAttr = ldapEntry.getAttributes().get(attributeId);
            String emptyRefMarker = ldapSourceDirectory.getDescriptor().getEmptyRefMarker();
            Attribute attrToAdd = new BasicAttribute(attributeId);
            for (String targetId : targetIds) {
                if (staticAttributeIdIsDn) {
                    // TODO optim: avoid LDAP search request when targetDn
                    // can be forged client side (rdnAttribute = idAttribute and scope is onelevel)
                    ldapEntry = targetSession.getLdapEntry(targetId);
                    if (ldapEntry == null) {
                        log.warn(String.format(
                                "entry '%s' in directory '%s' not found: could not add link from '%s' in directory '%s' for '%s'",
                                targetId, ldapTargetDirectory.getName(), sourceId,
                                ldapSourceDirectory.getName(), this));
                        continue;
                    }
                    String dn = ldapEntry.getNameInNamespace();
                    if (storedAttr == null || !storedAttr.contains(dn)) {
                        attrToAdd.add(dn);
                    }
                } else {
                    if (storedAttr == null || !storedAttr.contains(targetId)) {
                        attrToAdd.add(targetId);
                    }
                }
            }
            if (attrToAdd.size() > 0) {
                try {
                    // do the LDAP request to store missing dns
                    Attributes attrsToAdd = new BasicAttributes();
                    attrsToAdd.put(attrToAdd);

                    if (log.isDebugEnabled()) {
                        log.debug(String.format(
                                "LDAPReference.addLinks(%s, [%s]): LDAP modifyAttributes dn='%s' "
                                        + "mod_op='ADD_ATTRIBUTE' attrs='%s' [%s]",
                                sourceId, StringUtils.join(targetIds, ", "), sourceDn, attrsToAdd, this));
                    }
                    sourceSession.dirContext.modifyAttributes(sourceDn, DirContext.ADD_ATTRIBUTE, attrsToAdd);

                    // robustly clean any existing empty marker now that we are sure that the list in not empty
                    if (storedAttr.contains(emptyRefMarker)) {
                        Attributes cleanAttrs = new BasicAttributes(attributeId, emptyRefMarker);

                        if (log.isDebugEnabled()) {
                            log.debug(String.format(
                                    "LDAPReference.addLinks(%s, [%s]): LDAP modifyAttributes dn='%s'"
                                            + " mod_op='REMOVE_ATTRIBUTE' attrs='%s' [%s]",
                                    sourceId, StringUtils.join(targetIds, ", "), sourceDn, cleanAttrs, this));
                        }
                        sourceSession.dirContext.modifyAttributes(sourceDn, DirContext.REMOVE_ATTRIBUTE,
                                cleanAttrs);
                    }
                } catch (SchemaViolationException e) {
                    if (isDynamic()) {
                        // we are editing an entry that has no static part
                        log.warn(String.format("cannot update dynamic reference in field %s for source %s",
                                getFieldName(), sourceId));
                    } else {
                        // this is a real schema configuration problem,
                        // wrap up the exception
                        throw new DirectoryException(e);
                    }
                }
            }
        }
    } catch (NamingException e) {
        throw new DirectoryException("addLinks failed: " + e.getMessage(), e);
    }
}

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 w w  . j a va  2s.c  om
    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.apache.ranger.ldapusersync.process.LdapDeltaUserGroupBuilder.java

private void goUpGroupHierarchyLdap(Set<String> groupDNs, int groupHierarchyLevels) throws Throwable {
    if (groupHierarchyLevels <= 0 || groupDNs.isEmpty()) {
        return;/* w  w w  .j  a  v a 2  s .c o m*/
    }
    Set<String> nextLevelGroups = new HashSet<String>();

    NamingEnumeration<SearchResult> groupSearchResultEnum = null;
    try {
        createLdapContext();
        int total;
        // Activate paged results
        if (pagedResultsEnabled) {
            ldapContext.setRequestControls(
                    new Control[] { new PagedResultsControl(pagedResultsSize, Control.NONCRITICAL) });
        }
        String groupFilter = "(&(objectclass=" + groupObjectClass + ")";
        if (groupSearchFilter != null && !groupSearchFilter.trim().isEmpty()) {
            String customFilter = groupSearchFilter.trim();
            if (!customFilter.startsWith("(")) {
                customFilter = "(" + customFilter + ")";
            }
            groupFilter += customFilter + "(|";
        }
        StringBuilder filter = new StringBuilder();

        for (String groupDN : groupDNs) {
            filter.append("(").append(groupMemberAttributeName).append("=").append(groupDN).append(")");
        }
        filter.append("))");
        groupFilter += filter;

        LOG.info("extendedAllGroupsSearchFilter = " + groupFilter);
        for (int ou = 0; ou < groupSearchBase.length; ou++) {
            byte[] cookie = null;
            int counter = 0;
            try {
                do {
                    groupSearchResultEnum = ldapContext.search(groupSearchBase[ou], groupFilter,
                            groupSearchControls);
                    while (groupSearchResultEnum.hasMore()) {
                        final SearchResult groupEntry = groupSearchResultEnum.next();
                        if (groupEntry == null) {
                            if (LOG.isInfoEnabled()) {
                                LOG.info("groupEntry null, skipping sync for the entry");
                            }
                            continue;
                        }
                        counter++;
                        Attribute groupNameAttr = groupEntry.getAttributes().get(groupNameAttribute);
                        if (groupNameAttr == null) {
                            if (LOG.isInfoEnabled()) {
                                LOG.info(groupNameAttribute + " empty for entry "
                                        + groupEntry.getNameInNamespace() + ", skipping sync");
                            }
                            continue;
                        }
                        nextLevelGroups.add(groupEntry.getNameInNamespace());
                        String gName = (String) groupNameAttr.get();

                        Attribute groupMemberAttr = groupEntry.getAttributes().get(groupMemberAttributeName);
                        int userCount = 0;
                        if (groupMemberAttr == null || groupMemberAttr.size() <= 0) {
                            LOG.info("No members available for " + gName);
                            continue;
                        }

                        NamingEnumeration<?> userEnum = groupMemberAttr.getAll();
                        while (userEnum.hasMore()) {
                            String originalUserFullName = (String) userEnum.next();
                            if (originalUserFullName == null || originalUserFullName.trim().isEmpty()) {
                                continue;
                            }
                            userCount++;
                            originalUserFullName = originalUserFullName.toLowerCase();
                            if (userNameMap.get(originalUserFullName) != null) {
                                groupUserTable.put(gName, originalUserFullName,
                                        userNameMap.get(originalUserFullName));
                            } else {
                                groupUserTable.put(gName, originalUserFullName, originalUserFullName);
                            }
                            groupNameMap.put(groupEntry.getNameInNamespace().toLowerCase(), gName);
                        }
                        LOG.info("No. of members in the group " + gName + " = " + userCount);
                    }
                    // Examine the paged results control response
                    Control[] controls = ldapContext.getResponseControls();
                    if (controls != null) {
                        for (int i = 0; i < controls.length; i++) {
                            if (controls[i] instanceof PagedResultsResponseControl) {
                                PagedResultsResponseControl prrc = (PagedResultsResponseControl) controls[i];
                                total = prrc.getResultSize();
                                if (total != 0) {
                                    LOG.debug("END-OF-PAGE total : " + total);
                                } else {
                                    LOG.debug("END-OF-PAGE total : unknown");
                                }
                                cookie = prrc.getCookie();
                            }
                        }
                    } else {
                        LOG.debug("No controls were sent from the server");
                    }
                    // Re-activate paged results
                    if (pagedResultsEnabled) {
                        ldapContext.setRequestControls(new Control[] {
                                new PagedResultsControl(pagedResultsSize, cookie, Control.CRITICAL) });
                    }
                } while (cookie != null);
                LOG.info("LdapDeltaUserGroupBuilder.goUpGroupHierarchyLdap() completed with group count: "
                        + counter);
            } catch (RuntimeException re) {
                LOG.error("LdapDeltaUserGroupBuilder.goUpGroupHierarchyLdap() failed with runtime exception: ",
                        re);
                throw re;
            } catch (Exception t) {
                LOG.error("LdapDeltaUserGroupBuilder.goUpGroupHierarchyLdap() failed with exception: ", t);
                LOG.info("LdapDeltaUserGroupBuilder.goUpGroupHierarchyLdap() group count: " + counter);
            }
        }

    } catch (RuntimeException re) {
        LOG.error("LdapDeltaUserGroupBuilder.goUpGroupHierarchyLdap() failed with exception: ", re);
        throw re;
    } finally {
        if (groupSearchResultEnum != null) {
            groupSearchResultEnum.close();
        }
        closeLdapContext();
    }
    goUpGroupHierarchyLdap(nextLevelGroups, groupHierarchyLevels - 1);
}

From source file:org.apache.ranger.ldapusersync.process.LdapDeltaUserGroupBuilder.java

private void getGroups(UserGroupSink sink) throws Throwable {
    NamingEnumeration<SearchResult> groupSearchResultEnum = null;
    DateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
    long highestdeltaSyncGroupTime = deltaSyncGroupTime;
    try {//from  ww w .  jav  a2  s . co  m
        createLdapContext();
        int total;
        // Activate paged results
        if (pagedResultsEnabled) {
            ldapContext.setRequestControls(
                    new Control[] { new PagedResultsControl(pagedResultsSize, Control.NONCRITICAL) });
        }
        extendedGroupSearchFilter = "(objectclass=" + groupObjectClass + ")";
        if (groupSearchFilter != null && !groupSearchFilter.trim().isEmpty()) {
            String customFilter = groupSearchFilter.trim();
            if (!customFilter.startsWith("(")) {
                customFilter = "(" + customFilter + ")";
            }
            extendedGroupSearchFilter = extendedGroupSearchFilter + customFilter;
        }

        extendedAllGroupsSearchFilter = "(&" + extendedGroupSearchFilter + "(|(uSNChanged>="
                + deltaSyncGroupTime + ")(modifyTimestamp>=" + deltaSyncGroupTimeStamp + "Z)))";

        LOG.info("extendedAllGroupsSearchFilter = " + extendedAllGroupsSearchFilter);
        for (int ou = 0; ou < groupSearchBase.length; ou++) {
            byte[] cookie = null;
            int counter = 0;
            try {
                int paged = 0;
                do {
                    groupSearchResultEnum = ldapContext.search(groupSearchBase[ou],
                            extendedAllGroupsSearchFilter, groupSearchControls);
                    while (groupSearchResultEnum.hasMore()) {
                        final SearchResult groupEntry = groupSearchResultEnum.next();
                        if (groupEntry == null) {
                            if (LOG.isInfoEnabled()) {
                                LOG.info("groupEntry null, skipping sync for the entry");
                            }
                            continue;
                        }
                        counter++;
                        Attribute groupNameAttr = groupEntry.getAttributes().get(groupNameAttribute);
                        if (groupNameAttr == null) {
                            if (LOG.isInfoEnabled()) {
                                LOG.info(groupNameAttribute + " empty for entry "
                                        + groupEntry.getNameInNamespace() + ", skipping sync");
                            }
                            continue;
                        }
                        String gName = (String) groupNameAttr.get();
                        String transformGroupName = groupNameTransform(gName);
                        // If group based search is enabled, then
                        // update the group name to ranger admin
                        // check for group members and populate userInfo object with user's full name and group mapping
                        if (groupSearchFirstEnabled) {
                            LOG.debug("Update Ranger admin with " + transformGroupName);
                            sink.addOrUpdateGroup(transformGroupName);
                        }
                        Attribute timeStampAttr = groupEntry.getAttributes().get("uSNChanged");
                        if (timeStampAttr != null) {
                            String uSNChangedVal = (String) timeStampAttr.get();
                            long currentDeltaSyncTime = Long.parseLong(uSNChangedVal);
                            if (currentDeltaSyncTime > highestdeltaSyncGroupTime) {
                                highestdeltaSyncGroupTime = currentDeltaSyncTime;
                            }
                        } else {
                            timeStampAttr = groupEntry.getAttributes().get("modifytimestamp");
                            if (timeStampAttr != null) {
                                String timeStampVal = (String) timeStampAttr.get();
                                Date parseDate = dateFormat.parse(timeStampVal);
                                long currentDeltaSyncTime = parseDate.getTime();
                                LOG.info("timeStampVal = " + timeStampVal + "and currentDeltaSyncTime = "
                                        + currentDeltaSyncTime);
                                if (currentDeltaSyncTime > highestdeltaSyncGroupTime) {
                                    highestdeltaSyncGroupTime = currentDeltaSyncTime;
                                    deltaSyncGroupTimeStamp = timeStampVal;
                                }
                            }
                        }
                        Attribute groupMemberAttr = groupEntry.getAttributes().get(groupMemberAttributeName);
                        int userCount = 0;
                        if (groupMemberAttr == null || groupMemberAttr.size() <= 0) {
                            LOG.info("No members available for " + gName);
                            continue;
                        }

                        NamingEnumeration<?> userEnum = groupMemberAttr.getAll();
                        while (userEnum.hasMore()) {
                            String originalUserFullName = (String) userEnum.next();
                            if (originalUserFullName == null || originalUserFullName.trim().isEmpty()) {
                                continue;
                            }
                            userCount++;
                            String userName = getShortUserName(originalUserFullName);
                            originalUserFullName = originalUserFullName.toLowerCase();
                            if (groupSearchFirstEnabled && !userSearchEnabled) {
                                String transformUserName = userNameTransform(userName);
                                try {
                                    sink.addOrUpdateUser(transformUserName);
                                } catch (Throwable t) {
                                    LOG.error("sink.addOrUpdateUser failed with exception: " + t.getMessage()
                                            + ", for user: " + transformUserName);
                                }
                                userNameMap.put(originalUserFullName, transformUserName);
                            }
                            //System.out.println("Adding " + userNameMap.get(originalUserFullName) + " and fullname = " + originalUserFullName + " to " + gName);
                            if (userNameMap.get(originalUserFullName) != null) {
                                groupUserTable.put(gName, originalUserFullName,
                                        userNameMap.get(originalUserFullName));
                            } else {
                                groupUserTable.put(gName, originalUserFullName, originalUserFullName);
                            }
                            groupNameMap.put(groupEntry.getNameInNamespace().toLowerCase(), gName);
                        }
                        LOG.info("No. of members in the group " + gName + " = " + userCount);
                    }
                    // Examine the paged results control response
                    Control[] controls = ldapContext.getResponseControls();
                    if (controls != null) {
                        for (int i = 0; i < controls.length; i++) {
                            if (controls[i] instanceof PagedResultsResponseControl) {
                                PagedResultsResponseControl prrc = (PagedResultsResponseControl) controls[i];
                                total = prrc.getResultSize();
                                if (total != 0) {
                                    LOG.debug("END-OF-PAGE total : " + total);
                                } else {
                                    LOG.debug("END-OF-PAGE total : unknown");
                                }
                                cookie = prrc.getCookie();
                            }
                        }
                    } else {
                        LOG.debug("No controls were sent from the server");
                    }
                    // Re-activate paged results
                    if (pagedResultsEnabled) {
                        LOG.debug(String.format("Fetched paged results round: %s", ++paged));
                        ldapContext.setRequestControls(new Control[] {
                                new PagedResultsControl(pagedResultsSize, cookie, Control.CRITICAL) });
                    }
                } while (cookie != null);
                LOG.info("LdapDeltaUserGroupBuilder.getGroups() completed with group count: " + counter);
            } catch (Exception t) {
                LOG.error("LdapDeltaUserGroupBuilder.getGroups() failed with exception: " + t);
                LOG.info("LdapDeltaUserGroupBuilder.getGroups() group count: " + counter);
            }
        }

    } finally {
        if (groupSearchResultEnum != null) {
            groupSearchResultEnum.close();
        }
        closeLdapContext();
    }

    if (groupHierarchyLevels > 0) {
        LOG.debug("deltaSyncGroupTime = " + deltaSyncGroupTime);
        if (deltaSyncGroupTime > 0) {
            LOG.info(
                    "LdapDeltaUserGroupBuilder.getGroups(): Going through group hierarchy for nested group evaluation for deltasync");
            goUpGroupHierarchyLdap(groupNameMap.keySet(), groupHierarchyLevels - 1);
        }
    }

    if (deltaSyncGroupTime < highestdeltaSyncGroupTime) {
        // Incrementing highestdeltaSyncGroupTime (for AD) in order to avoid search record repetition for next sync cycle.
        deltaSyncGroupTime = highestdeltaSyncGroupTime + 1;
        // Incrementing the highest timestamp value (for OpenLdap) with 1min in order to avoid search record repetition for next sync cycle.
        deltaSyncGroupTimeStamp = dateFormat.format(new Date(highestdeltaSyncGroupTime + 60000l));
    }
}

From source file:org.josso.gateway.identity.service.store.ldap.LDAPIdentityStore.java

/**
 * Fetches the supplied user DN.//from   w  w w .  j  av  a  2  s .c  o  m
 *
 * @param uid the user id
 * @return the user DN for the supplied uid
 * @throws NamingException LDAP error obtaining user information.
 * @throws IOException 
 */
protected String selectUserDN(String uid) throws NamingException, IOException {

    String dn = null;

    InitialLdapContext ctx = createLdapInitialContext(false);

    StartTlsResponse tls = null;
    if (getEnableStartTls()) {
        tls = startTls(ctx);
    }

    String principalUidAttrName = 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, "(&(" + principalUidAttrName + "=" + uid + "))",
                getSearchControls());

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

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

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

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

    return dn;

}