Java Code Examples for javax.naming.NamingEnumeration#hasMoreElements()

The following examples show how to use javax.naming.NamingEnumeration#hasMoreElements() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LdapUtils.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
/**
 * Get the value of the Rdn with the requested key in the supplied Name.
 *
 * @param name the Name in which to search for the key.
 * @param key the attribute key to search for.
 * @return the value of the rdn corresponding to the <b>first</b> occurrence of the requested key.
 * @throws NoSuchElementException if no corresponding entry is found.
 * @since 2.0
 */
public static Object getValue(Name name, String key) {
    NamingEnumeration<? extends Attribute> allAttributes = getRdn(name, key).toAttributes().getAll();
    while (allAttributes.hasMoreElements()) {
        Attribute oneAttribute = allAttributes.nextElement();
        if(key.equalsIgnoreCase(oneAttribute.getID())) {
            try {
                return oneAttribute.get();
            } catch (javax.naming.NamingException e) {
                throw convertLdapException(e);
            }
        }
    }

    // This really shouldn't happen
    throw new NoSuchElementException("No Rdn with the requested key: '" + key + "'");
}
 
Example 2
Source File: JndiTest.java    From tomee with Apache License 2.0 6 votes vote down vote up
private void assertBindings(NamingEnumeration<Binding> namingEnumeration) {
    assertNotNull("namingEnumeration", namingEnumeration);

    Map<String, Object> map = new HashMap<String, Object>();
    while (namingEnumeration.hasMoreElements()) {
        Binding pair = namingEnumeration.nextElement();
        map.put(pair.getName(), pair.getObject());
    }

    assertTrue("OrangeRemote", map.containsKey("OrangeRemote"));
    assertTrue("OrangeRemote is FruitRemote", map.get("OrangeRemote") instanceof FruitRemote);

    assertTrue("AppleRemote", map.containsKey("AppleRemote"));
    assertTrue("AppleRemote is FruitRemote", map.get("AppleRemote") instanceof FruitRemote);

    assertTrue("PeachRemote", map.containsKey("PeachRemote"));
    assertTrue("PeachRemote is FruitRemote", map.get("PeachRemote") instanceof FruitRemote);

    assertTrue("PearRemote", map.containsKey("PearRemote"));
    assertTrue("PearRemote is FruitRemote", map.get("PearRemote") instanceof FruitRemote);

    assertTrue("PlumRemote", map.containsKey("PlumRemote"));
    assertTrue("PlumRemote is FruitRemote", map.get("PlumRemote") instanceof FruitRemote);
}
 
Example 3
Source File: LdapRepository.java    From library with Apache License 2.0 6 votes vote down vote up
/**
 * Simple version of {@link #listBy(LdapSearchOption, String, Object...)}  but this one will not map the return
 * attributes and let you do that and will not take an {@link LdapSearchOption} as template for search
 *
 * @param filter to be applied
 * @param parameters to be applied to the filter
 * @return a {@link List} of {@link Attributes} found
 */
public List<Attributes> listBy(String filter, Object... parameters) {

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

    final List<Attributes> attributes = new ArrayList<>();

    try {
        final LdapContext context = this.factory.getSystemLdapContext();

        final NamingEnumeration<SearchResult> answer = context.search(this.baseDN, filter, parameters, searchControls);

        while (answer.hasMoreElements()) {
            final SearchResult searchResult = answer.nextElement();
            attributes.add(searchResult.getAttributes());
        }
    } catch (NamingException ex) {
        throw new BusinessLogicException("error.ldap.cant-search-for-users", ex);
    }
    return attributes;
}
 
Example 4
Source File: LdapUtils.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
/**
 * Find the Rdn with the requested key in the supplied Name.
 *
 * @param name the Name in which to search for the key.
 * @param key the attribute key to search for.
 * @return the rdn corresponding to the <b>first</b> occurrence of the requested key.
 * @throws NoSuchElementException if no corresponding entry is found.
 * @since 2.0
 */
