Java Code Examples for javax.naming.directory.Attributes#getAll()

The following examples show how to use javax.naming.directory.Attributes#getAll() . 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: Rdn.java    From jdk1.8-source-analysis with Apache License 2.0 6 votes vote down vote up
/**
 * Constructs an Rdn from the given attribute set. See
 * {@link javax.naming.directory.Attributes Attributes}.
 * <p>
 * The string attribute values are not interpreted as
 * <a href="http://www.ietf.org/rfc/rfc2253.txt">RFC 2253</a>
 * formatted RDN strings. That is, the values are used
 * literally (not parsed) and assumed to be unescaped.
 *
 * @param attrSet The non-null and non-empty attributes containing
 * type/value mappings.
 * @throws InvalidNameException If contents of <tt>attrSet</tt> cannot
 *          be used to construct a valid RDN.
 */
public Rdn(Attributes attrSet) throws InvalidNameException {
    if (attrSet.size() == 0) {
        throw new InvalidNameException("Attributes cannot be empty");
    }
    entries = new ArrayList<>(attrSet.size());
    NamingEnumeration<? extends Attribute> attrs = attrSet.getAll();
    try {
        for (int nEntries = 0; attrs.hasMore(); nEntries++) {
            RdnEntry entry = new RdnEntry();
            Attribute attr = attrs.next();
            entry.type = attr.getID();
            entry.value = attr.get();
            entries.add(nEntries, entry);
        }
    } catch (NamingException e) {
        InvalidNameException e2 = new InvalidNameException(
                                    e.getMessage());
        e2.initCause(e);
        throw e2;
    }
    sort(); // arrange entries for comparison
}
 
Example 2
Source File: EtcdClientAutoConfiguration.java    From spring-boot-etcd with MIT License 6 votes vote down vote up
private List<String> discoverNodes(String serviceName) throws NamingException {
	List<String> locations = new ArrayList<>();

	Hashtable<String, String> env = new Hashtable<String, String>();
	env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
	env.put("java.naming.provider.url", "dns:");

	DirContext context = new InitialDirContext(env);
	Attributes attributes = context.getAttributes(serviceName, new String[] { "SRV" });
	for (NamingEnumeration<? extends Attribute> records = attributes.getAll(); records.hasMore();) {
		Attribute record = records.next();
		NamingEnumeration<String> values = (NamingEnumeration<String>) record.getAll();
		while (values.hasMore()) {
			String dns = values.next();
			String[] split = dns.split(" ");
			String host = split[3];
			if (host.endsWith(".")) {
				host = host.substring(0, host.length() - 1);
			}

			String location = "http://" + host + ":2379";
			locations.add(location);
		}
	}
	return locations;
}
 
Example 3
Source File: Rdn.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Constructs an Rdn from the given attribute set. See
 * {@link javax.naming.directory.Attributes Attributes}.
 * <p>
 * The string attribute values are not interpreted as
 * <a href="http://www.ietf.org/rfc/rfc2253.txt">RFC 2253</a>
 * formatted RDN strings. That is, the values are used
 * literally (not parsed) and assumed to be unescaped.
 *
 * @param attrSet The non-null and non-empty attributes containing
 * type/value mappings.
 * @throws InvalidNameException If contents of <tt>attrSet</tt> cannot
 *          be used to construct a valid RDN.
 */
public Rdn(Attributes attrSet) throws InvalidNameException {
    if (attrSet.size() == 0) {
        throw new InvalidNameException("Attributes cannot be empty");
    }
    entries = new ArrayList<>(attrSet.size());
    NamingEnumeration<? extends Attribute> attrs = attrSet.getAll();
    try {
        for (int nEntries = 0; attrs.hasMore(); nEntries++) {
            RdnEntry entry = new RdnEntry();
            Attribute attr = attrs.next();
            entry.type = attr.getID();
            entry.value = attr.get();
            entries.add(nEntries, entry);
        }
    } catch (NamingException e) {
        InvalidNameException e2 = new InvalidNameException(
                                    e.getMessage());
        e2.initCause(e);
        throw e2;
    }
    sort(); // arrange entries for comparison
}
 
