javax.naming.directory.Attribute Java Examples

The following examples show how to use javax.naming.directory.Attribute. 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: ResourceAttributes.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
/**
 * Get name.
 * 
 * @return Name value
 */
public String getName() {
    if (name != null)
        return name;
    if (attributes != null) {
        Attribute attribute = attributes.get(NAME);
        if (attribute != null) {
            try {
                name = attribute.get().toString();
            } catch (NamingException e) {
                // No value for the attribute
            }
        }
    }
    return name;
}
 
Example #2
Source File: LdapUserGroupProvider.java    From nifi with Apache License 2.0 6 votes vote down vote up
private String getReferencedUserValue(final DirContextOperations ctx) {
    final String referencedUserValue;

    if (StringUtils.isBlank(groupMemberReferencedUserAttribute)) {
        referencedUserValue = ctx.getDn().toString();
    } else {
        final Attribute attributeName = ctx.getAttributes().get(groupMemberReferencedUserAttribute);
        if (attributeName == null) {
            throw new AuthorizationAccessException("Referenced user value attribute [" + groupMemberReferencedUserAttribute + "] does not exist.");
        }

        try {
            referencedUserValue = (String) attributeName.get();
        } catch (NamingException e) {
            throw new AuthorizationAccessException("Error while retrieving reference user value attribute [" + groupMemberReferencedUserAttribute + "].");
        }
    }

    return groupMembershipEnforceCaseSensitivity ? referencedUserValue : referencedUserValue.toLowerCase();
}
 
Example #3
Source File: LdapConnection.java    From hop with Apache License 2.0 6 votes vote down vote up
private Attributes buildAttributes( String dn, String[] attributes, String[] values, String multValuedSeparator ) {
  Attributes attrs = new javax.naming.directory.BasicAttributes( true );
  int nrAttributes = attributes.length;
  for ( int i = 0; i < nrAttributes; i++ ) {
    if ( !Utils.isEmpty( values[ i ] ) ) {
      // We have a value
      String value = values[ i ].trim();
      if ( multValuedSeparator != null && value.indexOf( multValuedSeparator ) > 0 ) {
        Attribute attr = new javax.naming.directory.BasicAttribute( attributes[ i ] );
        for ( String attribute : value.split( multValuedSeparator ) ) {
          attr.add( attribute );
        }
        attrs.put( attr );
      } else {
        attrs.put( attributes[ i ], value );
      }
    }
  }
  return attrs;
}
 
Example #4
Source File: UserGroupAttributesMapper.java    From geofence with GNU General Public License v2.0 6 votes vote down vote up
@Override
public Object mapFromAttributes(Attributes attrs) throws NamingException
{
    UserGroup group = new UserGroup();

    String id = getAttribute(attrs, "id");
    if(StringUtils.isBlank(id)) {
        LOGGER.warn("Empty id for UserGroup");
        if(LOGGER.isDebugEnabled()) {
            for(Object oa: Collections.list(attrs.getAll())) {
                Attribute a = (Attribute)oa;
                LOGGER.debug("---> " + a);
            }
        }
    }
    group.setExtId(id);
    group.setName(getAttribute(attrs, "groupname"));
    group.setEnabled(true);

    return group;
}
 
Example #5
Source File: DirContextAdapterTest.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
@Test
public void testChangeMultiAttribute_SameValue() throws Exception {
	final Attributes fixtureAttrs = new BasicAttributes();
	Attribute multi = new BasicAttribute("abc");
	multi.add("123");
	multi.add("qwe");
	fixtureAttrs.put(multi);
	class TestableDirContextAdapter extends DirContextAdapter {
		public TestableDirContextAdapter() {
			super(fixtureAttrs, null);
			setUpdateMode(true);
		}
	}
	tested = new TestableDirContextAdapter();
	assertThat(tested.isUpdateMode()).isTrue();
	tested.setAttributeValues("abc", new String[] { "123", "qwe" });

	ModificationItem[] modificationItems = tested.getModificationItems();
	assertThat(modificationItems.length).isEqualTo(0);
}
 