public static Rdn getRdn(Name name, String key) {
    Assert.notNull(name, "name must not be null");
    Assert.hasText(key, "key must not be blank");

    LdapName ldapName = returnOrConstructLdapNameFromName(name);

    List<Rdn> rdns = ldapName.getRdns();
    for (Rdn rdn : rdns) {
        NamingEnumeration<String> ids = rdn.toAttributes().getIDs();
        while (ids.hasMoreElements()) {
            String id = ids.nextElement();
            if(key.equalsIgnoreCase(id)) {
                return rdn;
            }
        }
    }

    throw new NoSuchElementException("No Rdn with the requested key: '" + key + "'");
}
 
Example 5
Source File: OpenLdapUserManagerImpl.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
@Override
public List<LdapUser> getUsersInGroup(String groupName, LdapContext context, Long domainId) throws NamingException {
    String attributeName = _ldapConfiguration.getGroupUniqueMemberAttribute(domainId);
    final SearchControls controls = new SearchControls();
    controls.setSearchScope(_ldapConfiguration.getScope());
    controls.setReturningAttributes(new String[] {attributeName});

    NamingEnumeration<SearchResult> result = context.search(_ldapConfiguration.getBaseDn(domainId), generateGroupSearchFilter(groupName, domainId), controls);

    final List<LdapUser> users = new ArrayList<LdapUser>();
    //Expecting only one result which has all the users
    if (result.hasMoreElements()) {
        Attribute attribute = result.nextElement().getAttributes().get(attributeName);
        NamingEnumeration<?> values = attribute.getAll();

        while (values.hasMoreElements()) {
            String userdn = String.valueOf(values.nextElement());
            try{
                users.add(getUserForDn(userdn, context, domainId));
            } catch (NamingException e){
                LOGGER.info("Userdn: " + userdn + " Not Found:: Exception message: " + e.getMessage());
            }
        }
    }

    Collections.sort(users);

    return users;
}
 
Example 6
Source File: LdapSender.java    From iaf with Apache License 2.0 5 votes vote down vote up
/**
 *Strips all the values from the attributes in <code>input</code>. This is performed to be able to delete 
 *the attributes without having to match the values. If values exist they must be exactly matched too in
 *order to delete the attribute.
 */
protected Attributes removeValuesFromAttributes(Attributes input) {
	Attributes result = new BasicAttributes(true);
	// ignore attribute name case
	NamingEnumeration enumeration = input.getIDs();
	while (enumeration.hasMoreElements()) {
		String attrId = (String) enumeration.nextElement();
		result.put(new BasicAttribute(attrId));
	}
	return result;
}
 
Example 7
Source File: ActiveDirectoryGroupRealm.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
public List<String> searchForUserName(String containString, LdapContext ldapContext,
    int numUsersToFetch)
        throws NamingException {
  List<String> userNameList = new ArrayList<>();

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

  String searchFilter = String.format("(&(objectClass=*)(%s=*%s*))", this.getUserSearchAttributeName(), containString);

  Object[] searchArguments = new Object[]{containString};

  NamingEnumeration answer = ldapContext.search(searchBase, searchFilter, searchArguments,
      searchCtls);

  while (answer.hasMoreElements()) {
    SearchResult sr = (SearchResult) answer.next();

    if (log.isDebugEnabled()) {
      log.debug("Retrieving userprincipalname names for user [" + sr.getName() + "]");
    }

    Attributes attrs = sr.getAttributes();
    if (attrs != null) {
      NamingEnumeration ae = attrs.getAll();
      while (ae.hasMore()) {
        Attribute attr = (Attribute) ae.next();
        if (attr.getID().toLowerCase().equals(this.getUserSearchAttributeName().toLowerCase())) {
          userNameList.addAll(LdapUtils.getAllAttributeValues(attr));
        }
      }
    }
  }
  return userNameList;
}
 
