Example usage for javax.naming NamingEnumeration next

List of usage examples for javax.naming NamingEnumeration next

Introduction

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

Prototype

public T next() throws NamingException;

Source Link

Document

Retrieves the next element in the enumeration.

Usage

From source file:org.archone.ad.domain.LdapActions.java

@RPCAction(name = "user.membership.get", required = { "userId" })
@SecuredMethod(constraints = "administrator.by_domain")
public HashMap<String, Object> listMermbershipGroups(OperationContext opContext) throws NamingException {

    String userId = (String) opContext.getParams().get("userId");

    UserDn userDn = nameHelper.newUserDnFromId(userId);
    DomainDn domainDn = nameHelper.newDomainDnFromDomain(userDn.getDomain());

    DirContextAdapter userDirContext = (DirContextAdapter) SecurityUtils.getSubject().getPrincipal();

    SearchControls controls = new SearchControls();
    controls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    NamingEnumeration<SearchResult> searchResults = userDirContext.search(
            nameHelper.getGroupsBaseDn(nameHelper.newDomainDnFromDomain(userDn.getDomain())),
            "(uniqueMember=" + userDn.toString() + ")", controls);

    List<HashMap<String, Object>> groups = new LinkedList<HashMap<String, Object>>();
    while (searchResults.hasMore()) {
        SearchResult sr = searchResults.next();
        if (nameHelper.isGroupDn(sr.getNameInNamespace().toLowerCase())) {
            HashMap<String, Object> group = new HashMap<String, Object>();
            group.put("groupId", nameHelper.newGroupDn(sr.getNameInNamespace().toLowerCase()).getAsGroupId());
            groups.add(group);/*from  w w  w .  jav  a  2s .co  m*/
        }
    }

    HashMap<String, Object> response = new HashMap<String, Object>();
    response.put("groups", groups);

    return response;
}

From source file:net.spfbl.core.Analise.java

public static TreeSet<String> getIPSet(String hostname) {
    TreeSet<String> ipSet = new TreeSet<String>();
    try {//ww w  . j a v a 2s .c o m
        Attributes attributesA = Server.getAttributesDNS(hostname, new String[] { "A" });
        if (attributesA != null) {
            Enumeration enumerationA = attributesA.getAll();
            while (enumerationA.hasMoreElements()) {
                Attribute attributeA = (Attribute) enumerationA.nextElement();
                NamingEnumeration enumeration = attributeA.getAll();
                while (enumeration.hasMoreElements()) {
                    String address = (String) enumeration.next();
                    if (SubnetIPv4.isValidIPv4(address)) {
                        address = SubnetIPv4.normalizeIPv4(address);
                        ipSet.add(address);
                    }
                }
            }
        }
        Attributes attributesAAAA = Server.getAttributesDNS(hostname, new String[] { "AAAA" });
        if (attributesAAAA != null) {
            Enumeration enumerationAAAA = attributesAAAA.getAll();
            while (enumerationAAAA.hasMoreElements()) {
                Attribute attributeAAAA = (Attribute) enumerationAAAA.nextElement();
                NamingEnumeration enumeration = attributeAAAA.getAll();
                while (enumeration.hasMoreElements()) {
                    String address = (String) enumeration.next();
                    if (SubnetIPv6.isValidIPv6(address)) {
                        address = SubnetIPv6.normalizeIPv6(address);
                        ipSet.add(address);
                    }
                }
            }
        }
    } catch (NameNotFoundException ex) {
        return null;
    } catch (NamingException ex) {
        // Ignore.
    }
    return ipSet;
}

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