Example #6
Source File: NameAwareAttribute.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
/**
 * Construct a new instance from the supplied Attribute.
 *
 * @param attribute the Attribute to copy.
 */
public NameAwareAttribute(Attribute attribute) {
    this(attribute.getID(), attribute.isOrdered());
    try {
        NamingEnumeration<?> incomingValues = attribute.getAll();
        while(incomingValues.hasMore()) {
            this.add(incomingValues.next());
        }
    } catch (NamingException e) {
        throw LdapUtils.convertLdapException(e);
    }

    if (attribute instanceof NameAwareAttribute) {
        NameAwareAttribute nameAwareAttribute = (NameAwareAttribute) attribute;
        populateValuesAsNames(nameAwareAttribute, this);
    }
}
 
Example #7
Source File: LdapDao.java    From projectforge-webapp with GNU General Public License v3.0 6 votes vote down vote up
/**
 * @param ctx
 * @param ouBase If organizational units are given by the given obj then this parameter will be ignored, otherwise this is the ou where
 *          the new object will be inserted.
 * @param obj
 * @param args
 * @throws NamingException
 */
public void create(final DirContext ctx, final String ouBase, final T obj, final Object... args) throws NamingException
{
  final String dn = buildDn(ouBase, obj);
  log.info("Create " + getObjectClass() + ": " + dn + ": " + getLogInfo(obj));
  final Attributes attrs = new BasicAttributes();
  final List<ModificationItem> modificationItems = getModificationItems(new ArrayList<ModificationItem>(), obj);
  modificationItems.add(createModificationItem(DirContext.ADD_ATTRIBUTE, "objectClass", getObjectClass()));
  final String[] additionalObjectClasses = getAdditionalObjectClasses(obj);
  if (additionalObjectClasses != null) {
    for (final String objectClass : additionalObjectClasses) {
      modificationItems.add(createModificationItem(DirContext.ADD_ATTRIBUTE, "objectClass", objectClass));
    }
  }
  for (final ModificationItem modItem : modificationItems) {
    final Attribute attr = modItem.getAttribute();
    LdapUtils.putAttribute(attrs, attr.getID(), (String) attr.get());
  }
  LdapUtils.putAttribute(attrs, "cn", LdapUtils.escapeCommonName(obj.getCommonName()));
  onBeforeBind(dn, attrs, args);
  ctx.bind(dn, null, attrs);
}
 
Example #8
Source File: NamingManager.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
public static Context getURLContext(
        String scheme, Hashtable<?,?> environment)
        throws NamingException {
    return new DnsContext("", null, new Hashtable<String,String>()) {
        public Attributes getAttributes(String name, String[] attrIds)
                throws NamingException {
            return new BasicAttributes() {
                public Attribute get(String attrID) {
                    BasicAttribute ba  = new BasicAttribute(attrID);
                    ba.add("1 1 99 b.com.");
                    ba.add("0 0 88 a.com.");    // 2nd has higher priority
                    return ba;
                }
            };
        }
    };
}
 
Example #9
Source File: LDAPCertStore.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Get the values for the given attribute. If the attribute is null
 * or does not contain any values, a zero length byte array is
 * returned. NOTE that it is assumed that all values are byte arrays.
 */
private byte[][] getAttributeValues(Attribute attr)
        throws NamingException {
    byte[][] values;
    if (attr == null) {
        values = BB0;
    } else {
        values = new byte[attr.size()][];
        int i = 0;
        NamingEnumeration<?> enum_ = attr.getAll();
        while (enum_.hasMore()) {
            Object obj = enum_.next();
            if (debug != null) {
                if (obj instanceof String) {
                    debug.println("LDAPCertStore.getAttrValues() "
                        + "enum.next is a string!: " + obj);
                }
            }
            byte[] value = (byte[])obj;
            values[i++] = value;
        }
    }
    return values;
}
 
Example #10
Source File: Rdn.java    From dragonwell8_jdk 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 #11
Source File: LDAPCertStore.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Get the values for the given attribute. If the attribute is null
 * or does not contain any values, a zero length byte array is
 * returned. NOTE that it is assumed that all values are byte arrays.
 */