Example 8
Source File: SchemaViewer.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
private static void printAttrs(Attributes attrs) throws NamingException {
    NamingEnumeration<? extends Attribute> attrsEnum = attrs.getAll();
    while (attrsEnum.hasMore()) {
        Attribute currentAttr = attrsEnum.next();
        outstream.print(String.format("%1$s:", currentAttr.getID()));
        NamingEnumeration<?> valuesEnum = currentAttr.getAll();
        while (valuesEnum.hasMoreElements()) {
            outstream.print(String.format("%1$s ", valuesEnum.nextElement().toString()));
        }
        outstream.println();
    }
}
 
Example 9
Source File: NameAwareAttributes.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new instance, populated with the data from the supplied instance.
 * @param attributes the instance to copy.
 */
public NameAwareAttributes(Attributes attributes) {
    NamingEnumeration<? extends Attribute> allAttributes = attributes.getAll();
    while(allAttributes.hasMoreElements()) {
        Attribute attribute = allAttributes.nextElement();
        put(new NameAwareAttribute(attribute));
    }
}
 
Example 10
Source File: PingsResource.java    From ping with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/jndi/{namespace}")
public JsonObject jndi(@PathParam("namespace") String namespace) throws NamingException {
    JsonObjectBuilder builder = Json.createObjectBuilder();
    InitialContext c = new InitialContext();
    NamingEnumeration<NameClassPair> list = c.list(namespace);
    while (list.hasMoreElements()) {
        NameClassPair nameClassPair = list.nextElement();
        String name = nameClassPair.getName();
        String type = nameClassPair.getClassName();
        builder.add(name, type);
    }
    return builder.build();
}
 
Example 11
Source File: DirContextURLConnection.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/**
 * List children of this collection. The names given are relative to this
 * URI's path. The full uri of the children is then : path + "/" + name.
 */
public Enumeration<String> list()
    throws IOException {

    if (!connected) {
        connect();
    }

    if ((resource == null) && (collection == null)) {
        throw new FileNotFoundException(
                getURL() == null ? "null" : getURL().toString());
    }

    Vector<String> result = new Vector<String>();

    if (collection != null) {
        try {
            NamingEnumeration<NameClassPair> enumeration =
                collection.list("/");
            UEncoder urlEncoder = new UEncoder(UEncoder.SafeCharsSet.WITH_SLASH);
            while (enumeration.hasMoreElements()) {
                NameClassPair ncp = enumeration.nextElement();
                String s = ncp.getName();
                result.addElement(
                        urlEncoder.encodeURL(s, 0, s.length()).toString());
            }
        } catch (NamingException e) {
            // Unexpected exception
            throw new FileNotFoundException(
                    getURL() == null ? "null" : getURL().toString());
        }
    }

    return result.elements();

}
 
Example 12
Source File: LoginServiceLdapImpl.java    From griffin with Apache License 2.0 5 votes vote down vote up
private SearchResult getSingleUser(NamingEnumeration<SearchResult> results) throws NamingException {
    if (!results.hasMoreElements()) {
        throw new AuthenticationException("User does not exist or not allowed by search string");
    }
    SearchResult result = results.nextElement();
    if (results.hasMoreElements()) {
        SearchResult second = results.nextElement();
        throw new NamingException(String.format("Ambiguous search, found two users: %s, %s",
            result.getNameInNamespace(), second.getNameInNamespace()));
    }
    return result;
}
 
Example 13
Source File: OpenLdapUserManagerImpl.java    From cosmic with Apache License 2.0 5 votes vote down vote up
private LdapUser getUserForDn(final String userdn, final LdapContext context) throws NamingException {
    final SearchControls controls = new SearchControls();
    controls.setSearchScope(_ldapConfiguration.getScope());
    controls.setReturningAttributes(_ldapConfiguration.getReturnAttributes());

    final NamingEnumeration<SearchResult> result = context.search(userdn, "(objectClass=" + _ldapConfiguration.getUserObject() + ")", controls);
    if (result.hasMoreElements()) {
        return createUser(result.nextElement());
    } else {
        throw new NamingException("No user found for dn " + userdn);
    }
}
 