protected Set<PrivilegeEnum> convertLdapGroupsToOrganizationPrivileges(
        NamingEnumeration<SearchResult> pPrivilegesResult) {
    Set<PrivilegeEnum> vResult = EnumSet.noneOf(PrivilegeEnum.class);
    NamingEnumeration<SearchResult> vSearchResults = pPrivilegesResult;
    try {/*from   www .  jav a2  s  . c  o  m*/
        if (pPrivilegesResult != null) {
            PrivilegeEnum p;
            SearchResult sr;
            String vCnPrivileg;
            // construct privileges
            while (vSearchResults.hasMore()) {
                sr = vSearchResults.next();
                vCnPrivileg = (String) sr.getAttributes().get(Constants.ldap_ddbPrivilege_Cn).get();
                p = this.mapToPrivilege(sr.getAttributes(), Constants.ldap_ddbPrivilege_Cn);
                if (p != null) {
                    vResult.add(p);
                } else {
                    LOG.log(Level.WARNING,
                            "Es ist ein nicht existierende Privileg: ''{0}'' im LDAP gespeichert!",
                            new Object[] { vCnPrivileg });
                }
            }
            // -- releases this context's resources immediately, instead of
            // waiting for the garbage collector
            vSearchResults.close();
        }
    } catch (NamingException ne) {
        LOG.log(Level.SEVERE, null, ne);
    } finally {
        // -- releases this context's resources immediately, instead of
        // waiting for the garbage collector
        if (vSearchResults != null) {
            try {
                vSearchResults.close();
            } catch (NamingException ex) {
            }
        }
    }
    return vResult;
}

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

private String lookupUserId(String serverName) throws DirectoryServerManagerException {

    DirContext dirContext;/*from   w ww .  jav a 2  s. c om*/
    try {
        dirContext = this.connectionSource.getContext();
    } catch (UserStoreException e) {
        throw new DirectoryServerManagerException("Unable to retrieve directory connection.", e);
    }

    String searchBase = this.realmConfiguration.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE);

    //first search the existing user entry.
    String searchFilter = getServicePrincipleFilter(serverName);

    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    searchControls.setReturningAttributes(new String[] { "uid" });
    try {
        NamingEnumeration<SearchResult> namingEnumeration = dirContext.search(searchBase, searchFilter,
                searchControls);

        // here we assume only one user
        if (namingEnumeration.hasMore()) {

            SearchResult searchResult;

            searchResult = namingEnumeration.next();

            Attributes attributes = searchResult.getAttributes();

            Attribute userId = attributes.get("uid");
            return (String) userId.get();
        } else {
            return null;
        }

    } catch (NamingException e) {
        log.error("Could not find user id for given server " + serverName, e);
        throw new DirectoryServerManagerException("Could not find user id for given server " + serverName, e);
    } finally {
        try {
            JNDIUtil.closeContext(dirContext);
        } catch (UserStoreException e) {
            log.error("Unable to close directory context.", e);
        }
    }

}

From source file:com.nridge.core.app.ldap.ADQuery.java

/**
 * Queries Active Directory for attributes defined within the bag.
 * The LDAP_ACCOUNT_NAME field must be populated prior to invoking
 * this method.  Any site specific fields can be assigned to the
 * bag will be included in the attribute query.
 *
 * @param aUserBag Active Directory user fields.
 *
 * @throws NSException Thrown if an LDAP naming exception is occurs.
 *///from w  w  w  .  j  av a2  s.c o m
public void loadUserByAccountName(DataBag aUserBag) throws NSException {
    byte[] objectSid;
    Attribute responseAttribute;
    String fieldName, fieldValue;
    Attributes responseAttributes;
    Logger appLogger = mAppMgr.getLogger(this, "loadUserByAccountName");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    if (mLdapContext == null) {
        String msgStr = "LDAP context has not been established.";
        appLogger.error(msgStr);
        throw new NSException(msgStr);
    }

    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    int field = 0;
    String accountName = null;
    int attrCount = aUserBag.count();
    String[] ldapAttrNames = new String[attrCount];
    for (DataField dataField : aUserBag.getFields()) {
        fieldName = dataField.getName();
        if (fieldName.equals(LDAP_ACCOUNT_NAME))
            accountName = dataField.getValueAsString();
        ldapAttrNames[field++] = fieldName;
    }
    searchControls.setReturningAttributes(ldapAttrNames);

    if (accountName == null) {
        String msgStr = String.format("LDAP account name '%s' is unassigned.", LDAP_ACCOUNT_NAME);
        appLogger.error(msgStr);
        throw new NSException(msgStr);
    }

    String userSearchBaseDN = getPropertyValue("user_searchbasedn", null);
    String userSearchFilter = String.format("(&(objectClass=user)(%s=%s))", LDAP_ACCOUNT_NAME, accountName);
    try {
        NamingEnumeration<?> searchResponse = mLdapContext.search(userSearchBaseDN, userSearchFilter,
                searchControls);
        if ((searchResponse != null) && (searchResponse.hasMore())) {
            responseAttributes = ((SearchResult) searchResponse.next()).getAttributes();
            for (DataField complexField : aUserBag.getFields()) {
                fieldName = complexField.getName();
                responseAttribute = responseAttributes.get(fieldName);
                if (responseAttribute != null) {
                    if (fieldName.equals(LDAP_OBJECT_SID)) {
                        objectSid = (byte[]) responseAttribute.get();
                        fieldValue = objectSidToString2(objectSid);
                    } else
                        fieldValue = (String) responseAttribute.get();
                    if (StringUtils.isNotEmpty(fieldValue))
                        complexField.setValue(fieldValue);
                }
            }
            searchResponse.close();
        }
    } catch (NamingException e) {
        String msgStr = String.format("LDAP Search Error (%s): %s", userSearchFilter, e.getMessage());
        appLogger.error(msgStr, e);
        throw new NSException(msgStr);
    }

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);
}