private byte[][] getAttributeValues(Attribute attr)
        throws NamingException {
    byte[][] values;
    if (attr == null) {
        values = BB0;
    } else {
        values = new byte[attr.size()][];
        int i = 0;
        NamingEnumeration<?> enum_ = attr.getAll();
        while (enum_.hasMore()) {
            Object obj = enum_.next();
            if (debug != null) {
                if (obj instanceof String) {
                    debug.println("LDAPCertStore.getAttrValues() "
                        + "enum.next is a string!: " + obj);
                }
            }
            byte[] value = (byte[])obj;
            values[i++] = value;
        }
    }
    return values;
}
 
Example #12
Source File: DirContextAdapterTest.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
@Test
public void testRemoveAttributeValueAttributeWithOtherAndSameValueExists()
		throws NamingException {
	BasicAttribute basicAttribute = new BasicAttribute("abc");
	basicAttribute.add("123");
	basicAttribute.add("321");
	tested.setAttribute(basicAttribute);

	// Perform test
	tested.removeAttributeValue("abc", "123");

	Attributes attributes = tested.getAttributes();
	Attribute attr = attributes.get("abc");
	assertThat(attr).isNotNull();
	assertThat(attr.size()).isEqualTo(1);
	assertThat(attr.get()).isEqualTo("321");
}
 
Example #13
Source File: NamingManager.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
public static Context getURLContext(
        String scheme, Hashtable<?,?> environment)
        throws NamingException {
    return new DnsContext("", null, new Hashtable<String,String>()) {
        public Attributes getAttributes(String name, String[] attrIds)
                throws NamingException {
            return new BasicAttributes() {
                public Attribute get(String attrID) {
                    BasicAttribute ba  = new BasicAttribute(attrID);
                    ba.add("1 1 99 b.com.");
                    ba.add("0 0 88 a.com.");    // 2nd has higher priority
                    return ba;
                }
            };
        }
    };
}
 
Example #14
Source File: LDAPCertStore.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Get the values for the given attribute. If the attribute is null
 * or does not contain any values, a zero length byte array is
 * returned. NOTE that it is assumed that all values are byte arrays.
 */
private byte[][] getAttributeValues(Attribute attr)
        throws NamingException {
    byte[][] values;
    if (attr == null) {
        values = BB0;
    } else {
        values = new byte[attr.size()][];
        int i = 0;
        NamingEnumeration<?> enum_ = attr.getAll();
        while (enum_.hasMore()) {
            Object obj = enum_.next();
            if (debug != null) {
                if (obj instanceof String) {
                    debug.println("LDAPCertStore.getAttrValues() "
                        + "enum.next is a string!: " + obj);
                }
            }
            byte[] value = (byte[])obj;
            values[i++] = value;
        }
    }
    return values;
}
 
Example #15
Source File: DirContextAdapterTest.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
@Test
public void testRemoveAttributeValueInUpdateModeOtherValueExistsInUpdatedAttrs()
		throws NamingException {
	tested.setUpdateMode(true);
	tested.setAttributeValue("abc", "321");

	// Perform test
	tested.removeAttributeValue("abc", "123");

	assertThat(tested.getAttributes().get("abc")).isNull();

	ModificationItem[] modificationItems = tested.getModificationItems();
	assertThat(modificationItems.length).isEqualTo(1);
	Attribute modificationAttribute = modificationItems[0].getAttribute();
	assertThat(modificationAttribute.getID()).isEqualTo("abc");
	assertThat(modificationAttribute.size()).isEqualTo(1);
	assertThat(modificationAttribute.get()).isEqualTo("321");
}
 
Example #16
Source File: LDAPUserRegistry.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Does a case-insensitive search for the given value in an attribute.
 * 
 * @param attribute
 *            the attribute
 * @param value
 *            the value to search for
 * @return <code>true</code>, if the value was found
 * @throws NamingException
 *             if there is a problem accessing the attribute values
 */
