Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/javax/naming/ldap/LdapName.java
38918 views
/*1* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package javax.naming.ldap;2627import javax.naming.Name;28import javax.naming.InvalidNameException;2930import java.util.Enumeration;31import java.util.Collection;32import java.util.ArrayList;33import java.util.List;34import java.util.Iterator;35import java.util.ListIterator;36import java.util.Collections;3738import java.io.ObjectOutputStream;39import java.io.ObjectInputStream;40import java.io.IOException;4142/**43* This class represents a distinguished name as specified by44* <a href="http://www.ietf.org/rfc/rfc2253.txt">RFC 2253</a>.45* A distinguished name, or DN, is composed of an ordered list of46* components called <em>relative distinguished name</em>s, or RDNs.47* Details of a DN's syntax are described in RFC 2253.48*<p>49* This class resolves a few ambiguities found in RFC 225350* as follows:51* <ul>52* <li> RFC 2253 leaves the term "whitespace" undefined. The53* ASCII space character 0x20 (" ") is used in its place.54* <li> Whitespace is allowed on either side of ',', ';', '=', and '+'.55* Such whitespace is accepted but not generated by this code,56* and is ignored when comparing names.57* <li> AttributeValue strings containing '=' or non-leading '#'58* characters (unescaped) are accepted.59* </ul>60*<p>61* String names passed to <code>LdapName</code> or returned by it62* use the full Unicode character set. They may also contain63* characters encoded into UTF-8 with each octet represented by a64* three-character substring such as "\\B4".65* They may not, however, contain characters encoded into UTF-8 with66* each octet represented by a single character in the string: the67* meaning would be ambiguous.68*<p>69* <code>LdapName</code> will properly parse all valid names, but70* does not attempt to detect all possible violations when parsing71* invalid names. It is "generous" in accepting invalid names.72* The "validity" of a name is determined ultimately when it73* is supplied to an LDAP server, which may accept or74* reject the name based on factors such as its schema information75* and interoperability considerations.76*<p>77* When names are tested for equality, attribute types, both binary78* and string values, are case-insensitive.79* String values with different but equivalent usage of quoting,80* escaping, or UTF8-hex-encoding are considered equal. The order of81* components in multi-valued RDNs (such as "ou=Sales+cn=Bob") is not82* significant.83* <p>84* The components of a LDAP name, that is, RDNs, are numbered. The85* indexes of a LDAP name with n RDNs range from 0 to n-1.86* This range may be written as [0,n).87* The right most RDN is at index 0, and the left most RDN is at88* index n-1. For example, the distinguished name:89* "CN=Steve Kille, O=Isode Limited, C=GB" is numbered in the following90* sequence ranging from 0 to 2: {C=GB, O=Isode Limited, CN=Steve Kille}. An91* empty LDAP name is represented by an empty RDN list.92*<p>93* Concurrent multithreaded read-only access of an instance of94* <tt>LdapName</tt> need not be synchronized.95*<p>96* Unless otherwise noted, the behavior of passing a null argument97* to a constructor or method in this class will cause a98* NullPointerException to be thrown.99*100* @author Scott Seligman101* @since 1.5102*/103104public class LdapName implements Name {105106private transient List<Rdn> rdns; // parsed name components107private transient String unparsed; // if non-null, the DN in unparsed form108private static final long serialVersionUID = -1595520034788997356L;109110/**111* Constructs an LDAP name from the given distinguished name.112*113* @param name This is a non-null distinguished name formatted114* according to the rules defined in115* <a href="http://www.ietf.org/rfc/rfc2253.txt">RFC 2253</a>.116*117* @throws InvalidNameException if a syntax violation is detected.118* @see Rdn#escapeValue(Object value)119*/120public LdapName(String name) throws InvalidNameException {121unparsed = name;122parse();123}124125/**126* Constructs an LDAP name given its parsed RDN components.127* <p>128* The indexing of RDNs in the list follows the numbering of129* RDNs described in the class description.130*131* @param rdns The non-null list of <tt>Rdn</tt>s forming this LDAP name.132*/133public LdapName(List<Rdn> rdns) {134135// if (rdns instanceof ArrayList<Rdn>) {136// this.rdns = rdns.clone();137// } else if (rdns instanceof List<Rdn>) {138// this.rdns = new ArrayList<Rdn>(rdns);139// } else {140// throw IllegalArgumentException(141// "Invalid entries, list entries must be of type Rdn");142// }143144this.rdns = new ArrayList<>(rdns.size());145for (int i = 0; i < rdns.size(); i++) {146Object obj = rdns.get(i);147if (!(obj instanceof Rdn)) {148throw new IllegalArgumentException("Entry:" + obj +149" not a valid type;list entries must be of type Rdn");150}151this.rdns.add((Rdn)obj);152}153}154155/*156* Constructs an LDAP name given its parsed components (the elements157* of "rdns" in the range [beg,end)) and, optionally158* (if "name" is not null), the unparsed DN.159*160*/161private LdapName(String name, List<Rdn> rdns, int beg, int end) {162unparsed = name;163// this.rdns = rdns.subList(beg, end);164165List<Rdn> sList = rdns.subList(beg, end);166this.rdns = new ArrayList<>(sList);167}168169/**170* Retrieves the number of components in this LDAP name.171* @return The non-negative number of components in this LDAP name.172*/173public int size() {174return rdns.size();175}176177/**178* Determines whether this LDAP name is empty.179* An empty name is one with zero components.180* @return true if this LDAP name is empty, false otherwise.181*/182public boolean isEmpty() {183return rdns.isEmpty();184}185186/**187* Retrieves the components of this name as an enumeration188* of strings. The effect of updates to this name on this enumeration189* is undefined. If the name has zero components, an empty (non-null)190* enumeration is returned.191* The order of the components returned by the enumeration is same as192* the order in which the components are numbered as described in the193* class description.194*195* @return A non-null enumeration of the components of this LDAP name.196* Each element of the enumeration is of class String.197*/198public Enumeration<String> getAll() {199final Iterator<Rdn> iter = rdns.iterator();200201return new Enumeration<String>() {202public boolean hasMoreElements() {203return iter.hasNext();204}205public String nextElement() {206return iter.next().toString();207}208};209}210211/**212* Retrieves a component of this LDAP name as a string.213* @param posn The 0-based index of the component to retrieve.214* Must be in the range [0,size()).215* @return The non-null component at index posn.216* @exception IndexOutOfBoundsException if posn is outside the217* specified range.218*/219public String get(int posn) {220return rdns.get(posn).toString();221}222223/**224* Retrieves an RDN of this LDAP name as an Rdn.225* @param posn The 0-based index of the RDN to retrieve.226* Must be in the range [0,size()).227* @return The non-null RDN at index posn.228* @exception IndexOutOfBoundsException if posn is outside the229* specified range.230*/231public Rdn getRdn(int posn) {232return rdns.get(posn);233}234235/**236* Creates a name whose components consist of a prefix of the237* components of this LDAP name.238* Subsequent changes to this name will not affect the name239* that is returned and vice versa.240* @param posn The 0-based index of the component at which to stop.241* Must be in the range [0,size()].242* @return An instance of <tt>LdapName</tt> consisting of the243* components at indexes in the range [0,posn).244* If posn is zero, an empty LDAP name is returned.245* @exception IndexOutOfBoundsException246* If posn is outside the specified range.247*/248public Name getPrefix(int posn) {249try {250return new LdapName(null, rdns, 0, posn);251} catch (IllegalArgumentException e) {252throw new IndexOutOfBoundsException(253"Posn: " + posn + ", Size: "+ rdns.size());254}255}256257/**258* Creates a name whose components consist of a suffix of the259* components in this LDAP name.260* Subsequent changes to this name do not affect the name that is261* returned and vice versa.262*263* @param posn The 0-based index of the component at which to start.264* Must be in the range [0,size()].265* @return An instance of <tt>LdapName</tt> consisting of the266* components at indexes in the range [posn,size()).267* If posn is equal to size(), an empty LDAP name is268* returned.269* @exception IndexOutOfBoundsException270* If posn is outside the specified range.271*/272public Name getSuffix(int posn) {273try {274return new LdapName(null, rdns, posn, rdns.size());275} catch (IllegalArgumentException e) {276throw new IndexOutOfBoundsException(277"Posn: " + posn + ", Size: "+ rdns.size());278}279}280281/**282* Determines whether this LDAP name starts with a specified LDAP name283* prefix.284* A name <tt>n</tt> is a prefix if it is equal to285* <tt>getPrefix(n.size())</tt>--in other words this LDAP286* name starts with 'n'. If n is null or not a RFC2253 formatted name287* as described in the class description, false is returned.288*289* @param n The LDAP name to check.290* @return true if <tt>n</tt> is a prefix of this LDAP name,291* false otherwise.292* @see #getPrefix(int posn)293*/294public boolean startsWith(Name n) {295if (n == null) {296return false;297}298int len1 = rdns.size();299int len2 = n.size();300return (len1 >= len2 &&301matches(0, len2, n));302}303304/**305* Determines whether the specified RDN sequence forms a prefix of this306* LDAP name. Returns true if this LdapName is at least as long as rdns,307* and for every position p in the range [0, rdns.size()) the component308* getRdn(p) matches rdns.get(p). Returns false otherwise. If rdns is309* null, false is returned.310*311* @param rdns The sequence of <tt>Rdn</tt>s to check.312* @return true if <tt>rdns</tt> form a prefix of this LDAP name,313* false otherwise.314*/315public boolean startsWith(List<Rdn> rdns) {316if (rdns == null) {317return false;318}319int len1 = this.rdns.size();320int len2 = rdns.size();321return (len1 >= len2 &&322doesListMatch(0, len2, rdns));323}324325/**326* Determines whether this LDAP name ends with a specified327* LDAP name suffix.328* A name <tt>n</tt> is a suffix if it is equal to329* <tt>getSuffix(size()-n.size())</tt>--in other words this LDAP330* name ends with 'n'. If n is null or not a RFC2253 formatted name331* as described in the class description, false is returned.332*333* @param n The LDAP name to check.334* @return true if <tt>n</tt> is a suffix of this name, false otherwise.335* @see #getSuffix(int posn)336*/337public boolean endsWith(Name n) {338if (n == null) {339return false;340}341int len1 = rdns.size();342int len2 = n.size();343return (len1 >= len2 &&344matches(len1 - len2, len1, n));345}346347/**348* Determines whether the specified RDN sequence forms a suffix of this349* LDAP name. Returns true if this LdapName is at least as long as rdns,350* and for every position p in the range [size() - rdns.size(), size())351* the component getRdn(p) matches rdns.get(p). Returns false otherwise.352* If rdns is null, false is returned.353*354* @param rdns The sequence of <tt>Rdn</tt>s to check.355* @return true if <tt>rdns</tt> form a suffix of this LDAP name,356* false otherwise.357*/358public boolean endsWith(List<Rdn> rdns) {359if (rdns == null) {360return false;361}362int len1 = this.rdns.size();363int len2 = rdns.size();364return (len1 >= len2 &&365doesListMatch(len1 - len2, len1, rdns));366}367368private boolean doesListMatch(int beg, int end, List<Rdn> rdns) {369for (int i = beg; i < end; i++) {370if (!this.rdns.get(i).equals(rdns.get(i - beg))) {371return false;372}373}374return true;375}376377/*378* Helper method for startsWith() and endsWith().379* Returns true if components [beg,end) match the components of "n".380* If "n" is not an LdapName, each of its components is parsed as381* the string form of an RDN.382* The following must hold: end - beg == n.size().383*/384private boolean matches(int beg, int end, Name n) {385if (n instanceof LdapName) {386LdapName ln = (LdapName) n;387return doesListMatch(beg, end, ln.rdns);388} else {389for (int i = beg; i < end; i++) {390Rdn rdn;391String rdnString = n.get(i - beg);392try {393rdn = (new Rfc2253Parser(rdnString)).parseRdn();394} catch (InvalidNameException e) {395return false;396}397if (!rdn.equals(rdns.get(i))) {398return false;399}400}401}402return true;403}404405/**406* Adds the components of a name -- in order -- to the end of this name.407*408* @param suffix The non-null components to add.409* @return The updated name (not a new instance).410*411* @throws InvalidNameException if <tt>suffix</tt> is not a valid LDAP412* name, or if the addition of the components would violate the413* syntax rules of this LDAP name.414*/415public Name addAll(Name suffix) throws InvalidNameException {416return addAll(size(), suffix);417}418419420/**421* Adds the RDNs of a name -- in order -- to the end of this name.422*423* @param suffixRdns The non-null suffix <tt>Rdn</tt>s to add.424* @return The updated name (not a new instance).425*/426public Name addAll(List<Rdn> suffixRdns) {427return addAll(size(), suffixRdns);428}429430/**431* Adds the components of a name -- in order -- at a specified position432* within this name. Components of this LDAP name at or after the433* index (if any) of the first new component are shifted up434* (away from index 0) to accommodate the new components.435*436* @param suffix The non-null components to add.437* @param posn The index at which to add the new component.438* Must be in the range [0,size()].439*440* @return The updated name (not a new instance).441*442* @throws InvalidNameException if <tt>suffix</tt> is not a valid LDAP443* name, or if the addition of the components would violate the444* syntax rules of this LDAP name.445* @throws IndexOutOfBoundsException446* If posn is outside the specified range.447*/448public Name addAll(int posn, Name suffix)449throws InvalidNameException {450unparsed = null; // no longer valid451if (suffix instanceof LdapName) {452LdapName s = (LdapName) suffix;453rdns.addAll(posn, s.rdns);454} else {455Enumeration<String> comps = suffix.getAll();456while (comps.hasMoreElements()) {457rdns.add(posn++,458(new Rfc2253Parser(comps.nextElement()).459parseRdn()));460}461}462return this;463}464465/**466* Adds the RDNs of a name -- in order -- at a specified position467* within this name. RDNs of this LDAP name at or after the468* index (if any) of the first new RDN are shifted up (away from index 0) to469* accommodate the new RDNs.470*471* @param suffixRdns The non-null suffix <tt>Rdn</tt>s to add.472* @param posn The index at which to add the suffix RDNs.473* Must be in the range [0,size()].474*475* @return The updated name (not a new instance).476* @throws IndexOutOfBoundsException477* If posn is outside the specified range.478*/479public Name addAll(int posn, List<Rdn> suffixRdns) {480unparsed = null;481for (int i = 0; i < suffixRdns.size(); i++) {482Object obj = suffixRdns.get(i);483if (!(obj instanceof Rdn)) {484throw new IllegalArgumentException("Entry:" + obj +485" not a valid type;suffix list entries must be of type Rdn");486}487rdns.add(i + posn, (Rdn)obj);488}489return this;490}491492/**493* Adds a single component to the end of this LDAP name.494*495* @param comp The non-null component to add.496* @return The updated LdapName, not a new instance.497* Cannot be null.498* @exception InvalidNameException If adding comp at end of the name499* would violate the name's syntax.500*/501public Name add(String comp) throws InvalidNameException {502return add(size(), comp);503}504505/**506* Adds a single RDN to the end of this LDAP name.507*508* @param comp The non-null RDN to add.509*510* @return The updated LdapName, not a new instance.511* Cannot be null.512*/513public Name add(Rdn comp) {514return add(size(), comp);515}516517/**518* Adds a single component at a specified position within this519* LDAP name.520* Components of this LDAP name at or after the index (if any) of the new521* component are shifted up by one (away from index 0) to accommodate522* the new component.523*524* @param comp The non-null component to add.525* @param posn The index at which to add the new component.526* Must be in the range [0,size()].527* @return The updated LdapName, not a new instance.528* Cannot be null.529* @exception IndexOutOfBoundsException530* If posn is outside the specified range.531* @exception InvalidNameException If adding comp at the532* specified position would violate the name's syntax.533*/534public Name add(int posn, String comp) throws InvalidNameException {535Rdn rdn = (new Rfc2253Parser(comp)).parseRdn();536rdns.add(posn, rdn);537unparsed = null; // no longer valid538return this;539}540541/**542* Adds a single RDN at a specified position within this543* LDAP name.544* RDNs of this LDAP name at or after the index (if any) of the new545* RDN are shifted up by one (away from index 0) to accommodate546* the new RDN.547*548* @param comp The non-null RDN to add.549* @param posn The index at which to add the new RDN.550* Must be in the range [0,size()].551* @return The updated LdapName, not a new instance.552* Cannot be null.553* @exception IndexOutOfBoundsException554* If posn is outside the specified range.555*/556public Name add(int posn, Rdn comp) {557if (comp == null) {558throw new NullPointerException("Cannot set comp to null");559}560rdns.add(posn, comp);561unparsed = null; // no longer valid562return this;563}564565/**566* Removes a component from this LDAP name.567* The component of this name at the specified position is removed.568* Components with indexes greater than this position (if any)569* are shifted down (toward index 0) by one.570*571* @param posn The index of the component to remove.572* Must be in the range [0,size()).573* @return The component removed (a String).574*575* @throws IndexOutOfBoundsException576* if posn is outside the specified range.577* @throws InvalidNameException if deleting the component578* would violate the syntax rules of the name.579*/580public Object remove(int posn) throws InvalidNameException {581unparsed = null; // no longer valid582return rdns.remove(posn).toString();583}584585/**586* Retrieves the list of relative distinguished names.587* The contents of the list are unmodifiable.588* The indexing of RDNs in the returned list follows the numbering of589* RDNs as described in the class description.590* If the name has zero components, an empty list is returned.591*592* @return The name as a list of RDNs which are instances of593* the class {@link Rdn Rdn}.594*/595public List<Rdn> getRdns() {596return Collections.unmodifiableList(rdns);597}598599/**600* Generates a new copy of this name.601* Subsequent changes to the components of this name will not602* affect the new copy, and vice versa.603*604* @return A copy of the this LDAP name.605*/606public Object clone() {607return new LdapName(unparsed, rdns, 0, rdns.size());608}609610/**611* Returns a string representation of this LDAP name in a format612* defined by <a href="http://www.ietf.org/rfc/rfc2253.txt">RFC 2253</a>613* and described in the class description. If the name has zero614* components an empty string is returned.615*616* @return The string representation of the LdapName.617*/618public String toString() {619if (unparsed != null) {620return unparsed;621}622StringBuilder builder = new StringBuilder();623int size = rdns.size();624if ((size - 1) >= 0) {625builder.append(rdns.get(size - 1));626}627for (int next = size - 2; next >= 0; next--) {628builder.append(',');629builder.append(rdns.get(next));630}631unparsed = builder.toString();632return unparsed;633}634635/**636* Determines whether two LDAP names are equal.637* If obj is null or not an LDAP name, false is returned.638* <p>639* Two LDAP names are equal if each RDN in one is equal640* to the corresponding RDN in the other. This implies641* both have the same number of RDNs, and each RDN's642* equals() test against the corresponding RDN in the other643* name returns true. See {@link Rdn#equals(Object obj)}644* for a definition of RDN equality.645*646* @param obj The possibly null object to compare against.647* @return true if obj is equal to this LDAP name,648* false otherwise.649* @see #hashCode650*/651public boolean equals(Object obj) {652// check possible shortcuts653if (obj == this) {654return true;655}656if (!(obj instanceof LdapName)) {657return false;658}659LdapName that = (LdapName) obj;660if (rdns.size() != that.rdns.size()) {661return false;662}663if (unparsed != null && unparsed.equalsIgnoreCase(664that.unparsed)) {665return true;666}667// Compare RDNs one by one for equality668for (int i = 0; i < rdns.size(); i++) {669// Compare a single pair of RDNs.670Rdn rdn1 = rdns.get(i);671Rdn rdn2 = that.rdns.get(i);672if (!rdn1.equals(rdn2)) {673return false;674}675}676return true;677}678679/**680* Compares this LdapName with the specified Object for order.681* Returns a negative integer, zero, or a positive integer as this682* Name is less than, equal to, or greater than the given Object.683* <p>684* If obj is null or not an instance of LdapName, ClassCastException685* is thrown.686* <p>687* Ordering of LDAP names follows the lexicographical rules for688* string comparison, with the extension that this applies to all689* the RDNs in the LDAP name. All the RDNs are lined up in their690* specified order and compared lexicographically.691* See {@link Rdn#compareTo(Object obj) Rdn.compareTo(Object obj)}692* for RDN comparison rules.693* <p>694* If this LDAP name is lexicographically lesser than obj,695* a negative number is returned.696* If this LDAP name is lexicographically greater than obj,697* a positive number is returned.698* @param obj The non-null LdapName instance to compare against.699*700* @return A negative integer, zero, or a positive integer as this Name701* is less than, equal to, or greater than the given obj.702* @exception ClassCastException if obj is null or not a LdapName.703*/704public int compareTo(Object obj) {705706if (!(obj instanceof LdapName)) {707throw new ClassCastException("The obj is not a LdapName");708}709710// check possible shortcuts711if (obj == this) {712return 0;713}714LdapName that = (LdapName) obj;715716if (unparsed != null && unparsed.equalsIgnoreCase(717that.unparsed)) {718return 0;719}720721// Compare RDNs one by one, lexicographically.722int minSize = Math.min(rdns.size(), that.rdns.size());723for (int i = 0; i < minSize; i++) {724// Compare a single pair of RDNs.725Rdn rdn1 = rdns.get(i);726Rdn rdn2 = that.rdns.get(i);727728int diff = rdn1.compareTo(rdn2);729if (diff != 0) {730return diff;731}732}733return (rdns.size() - that.rdns.size()); // longer DN wins734}735736/**737* Computes the hash code of this LDAP name.738* The hash code is the sum of the hash codes of individual RDNs739* of this name.740*741* @return An int representing the hash code of this name.742* @see #equals743*/744public int hashCode() {745// Sum up the hash codes of the components.746int hash = 0;747748// For each RDN...749for (int i = 0; i < rdns.size(); i++) {750Rdn rdn = rdns.get(i);751hash += rdn.hashCode();752}753return hash;754}755756/**757* Serializes only the unparsed DN, for compactness and to avoid758* any implementation dependency.759*760* @serialData The DN string761*/762private void writeObject(ObjectOutputStream s)763throws java.io.IOException {764s.defaultWriteObject();765s.writeObject(toString());766}767768private void readObject(ObjectInputStream s)769throws java.io.IOException, ClassNotFoundException {770s.defaultReadObject();771unparsed = (String)s.readObject();772try {773parse();774} catch (InvalidNameException e) {775// shouldn't happen776throw new java.io.StreamCorruptedException(777"Invalid name: " + unparsed);778}779}780781private void parse() throws InvalidNameException {782// rdns = (ArrayList<Rdn>) (new RFC2253Parser(unparsed)).getDN();783784rdns = new Rfc2253Parser(unparsed).parseDn();785}786}787788789