Java Code Examples for javax.naming.directory.Attribute#get()

The following examples show how to use javax.naming.directory.Attribute#get() . 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: JNDIRealm.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * Return a String representing the value of the specified attribute.
 *
 * @param attrId Attribute name
 * @param attrs Attributes containing the required value
 * @return the attribute value
 * @exception NamingException if a directory server error occurs
 */
private String getAttributeValue(String attrId, Attributes attrs)
    throws NamingException {

    if (containerLog.isTraceEnabled())
        containerLog.trace("  retrieving attribute " + attrId);

    if (attrId == null || attrs == null)
        return null;

    Attribute attr = attrs.get(attrId);
    if (attr == null)
        return null;
    Object value = attr.get();
    if (value == null)
        return null;
    String valueString = null;
    if (value instanceof byte[])
        valueString = new String((byte[]) value);
    else
        valueString = value.toString();

    return valueString;
}
 
Example 2
Source File: Rdn.java    From jdk8u-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 3
Source File: JNDIRealm.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
/**
 * Return a String representing the value of the specified attribute.
 *
 * @param attrId Attribute name
 * @param attrs Attributes containing the required value
 *
 * @exception NamingException if a directory server error occurs
 */
private String getAttributeValue(String attrId, Attributes attrs)
    throws NamingException {

    if (containerLog.isTraceEnabled())
        containerLog.trace("  retrieving attribute " + attrId);

    if (attrId == null || attrs == null)
        return null;

    Attribute attr = attrs.get(attrId);
    if (attr == null)
        return (null);
    Object value = attr.get();
    if (value == null)
        return (null);
    String valueString = null;
    if (value instanceof byte[])
        valueString = new String((byte[]) value);
    else
        valueString = value.toString();

    return valueString;
}
 
Example 4
Source File: LdapExtLoginModule.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns Attributes from referral entity and check them if they belong to user or userDN currently in evaluation.
 * Returns null in case of user is not validated.
 *
 * @param sr SearchResult
 * @param users to check
 * @return
 * @throws NamingException
 */
private Attributes getAttributesFromReferralEntity(SearchResult sr, String... users) throws NamingException {

   Attributes result = sr.getAttributes();
   boolean chkSuccessful = false;
   if (referralUserAttributeIDToCheck != null) {
      Attribute usersToCheck = result.get(referralUserAttributeIDToCheck);
      check:
      for (int i = 0; usersToCheck != null && i < usersToCheck.size(); i++) {
         String userDNToCheck = (String) usersToCheck.get(i);
         for (String u: users) {
            if (u.equals(userDNToCheck)) {
               chkSuccessful = true;
               break check;
            }
         }
      }
   }
   return (chkSuccessful ? result : null);
}
 
Example 5
Source File: Rdn.java    From jdk8u-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 6
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 7
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 8
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 9
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 10
Source File: DefaultObjectDirectoryMapper.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
private <T> void populateSingleValueField(T result, Map<CaseIgnoreString, Attribute> attributeValueMap, Field field, AttributeMetaData attributeInfo) throws NamingException, IllegalAccessException {
    Attribute attribute = attributeValueMap.get(attributeInfo.getName());
    // There is no guarantee that this attribute is present in the directory - so ignore nulls
    if (attribute != null) {
        // Grab the JNDI value
        Object value = attribute.get();
        // Check the value is not null
        if (value != null) {
            // Convert the JNDI value to its Java representation - this will throw if the
            // conversion fails
            Object convertedValue = converterManager.convert(value, attributeInfo.getSyntax(),
                    attributeInfo.getValueClass());
            // Set it in the Java version
            field.set(result, convertedValue);
        }
    }
}
 
Example 11
Source File: LdapUserGroupProvider.java    From nifi-registry 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 12
Source File: LoginServiceLdapImpl.java    From griffin with Apache License 2.0 5 votes vote down vote up
private String getAttributeValue(SearchResult searchResult, String key, String defaultValue) throws NamingException {
    Attributes attrs = searchResult.getAttributes();
    if (attrs == null) {
        return defaultValue;
    }
    Attribute attrObj = attrs.get(key);
    if (attrObj == null) {
        return defaultValue;
    }
    try {
        return (String) attrObj.get();
    } catch (NoSuchElementException e) {
        return defaultValue;
    }
}
 
Example 13
Source File: ModifyAttributesOperationRecorderTest.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetCompensatingModificationItem_ReplaceExistingAttribute()
        throws NamingException {
    BasicAttribute attribute = new BasicAttribute("someattr");
    attribute.add("value1");
    attribute.add("value2");
    Attributes attributes = new BasicAttributes();
    attributes.put(attribute);

    BasicAttribute modificationAttribute = new BasicAttribute("someattr");
    modificationAttribute.add("newvalue1");
    modificationAttribute.add("newvalue2");
    ModificationItem originalItem = new ModificationItem(
            DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("someattr"));

    // Perform test
    ModificationItem result = tested.getCompensatingModificationItem(
            attributes, originalItem);

    // Verify result
    assertThat(result.getModificationOp()).isEqualTo(DirContext.REPLACE_ATTRIBUTE);
    Attribute resultAttribute = result.getAttribute();
    assertThat(resultAttribute.getID()).isEqualTo("someattr");
    Object object = resultAttribute.get(0);
    assertThat(object).isEqualTo("value1");
    assertThat(resultAttribute.get(1)).isEqualTo("value2");
}
 
