下面列出了怎么用javax.naming.directory.Attribute的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 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;
}
@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);
}
/**
* 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);
}
}
@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;
}
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;
}
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();
}
/**
* @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);
}
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;
}
};
}
};
}
/**
* 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;
}
/**
* 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
}
/**
* 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;
}
@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");
}
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;
}
};
}
};
}
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;
}
};
}
};
}
@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");
}
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;
}
};
}
};
}
/**
* 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
}
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;
}
/**
* 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;
}
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);
}
}
/**
* 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));
}
/**
* 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;
}
@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");
}
/**
* 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;
}
/**
* 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;
}
}
private void collectModifications(Attribute originalAttr,
Attribute changedAttr, List<ModificationItem> modificationList)
throws NamingException {
Attribute originalClone = (Attribute) originalAttr.clone();
Attribute addedValuesAttribute = new NameAwareAttribute(originalAttr
.getID());
NamingEnumeration<?> allValues = changedAttr.getAll();
while(allValues.hasMoreElements()) {
Object attributeValue = allValues.nextElement();
if (!originalClone.remove(attributeValue)) {
addedValuesAttribute.add(attributeValue);
}
}
// We have now traversed and removed all values from the original that
// were also present in the new values. The remaining values in the
// original must be the ones that were removed.
if(originalClone.size() > 0 && originalClone.size() == originalAttr.size()) {
// This is actually a complete replacement of the attribute values.
// Fall back to REPLACE
modificationList.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
addedValuesAttribute));
} else {
if (originalClone.size() > 0) {
modificationList.add(new ModificationItem(
DirContext.REMOVE_ATTRIBUTE, originalClone));
}
if (addedValuesAttribute.size() > 0) {
modificationList.add(new ModificationItem(DirContext.ADD_ATTRIBUTE,
addedValuesAttribute));
}
}
}
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;
}
}
/**
* Returns a attribute given it's id
*
* @param attributeId
* The attribute Id
* @return The attribute if it exists
*/
public Attribute get( String attributeId )
{
if ( "dn".equalsIgnoreCase( attributeId ) )
{
return new BasicAttribute( "dn", dn );
}
return attributeList.get( attributeId );
}
@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");
}
/**
* Retrieves the {@link javax.naming.directory.Attributes Attributes}
* view of the type/value mappings contained in this Rdn.
*
* @return The non-null attributes containing the type/value
* mappings of this Rdn.
*/
public Attributes toAttributes() {
Attributes attrs = new BasicAttributes(true);
for (int i = 0; i < entries.size(); i++) {
RdnEntry entry = entries.get(i);
Attribute attr = attrs.put(entry.getType(), entry.getValue());
if (attr != null) {
attr.add(entry.getValue());
attrs.put(attr);
}
}
return attrs;
}