Example 14
Source File: LdapUserService.java    From pmq with Apache License 2.0 5 votes vote down vote up
private void doInitUser(Map<String, UserInfo> userInfos, Map<String, Organization> orgMap, String serverPath)
		throws NamingException {
	Properties env = new Properties();
	env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
	env.put(Context.SECURITY_AUTHENTICATION, "simple");
	env.put(Context.SECURITY_PRINCIPAL, "corp\\" + soaConfig.getMqLdapUser());
	env.put(Context.SECURITY_CREDENTIALS, soaConfig.getMqLdapPass());
	env.put(Context.PROVIDER_URL, adServer.get());

	LdapContext ctx = new InitialLdapContext(env, null);
	SearchControls searchCtls = new SearchControls();
	searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

	String searchFilter = String
			.format("(&(objectClass=top)(objectClass=user)(objectClass=person)(objectClass=organizationalPerson))");

	String returnedAtts[] = { "memberOf", "sAMAccountName", "cn", "distinguishedName", "mail" };
	searchCtls.setReturningAttributes(returnedAtts);
	NamingEnumeration<SearchResult> answer = ctx.search(serverPath, searchFilter, searchCtls);
	while (answer.hasMoreElements()) {
		SearchResult sr = (SearchResult) answer.next();
		Attributes at = sr.getAttributes();
		UserInfo userInfo = new UserInfo();
		userInfo.setDepartment(getDValue(at.get("distinguishedName")));
		userInfo.setEmail(getValue(at.get("mail")));
		userInfo.setUserId(getValue(at.get("sAMAccountName")));
		userInfo.setName(getValue(at.get("cn")));
		userInfo.setAdmin(roleService.isAdmin(userInfo.getUserId()));
		userInfos.put(userInfo.getUserId(), userInfo);
		if (!StringUtils.isEmpty(userInfo.getDepartment())) {
			Organization organization = new Organization();
			organization.setOrgId(userInfo.getDepartment());
			orgMap.put(userInfo.getDepartment(), organization);
		}
	}
	ctx.close();
}
 
Example 15
Source File: LdapAuthorizationMapping.java    From Openfire with Apache License 2.0 4 votes vote down vote up
@Override
public String map(String principal) {
    String username = principal;
    DirContext ctx = null;
    try {
        Log.debug("LdapAuthorizationMapping: Starting LDAP search...");
        String usernameField = manager.getUsernameField();
        //String baseDN = manager.getBaseDN();
        boolean subTreeSearch = manager.isSubTreeSearch();
        ctx = manager.getContext();
        SearchControls constraints = new SearchControls();
        if (subTreeSearch) {
            constraints.setSearchScope
        (SearchControls.SUBTREE_SCOPE);
        }
        // Otherwise, only search a single level.
        else {
            constraints.setSearchScope(SearchControls.ONELEVEL_SCOPE);
        }
        constraints.setReturningAttributes(new String[] { usernameField });

        NamingEnumeration answer = ctx.search("", princSearchFilter, 
                new String[] {LdapManager.sanitizeSearchFilter(principal)},
                constraints);
        Log.debug("LdapAuthorizationMapping: ... search finished");
        if (answer == null || !answer.hasMoreElements()) {
            Log.debug("LdapAuthorizationMapping: Username based on principal '" + principal + "' not found.");
            return principal;
        }
        Attributes atrs = ((SearchResult)answer.next()).getAttributes();
        Attribute usernameAttribute = atrs.get(usernameField);
        username = (String) usernameAttribute.get();
    }
    catch (Exception e) {
        // Ignore.
    }
    finally {
        try {
            if (ctx != null) {
                ctx.close();
            }
        }
        catch (Exception ex) {
            Log.debug("An exception occurred while trying to close a LDAP context after trying to map authorization for principal {}.", principal, ex);
        }
    }
    return username;
}
 
Example 16
Source File: AttributeUtils.java    From directory-ldap-api with Apache License 2.0 4 votes vote down vote up
/**
 * Check if the attributes is a BasicAttributes, and if so, switch
 * the case sensitivity to false to avoid tricky problems in the server.
 * (Ldap attributeTypes are *always* case insensitive)
 * 
 * @param attributes The Attributes to check
 * @return The modified Attributes
 */