Example 4
Source File: LdapSender.java    From iaf with Apache License 2.0 6 votes vote down vote up
protected XmlBuilder attributesToXml(Attributes atts)
	throws NamingException {
	XmlBuilder attributesElem = new XmlBuilder("attributes");
	
	NamingEnumeration all = atts.getAll();
	while (all.hasMore()) {
		Attribute attribute = (Attribute) all.next();
		XmlBuilder attributeElem = new XmlBuilder("attribute");
		attributeElem.addAttribute("name", attribute.getID());
		if (attribute.size() == 1 && attribute.get() != null) {
			attributeElem.addAttribute("value", attribute.get().toString());
		} else {
			NamingEnumeration values = attribute.getAll();
			while (values.hasMore()) {
				Object value = values.next();
				XmlBuilder itemElem = new XmlBuilder("item");
				itemElem.addAttribute("value", value.toString());
				attributeElem.addSubElement(itemElem);
			}
		}
		attributesElem.addSubElement(attributeElem);
	}
	return attributesElem;
}
 
Example 5
Source File: Rdn.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Constructs an Rdn from the given attribute set. See
 * {@link javax.naming.directory.Attributes Attributes}.
 * <p>
 * The string attribute values are not interpreted as
 * <a href="http://www.ietf.org/rfc/rfc2253.txt">RFC 2253</a>
 * formatted RDN strings. That is, the values are used
 * literally (not parsed) and assumed to be unescaped.
 *
 * @param attrSet The non-null and non-empty attributes containing
 * type/value mappings.
 * @throws InvalidNameException If contents of <tt>attrSet</tt> cannot
 *          be used to construct a valid RDN.
 */
public Rdn(Attributes attrSet) throws InvalidNameException {
    if (attrSet.size() == 0) {
        throw new InvalidNameException("Attributes cannot be empty");
    }
    entries = new ArrayList<>(attrSet.size());
    NamingEnumeration<? extends Attribute> attrs = attrSet.getAll();
    try {
        for (int nEntries = 0; attrs.hasMore(); nEntries++) {
            RdnEntry entry = new RdnEntry();
            Attribute attr = attrs.next();
            entry.type = attr.getID();
            entry.value = attr.get();
            entries.add(nEntries, entry);
        }
    } catch (NamingException e) {
        InvalidNameException e2 = new InvalidNameException(
                                    e.getMessage());
        e2.initCause(e);
        throw e2;
    }
    sort(); // arrange entries for comparison
}
 
Example 6
Source File: Rdn.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Constructs an Rdn from the given attribute set. See
 * {@link javax.naming.directory.Attributes Attributes}.
 * <p>
 * The string attribute values are not interpreted as
 * <a href="http://www.ietf.org/rfc/rfc2253.txt">RFC 2253</a>
 * formatted RDN strings. That is, the values are used
 * literally (not parsed) and assumed to be unescaped.
 *
 * @param attrSet The non-null and non-empty attributes containing
 * type/value mappings.
 * @throws InvalidNameException If contents of <tt>attrSet</tt> cannot
 *          be used to construct a valid RDN.
 */
public Rdn(Attributes attrSet) throws InvalidNameException {
    if (attrSet.size() == 0) {
        throw new InvalidNameException("Attributes cannot be empty");
    }
    entries = new ArrayList<>(attrSet.size());
    NamingEnumeration<? extends Attribute> attrs = attrSet.getAll();
    try {
        for (int nEntries = 0; attrs.hasMore(); nEntries++) {
            RdnEntry entry = new RdnEntry();
            Attribute attr = attrs.next();
            entry.type = attr.getID();
            entry.value = attr.get();
            entries.add(nEntries, entry);
        }
    } catch (NamingException e) {
        InvalidNameException e2 = new InvalidNameException(
                                    e.getMessage());
        e2.initCause(e);
        throw e2;
    }
    sort(); // arrange entries for comparison
}
 
