1 /* ObjectName.java -- Represent the name of a bean, or a pattern for a name.
2 Copyright (C) 2006, 2007 Free Software Foundation, Inc.
4 This file is part of GNU Classpath.
6 GNU Classpath is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
11 GNU Classpath is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GNU Classpath; see the file COPYING. If not, write to the
18 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
21 Linking this library statically or dynamically with other modules is
22 making a combined work based on this library. Thus, the terms and
23 conditions of the GNU General Public License cover the whole
26 As a special exception, the copyright holders of this library give you
27 permission to link this library with independent modules to produce an
28 executable, regardless of the license terms of these independent
29 modules, and to copy and distribute the resulting executable under
30 terms of your choice, provided that you also meet, for each linked
31 independent module, the terms and conditions of the license of that
32 module. An independent module is a module which is not derived from
33 or based on this library. If you modify this library, you may extend
34 this exception to your version of the library, but you are not
35 obligated to do so. If you do not wish to do so, delete this
36 exception statement from your version. */
38 package javax.management;
40 import java.io.Serializable;
42 import java.util.Collections;
43 import java.util.Hashtable;
44 import java.util.Iterator;
46 import java.util.TreeMap;
50 * An {@link ObjectName} instance represents the name of a management
51 * bean, or a pattern which may match the name of one or more
52 * management beans. Patterns are distinguished from names by the
53 * presence of the '?' and '*' characters (which match a single
54 * character and a series of zero or more characters, respectively).
57 * Each name begins with a domain element, which is terminated by
58 * a ':' character. The domain may be empty. If so, it will be
59 * replaced by the default domain of the bean server in certain
60 * contexts. The domain is a pattern, if it contains either '?'
61 * or '*'. To avoid collisions, it is usual to use reverse
62 * DNS names for the domain, as in Java package and property names.
65 * Following the ':' character is a series of properties. The list
66 * is separated by commas, and largely consists of unordered key-value
67 * pairs, separated by an equals sign ('='). At most one element may
68 * be an asterisk ('*'), which turns the {@link ObjectName} instance
69 * into a <emph>property pattern</emph>. In this situation, the pattern
70 * matches a name if the name contains at least those key-value pairs
71 * given and has the same domain.
74 * A <emph>key</emph> is a string of characters which doesn't include
75 * any of those used as delimiters or in patterns (':', '=', ',', '?'
76 * and '*'). Keys must be unique.
79 * A value may be <emph>quoted</emph> or <emph>unquoted</emph>. Unquoted
80 * values obey the same rules as given for keys above. Quoted values are
81 * surrounded by quotation marks ("), and use a backslash ('\') character
82 * to include quotes ('\"'), backslashes ('\\'), newlines ('\n'), and
83 * the pattern characters ('\?' and '\*'). The quotes and backslashes
84 * (after expansion) are considered part of the value.
87 * Spaces are maintained within the different parts of the name. Thus,
88 * '<code>domain: key1 = value1 </code>' has a key ' key1 ' with value
89 * ' value1 '. Newlines are disallowed, except where escaped in quoted
93 * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
96 public class ObjectName
97 implements Serializable, QueryExp
101 * The domain of the name.
103 private String domain;
106 * The properties, as key-value pairs.
108 private TreeMap<String,String> properties = new TreeMap<String,String>();
111 * The properties as a string (stored for ordering).
113 private String propertyListString;
116 * True if this object name is a property pattern.
118 private boolean propertyPattern;
121 * The management server associated with this object name.
123 private MBeanServer server;
126 * Constructs an {@link ObjectName} instance from the given string,
127 * which should be of the form
128 * <domain>:<properties><wild>. <domain>
129 * represents the domain section of the name. <properties>
130 * represents the key-value pairs, as returned by {@link
131 * #getKeyPropertyListString()}. <wild> is the optional
132 * asterisk present in the property list. If the string doesn't
133 * represent a property pattern, it will be empty. If it does,
134 * it will be either ',*' or '*', depending on whether other
135 * properties are present or not, respectively.
137 * @param name the string to use to construct this instance.
138 * @throws MalformedObjectNameException if the string is of the
140 * @throws NullPointerException if <code>name</code> is
143 public ObjectName(String name)
144 throws MalformedObjectNameException
146 if (name.length() == 0)
149 int domainSep = name.indexOf(':');
151 throw new MalformedObjectNameException("No domain separator was found.");
152 domain = name.substring(0, domainSep);
153 String rest = name.substring(domainSep + 1);
154 if (rest.equals("*"))
155 propertyPattern = true;
158 if (rest.endsWith(",*"))
160 propertyPattern = true;
161 propertyListString = rest.substring(0, rest.length() - 2);
164 propertyListString = rest;
165 String[] pairs = propertyListString.split(",");
166 if (pairs.length == 0 && !isPattern())
167 throw new MalformedObjectNameException("A name that is not a " +
168 "pattern must contain at " +
169 "least one key-value pair.");
170 for (int a = 0; a < pairs.length; ++a)
172 int sep = pairs[a].indexOf('=');
173 String key = pairs[a].substring(0, sep);
174 if (properties.containsKey(key))
175 throw new MalformedObjectNameException("The same key occurs " +
177 properties.put(key, pairs[a].substring(sep + 1));
184 * Constructs an {@link ObjectName} instance using the given
185 * domain and the one specified property.
187 * @param domain the domain part of the object name.
188 * @param key the key of the property.
189 * @param value the value of the property.
190 * @throws MalformedObjectNameException the domain, key or value
191 * contains an illegal
192 * character or the value
193 * does not follow the quoting
195 * @throws NullPointerException if one of the parameters is
198 public ObjectName(String domain, String key, String value)
199 throws MalformedObjectNameException
201 this.domain = domain;
202 properties.put(key, value);
207 * Constructs an {@link ObjectName} instance using the given
208 * domain and properties.
210 * @param domain the domain part of the object name.
211 * @param properties the key-value property pairs.
212 * @throws MalformedObjectNameException the domain, a key or a value
213 * contains an illegal
214 * character or a value
215 * does not follow the quoting
217 * @throws NullPointerException if one of the parameters is
220 public ObjectName(String domain, Hashtable<String,String> properties)
221 throws MalformedObjectNameException
223 this.domain = domain;
224 this.properties.putAll(properties);
229 * Checks the legality of the domain and the properties.
231 * @throws MalformedObjectNameException the domain, a key or a value
232 * contains an illegal
233 * character or a value
234 * does not follow the quoting
237 private void checkComponents()
238 throws MalformedObjectNameException
240 if (domain.indexOf(':') != -1)
241 throw new MalformedObjectNameException("The domain includes a ':' " +
243 if (domain.indexOf('\n') != -1)
244 throw new MalformedObjectNameException("The domain includes a newline " +
246 char[] chars = new char[] { ':', ',', '*', '?', '=' };
247 Iterator i = properties.entrySet().iterator();
250 Map.Entry entry = (Map.Entry) i.next();
251 String key = (String) entry.getKey();
252 for (int a = 0; a < chars.length; ++a)
253 if (key.indexOf(chars[a]) != -1)
254 throw new MalformedObjectNameException("A key contains a '" +
257 String value = (String) entry.getValue();
258 int quote = value.indexOf('"');
265 catch (IllegalArgumentException e)
267 throw new MalformedObjectNameException("The quoted value is " +
271 else if (quote != -1)
272 throw new MalformedObjectNameException("A value contains " +
273 "a '\"' character.");
276 for (int a = 0; a < chars.length; ++a)
277 if (value.indexOf(chars[a]) != -1)
278 throw new MalformedObjectNameException("A value contains " +
279 "a '" + chars[a] + "' " +
287 * Attempts to find a match between this name and the one supplied.
288 * The following criteria are used:
291 * <li>If the supplied name is a pattern, <code>false</code> is
293 * <li>If this name is a pattern, this method returns <code>true</code>
294 * if the supplied name matches the pattern.</li>
295 * <li>If this name is not a pattern, the result of
296 * <code>equals(name)</code> is returned.
299 * @param name the name to find a match with.
300 * @return true if the name either matches this pattern or is
301 * equivalent to this name under the criteria of
302 * {@link #equals(java.lang.Object)}
303 * @throws NullPointerException if <code>name</code> is <code>null</code>.
305 public boolean apply(ObjectName name)
307 if (name.isPattern())
313 if (isDomainPattern())
315 if (!domainMatches(domain, 0, name.getDomain(), 0))
320 if (!domain.equals(name.getDomain()))
324 if (isPropertyPattern())
326 Hashtable oProps = name.getKeyPropertyList();
327 Iterator i = properties.entrySet().iterator();
330 Map.Entry entry = (Map.Entry) i.next();
331 String key = (String) entry.getKey();
332 if (!(oProps.containsKey(key)))
334 String val = (String) entry.getValue();
335 if (!(val.equals(oProps.get(key))))
341 if (!getCanonicalKeyPropertyListString().equals
342 (name.getCanonicalKeyPropertyListString()))
349 * Returns true if the domain matches the pattern.
351 * @param pattern the pattern to match against.
352 * @param patternindex the index into the pattern to start matching.
353 * @param domain the domain to match.
354 * @param domainindex the index into the domain to start matching.
355 * @return true if the domain matches the pattern.
357 private static boolean domainMatches(String pattern, int patternindex,
358 String domain, int domainindex)
360 while (patternindex < pattern.length())
362 char c = pattern.charAt(patternindex++);
366 for (int i = domain.length(); i >= domainindex; i--)
368 if (domainMatches(pattern, patternindex, domain, i))
374 if (domainindex >= domain.length())
377 if (c != '?' && c != domain.charAt(domainindex))
386 * Compares the specified object with this one. The two
387 * are judged to be equivalent if the given object is an
388 * instance of {@link ObjectName} and has an equal canonical
389 * form (as returned by {@link #getCanonicalName()}).
391 * @param obj the object to compare with this.
392 * @return true if the object is also an {@link ObjectName}
393 * with an equivalent canonical form.
395 public boolean equals(Object obj)
397 if (obj instanceof ObjectName)
399 ObjectName o = (ObjectName) obj;
400 return getCanonicalName().equals(o.getCanonicalName());
406 * Returns the property list in canonical form. The keys
407 * are ordered using the lexicographic ordering used by
408 * {@link java.lang.String#compareTo(java.lang.Object)}.
410 * @return the property list, with the keys in lexicographic
413 public String getCanonicalKeyPropertyListString()
415 StringBuilder builder = new StringBuilder();
416 Iterator i = properties.entrySet().iterator();
419 Map.Entry entry = (Map.Entry) i.next();
420 builder.append(entry.getKey() + "=" + entry.getValue());
424 return builder.toString();
429 * Returns the name as a string in canonical form. More precisely,
430 * this returns a string of the format
431 * <domain>:<properties><wild>. <properties>
432 * is the same value as returned by
433 * {@link #getCanonicalKeyPropertyListString()}. <wild>
437 * <li>an empty string, if the object name is not a property pattern.</li>
438 * <li>'*' if <properties> is empty.</li>
439 * <li>',*' if there is at least one key-value pair.</li>
442 * @return the canonical string form of the object name, as specified
445 public String getCanonicalName()
447 return domain + ":" +
448 getCanonicalKeyPropertyListString() +
449 (isPropertyPattern() ? (properties.isEmpty() ? "*" : ",*") : "");
453 * Returns the domain part of the object name.
455 * @return the domain.
457 public String getDomain()
463 * Returns an {@link ObjectName} instance that is substitutable for the
464 * one given. The instance returned may be a subclass of {@link ObjectName},
465 * but is not guaranteed to be of the same type as the given name, if that
466 * should also turn out to be a subclass. The returned instance may or may
467 * not be equivalent to the one given. The purpose of this method is to provide
468 * an instance of {@link ObjectName} with a well-defined semantics, such as may
469 * be used in cases where the given name is not trustworthy.
471 * @param name the {@link ObjectName} to provide a substitute for.
472 * @return a substitute for the given name, which may or may not be a subclass
473 * of {@link ObjectName}. In either case, the returned object is
474 * guaranteed to have the semantics defined here.
475 * @throws NullPointerException if <code>name</code> is <code>null</code>.
477 public static ObjectName getInstance(ObjectName name)
481 return new ObjectName(name.getCanonicalName());
483 catch (MalformedObjectNameException e)
485 throw (InternalError)
486 (new InternalError("The canonical name of " +
487 "the given name is invalid.").initCause(e));
492 * Returns an {@link ObjectName} instance for the specified name, represented
493 * as a {@link java.lang.String}. The instance returned may be a subclass of
494 * {@link ObjectName} and may or may not be equivalent to earlier instances
495 * returned by this method for the same string.
497 * @param name the {@link ObjectName} to provide an instance of.
498 * @return a instance for the given name, which may or may not be a subclass
499 * of {@link ObjectName}.
500 * @throws MalformedObjectNameException the domain, a key or a value
501 * contains an illegal
502 * character or a value
503 * does not follow the quoting
505 * @throws NullPointerException if <code>name</code> is <code>null</code>.
507 public static ObjectName getInstance(String name)
508 throws MalformedObjectNameException
510 return new ObjectName(name);
514 * Returns an {@link ObjectName} instance for the specified name, represented
515 * as a series of {@link java.lang.String} objects for the domain and a single
516 * property, as a key-value pair. The instance returned may be a subclass of
517 * {@link ObjectName} and may or may not be equivalent to earlier instances
518 * returned by this method for the same parameters.
520 * @param domain the domain part of the object name.
521 * @param key the key of the property.
522 * @param value the value of the property.
523 * @return a instance for the given name, which may or may not be a subclass
524 * of {@link ObjectName}.
525 * @throws MalformedObjectNameException the domain, a key or a value
526 * contains an illegal
527 * character or a value
528 * does not follow the quoting
530 * @throws NullPointerException if <code>name</code> is <code>null</code>.
532 public static ObjectName getInstance(String domain, String key, String value)
533 throws MalformedObjectNameException
535 return new ObjectName(domain, key, value);
539 * Returns an {@link ObjectName} instance for the specified name, represented
540 * as a domain {@link java.lang.String} and a table of properties. The
541 * instance returned may be a subclass of {@link ObjectName} and may or may
542 * not be equivalent to earlier instances returned by this method for the
545 * @param domain the domain part of the object name.
546 * @param properties the key-value property pairs.
547 * @return a instance for the given name, which may or may not be a subclass
548 * of {@link ObjectName}.
549 * @throws MalformedObjectNameException the domain, a key or a value
550 * contains an illegal
551 * character or a value
552 * does not follow the quoting
554 * @throws NullPointerException if <code>name</code> is <code>null</code>.
556 public static ObjectName getInstance(String domain,
557 Hashtable<String,String> properties)
558 throws MalformedObjectNameException
560 return new ObjectName(domain, properties);
564 * Returns the property value corresponding to the given key.
566 * @param key the key of the property to be obtained.
567 * @return the value of the specified property.
568 * @throws NullPointerException if <code>key</code> is <code>null</code>.
570 public String getKeyProperty(String key)
573 throw new NullPointerException("Null key given in request for a value.");
574 return (String) properties.get(key);
578 * Returns the properties in a {@link java.util.Hashtable}. The table
579 * contains each of the properties as keys mapped to their value. The
580 * returned table is not unmodifiable, but changes made to it will not
581 * be reflected in the object name.
583 * @return a {@link java.util.Hashtable}, containing each of the object
586 public Hashtable<String,String> getKeyPropertyList()
588 return new Hashtable<String,String>(properties);
592 * Returns a {@link java.lang.String} representation of the property
593 * list. If the object name was created using {@link
594 * ObjectName(String)}, then this string will contain the properties
595 * in the same order they were given in at creation.
597 * @return the property list.
599 public String getKeyPropertyListString()
601 if (propertyListString != null)
602 return propertyListString;
603 return getCanonicalKeyPropertyListString();
607 * Returns a hash code for this object name. This is calculated as the
608 * summation of the hash codes of the domain and the properties.
610 * @return a hash code for this object name.
612 public int hashCode()
614 return domain.hashCode() + properties.hashCode();
618 * Returns true if the domain of this object name is a pattern.
619 * This is the case if it contains one or more wildcard characters
622 * @return true if the domain is a pattern.
624 public boolean isDomainPattern()
626 return domain.contains("?") || domain.contains("*");
630 * Returns true if this is an object name pattern. An object
631 * name pattern has a domain containing a wildcard character
632 * ('*' or '?') and/or a '*' in the list of properties.
633 * This method will return true if either {@link #isDomainPattern()}
634 * or {@link #isPropertyPattern()} does.
636 * @return true if this is an object name pattern.
638 public boolean isPattern()
640 return isDomainPattern() || isPropertyPattern();
644 * Returns true if this object name is a property pattern. This is
645 * the case if the list of properties contains an '*'.
647 * @return true if this is a property pattern.
649 public boolean isPropertyPattern()
651 return propertyPattern;
656 * Returns a quoted version of the supplied string. The string may
657 * contain any character. The resulting quoted version is guaranteed
658 * to be usable as the value of a property, so this method provides
659 * a good way of ensuring that a value is legal.
662 * The string is transformed as follows:
665 * <li>The string is prefixed with an opening quote character, '"'.
666 * <li>For each character, s:
668 * <li>If s is a quote ('"'), it is replaced by a backslash
669 * followed by a quote.</li>
670 * <li>If s is a star ('*'), it is replaced by a backslash followed
672 * <li>If s is a question mark ('?'), it is replaced by a backslash
673 * followed by a question mark.</li>
674 * <li>If s is a backslash ('\'), it is replaced by two backslashes.</li>
675 * <li>If s is a newline character, it is replaced by a backslash followed by
677 * <li>Otherwise, s is used verbatim.
679 * <li>The string is terminated with a closing quote character, '"'.</li>
682 * @param string the string to quote.
683 * @return a quoted version of the supplied string.
684 * @throws NullPointerException if <code>string</code> is <code>null</code>.
686 public static String quote(String string)
688 StringBuilder builder = new StringBuilder();
690 for (int a = 0; a < string.length(); ++a)
692 char s = string.charAt(a);
696 builder.append("\\\"");
699 builder.append("\\*");
702 builder.append("\\?");
705 builder.append("\\\\");
708 builder.append("\\\n");
715 return builder.toString();
719 * Changes the {@link MBeanServer} on which this query is performed.
721 * @param server the new server to use.
723 public void setMBeanServer(MBeanServer server)
725 this.server = server;
729 * Returns a textual representation of the object name.
731 * <p>The format is unspecified beyond that equivalent object
732 * names will return the same string from this method, but note
733 * that Tomcat depends on the string returned by this method
734 * being a valid textual representation of the object name and
735 * will fail to start if it is not.
737 * @return a textual representation of the object name.
739 public String toString()
741 return getCanonicalName();
745 * Unquotes the supplied string. The quotation marks are removed as
746 * are the backslashes preceding the escaped characters ('"', '?',
747 * '*', '\n', '\\'). A one-to-one mapping exists between quoted and
748 * unquoted values. As a result, a string <code>s</code> should be
749 * equal to <code>unquote(quote(s))</code>.
751 * @param q the quoted string to unquote.
752 * @return the unquoted string.
753 * @throws NullPointerException if <code>q</code> is <code>null</code>.
754 * @throws IllegalArgumentException if the string is not a valid
755 * quoted string i.e. it is not
756 * surrounded by quotation marks
757 * and/or characters are not properly
760 public static String unquote(String q)
762 if (q.charAt(0) != '"')
763 throw new IllegalArgumentException("The string does " +
764 "not start with a quote.");
765 if (q.charAt(q.length() - 1) != '"')
766 throw new IllegalArgumentException("The string does " +
767 "not end with a quote.");
768 StringBuilder builder = new StringBuilder();
769 for (int a = 1; a < (q.length() - 1); ++a)
771 char n = q.charAt(a);
775 if (n != '"' && n != '?' && n != '*' &&
776 n != '\n' && n != '\\')
777 throw new IllegalArgumentException("Illegal escaped character: "
783 return builder.toString();