private boolean hasAttributeValue(Attribute attribute, String value) throws NamingException
{
    if (attribute != null)
    {
        NamingEnumeration<?> values = attribute.getAll();
        while (values.hasMore())
        {
            try
            {
                if (value.equalsIgnoreCase((String) values.next()))
                {
                    return true;
                }
            }
            catch (ClassCastException e)
            {
                // Not a string value. ignore and continue
            }
        }
    }
    return false;
}
 
Example #17
Source File: LdapUtils.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
/**
 * Collect all the values of a the specified attribute from the supplied
 * Attributes as the specified class.
 *
 * @param attributes The Attributes; not <code>null</code>.
 * @param name The name of the Attribute to get values for.
 * @param collection the collection to collect the values in.
 * @param clazz the class of the collected attribute values
 * @throws NoSuchAttributeException if no attribute with the specified name
 * exists.
 * @throws IllegalArgumentException if an attribute value cannot be cast to the specified class.
 * @since 2.0
 */
public static <T> void collectAttributeValues(
        Attributes attributes, String name, Collection<T> collection, Class<T> clazz) {

    Assert.notNull(attributes, "Attributes must not be null");
    Assert.hasText(name, "Name must not be empty");
    Assert.notNull(collection, "Collection must not be null");

    Attribute attribute = attributes.get(name);
    if (attribute == null) {
        throw new NoSuchAttributeException("No attribute with name '" + name + "'");
    }

    iterateAttributeValues(attribute, new CollectingAttributeValueCallbackHandler<T>(collection, clazz));

}
 
Example #18
Source File: LdapCertificateRepo.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected List<X509Certificate> getCertificatesFromLdap(String tmpRootDN, String tmpFilter, String tmpAttrName) {
    try {
        List<X509Certificate> certificates = new ArrayList<>();
        NamingEnumeration<SearchResult> answer = ldapSearch.searchSubTree(tmpRootDN, tmpFilter);
        while (answer.hasMore()) {
            SearchResult sr = answer.next();
            Attributes attrs = sr.getAttributes();
            Attribute attribute = attrs.get(tmpAttrName);
            if (attribute != null) {
                CertificateFactory cf = CertificateFactory.getInstance("X.509");
                X509Certificate certificate = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(
                        (byte[]) attribute.get()));
                certificates.add(certificate);
            }
        }
        return certificates;
    } catch (CertificateException | NamingException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}
 
Example #19
Source File: LDAPCertStore.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Get the values for the given attribute. If the attribute is null
 * or does not contain any values, a zero length byte array is
 * returned. NOTE that it is assumed that all values are byte arrays.
 */
private byte[][] getAttributeValues(Attribute attr)
        throws NamingException {
    byte[][] values;
    if (attr == null) {
        values = BB0;
    } else {
        values = new byte[attr.size()][];
        int i = 0;
        NamingEnumeration<?> enum_ = attr.getAll();
        while (enum_.hasMore()) {
            Object obj = enum_.next();
            if (debug != null) {
                if (obj instanceof String) {
                    debug.println("LDAPCertStore.getAttrValues() "
                        + "enum.next is a string!: " + obj);
                }
            }
            byte[] value = (byte[])obj;
            values[i++] = value;
        }
    }
    return values;
}
 
Example #20
Source File: LDAPConnection.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
private Attributes buildAttributes( String dn, String[] attributes, String[] values, String multValuedSeparator ) {
  Attributes attrs = new javax.naming.directory.BasicAttributes( true );
  int nrAttributes = attributes.length;
  for ( int i = 0; i < nrAttributes; i++ ) {
    if ( !Utils.isEmpty( values[i] ) ) {
      // We have a value
      String value = values[i].trim();
      if ( multValuedSeparator != null && value.indexOf( multValuedSeparator ) > 0 ) {
        Attribute attr = new javax.naming.directory.BasicAttribute( attributes[i] );
        for ( String attribute : value.split( multValuedSeparator ) ) {
          attr.add( attribute );
        }
        attrs.put( attr );
      } else {
        attrs.put( attributes[i], value );
      }
    }
  }
  return attrs;
}
 