Example 7
Source File: LdapClient.java    From iaf with Apache License 2.0 5 votes vote down vote up
public void mapMultiValuedAttribute(NamingEnumeration<SearchResult> searchResultEnum, Callback<Attribute,Object> callback) throws NamingException {
  	try {
   	while (searchResultEnum.hasMore()) {
   		Attributes attributes=searchResultEnum.next().getAttributes();
   		NamingEnumeration<? extends Attribute> attrenum=attributes.getAll();
   		try {
   			while (attrenum.hasMore()) {
   				Attribute attr=attrenum.next();
   	    		NamingEnumeration<?> multivalueattribute=attr.getAll();
   	    		try {
   	    			while (multivalueattribute.hasMore()) {
   	    				callback.handle(attr,multivalueattribute.next());
   	    			}
   	    		} finally {
   	    			multivalueattribute.close();
   	    		}
   			}
   		} finally {
   			attrenum.close();
   		}
   	}
} catch(PartialResultException e) {
	if (log.isDebugEnabled()) log.debug("ignoring Exception: "+e); 
} finally {
	searchResultEnum.close();
}
  }
 
Example 8
Source File: ServerEntryUtils.java    From MyVirtualDirectory with Apache License 2.0 5 votes vote down vote up
/**
 * Convert a BasicAttributes or a AttributesImpl to a ServerEntry
 *
 * @param attributes the BasicAttributes or AttributesImpl instance to convert
 * @param registries The registries, needed ro build a ServerEntry
 * @param dn The Dn which is needed by the ServerEntry
 * @return An instance of a ServerEntry object
 * 
 * @throws LdapInvalidAttributeTypeException If we get an invalid attribute
 */
public static Entry toServerEntry( Attributes attributes, Dn dn, SchemaManager schemaManager )
    throws LdapInvalidAttributeTypeException
{
    if ( attributes instanceof BasicAttributes )
    {
        try
        {
            Entry entry = new DefaultEntry( schemaManager, dn );

            for ( NamingEnumeration<? extends javax.naming.directory.Attribute> attrs = attributes.getAll(); attrs
                .hasMoreElements(); )
            {
                javax.naming.directory.Attribute attr = attrs.nextElement();

                String attributeId = attr.getID();
                String id = SchemaUtils.stripOptions( attributeId );
                Set<String> options = SchemaUtils.getOptions( attributeId );
                // TODO : handle options.
                AttributeType attributeType = schemaManager.lookupAttributeTypeRegistry( id );
                Attribute serverAttribute = ServerEntryUtils.toServerAttribute( attr, attributeType );

                if ( serverAttribute != null )
                {
                    entry.put( serverAttribute );
                }
            }

            return entry;
        }
        catch ( LdapException ne )
        {
            throw new LdapInvalidAttributeTypeException( ne.getLocalizedMessage() );
        }
    }
    else
    {
        return null;
    }
}
 
Example 9
Source File: LdapGroupRealm.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
public Set<String> getRoleNamesForUser(String username, LdapContext ldapContext,
        String userDnTemplate) throws NamingException {
  try {
    Set<String> roleNames = new LinkedHashSet<>();

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

    String searchFilter = "(&(objectClass=groupOfNames)(member=" + userDnTemplate + "))";
    Object[] searchArguments = new Object[]{username};

    NamingEnumeration<?> answer = ldapContext.search(
        String.valueOf(ldapContext.getEnvironment().get("ldap.searchBase")),
        searchFilter,
        searchArguments,
        searchCtls);

    while (answer.hasMoreElements()) {
      SearchResult sr = (SearchResult) answer.next();
      Attributes attrs = sr.getAttributes();
      if (attrs != null) {
        NamingEnumeration<?> ae = attrs.getAll();
        while (ae.hasMore()) {
          Attribute attr = (Attribute) ae.next();
          if (attr.getID().equals("cn")) {
            roleNames.add((String) attr.get());
          }
        }
      }
    }
    return roleNames;

  } catch (Exception e) {
    LOG.error("Error", e);
  }

  return new HashSet<>();
}
 
