下面列出了怎么用javax.naming.ldap.LdapName的API类实例代码及写法,或者点击链接到github查看源代码。
@SuppressWarnings("deprecation")
private static void loadLdif(DirContext context, Name rootNode, Resource ldifFile) {
try {
LdapName baseDn = (LdapName)
context.getEnvironment().get(DefaultDirObjectFactory.JNDI_ENV_BASE_PATH_KEY);
LdifParser parser = new LdifParser(ldifFile);
parser.open();
while (parser.hasMoreRecords()) {
LdapAttributes record = parser.getRecord();
LdapName dn = record.getName();
if(baseDn != null) {
dn = LdapUtils.removeFirst(dn, baseDn);
}
if(!rootNode.isEmpty()) {
dn = LdapUtils.prepend(dn, rootNode);
}
context.bind(dn, null, record);
}
} catch (Exception e) {
throw new UncategorizedLdapException("Failed to populate LDIF", e);
}
}
private Role createRole(LdapName dn, Attributes attr) throws NamingException {
// Must attributes
String cn = getAttributeAsString(attr, ATTR_COMMON_NAME);
// May attributes
String description = getAttributeAsString(attr, ATTR_DESCRIPTION);
String notes = getAttributeAsString(attr, ATTR_NOTES);
String displayName = getAttributeAsString(attr, ATTR_DISPLAYNAME);
String yawlInternalId = getAttributeAsString(attr, ATTR_YAWL_INTERNAL_ID);
Role role = new Role(cn);
role.setDescription(description);
role.setNotes(notes);
if (isNotNullOrEmpty(yawlInternalId)) {
role.setID(yawlInternalId);
} else {
role.setID(UUID.nameUUIDFromBytes(dn.toString().getBytes()).toString());
}
if (isNotNullOrEmpty(displayName)) {
role.setLabel(displayName);
}
return role;
}
/**
* Removes the cache entry given the user name.
*
* @param userName the User name to remove.
* @return true if removal was successful.
*/
protected boolean removeFromUserCache(String userName) {
try {
Cache<String, LdapName> userDnCache = createOrGetUserDnCache();
if (userDnCache == null) {
// User cache may be null while initializing.
// Return true as removal result is successful when there is no cache. Nothing was held.
return true;
}
return userDnCache.remove(userName);
} catch (IllegalStateException e) {
// There is no harm ignoring the removal, as the cache(local) is already is of no use.
log.error("Error occurred while removing User DN from cache having search base : " + userSearchBase, e);
return true;
}
}
public void initValuesAsNames() {
if(hasValuesAsNames()) {
return;
}
Map<Name, String> newValuesAsNames = new HashMap<Name, String>();
for (Object value : values) {
if (value instanceof String) {
String s = (String) value;
try {
newValuesAsNames.put(LdapUtils.newLdapName(s), s);
} catch (InvalidNameException e) {
throw new IllegalArgumentException("This instance has values that are not valid distinguished names; " +
"cannot handle Name values", e);
}
} else if (value instanceof LdapName) {
newValuesAsNames.put((LdapName) value, value.toString());
} else {
throw new IllegalArgumentException("This instance has non-string attribute values; " +
"cannot handle Name values");
}
}
this.valuesAsNames = newValuesAsNames;
}
/**
* Returns true if the two provided DNs are equivalent, regardless of the order of the elements. Returns false if one or both are invalid DNs.
* <p>
* Example:
* <p>
* CN=test1, O=testOrg, C=US compared to CN=test1, O=testOrg, C=US -> true
* CN=test1, O=testOrg, C=US compared to O=testOrg, CN=test1, C=US -> true
* CN=test1, O=testOrg, C=US compared to CN=test2, O=testOrg, C=US -> false
* CN=test1, O=testOrg, C=US compared to O=testOrg, CN=test2, C=US -> false
* CN=test1, O=testOrg, C=US compared to -> false
* compared to -> true
*
* @param dn1 the first DN to compare
* @param dn2 the second DN to compare
* @return true if the DNs are equivalent, false otherwise
*/
public static boolean compareDNs(String dn1, String dn2) {
if (dn1 == null) {
dn1 = "";
}
if (dn2 == null) {
dn2 = "";
}
if (StringUtils.isEmpty(dn1) || StringUtils.isEmpty(dn2)) {
return dn1.equals(dn2);
}
try {
List<Rdn> rdn1 = new LdapName(dn1).getRdns();
List<Rdn> rdn2 = new LdapName(dn2).getRdns();
return rdn1.size() == rdn2.size() && rdn1.containsAll(rdn2);
} catch (InvalidNameException e) {
logger.warn("Cannot compare DNs: {} and {} because one or both is not a valid DN", dn1, dn2);
return false;
}
}
public static String extractCnFromDn(String dn) {
String cn = null;
try {
LdapName ldapName = new LdapName(dn);
for (Rdn rdn : ldapName.getRdns()) {
if (rdn.getType().equalsIgnoreCase("CN")) {
cn = (String) rdn.getValue();
}
}
} catch (InvalidNameException e) {
throw new IllegalArgumentException("Invalid DN: " + dn, e);
}
if (cn == null) {
throw new IllegalArgumentException("Can't find CN in DN: " + dn);
}
return cn;
}
/**
* Returns the BaseDN for the given groupname.
*
* @param groupname groupname to return its base DN.
* @return the BaseDN for the given groupname. If no baseDN is found,
* this method will return {@code null}.
*/
public LdapName getGroupsBaseDN(String groupname) {
try {
findGroupRDN(groupname, baseDN);
return baseDN;
}
catch (Exception e) {
try {
if (alternateBaseDN != null) {
findGroupRDN(groupname, alternateBaseDN);
return alternateBaseDN;
}
}
catch (Exception ex) {
Log.debug("An exception occurred while trying to find the base dn for group: {}", groupname, ex);
}
}
return null;
}
@Test
public void testLookupContextWithName() {
final DirContextAdapter expectedResult = new DirContextAdapter();
final LdapName expectedName = LdapUtils.emptyLdapName();
LdapTemplate tested = new LdapTemplate() {
public Object lookup(Name dn) {
assertThat(dn).isSameAs(dn);
return expectedResult;
}
};
DirContextOperations result = tested.lookupContext(expectedName);
assertThat(result).isSameAs(expectedResult);
}
/**
* Find the Rdn with the requested key in the supplied Name.
*
* @param name the Name in which to search for the key.
* @param key the attribute key to search for.
* @return the rdn corresponding to the <b>first</b> occurrence of the requested key.
* @throws NoSuchElementException if no corresponding entry is found.
* @since 2.0
*/
public static Rdn getRdn(Name name, String key) {
Assert.notNull(name, "name must not be null");
Assert.hasText(key, "key must not be blank");
LdapName ldapName = returnOrConstructLdapNameFromName(name);
List<Rdn> rdns = ldapName.getRdns();
for (Rdn rdn : rdns) {
NamingEnumeration<String> ids = rdn.toAttributes().getIDs();
while (ids.hasMoreElements()) {
String id = ids.nextElement();
if(key.equalsIgnoreCase(id)) {
return rdn;
}
}
}
throw new NoSuchElementException("No Rdn with the requested key: '" + key + "'");
}
public DistinguishedName(X500Principal principal) throws TechnicalConnectorException {
CertificateParser parser = new CertificateParser(principal.getName("RFC2253"));
this.setId(parser.getId());
this.setType(parser.getIdentifier());
this.setApplicationId(parser.getApplication());
try {
List<Rdn> rdns = (new LdapName(principal.getName("RFC1779"))).getRdns();
Iterator i$ = rdns.iterator();
while(i$.hasNext()) {
Rdn rdn = (Rdn)i$.next();
if (rdn.getType().equals("OU")) {
String value = this.getValue(rdn.getValue());
if (!"eHealth-platform Belgium".equals(value) && !value.contains("=")) {
this.setName(this.getValue(rdn.getValue()));
break;
}
}
}
} catch (InvalidNameException var7) {
throw new IllegalArgumentException("Invalid Principal", var7);
}
}
public DistinguishedName(X500Principal principal) throws TechnicalConnectorException {
CertificateParser parser = new CertificateParser(principal.getName("RFC2253"));
this.setId(parser.getId());
this.setType(parser.getIdentifier());
this.setApplicationId(parser.getApplication());
try {
List<Rdn> rdns = (new LdapName(principal.getName("RFC1779"))).getRdns();
Iterator i$ = rdns.iterator();
while(i$.hasNext()) {
Rdn rdn = (Rdn)i$.next();
if (rdn.getType().equals("OU")) {
String value = this.getValue(rdn.getValue());
if (!"eHealth-platform Belgium".equals(value) && !value.contains("=")) {
this.setName(this.getValue(rdn.getValue()));
break;
}
}
}
} catch (InvalidNameException var7) {
throw new IllegalArgumentException("Invalid Principal", var7);
}
}
public DistinguishedName(X500Principal principal) throws TechnicalConnectorException {
CertificateParser parser = new CertificateParser(principal.getName("RFC2253"));
this.setId(parser.getId());
this.setType(parser.getIdentifier());
this.setApplicationId(parser.getApplication());
try {
List<Rdn> rdns = (new LdapName(principal.getName("RFC1779"))).getRdns();
Iterator i$ = rdns.iterator();
while(i$.hasNext()) {
Rdn rdn = (Rdn)i$.next();
if (rdn.getType().equals("OU")) {
String value = this.getValue(rdn.getValue());
if (!"eHealth-platform Belgium".equals(value) && !value.contains("=")) {
this.setName(this.getValue(rdn.getValue()));
break;
}
}
}
} catch (InvalidNameException var7) {
throw new IllegalArgumentException("Invalid Principal", var7);
}
}
/**
* Set the list of Athenz CA issuers with their full DNs that
* ZPE should honor.
* @param issuers list of Athenz CA issuers separated by |
*/
public static void setX509CAIssuers(final String issuers) {
if (issuers == null || issuers.isEmpty()) {
return;
}
String[] issuerArray = issuers.split("\\|");
for (String issuer : issuerArray) {
if (LOG.isDebugEnabled()) {
LOG.debug("x509 issuer: {}", issuer);
}
X509_ISSUERS_NAMES.add(issuer.replaceAll("\\s+", ""));
try {
X509_ISSUERS_RDNS.add(new LdapName(issuer).getRdns());
} catch (InvalidNameException ex) {
LOG.error("Invalid issuer: {}, error: {}", issuer, ex.getMessage());
}
}
}
private static void loadLdif(DirContext context, Name rootNode, Resource ldifFile) {
try {
LdapName baseDn = (LdapName)
context.getEnvironment().get(DefaultDirObjectFactory.JNDI_ENV_BASE_PATH_KEY);
LdifParser parser = new LdifParser(ldifFile);
parser.open();
while (parser.hasMoreRecords()) {
LdapAttributes record = parser.getRecord();
LdapName dn = record.getName();
if(baseDn != null) {
dn = LdapUtils.removeFirst(dn, baseDn);
}
if(!rootNode.isEmpty()) {
dn = LdapUtils.prepend(dn, rootNode);
}
context.bind(dn, null, record);
}
} catch (Exception e) {
throw new UncategorizedLdapException("Failed to populate LDIF", e);
}
}
/**
* Returns true if the two provided DNs are equivalent, regardless of the order of the elements. Returns false if one or both are invalid DNs.
*
* Example:
*
* CN=test1, O=testOrg, C=US compared to CN=test1, O=testOrg, C=US -> true
* CN=test1, O=testOrg, C=US compared to O=testOrg, CN=test1, C=US -> true
* CN=test1, O=testOrg, C=US compared to CN=test2, O=testOrg, C=US -> false
* CN=test1, O=testOrg, C=US compared to O=testOrg, CN=test2, C=US -> false
* CN=test1, O=testOrg, C=US compared to -> false
* compared to -> true
*
* @param dn1 the first DN to compare
* @param dn2 the second DN to compare
* @return true if the DNs are equivalent, false otherwise
*/
public static boolean compareDNs(String dn1, String dn2) {
if (dn1 == null) {
dn1 = "";
}
if (dn2 == null) {
dn2 = "";
}
if (StringUtils.isEmpty(dn1) || StringUtils.isEmpty(dn2)) {
return dn1.equals(dn2);
}
try {
List<Rdn> rdn1 = new LdapName(dn1).getRdns();
List<Rdn> rdn2 = new LdapName(dn2).getRdns();
return rdn1.size() == rdn2.size() && rdn1.containsAll(rdn2);
} catch (InvalidNameException e) {
logger.warn("Cannot compare DNs: {} and {} because one or both is not a valid DN", dn1, dn2);
return false;
}
}
@Test
public void testUpdateWithIdChanged() throws NamingException {
Object expectedObject = new Object();
when(contextSourceMock.getReadWriteContext()).thenReturn(dirContextMock, dirContextMock);
LdapName expectedOriginalName = LdapUtils.newLdapName("ou=someOu");
LdapName expectedNewName = LdapUtils.newLdapName("ou=someOtherOu");
ArgumentCaptor<DirContextAdapter> ctxCaptor = ArgumentCaptor.forClass(DirContextAdapter.class);
doNothing().when(odmMock).mapToLdapDataEntry(eq(expectedObject), ctxCaptor.capture());
when(odmMock.getId(expectedObject)).thenReturn(expectedOriginalName);
when(odmMock.getCalculatedId(expectedObject)).thenReturn(expectedNewName);
tested.update(expectedObject);
verify(odmMock).setId(expectedObject, expectedNewName);
verify(dirContextMock).unbind(expectedOriginalName);
verify(dirContextMock).bind(expectedNewName, ctxCaptor.getValue(), null);
verify(dirContextMock, times(2)).close();
}
/**
* Remove the supplied path from the beginning the specified
* <code>Name</code> if the name instance starts with
* <code>path</code>. Useful for stripping base path suffix from a
* <code>Name</code>. The original Name will not be affected.
*
* @param dn the dn to strip from.
* @param pathToRemove the path to remove from the beginning the dn instance.
* @return an LdapName instance that is a copy of the original name with the
* specified path stripped from its beginning.
* @since 2.0
*/
public static LdapName removeFirst(Name dn, Name pathToRemove) {
Assert.notNull(dn, "dn must not be null");
Assert.notNull(pathToRemove, "pathToRemove must not be null");
LdapName result = newLdapName(dn);
LdapName path = returnOrConstructLdapNameFromName(pathToRemove);
if(path.size() == 0 || !dn.startsWith(path)) {
return result;
}
for(int i = 0; i < path.size(); i++) {
try {
result.remove(0);
} catch (InvalidNameException e) {
throw convertLdapException(e);
}
}
return result;
}
/**
* Returns Subject DN from X509Certificate
*
* @param cert
* @return Subject DN as a user name
*/
@Override
public String getUserName(Certificate cert) {
X509Certificate certificate = (X509Certificate) cert;
String dn = certificate.getSubjectDN().getName();
LdapName ldapDn = getLdapName(dn);
if (key == null) {
throw new IllegalArgumentException("Must set a key");
}
for (Rdn rdn : ldapDn.getRdns()) {
if (key.equalsIgnoreCase(rdn.getType())) {
return (String)rdn.getValue();
}
}
throw new IllegalArgumentException("No " + key + " key found in certificate DN: " + dn);
}
private void initMaps() {
// init maps
// this map contains <UID, DN> pairs to resolve a uid to a DN used
_uid2dnMap = new HashMap<String, String>();
_inputMap = new HashMap<LdapName, Attributes>();
_participantsWithDNasKey = new HashMap<String, Participant>();
_participantsWithIDasKey = new HashMap<String, Participant>();
_rolesWithDNasKey = new HashMap<String, Role>();
_rolesWithIDasKey = new HashMap<String, Role>();
_orgGroupsWithDNasKey = new HashMap<String, OrgGroup>();
_orgGroupsWithIDasKey = new HashMap<String, OrgGroup>();
_capabilitiesWithDNasKey = new HashMap<String, Capability>();
_capabilitiesWithIDasKey = new HashMap<String, Capability>();
_positionsWithDNasKey = new HashMap<String, Position>();
_positionsWithIDasKey = new HashMap<String, Position>();
}
private Position createPosition(LdapName dn, Attributes attr) throws NamingException {
// Must attributes
String cn = getAttributeAsString(attr, ATTR_COMMON_NAME);
// May attributes
String description = getAttributeAsString(attr, ATTR_DESCRIPTION);
String notes = getAttributeAsString(attr, ATTR_NOTES);
String displayName = getAttributeAsString(attr, ATTR_DISPLAYNAME);
String yawlInternalId = getAttributeAsString(attr, ATTR_YAWL_INTERNAL_ID);
Position position = new Position(cn);
if (isNotNullOrEmpty(yawlInternalId)) {
position.setID(yawlInternalId);
} else {
position.setID(UUID.nameUUIDFromBytes(dn.toString().getBytes()).toString());
}
position.setDescription(description);
position.setNotes(notes);
if (isNotNullOrEmpty(displayName)) {
position.setLabel(displayName);
}
return position;
}
@Test
public void testCommit() {
LdapName expectedOriginalDn = LdapUtils.newLdapName(
"cn=john doe");
LdapName expectedTempDn = LdapUtils.newLdapName(
"cn=john doe_temp");
Object expectedObject = new Object();
BasicAttributes expectedAttributes = new BasicAttributes();
RebindOperationExecutor tested = new RebindOperationExecutor(
ldapOperationsMock, expectedOriginalDn, expectedTempDn,
expectedObject, expectedAttributes);
// perform test
tested.commit();
verify(ldapOperationsMock).unbind(expectedTempDn);
}
/**
* Test if {@link LdapManager#getProviderURL(LdapName)} generates a URL using basic attributes (happy-flow test).
*/
@Test
public void testGetProviderURL() throws Exception
{
// Setup fixture.
final Map<String, String> properties = new HashMap<>();
properties.put("ldap.host", "localhost");
properties.put("ldap.port", "389");
final LdapManager manager = new LdapManager( properties );
final LdapName name = new LdapName("ou=people,dc=example,dc=org");
// Execute system under test.
final String result = manager.getProviderURL( name );
// Verify result.
assertEquals("ldaps://localhost:389/ou=people,dc=example,dc=org", result);
}
public void ldapInjectionSunApi(String input) throws NamingException {
//Stub instances
Properties props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
props.put(Context.PROVIDER_URL, "ldap://ldap.example.com");
props.put(Context.REFERRAL, "ignore");
SearchControls ctrls = new SearchControls();
ctrls.setReturningAttributes(new String[]{"givenName", "sn"});
ctrls.setSearchScope(SearchControls.SUBTREE_SCOPE);
//Two context instances mostly usable with sun specific API
LdapCtx context5 = null;
EventDirContext context6 = null; //LdapCtx is the only known class to implements to this interface
NamingEnumeration<SearchResult> answers;
answers = context5.search(new LdapName("dc=People,dc=example,dc=com"), "(uid=" + input + ")", ctrls);
answers = context5.search(new LdapName("dc=People,dc=example,dc=com"), "(uid=" + input + ")", new Object[0], ctrls);
answers = context5.search("dc=People,dc=example,dc=com", "(uid=" + input + ")", ctrls);
answers = context5.search("dc=People,dc=example,dc=com", "(uid=" + input + ")", new Object[0], ctrls);
answers = context6.search(new LdapName("dc=People,dc=example,dc=com"), "(uid=" + input + ")", ctrls);
answers = context6.search(new LdapName("dc=People,dc=example,dc=com"), "(uid=" + input + ")", new Object[0], ctrls);
answers = context6.search("dc=People,dc=example,dc=com", "(uid=" + input + ")", ctrls);
answers = context6.search("dc=People,dc=example,dc=com", "(uid=" + input + ")", new Object[0], ctrls);
}
@Test
public void testRemoveFirstEmptyBase() throws InvalidNameException {
LdapName ldapName = new LdapName(EXPECTED_DN_STRING);
LdapName result = LdapUtils.removeFirst(ldapName, LdapUtils.emptyLdapName());
assertThat(result).isNotSameAs(ldapName);
assertThat(result).isEqualTo(ldapName);
}
/**
*
* @see <a href="https://stackoverflow.com/questions/2914521/how-to-extract-cn-from-x509certificate-in-java>https://stackoverflow.com/questions/2914521/how-to-extract-cn-from-x509certificate-in-java</a>
*/
public static Set<String> parse( String distinguishedName, String identifier ) throws Exception
{
final Set<String> result = new HashSet<>();
final LdapName ln = new LdapName( distinguishedName);
for( final Rdn rdn : ln.getRdns() )
{
if( rdn.getType().equalsIgnoreCase( identifier ) )
{
result.add( rdn.getValue().toString() );
}
}
return result;
}
@Override
public Group getGroup(String groupName) throws GroupNotFoundException {
try {
LdapName groupDN = manager.findGroupAbsoluteDN(groupName);
return getGroupByDN(groupDN, new HashSet<>(Collections.singleton(groupDN.toString())));
}
catch (Exception e) {
Log.error("Unable to load group: {}", groupName, e);
throw new GroupNotFoundException("Group with name " + groupName + " not found.", e);
}
}
private static String escapeDn(String dn) throws InvalidNameException {
final LdapName dnName = new LdapName(dn);
final List<Rdn> escaped = new ArrayList<>(dnName.size());
for(Rdn rdn: dnName.getRdns()) {
escaped.add(new Rdn(rdn.getType(), escapeForwardSlash(rdn.getValue())));
}
return new LdapName(escaped).toString();
}
public Name composeName(Name name, Name prefix)
throws NamingException
{
Name result;
// Handle compound names. A pair of LdapNames is an easy case.
if ((name instanceof LdapName) && (prefix instanceof LdapName)) {
result = (Name)(prefix.clone());
result.addAll(name);
return new CompositeName().add(result.toString());
}
if (!(name instanceof CompositeName)) {
name = new CompositeName().add(name.toString());
}
if (!(prefix instanceof CompositeName)) {
prefix = new CompositeName().add(prefix.toString());
}
int prefixLast = prefix.size() - 1;
if (name.isEmpty() || prefix.isEmpty() ||
name.get(0).equals("") || prefix.get(prefixLast).equals("")) {
return super.composeName(name, prefix);
}
result = (Name)(prefix.clone());
result.addAll(name);
if (parentIsLdapCtx) {
String ldapComp = concatNames(result.get(prefixLast + 1),
result.get(prefixLast));
result.remove(prefixLast + 1);
result.remove(prefixLast);
result.add(prefixLast, ldapComp);
}
return result;
}
@Test
public void testGetTemporaryDN_MultivalueDN() {
LdapName expectedOriginalName = LdapUtils.newLdapName(
"cn=john doe+sn=doe, ou=somecompany, c=SE");
DefaultTempEntryRenamingStrategy tested = new DefaultTempEntryRenamingStrategy();
Name result = tested.getTemporaryName(expectedOriginalName);
assertThat(result.toString()).isEqualTo("cn=john doe+sn=doe_temp,ou=somecompany,c=SE");
}
/**
* {@inheritDoc}
*/
@Override
public <T> T lookup(final String dn, final String[] attributes, final ContextMapper<T> mapper) {
return executeReadOnly(new ContextExecutor<T>() {
public T executeWithContext(DirContext ctx) throws javax.naming.NamingException {
Attributes filteredAttributes = ctx.getAttributes(dn, attributes);
LdapName name = LdapUtils.newLdapName(dn);
DirContextAdapter contextAdapter = new DirContextAdapter(filteredAttributes, name);
return mapper.mapFromContext(contextAdapter);
}
});
}