Example #21
Source File: Rdn.java    From openjdk-jdk9 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 {@code attrSet} 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 #22
Source File: NamingManager.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
public static Context getURLContext(
        String scheme, Hashtable<?,?> environment)
        throws NamingException {
    return new DnsContext("", null, new Hashtable<String,String>()) {
        public Attributes getAttributes(String name, String[] attrIds)
                throws NamingException {
            return new BasicAttributes() {
                public Attribute get(String attrID) {
                    BasicAttribute ba  = new BasicAttribute(attrID);
                    ba.add("1 1 99 b.com.");
                    ba.add("0 0 88 a.com.");    // 2nd has higher priority
                    return ba;
                }
            };
        }
    };
}
 
Example #23
Source File: DirContextAdapterTest.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddAttribute_Multivalue() throws Exception {
	final Attributes fixtureAttrs = new BasicAttributes();
	Attribute multi = new BasicAttribute("abc");
	multi.add("123");
	multi.add("qwe");
	fixtureAttrs.put(multi);
	class TestableDirContextAdapter extends DirContextAdapter {
		public TestableDirContextAdapter() {
			super(fixtureAttrs, null);
			setUpdateMode(true);
		}
	}
	tested = new TestableDirContextAdapter();
	assertThat(tested.isUpdateMode()).isTrue();
	tested.setAttributeValues("def", new String[] { "kalle", "klytt" });

	ModificationItem[] modificationItems = tested.getModificationItems();
	assertThat(modificationItems.length).isEqualTo(1);
	assertThat(modificationItems[0].getAttribute().getID()).isEqualTo("def");
}
 
Example #24
Source File: NamingManager.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
public static Context getURLContext(
        String scheme, Hashtable<?,?> environment)
        throws NamingException {
    return new DnsContext("", null, new Hashtable<String,String>()) {
        public Attributes getAttributes(String name, String[] attrIds)
                throws NamingException {
            return new BasicAttributes() {
                public Attribute get(String attrID) {
                    BasicAttribute ba  = new BasicAttribute(attrID);
                    ba.add("1 1 99 b.com.");
                    ba.add("0 0 88 a.com.");    // 2nd has higher priority
                    return ba;
                }
            };
        }
    };
}
 
Example #25
Source File: ReadWriteLDAPUserStoreManager.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
private String getGroupName(SearchResult resultedGroup) throws NamingException {

        Attribute attribute = resultedGroup.getAttributes()
                .get(realmConfig.getUserStoreProperty(LDAPConstants.GROUP_NAME_ATTRIBUTE));
        if (attribute == null) {
            return resultedGroup.getName();
        } else {
            String groupNameAttributeValue = (String) attribute.get();
            return realmConfig.getUserStoreProperty(LDAPConstants.GROUP_NAME_ATTRIBUTE) +
                    "=" + groupNameAttributeValue;
        }
    }
 
Example #26
Source File: GatekeeperOpenLDAPAuthorizationService.java    From Gatekeeper with Apache License 2.0 5 votes vote down vote up
@Override
public GatekeeperUserEntry mapFromAttributes(Attributes attributes) throws NamingException {
    Attribute idAttr    =   attributes.get(ldapUserId);
    Attribute dnAttr    =   attributes.get(ldapUserDn);
    Attribute mailAttr  =   attributes.get(ldapUserEmail);
    Attribute nameAttr  =   attributes.get(ldapUserName);

    String id   =   idAttr      != null ? ((String) idAttr.get()).toLowerCase() : null;
    String dn   =   dnAttr      != null ? (String) dnAttr.get() : null;
    String mail =   mailAttr    != null ? (String) mailAttr.get() : null;
    String name =   nameAttr    != null ? (String) nameAttr.get() : null;


    return new GatekeeperUserEntry(id, dn, mail, name);
}
 
Example #27
Source File: DirContextAdapter.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
/**
 * returns true if the attribute is empty. It is empty if a == null, size ==
 * 0 or get() == null or an exception if thrown when accessing the get
 * method
 */
private boolean isEmptyAttribute(Attribute a) {
	try {
		return (a == null || a.size() == 0 || a.get() == null);
	}
	catch (NamingException e) {
		return true;
	}
}
 