Example 10
Source File: LdapUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static Map<String, Attribute> getAttributesOfEntry(LdapTemplate ldapTemplate, String baseDN,
    String objectClass, String filterAttributeName, String filterAttributeValue,
    String[] searchAttributes) {

    Map<String, Attribute> ldapAttributes = null;

    AttributesMapper<Map<String, Attribute>> mapper =
        new AttributesMapper<Map<String, Attribute>>() {
            public Map<String, Attribute> mapFromAttributes(Attributes attrs) throws NamingException {
                Map<String, Attribute> map = new HashMap<>();
                NamingEnumeration<? extends Attribute> attrEnum = attrs.getAll();
                while (attrEnum.hasMore()) {
                    Attribute att = attrEnum.next();
                    map.put(att.getID(), att);
                }
                return map;
            }
        };

    List<?> result = null;
    AndFilter filter = new AndFilter();
    filter.and(
            new EqualsFilter("objectclass", objectClass)).and(
                    new EqualsFilter(filterAttributeName, filterAttributeValue));

    result = ldapTemplate.search((baseDN == null) ? "" : baseDN, filter.toString(),
        SearchControls.SUBTREE_SCOPE, searchAttributes, mapper);
    if (result != null && !result.isEmpty()) {
        ldapAttributes = CastUtils.cast((Map<?, ?>)result.get(0));
    }

    return ldapAttributes;
}
 
Example 11
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 12
Source File: LDAPLoginManagerImpl.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * Checks if LDAP properties are different then OLAT properties of a User. If they are different a Map (OlatPropertyName,LDAPValue) is returned.
 * 
 * @param attributes
 *            Set of LDAP Attribute of Identity
 * @param identity
 *            Identity to compare
 * @return Map(OlatPropertyName,LDAPValue) of properties Identity, where property has changed. NULL is returned it no attributes have to be synced
 */
@SuppressWarnings("unchecked")
public Map<String, String> prepareUserPropertyForSync(final Attributes attributes, final Identity identity) {
    final Map<String, String> olatPropertyMap = new HashMap<String, String>();
    final User user = identity.getUser();
    final NamingEnumeration<Attribute> neAttrs = (NamingEnumeration<Attribute>) attributes.getAll();
    try {
        while (neAttrs.hasMore()) {
            final Attribute attr = neAttrs.next();
            final String olatProperty = mapLdapAttributeToOlatProperty(attr.getID());
            if (olatProperty == null) {
                continue;
            }
            final String ldapValue = getAttributeValue(attr);
            final String olatValue = userService.getUserProperty(user, olatProperty);
            if (olatValue == null) {
                // new property or user ID (will always be null, pseudo property)
                olatPropertyMap.put(olatProperty, ldapValue);
            } else {
                if (ldapValue.compareTo(olatValue) != 0) {
                    olatPropertyMap.put(olatProperty, ldapValue);
                }
            }
        }
        if (olatPropertyMap.size() == 1 && olatPropertyMap.get(LDAPConstants.LDAP_USER_IDENTIFYER) != null) {
            return null;
        }
        return olatPropertyMap;

    } catch (final NamingException e) {
        log.error("NamingException when trying to prepare user properties for LDAP sync", e);
        return null;
    }
}
 
Example 13
Source File: LDAPLoginManagerImpl.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * Checks if LDAP properties are different then OLAT properties of a User. If they are different a Map (OlatPropertyName,LDAPValue) is returned.
 * 
 * @param attributes
 *            Set of LDAP Attribute of Identity
 * @param identity
 *            Identity to compare
 * @return Map(OlatPropertyName,LDAPValue) of properties Identity, where property has changed. NULL is returned it no attributes have to be synced
 */