public static Attributes toCaseInsensitive( Attributes attributes )
{
    if ( attributes == null )
    {
        return attributes;
    }

    if ( attributes instanceof BasicAttributes )
    {
        if ( attributes.isCaseIgnored() )
        {
            // Just do nothing if the Attributes is already case insensitive
            return attributes;
        }
        else
        {
            // Ok, bad news : we have to create a new BasicAttributes
            // which will be case insensitive
            Attributes newAttrs = new BasicAttributes( true );

            NamingEnumeration<?> attrs = attributes.getAll();

            if ( attrs != null )
            {
                // Iterate through the attributes now
                while ( attrs.hasMoreElements() )
                {
                    newAttrs.put( ( javax.naming.directory.Attribute ) attrs.nextElement() );
                }
            }

            return newAttrs;
        }
    }
    else
    {
        // we can safely return the attributes if it's not a BasicAttributes
        return attributes;
    }
}
 
Example 17
Source File: DefaultObjectDirectoryMapper.java    From spring-ldap with Apache License 2.0 4 votes vote down vote up
@Override
public <T> T mapFromLdapDataEntry(LdapDataEntry context, Class<T> clazz) {
    if (LOG.isDebugEnabled()) {
        LOG.debug(String.format("Converting to Java Entry class %1$s from %2$s", clazz, context));
    }

    // The Java representation of the LDAP entry
    T result;

    ObjectMetaData metaData=getEntityData(clazz).metaData;

    try {
        // The result class must have a zero argument constructor
        result = clazz.newInstance();

        // Build a map of JNDI attribute names to values
        Map<CaseIgnoreString, Attribute> attributeValueMap = new HashMap<CaseIgnoreString, Attribute>();
        // Get a NamingEnumeration to loop through the JNDI attributes in the entry
        Attributes attributes = context.getAttributes();
        NamingEnumeration<? extends Attribute> attributesEnumeration = attributes.getAll();
        // Loop through all of the JNDI attributes
        while (attributesEnumeration.hasMoreElements()) {
            Attribute currentAttribute = attributesEnumeration.nextElement();
            // Add the current attribute to the map keyed on the lowercased (case indep) id of the attribute
            attributeValueMap.put(new CaseIgnoreString(currentAttribute.getID()), currentAttribute);
        }


        // If this is the objectclass attribute then check that values correspond to the metadata we have
        // for the Java representation
        Attribute ocAttribute = attributeValueMap.get(OBJECT_CLASS_ATTRIBUTE_CI);
        if (ocAttribute != null) {
            // Get all object class values from the JNDI attribute
            Set<CaseIgnoreString> objectClassesFromJndi = new HashSet<CaseIgnoreString>();
            NamingEnumeration<?> objectClassesFromJndiEnum = ocAttribute.getAll();
            while (objectClassesFromJndiEnum.hasMoreElements()) {
                objectClassesFromJndi.add(new CaseIgnoreString((String)objectClassesFromJndiEnum.nextElement()));
            }
            // OK - checks its the same as the meta-data we have
            if(!collectionContainsAll(objectClassesFromJndi, metaData.getObjectClasses())) {
                return null;
            }
        } else {
            throw new InvalidEntryException(String.format("No object classes were returned for class %1$s",
                    clazz.getName()));
        }

        // Now loop through all the fields in the Java representation populating it with values from the
        // attributeValueMap
        for (Field field : metaData) {
            // Get the current field
            AttributeMetaData attributeInfo = metaData.getAttribute(field);
            // We deal with the Id field specially
            Name dn = context.getDn();
            if (!attributeInfo.isTransient() && !attributeInfo.isId()) {
                // Not the ID - but is is multi valued?
                if (!attributeInfo.isCollection()) {
                    // No - its single valued, grab the JNDI attribute that corresponds to the metadata on the
                    // current field
                    populateSingleValueField(result, attributeValueMap, field, attributeInfo);
                } else {
                    // We are dealing with a multi valued attribute
                    populateMultiValueField(result, attributeValueMap, field, attributeInfo);
                }
            } else if(attributeInfo.isId()) { // The id field
                field.set(result, converterManager.convert(dn, attributeInfo.getSyntax(),
                        attributeInfo.getValueClass()));
            }

            DnAttribute dnAttribute = attributeInfo.getDnAttribute();
            if(dnAttribute != null) {
                String dnValue;
                int index = dnAttribute.index();

                if(index != -1) {
                    dnValue = LdapUtils.getStringValue(dn, index);
                } else {
                    dnValue = LdapUtils.getStringValue(dn, dnAttribute.value());
                }
                field.set(result, dnValue);
            }
        }
    } catch (NamingException ne) {
        throw new InvalidEntryException(String.format("Problem creating %1$s from LDAP Entry %2$s",
                clazz, context), ne);
    } catch (IllegalAccessException iae) {
        throw new InvalidEntryException(String.format(
                "Could not create an instance of %1$s could not access field", clazz.getName()), iae);
    } catch (InstantiationException ie) {
        throw new InvalidEntryException(String.format("Could not instantiate %1$s", clazz), ie);
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug(String.format("Converted object - %1$s", result));
    }

    return result;
}
 