From source file:com.nridge.core.app.ldap.ADQuery.java

/**
 * Queries Active Directory for attributes defined within the bag.
 * The LDAP_COMMON_NAME field must be populated prior to invoking
 * this method.  Any site specific fields can be assigned to the
 * bag will be included in the attribute query.
 *
 * @param aUserBag Active Directory user fields.
 *
 * @throws NSException Thrown if an LDAP naming exception is occurs.
 *///from   w w w .  ja v  a  2 s.  com
public void loadUserByCommonName(DataBag aUserBag) throws NSException {
    byte[] objectSid;
    Attribute responseAttribute;
    String fieldName, fieldValue;
    Attributes responseAttributes;
    Logger appLogger = mAppMgr.getLogger(this, "loadUserByCommonName");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    if (mLdapContext == null) {
        String msgStr = "LDAP context has not been established.";
        appLogger.error(msgStr);
        throw new NSException(msgStr);
    }

    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    int field = 0;
    String commonName = null;
    int attrCount = aUserBag.count();
    String[] ldapAttrNames = new String[attrCount];
    for (DataField complexField : aUserBag.getFields()) {
        fieldName = complexField.getName();
        if (fieldName.equals(LDAP_COMMON_NAME))
            commonName = complexField.getValueAsString();
        ldapAttrNames[field++] = fieldName;
    }
    searchControls.setReturningAttributes(ldapAttrNames);

    if (commonName == null) {
        String msgStr = String.format("LDAP common name '%s' is unassigned.", LDAP_COMMON_NAME);
        appLogger.error(msgStr);
        throw new NSException(msgStr);
    }

    String userSearchBaseDN = getPropertyValue("user_searchbasedn", null);
    String userSearchFilter = String.format("(&(objectClass=user)(%s=%s))", LDAP_COMMON_NAME, commonName);
    try {
        NamingEnumeration<?> searchResponse = mLdapContext.search(userSearchBaseDN, userSearchFilter,
                searchControls);
        if ((searchResponse != null) && (searchResponse.hasMore())) {
            responseAttributes = ((SearchResult) searchResponse.next()).getAttributes();
            for (DataField complexField : aUserBag.getFields()) {
                fieldName = complexField.getName();
                responseAttribute = responseAttributes.get(fieldName);
                if (responseAttribute != null) {
                    if (fieldName.equals(LDAP_OBJECT_SID)) {
                        objectSid = (byte[]) responseAttribute.get();
                        fieldValue = objectSidToString2(objectSid);
                    } else
                        fieldValue = (String) responseAttribute.get();
                    if (StringUtils.isNotEmpty(fieldValue))
                        complexField.setValue(fieldValue);
                }
            }
            searchResponse.close();
        }
    } catch (NamingException e) {
        String msgStr = String.format("LDAP Search Error (%s): %s", userSearchFilter, e.getMessage());
        appLogger.error(msgStr, e);
        throw new NSException(msgStr);
    }

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);
}

From source file:com.nridge.core.app.ldap.ADQuery.java

/**
 * Queries Active Directory for attributes defined within the bag.
 * The LDAP_ACCOUNT_NAME field must be populated prior to invoking
 * this method.  Any site specific fields can be assigned to the
 * bag will be included in the attribute query.
 *
 * @param aGroupBag Active Directory group fields.
 *
 * @throws NSException Thrown if an LDAP naming exception is occurs.
 *//*from   w  ww.j a v a2 s.  c om*/