Example #28
Source File: LDAPCertStoreImpl.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Get a map containing the values for this request. The first time
 * this method is called on an object, the LDAP request is sent,
 * the results parsed and added to a private map and also to the
 * cache of this LDAPCertStore. Subsequent calls return the private
 * map immediately.
 *
 * The map contains an entry for each requested attribute. The
 * attribute name is the key, values are byte[][]. If there are no
 * values for that attribute, values are byte[0][].
 *
 * @return                      the value Map
 * @throws NamingException      if a naming exception occurs
 */
private Map<String, byte[][]> getValueMap() throws NamingException {
    if (valueMap != null) {
        return valueMap;
    }
    if (DEBUG) {
        System.out.println("Request: " + name + ":" + requestedAttributes);
        requests++;
        if (requests % 5 == 0) {
            System.out.println("LDAP requests: " + requests);
        }
    }
    valueMap = new HashMap<>(8);
    String[] attrIds = requestedAttributes.toArray(STRING0);
    Attributes attrs;

    if (communicationError) {
        ctx.reconnect(null);
        communicationError = false;
    }

    try {
        attrs = ctx.getAttributes(name, attrIds);
    } catch (CommunicationException ce) {
        communicationError = true;
        throw ce;
    } catch (NameNotFoundException e) {
        // name does not exist on this LDAP server
        // treat same as not attributes found
        attrs = EMPTY_ATTRIBUTES;
    }
    for (String attrId : requestedAttributes) {
        Attribute attr = attrs.get(attrId);
        byte[][] values = getAttributeValues(attr);
        cacheAttribute(attrId, values);
        valueMap.put(attrId, values);
    }
    return valueMap;
}
 
Example #29
Source File: DirContextAdapterTest.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddAttributeValue() throws NamingException {
	// Perform test
	tested.addAttributeValue("abc", "123");

	Attributes attrs = tested.getAttributes();
	Attribute attr = attrs.get("abc");
	assertThat((String) attr.get()).isEqualTo("123");
}
 
Example #30
Source File: ReadOnlyLDAPUsersDAO.java    From james-project with Apache License 2.0 5 votes vote down vote up
/**
 * For a given name, this method makes ldap search in userBase with filter {@link LdapRepositoryConfiguration#userIdAttribute}=name
 * and objectClass={@link LdapRepositoryConfiguration#userObjectClass} and builds {@link User} based on search result.
 *
 * @param name
 *            The userId which should be value of the field {@link LdapRepositoryConfiguration#userIdAttribute}
 * @return A {@link ReadOnlyLDAPUser} instance which is initialized with the
 *         userId of this user and ldap connection information with which
 *         the user was searched. Return null if such a user was not found.
 * @throws NamingException
 *             Propagated by the underlying LDAP communication layer.
 */
private ReadOnlyLDAPUser searchAndBuildUser(Username name) throws NamingException {
    SearchControls sc = new SearchControls();
    sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
    sc.setReturningAttributes(new String[] { ldapConfiguration.getUserIdAttribute() });
    sc.setCountLimit(1);

    String filterTemplate = "(&({0}={1})(objectClass={2})" +
        StringUtils.defaultString(ldapConfiguration.getFilter(), "") +
        ")";

    String sanitizedFilter = FilterEncoder.format(
        filterTemplate,
        ldapConfiguration.getUserIdAttribute(),
        name.asString(),
        ldapConfiguration.getUserObjectClass());

    NamingEnumeration<SearchResult> sr = ldapContext.search(ldapConfiguration.getUserBase(), sanitizedFilter, sc);

    if (!sr.hasMore()) {
        return null;
    }

    SearchResult r = sr.next();
    Attribute userName = r.getAttributes().get(ldapConfiguration.getUserIdAttribute());

    if (!ldapConfiguration.getRestriction().isActivated()
        || userInGroupsMembershipList(r.getNameInNamespace(), ldapConfiguration.getRestriction().getGroupMembershipLists(ldapContext))) {
        return new ReadOnlyLDAPUser(Username.of(userName.get().toString()), r.getNameInNamespace(), ldapContext);
    }

    return null;
}