@SuppressWarnings("unchecked")
public Map<String, String> prepareUserPropertyForSync(final Attributes attributes, final Identity identity) {
    final Map<String, String> olatPropertyMap = new HashMap<String, String>();
    final User user = identity.getUser();
    final NamingEnumeration<Attribute> neAttrs = (NamingEnumeration<Attribute>) attributes.getAll();
    try {
        while (neAttrs.hasMore()) {
            final Attribute attr = neAttrs.next();
            final String olatProperty = mapLdapAttributeToOlatProperty(attr.getID());
            if (olatProperty == null) {
                continue;
            }
            final String ldapValue = getAttributeValue(attr);
            final String olatValue = userService.getUserProperty(user, olatProperty);
            if (olatValue == null) {
                // new property or user ID (will always be null, pseudo property)
                olatPropertyMap.put(olatProperty, ldapValue);
            } else {
                if (ldapValue.compareTo(olatValue) != 0) {
                    olatPropertyMap.put(olatProperty, ldapValue);
                }
            }
        }
        if (olatPropertyMap.size() == 1 && olatPropertyMap.get(LDAPConstants.LDAP_USER_IDENTIFYER) != null) {
            return null;
        }
        return olatPropertyMap;

    } catch (final NamingException e) {
        log.error("NamingException when trying to prepare user properties for LDAP sync", e);
        return null;
    }
}
 
Example 14
Source File: LdapClient.java    From iaf with Apache License 2.0 5 votes vote down vote up
/**
   * runs a set of attribute values through a Mapper. Only the first value of each attribute is mapped. 
   */
  public void mapMultipleAttributes(NamingEnumeration<SearchResult> searchResultEnum, Callback<Attribute,Object> callback) throws NamingException {
  	try {
   	while (searchResultEnum.hasMore()) {
   		Attributes attributes=searchResultEnum.next().getAttributes();
   		NamingEnumeration<? extends Attribute> attrenum=attributes.getAll();
   		try {
   			while (attrenum.hasMore()) {
   				Attribute attr=attrenum.next();
   	    		NamingEnumeration<?> multivalueattribute=attr.getAll();
   	    		try {
   	    			if (multivalueattribute.hasMore()) {
   	    				callback.handle(attr,multivalueattribute.next());
   	    			}
   	    		} finally {
   	    			multivalueattribute.close();
   	    		}
   			}
   		} finally {
   			attrenum.close();
   		}
   	}
} catch(PartialResultException e) {
	if (log.isDebugEnabled()) log.debug("ignoring Exception: "+e); 
} finally {
	searchResultEnum.close();
}
  }
 
Example 15
Source File: LDAPConnection.java    From pentaho-kettle with Apache License 2.0 4 votes vote down vote up
public RowMeta getFields( String searchBase ) throws KettleException {
  RowMeta fields = new RowMeta();
  List<String> fieldsl = new ArrayList<String>();
  try {
    search( searchBase, null, 0, null, SEARCH_SCOPE_SUBTREE_SCOPE );
    Attributes attributes = null;
    fieldsl = new ArrayList<String>();
    while ( ( attributes = getAttributes() ) != null ) {

      NamingEnumeration<? extends Attribute> ne = attributes.getAll();

      while ( ne.hasMore() ) {
        Attribute attr = ne.next();
        String fieldName = attr.getID();
        if ( !fieldsl.contains( fieldName ) ) {
          fieldsl.add( fieldName );

          String attributeValue = attr.get().toString();
          int valueType;

          // Try to determine the data type
          //
          if ( IsDate( attributeValue ) ) {
            valueType = ValueMetaInterface.TYPE_DATE;
          } else if ( IsInteger( attributeValue ) ) {
            valueType = ValueMetaInterface.TYPE_INTEGER;
          } else if ( IsNumber( attributeValue ) ) {
            valueType = ValueMetaInterface.TYPE_NUMBER;
          } else {
            valueType = ValueMetaInterface.TYPE_STRING;
          }

          ValueMetaInterface value = ValueMetaFactory.createValueMeta( fieldName, valueType );
          fields.addValueMeta( value );
        }
      }
    }
    return fields;
  } catch ( Exception e ) {
    throw new KettleException( BaseMessages.getString( PKG, "LDAPConnection.Error.RetrievingFields" ) );
  } finally {
    fieldsl = null;
  }
}
 
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: ActiveDirectoryGroupRealm.java    From zeppelin with Apache License 2.0 4 votes vote down vote up
private Set<String> getRoleNamesForUser(String username, LdapContext ldapContext)
        throws NamingException {
  Set<String> roleNames = new LinkedHashSet<>();

  SearchControls searchCtls = new SearchControls();
  searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
  String userPrincipalName = username;
  if (this.principalSuffix != null && userPrincipalName.indexOf('@') > 1) {
    userPrincipalName = userPrincipalName.split("@")[0];
  }

  String searchFilter = String.format("(&(objectClass=*)(%s=%s))", this.getUserSearchAttributeName(), userPrincipalName);
  Object[] searchArguments = new Object[]{userPrincipalName};

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

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

    if (log.isDebugEnabled()) {
      log.debug("Retrieving group 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().equals("memberOf")) {

          Collection<String> groupNames = LdapUtils.getAllAttributeValues(attr);

          if (log.isDebugEnabled()) {
            log.debug("Groups found for user [" + username + "]: " + groupNames);
          }

          Collection<String> rolesForGroups = getRoleNamesForGroups(groupNames);
          roleNames.addAll(rolesForGroups);
        }
      }
    }
  }
  return roleNames;
}
 