Example 18
Source File: LdapManager.java    From Openfire with Apache License 2.0 4 votes vote down vote up
/**
 * Generic routine for retrieving a single element from the LDAP server.  It's meant to be very
 * flexible so that just about any query for a single results can make use of it without having
 * to reimplement their own calls to LDAP.
 * <p>
 * The passed in filter string needs to be pre-prepared!  In other words, nothing will be changed
 * in the string before it is used as a string.
 *
 * @param attribute             LDAP attribute to be pulled from each result and placed in the return results.
 *                              Typically pulled from this manager. Null means the the absolute DN is returned.
 * @param searchFilter          Filter to use to perform the search.  Typically pulled from this manager.
 * @param failOnMultipleResults It true, an {@link IllegalStateException} will be thrown, if the
 *                              search result is not unique. If false, just the first result will be returned.
 * @param baseDN                DN where to start the search. Typically {@link #getBaseDN()} or {@link #getAlternateBaseDN()}.
 * @return A single string.
 */
public String retrieveSingle(String attribute, String searchFilter, boolean failOnMultipleResults, LdapName baseDN) {
    LdapContext ctx = null;
    try {
        ctx = getContext(baseDN);

        SearchControls searchControls = new SearchControls();
        // See if recursive searching is enabled. Otherwise, only search one level.
        if (isSubTreeSearch()) {
            searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        }
        else {
            searchControls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
        }
        searchControls.setReturningAttributes(attribute == null ? new String[0] : new String[]{attribute});

        NamingEnumeration<SearchResult> answer = ctx.search("", searchFilter, searchControls);
        if (answer == null || !answer.hasMoreElements()) {
            return null;
        }
        SearchResult searchResult = answer.next();
        String result = attribute == null
            ? new LdapName(searchResult.getName()).addAll(0, baseDN).toString() :
            (String) searchResult.getAttributes().get(attribute).get();
        if (answer.hasMoreElements()) {
            Log.debug("Search result for '{}' is not unique.", searchFilter);
            if (failOnMultipleResults)
                throw new IllegalStateException("Search result for " + searchFilter + " is not unique.");
        }
        answer.close();
        return result;
    }
    catch (Exception e) {
        Log.error("Error while searching for single result of: {}", searchFilter, e);
        return null;
    }
    finally {
        try {
            if (ctx != null) {
                ctx.close();
            }
        } catch (Exception ex) {
            Log.debug("An exception occurred while trying to close a LDAP context after trying to retrieve a single attribute element for {}.", attribute, ex);
        }
    }
}
 
Example 19
Source File: LdapUserTester.java    From Openfire with Apache License 2.0 4 votes vote down vote up
/**
 * Returns a list of usernames with a sample of the users found in LDAP.
 *
 * @param maxSample the max size of the sample to return.
 * @return a list of usernames with a sample of the users found in LDAP.
 * @throws NamingException if something goes wrong....
 */