Example 14
Source File: J_AbstractVerifier_F.java    From steady with Apache License 2.0 5 votes vote down vote up
static String[] extractCNs(final String subjectPrincipal) throws SSLException {
    if (subjectPrincipal == null) {
        return null;
    }
    final List<String> cns = new ArrayList<String>();
    try {
        final LdapName subjectDN = new LdapName(subjectPrincipal);
        final List<Rdn> rdns = subjectDN.getRdns();
        for (int i = rdns.size() - 1; i >= 0; i--) {
            final Rdn rds = rdns.get(i);
            final Attributes attributes = rds.toAttributes();
            final Attribute cn = attributes.get("cn");
            if (cn != null) {
                try {
                    final Object value = cn.get();
                    if (value != null) {
                        cns.add(value.toString());
                    }
                } catch (NamingException ignore) {
                }
            }
        }
    } catch (InvalidNameException e) {
        throw new SSLException(subjectPrincipal + " is not a valid X500 distinguished name");
    }
    return cns.isEmpty() ? null : cns.toArray(new String[ cns.size() ]);
}
 
Example 15
Source File: LdapUtils.java    From projectforge-webapp with GNU General Public License v3.0 5 votes vote down vote up
public static String getAttributeStringValue(final Attributes attributes, final String attrId) throws NamingException
{
  final Attribute attr = attributes.get(attrId);
  if (attr == null) {
    return null;
  }
  return (String) attr.get();
}
 
Example 16
Source File: LDAPLoginManagerImpl.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * Extracts Value out of LDAP Attribute
 * 
 * @param attribute
 *            LDAP Naming Attribute
 * @return String value of Attribute, null on Exception
 * @throws NamingException
 */
private String getAttributeValue(final Attribute attribute) {
    try {
        final String attrValue = (String) attribute.get();
        return attrValue;
    } catch (final NamingException e) {
        log.error("NamingException when trying to get attribute value for attribute::" + attribute, e);
        return null;
    }
}
 
Example 17
Source File: DirContextURLConnection.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the name of the specified header field.
 */
@Override
public String getHeaderField(String name) {

    if (!connected) {
        // Try to connect (silently)
        try {
            connect();
        } catch (IOException e) {
            // Ignore
        }
    }

    if (attributes == null)
        return (null);

    NamingEnumeration<String> attributeEnum = attributes.getIDs();
    try {
        while (attributeEnum.hasMore()) {
            String attributeID = attributeEnum.next();
            if (attributeID.equalsIgnoreCase(name)) {
                Attribute attribute = attributes.get(attributeID);
                if (attribute == null) return null;
                Object attrValue = attribute.get(attribute.size()-1);
                return getHeaderValueAsString(attrValue);
            }
        }
    } catch (NamingException ne) {
        // Shouldn't happen
    }

    return (null);

}
 
Example 18
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 19
Source File: SubjectMatterExpertDaoImpl.java    From herd with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves a single attribute value from attributes per specified attribute id.
 *
 * @param attributes the attributes from a search result
 * @param attributeId the attribute id
 *
 * @return the value of the attribute, or null if attribute value is not present
 */
private String getAttributeById(Attributes attributes, String attributeId) throws NamingException
{
    String attributeValue = null;

    Attribute attribute = attributes.get(attributeId);
    if (attribute != null)
    {
        attributeValue = (String) attribute.get();
    }

    return attributeValue;
}
 
Example 20
Source File: LDAPUserRegistry.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
private NodeDescription mapToNode(Map<String, String> attributeMapping, Map<String, String> attributeDefaults,
        SearchResult result) throws NamingException
{
    NodeDescription nodeDescription = new NodeDescription(result.getNameInNamespace());
    Attributes ldapAttributes = result.getAttributes();

    // Parse the timestamp
    Attribute modifyTimestamp = ldapAttributes.get(this.modifyTimestampAttributeName);
    if (modifyTimestamp != null)
    {
        try
        {
            nodeDescription.setLastModified(this.timestampFormat.parse(modifyTimestamp.get().toString()));
        }
        catch (ParseException e)
        {
            throw new AlfrescoRuntimeException("Failed to parse timestamp.", e);
        }
    }

    // Apply the mapped attributes
    PropertyMap properties = nodeDescription.getProperties();
    for (String key : attributeMapping.keySet())
    {
        QName keyQName = QName.createQName(key, this.namespaceService);

        // cater for null
        String attributeName = attributeMapping.get(key);
        if (attributeName != null)
        {
            Attribute attribute = ldapAttributes.get(attributeName);
            String defaultAttribute = attributeDefaults.get(key);
            
            if (attribute != null)
            {
                String value = (String) attribute.get(0);
                if (value != null)
                {
                    properties.put(keyQName, value);
                }
            }
            else if (defaultAttribute != null)
            {
                properties.put(keyQName, defaultAttribute);
            }
            else
            {
                // Make sure that a 2nd sync, updates deleted ldap attributes(MNT-14026)
                properties.put(keyQName, null);
            }
        }
        else
        {
            String defaultValue = attributeDefaults.get(key);
            if (defaultValue != null)
            {
                properties.put(keyQName, defaultValue);
            }
        }
    }
    return nodeDescription;
}