Example 18
Source File: SchemaReader.java    From spring-ldap with Apache License 2.0 4 votes vote down vote up
private void createObjectClass(Set<String> objectClasses, DirContext schemaContext, ObjectSchema schema)
        throws NamingException, ClassNotFoundException {

    // Super classes
    Set<String> supList = new HashSet<String>();

    // For each of the given object classes
    for (String objectClass : objectClasses) {
        // Add to set of included object classes
        schema.addObjectClass(objectClass);
        
        // Grab the LDAP schema of the object class
        Attributes attributes = schemaContext.getAttributes("ClassDefinition/" + objectClass);
        NamingEnumeration<? extends Attribute> valuesEnumeration = attributes.getAll();

        // Loop through each of the attributes
        while (valuesEnumeration.hasMoreElements()) {
            Attribute currentAttribute = valuesEnumeration.nextElement();

            // Get the attribute name and lower case it (as this is all case indep)
            String currentId = currentAttribute.getID().toUpperCase();
            
            // Is this a MUST, MAY or SUP attribute
            SchemaAttributeType type = getSchemaAttributeType(currentId);

            // Loop through all the values
            NamingEnumeration<?> currentValues = currentAttribute.getAll();
            while (currentValues.hasMoreElements()) {
                String currentValue = (String)currentValues.nextElement();
                switch (type) {
                    case SUP:
                        // Its a super class
                        String lowerCased=currentValue.toLowerCase();
                        if (!schema.getObjectClass().contains(lowerCased)) {
                            supList.add(lowerCased);
                        }
                        break;
                    case MUST:
                        // Add must attribute
                        schema.addMust(createAttributeSchema(currentValue, schemaContext));
                        break;
                    case MAY:
                        // Add may attribute
                        schema.addMay(createAttributeSchema(currentValue, schemaContext));
                        break;
                    default:
                        // Nothing to do
                }
            }
        }

        // Recurse for super classes
        createObjectClass(supList, schemaContext, schema);
    }
}
 
Example 19
Source File: LdapConnection.java    From hop with Apache License 2.0 4 votes vote down vote up
public RowMeta getFields( String searchBase ) throws HopException {
  RowMeta fields = new RowMeta();
  List<String> fieldsl = new ArrayList<>();
  try {
    search( searchBase, null, 0, null, SEARCH_SCOPE_SUBTREE_SCOPE );
    Attributes attributes = null;
    fieldsl = new ArrayList<>();
    while ( ( attributes = getAttributes() ) != null ) {

      NamingEnumeration<? extends Attribute> ne = attributes.getAll();

      while ( ne.hasMore() ) {
        Attribute attr = ne.next();
        String fieldName = attr.getID();
        if ( !fieldsl.contains( fieldName ) ) {
          fieldsl.add( fieldName );

          String attributeValue = attr.get().toString();
          int valueType;

          // Try to determine the data type
          //
          if ( IsDate( attributeValue ) ) {
            valueType = IValueMeta.TYPE_DATE;
          } else if ( IsInteger( attributeValue ) ) {
            valueType = IValueMeta.TYPE_INTEGER;
          } else if ( IsNumber( attributeValue ) ) {
            valueType = IValueMeta.TYPE_NUMBER;
          } else {
            valueType = IValueMeta.TYPE_STRING;
          }

          IValueMeta value = ValueMetaFactory.createValueMeta( fieldName, valueType );
          fields.addValueMeta( value );
        }
      }
    }
    return fields;
  } catch ( Exception e ) {
    throw new HopException( BaseMessages.getString( PKG, "LdapConnection.Error.RetrievingFields" ) );
  } finally {
    fieldsl = null;
  }
}
 
