X-Git-Url: https://git.argeo.org/?p=lgpl%2Fargeo-commons.git;a=blobdiff_plain;f=org.argeo.api.acr%2Fsrc%2Forg%2Fargeo%2Fapi%2Facr%2Fldap%2FLdapNameUtils.java;fp=org.argeo.api.acr%2Fsrc%2Forg%2Fargeo%2Fapi%2Facr%2Fldap%2FLdapNameUtils.java;h=72fa65ab04869987fa746c8beef760cbc480f354;hp=0000000000000000000000000000000000000000;hb=40f2d6712d120dd62a42b7db3a6f074ce49c83d4;hpb=c7b612ca9bd7df43b0bec37c8abcae846587c978 diff --git a/org.argeo.api.acr/src/org/argeo/api/acr/ldap/LdapNameUtils.java b/org.argeo.api.acr/src/org/argeo/api/acr/ldap/LdapNameUtils.java new file mode 100644 index 000000000..72fa65ab0 --- /dev/null +++ b/org.argeo.api.acr/src/org/argeo/api/acr/ldap/LdapNameUtils.java @@ -0,0 +1,69 @@ +package org.argeo.api.acr.ldap; + +import javax.naming.InvalidNameException; +import javax.naming.ldap.LdapName; +import javax.naming.ldap.Rdn; + +/** Utilities to simplify using {@link LdapName}. */ +public class LdapNameUtils { + + public static LdapName relativeName(LdapName prefix, LdapName dn) { + try { + if (!dn.startsWith(prefix)) + throw new IllegalArgumentException("Prefix " + prefix + " not consistent with " + dn); + LdapName res = (LdapName) dn.clone(); + for (int i = 0; i < prefix.size(); i++) { + res.remove(0); + } + return res; + } catch (InvalidNameException e) { + throw new IllegalStateException("Cannot find realtive name", e); + } + } + + public static LdapName getParent(LdapName dn) { + try { + LdapName parent = (LdapName) dn.clone(); + parent.remove(parent.size() - 1); + return parent; + } catch (InvalidNameException e) { + throw new IllegalArgumentException("Cannot get parent of " + dn, e); + } + } + + public static Rdn getParentRdn(LdapName dn) { + if (dn.size() < 2) + throw new IllegalArgumentException(dn + " has no parent"); + Rdn parentRdn = dn.getRdn(dn.size() - 2); + return parentRdn; + } + + public static LdapName toLdapName(String distinguishedName) { + try { + return new LdapName(distinguishedName); + } catch (InvalidNameException e) { + throw new IllegalArgumentException("Cannot parse " + distinguishedName + " as LDAP name", e); + } + } + + public static Rdn getLastRdn(LdapName dn) { + return dn.getRdn(dn.size() - 1); + } + + public static String getLastRdnAsString(LdapName dn) { + return getLastRdn(dn).toString(); + } + + public static String getLastRdnValue(String dn) { + return getLastRdnValue(toLdapName(dn)); + } + + public static String getLastRdnValue(LdapName dn) { + return getLastRdn(dn).getValue().toString(); + } + + /** singleton */ + private LdapNameUtils() { + + } +}