public void loadGroupByAccountName(DataBag aGroupBag) throws NSException {
    byte[] objectSid;
    Attribute responseAttribute;
    String fieldName, fieldValue;
    Attributes responseAttributes;
    Logger appLogger = mAppMgr.getLogger(this, "loadGroupByAccountName");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    if (mLdapContext == null) {
        String msgStr = "LDAP context has not been established.";
        appLogger.error(msgStr);
        throw new NSException(msgStr);
    }

    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    int field = 0;
    String accountName = null;
    int attrCount = aGroupBag.count();
    String[] ldapAttrNames = new String[attrCount];
    for (DataField complexField : aGroupBag.getFields()) {
        fieldName = complexField.getName();
        if (fieldName.equals(LDAP_ACCOUNT_NAME))
            accountName = complexField.getValueAsString();
        ldapAttrNames[field++] = fieldName;
    }
    searchControls.setReturningAttributes(ldapAttrNames);

    if (accountName == null) {
        String msgStr = String.format("LDAP account name '%s' is unassigned.", LDAP_ACCOUNT_NAME);
        appLogger.error(msgStr);
        throw new NSException(msgStr);
    }

    String groupSearchBaseDN = getPropertyValue("group_searchbasedn", null);
    String groupSearchFilter = String.format("(&(objectClass=group)(%s=%s))", LDAP_ACCOUNT_NAME, accountName);
    try {
        NamingEnumeration<?> searchResponse = mLdapContext.search(groupSearchBaseDN, groupSearchFilter,
                searchControls);
        if ((searchResponse != null) && (searchResponse.hasMore())) {
            responseAttributes = ((SearchResult) searchResponse.next()).getAttributes();
            for (DataField complexField : aGroupBag.getFields()) {
                fieldName = complexField.getName();
                responseAttribute = responseAttributes.get(fieldName);
                if (responseAttribute != null) {
                    if (fieldName.equals(LDAP_OBJECT_SID)) {
                        objectSid = (byte[]) responseAttribute.get();
                        fieldValue = objectSidToString2(objectSid);
                    } else
                        fieldValue = (String) responseAttribute.get();
                    if (StringUtils.isNotEmpty(fieldValue))
                        complexField.setValue(fieldValue);
                }
            }
            searchResponse.close();
        }
    } catch (NamingException e) {
        String msgStr = String.format("LDAP Search Error (%s): %s", groupSearchFilter, e.getMessage());
        appLogger.error(msgStr, e);
        throw new NSException(msgStr);
    }

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);
}

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

protected Set<Privilege> convertLdapGroupsToOrganizationPrivilegesWithUsers(
        NamingEnumeration<SearchResult> pPrivilegesSearchResults)
        throws NamingException, IllegalAccessException {
    Set<Privilege> vResult = new HashSet<Privilege>();
    try {/*from   ww w  .ja  v  a  2  s . co m*/
        Privilege vOrgPrivilege;
        // construct privileges
        while (pPrivilegesSearchResults.hasMore()) {
            if ((vOrgPrivilege = this.convertLdapGroupToOrgPriv(pPrivilegesSearchResults.next())) != null) {
                vResult.add(vOrgPrivilege);
            }
        }
    } finally {
        // -- releases this context's resources immediately, instead of
        // waiting for the garbage collector
        if (pPrivilegesSearchResults != null) {
            try {
                pPrivilegesSearchResults.close();
            } catch (NamingException ex) {
            }
        }
    }
    return vResult;
}

From source file:org.projectforge.business.ldap.LdapDao.java

public T findById(final DirContext ctx, final Object id, final String... organizationalUnits)
        throws NamingException {
    NamingEnumeration<?> results = null;
    final SearchControls controls = new SearchControls();
    controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    final String searchBase = getSearchBase(organizationalUnits);
    final String args = "(&(objectClass=" + getObjectClass() + ")(" + getIdAttrId() + "=" + buildId(id) + "))";
    results = ctx.search(searchBase, args, controls);
    if (results.hasMore() == false) {
        return null;
    }//from   w  ww  .ja v  a2 s . c  o m
    final SearchResult searchResult = (SearchResult) results.next();
    final String dn = searchResult.getName();
    final Attributes attributes = searchResult.getAttributes();
    if (results.hasMore() == true) {
        log.error("Oups, found entries with multiple id's: " + getObjectClass() + "." + id);
    }
    return mapToObject(dn, searchBase, attributes);
}

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.");
    }/*  ww w .  ja va2s. com*/

    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;

}