Example 20
Source File: ReadOnlyLDAPUserStoreManager.java    From micro-integrator with Apache License 2.0 4 votes vote down vote up
/**
 * Parse the search result of group filtering and get the user list.
 * If it's membership group filtering, we retrieve all members of the requested group(s) and then
 * get the mutual members' out of it as a DN list.
 * If it's memberOf group filtering, directly get the user name list from search result.
 *
 * @param answer                  Answer
 * @param returnedAttributes      Returned Attributes
 * @param isSingleAttributeFilter Whether the original request is from a single attribute filter or a multi
 *                                attribute filter, so that AND operation can be omitted during the filtering
 *                                process.
 * @return A users list
 * @throws UserStoreException
 */
private List<String> getUserListFromGroupFilterResult(NamingEnumeration<SearchResult> answer,
        List<String> returnedAttributes, boolean isSingleAttributeFilter) throws UserStoreException {

    // Can be user DN list or username list
    List<String> userListFromSearch = new ArrayList<>();
    // Multi group retrieval
    int count = 0;
    NamingEnumeration<?> attrs = null;
    List<String> finalUserList;

    try {
        while (answer.hasMoreElements()) {
            count++;
            List<String> tempUserList = new ArrayList<>();
            SearchResult searchResult = answer.next();
            Attributes attributes = searchResult.getAttributes();
            if (attributes == null)
                continue;
            NamingEnumeration attributeEntry;
            for (attributeEntry = attributes.getAll(); attributeEntry.hasMore(); ) {
                Attribute valAttribute = (Attribute) attributeEntry.next();
                if (isAttributeEqualsProperty(returnedAttributes.get(0), valAttribute.getID())) {
                    NamingEnumeration values;
                    for (values = valAttribute.getAll(); values.hasMore(); ) {
                        tempUserList.add(values.next().toString());
                    }
                }
            }
            /*
             When singleAttributeFilter is true, that implies that the request is a single attribute filter. In
             this case, the intersection (AND operation) should not be performed on the filtered results.
             Following IF block handles the single attribute filter.
             */
            if (isSingleAttributeFilter) {
                userListFromSearch.addAll(tempUserList);
            } else {
                /*
                 * If returnedAttributes doesn't contain 'member' attribute, then it's memberOf group filter.
                 * If so we  don't need to do post processing.
                 */
                if (!returnedAttributes
                        .contains(realmConfig.getUserStoreProperty(LDAPConstants.MEMBERSHIP_ATTRIBUTE))
                        || count == 1) {
                    userListFromSearch.addAll(tempUserList);
                } else {
                    userListFromSearch.retainAll(tempUserList);
                }
            }
        }
    } catch (NamingException e) {
        log.error(String.format("Error occurred while getting user list from group filter %s", e.getMessage()));
        throw new UserStoreException(e.getMessage(), e);
    } finally {
        JNDIUtil.closeNamingEnumeration(attrs);
    }

    // If 'member' attribute found, we need iterate over users' DN list and get userName.
    if (returnedAttributes.contains(realmConfig.getUserStoreProperty(LDAPConstants.MEMBERSHIP_ATTRIBUTE))) {
        finalUserList = getUserNamesFromDNList(userListFromSearch);
    } else {
        finalUserList = userListFromSearch;
    }
    return finalUserList;
}