public List<String> getSample(int maxSample) throws NamingException {
    List<String> usernames = new ArrayList<>();
    LdapContext ctx = null;

    try {
        ctx = manager.getContext();

        // Sort on username field.
        Control[] searchControl;
        try {
            searchControl = new Control[]{
                    new SortControl(new String[]{manager.getUsernameField()}, Control.NONCRITICAL)
            };
        } catch (IOException e) {
            Log.error(e.getMessage(), e);
            return Collections.emptyList();
        }
        ctx.setRequestControls(searchControl);

        // Search for the dn based on the username.
        SearchControls searchControls = new SearchControls();
        // See if recursive searching is enabled. Otherwise, only search one level.
        if (manager.isSubTreeSearch()) {
            searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        } else {
            searchControls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
        }
        searchControls.setReturningAttributes(new String[]{manager.getUsernameField()});
        // Limit results to those we'll need to process
        searchControls.setCountLimit(maxSample);
        String filter = MessageFormat.format(manager.getSearchFilter(), "*");
        NamingEnumeration answer = ctx.search("", filter, searchControls);

        while (answer.hasMoreElements()) {
            // Get the next userID.
            String username = (String) ((SearchResult) answer.next()).getAttributes().get(
                    manager.getUsernameField()).get();
            // Escape username and add to results.
            usernames.add(JID.escapeNode(username));
        }
        // Close the enumeration.
        answer.close();
    } finally {
        try {
            if (ctx != null) {
                ctx.setRequestControls(null);
                ctx.close();
            }
        }
        catch (Exception ex) {
            Log.debug("An exception occurred while trying to close a LDAP context after trying to get a sample of data from LDAP.", ex);
        }
    }
    return usernames;
}
 
Example 20
Source File: QueryDNS.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
@Override
public void onTrigger(ProcessContext context, ProcessSession session) throws ProcessException {
    if (!initialized.get()) {
        initializeResolver(context);
        getLogger().warn("Resolver was initialized at onTrigger instead of onScheduled");

    }

    FlowFile flowFile = session.get();
    if (flowFile == null) {
        return;
    }

    final String queryType = context.getProperty(DNS_QUERY_TYPE).getValue();
    final String queryInput = context.getProperty(QUERY_INPUT).evaluateAttributeExpressions(flowFile).getValue();
    final String queryParser = context.getProperty(QUERY_PARSER).getValue();
    final String queryRegex = context.getProperty(QUERY_PARSER_INPUT).getValue();

    boolean found = false;
    try {
        Attributes results = doLookup(queryInput, queryType);
        // NOERROR & NODATA seem to return empty Attributes handled bellow
        // but defaulting to not found in any case
        if (results.size() < 1) {
            found = false;
        } else {
            int recordNumber = 0;
            NamingEnumeration<?> dnsEntryIterator = results.get(queryType).getAll();

            while (dnsEntryIterator.hasMoreElements()) {
                String dnsRecord = dnsEntryIterator.next().toString();
                // While NXDOMAIN is being generated by doLookup catch

                if (dnsRecord != "NXDOMAIN") {
                    // Map<String, String> parsedResults = parseResponse(recordNumber, dnsRecord, queryParser, queryRegex, "dns");
                    Map<String, String> parsedResults = parseResponse(String.valueOf(recordNumber), dnsRecord, queryParser, queryRegex, "dns");
                    flowFile = session.putAllAttributes(flowFile, parsedResults);
                    found = true;
                } else {
                    // Otherwise treat as not found
                    found = false;
                }

                // Increase the counter and iterate over next record....
                recordNumber++;
            }
        }
    } catch (NamingException e) {
        context.yield();
        throw new ProcessException("Unexpected NamingException while processing records. Please review your configuration.", e);

    }

    // Finally prepare to send the data down the pipeline
    if (found) {
        // Sending the resulting flowfile (with attributes) to REL_FOUND
        session.transfer(flowFile, REL_FOUND);
    } else {
        // NXDOMAIN received, accepting the fate but forwarding
        // to REL_NOT_FOUND
        session.transfer(flowFile, REL_NOT_FOUND);
    }
}