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 int domainSep = name.indexOf(':');
148 throw new MalformedObjectNameException("No domain separator was found.");
149 domain = name.substring(0, domainSep);
150 String rest = name.substring(domainSep + 1);
151 if (rest.equals("*"))
152 propertyPattern = true;
155 if (rest.endsWith(",*"))
157 propertyPattern = true;
158 propertyListString = rest.substring(0, rest.length() - 2);
161 propertyListString = rest;
162 String[] pairs = propertyListString.split(",");
163 if (pairs.length == 0 && !isPattern())
164 throw new MalformedObjectNameException("A name that is not a " +
165 "pattern must contain at " +
166 "least one key-value pair.");
167 for (int a = 0; a < pairs.length; ++a)
169 int sep = pairs[a].indexOf('=');
170 String key = pairs[a].substring(0, sep);
171 if (properties.containsKey(key))
172 throw new MalformedObjectNameException("The same key occurs " +
174 properties.put(key, pairs[a].substring(sep + 1));
181 * Constructs an {@link ObjectName} instance using the given
182 * domain and the one specified property.
184 * @param domain the domain part of the object name.
185 * @param key the key of the property.
186 * @param value the value of the property.
187 * @throws MalformedObjectNameException the domain, key or value
188 * contains an illegal
189 * character or the value
190 * does not follow the quoting
192 * @throws NullPointerException if one of the parameters is
195 public ObjectName(String domain, String key, String value)
196 throws MalformedObjectNameException
198 this.domain = domain;
199 properties.put(key, value);
204 * Constructs an {@link ObjectName} instance using the given
205 * domain and properties.
207 * @param domain the domain part of the object name.
208 * @param properties the key-value property pairs.
209 * @throws MalformedObjectNameException the domain, a key or a value
210 * contains an illegal
211 * character or a value
212 * does not follow the quoting
214 * @throws NullPointerException if one of the parameters is
217 public ObjectName(String domain, Hashtable<String,String> properties)
218 throws MalformedObjectNameException
220 this.domain = domain;
221 this.properties.putAll(properties);
226 * Checks the legality of the domain and the properties.
228 * @throws MalformedObjectNameException the domain, a key or a value
229 * contains an illegal
230 * character or a value
231 * does not follow the quoting
234 private void checkComponents()
235 throws MalformedObjectNameException
237 if (domain.indexOf(':') != -1)
238 throw new MalformedObjectNameException("The domain includes a ':' " +
240 if (domain.indexOf('\n') != -1)
241 throw new MalformedObjectNameException("The domain includes a newline " +
243 char[] chars = new char[] { ':', ',', '*', '?', '=' };
244 Iterator i = properties.entrySet().iterator();
247 Map.Entry entry = (Map.Entry) i.next();
248 String key = (String) entry.getKey();
249 for (int a = 0; a < chars.length; ++a)
250 if (key.indexOf(chars[a]) != -1)
251 throw new MalformedObjectNameException("A key contains a '" +
254 String value = (String) entry.getValue();
255 int quote = value.indexOf('"');
262 catch (IllegalArgumentException e)
264 throw new MalformedObjectNameException("The quoted value is " +
268 else if (quote != -1)
269 throw new MalformedObjectNameException("A value contains " +
270 "a '\"' character.");
273 for (int a = 0; a < chars.length; ++a)
274 if (value.indexOf(chars[a]) != -1)
275 throw new MalformedObjectNameException("A value contains " +
276 "a '" + chars[a] + "' " +
284 * Attempts to find a match between this name and the one supplied.
285 * The following criteria are used:
288 * <li>If the supplied name is a pattern, <code>false</code> is
290 * <li>If this name is a pattern, this method returns <code>true</code>
291 * if the supplied name matches the pattern.</li>
292 * <li>If this name is not a pattern, the result of
293 * <code>equals(name)</code> is returned.
296 * @param name the name to find a match with.
297 * @return true if the name either matches this pattern or is
298 * equivalent to this name under the criteria of
299 * {@link #equals(java.lang.Object)}
300 * @throws NullPointerException if <code>name</code> is <code>null</code>.
302 public boolean apply(ObjectName name)
304 if (name.isPattern())
310 if (isDomainPattern())
312 if (!domainMatches(domain, 0, name.getDomain(), 0))
317 if (!domain.equals(name.getDomain()))
321 if (isPropertyPattern())
323 Hashtable oProps = name.getKeyPropertyList();
324 Iterator i = properties.entrySet().iterator();
327 Map.Entry entry = (Map.Entry) i.next();
328 String key = (String) entry.getKey();
329 if (!(oProps.containsKey(key)))
331 String val = (String) entry.getValue();
332 if (!(val.equals(oProps.get(key))))
338 if (!getCanonicalKeyPropertyListString().equals
339 (name.getCanonicalKeyPropertyListString()))
346 * Returns true if the domain matches the pattern.
348 * @param pattern the pattern to match against.
349 * @param patternindex the index into the pattern to start matching.
350 * @param domain the domain to match.
351 * @param domainindex the index into the domain to start matching.
352 * @return true if the domain matches the pattern.
354 private static boolean domainMatches(String pattern, int patternindex,
355 String domain, int domainindex)
357 while (patternindex < pattern.length())
359 char c = pattern.charAt(patternindex++);
363 for (int i = domain.length(); i >= domainindex; i--)
365 if (domainMatches(pattern, patternindex, domain, i))
371 if (domainindex >= domain.length())
374 if (c != '?' && c != domain.charAt(domainindex))
383 * Compares the specified object with this one. The two
384 * are judged to be equivalent if the given object is an
385 * instance of {@link ObjectName} and has an equal canonical
386 * form (as returned by {@link #getCanonicalName()}).
388 * @param obj the object to compare with this.
389 * @return true if the object is also an {@link ObjectName}
390 * with an equivalent canonical form.
392 public boolean equals(Object obj)
394 if (obj instanceof ObjectName)
396 ObjectName o = (ObjectName) obj;
397 return getCanonicalName().equals(o.getCanonicalName());
403 * Returns the property list in canonical form. The keys
404 * are ordered using the lexicographic ordering used by
405 * {@link java.lang.String#compareTo(java.lang.Object)}.
407 * @return the property list, with the keys in lexicographic
410 public String getCanonicalKeyPropertyListString()
412 StringBuilder builder = new StringBuilder();
413 Iterator i = properties.entrySet().iterator();
416 Map.Entry entry = (Map.Entry) i.next();
417 builder.append(entry.getKey() + "=" + entry.getValue());
421 return builder.toString();
426 * Returns the name as a string in canonical form. More precisely,
427 * this returns a string of the format
428 * <domain>:<properties><wild>. <properties>
429 * is the same value as returned by
430 * {@link #getCanonicalKeyPropertyListString()}. <wild>
434 * <li>an empty string, if the object name is not a property pattern.</li>
435 * <li>'*' if <properties> is empty.</li>
436 * <li>',*' if there is at least one key-value pair.</li>
439 * @return the canonical string form of the object name, as specified
442 public String getCanonicalName()
444 return domain + ":" +
445 getCanonicalKeyPropertyListString() +
446 (isPropertyPattern() ? (properties.isEmpty() ? "*" : ",*") : "");
450 * Returns the domain part of the object name.
452 * @return the domain.
454 public String getDomain()
460 * Returns an {@link ObjectName} instance that is substitutable for the
461 * one given. The instance returned may be a subclass of {@link ObjectName},
462 * but is not guaranteed to be of the same type as the given name, if that
463 * should also turn out to be a subclass. The returned instance may or may
464 * not be equivalent to the one given. The purpose of this method is to provide
465 * an instance of {@link ObjectName} with a well-defined semantics, such as may
466 * be used in cases where the given name is not trustworthy.
468 * @param name the {@link ObjectName} to provide a substitute for.
469 * @return a substitute for the given name, which may or may not be a subclass
470 * of {@link ObjectName}. In either case, the returned object is
471 * guaranteed to have the semantics defined here.
472 * @throws NullPointerException if <code>name</code> is <code>null</code>.
474 public static ObjectName getInstance(ObjectName name)
478 return new ObjectName(name.getCanonicalName());
480 catch (MalformedObjectNameException e)
482 throw (InternalError)
483 (new InternalError("The canonical name of " +
484 "the given name is invalid.").initCause(e));
489 * Returns an {@link ObjectName} instance for the specified name, represented
490 * as a {@link java.lang.String}. The instance returned may be a subclass of
491 * {@link ObjectName} and may or may not be equivalent to earlier instances
492 * returned by this method for the same string.
494 * @param name the {@link ObjectName} to provide an instance of.
495 * @return a instance for the given name, which may or may not be a subclass
496 * of {@link ObjectName}.
497 * @throws MalformedObjectNameException the domain, a key or a value
498 * contains an illegal
499 * character or a value
500 * does not follow the quoting
502 * @throws NullPointerException if <code>name</code> is <code>null</code>.
504 public static ObjectName getInstance(String name)
505 throws MalformedObjectNameException
507 return new ObjectName(name);
511 * Returns an {@link ObjectName} instance for the specified name, represented
512 * as a series of {@link java.lang.String} objects for the domain and a single
513 * property, as a key-value pair. The instance returned may be a subclass of
514 * {@link ObjectName} and may or may not be equivalent to earlier instances
515 * returned by this method for the same parameters.
517 * @param domain the domain part of the object name.
518 * @param key the key of the property.
519 * @param value the value of the property.
520 * @return a instance for the given name, which may or may not be a subclass
521 * of {@link ObjectName}.
522 * @throws MalformedObjectNameException the domain, a key or a value
523 * contains an illegal
524 * character or a value
525 * does not follow the quoting
527 * @throws NullPointerException if <code>name</code> is <code>null</code>.
529 public static ObjectName getInstance(String domain, String key, String value)
530 throws MalformedObjectNameException
532 return new ObjectName(domain, key, value);
536 * Returns an {@link ObjectName} instance for the specified name, represented
537 * as a domain {@link java.lang.String} and a table of properties. The
538 * instance returned may be a subclass of {@link ObjectName} and may or may
539 * not be equivalent to earlier instances returned by this method for the
542 * @param domain the domain part of the object name.
543 * @param properties the key-value property pairs.
544 * @return a instance for the given name, which may or may not be a subclass
545 * of {@link ObjectName}.
546 * @throws MalformedObjectNameException the domain, a key or a value
547 * contains an illegal
548 * character or a value
549 * does not follow the quoting
551 * @throws NullPointerException if <code>name</code> is <code>null</code>.
553 public static ObjectName getInstance(String domain,
554 Hashtable<String,String> properties)
555 throws MalformedObjectNameException
557 return new ObjectName(domain, properties);
561 * Returns the property value corresponding to the given key.
563 * @param key the key of the property to be obtained.
564 * @return the value of the specified property.
565 * @throws NullPointerException if <code>key</code> is <code>null</code>.
567 public String getKeyProperty(String key)
570 throw new NullPointerException("Null key given in request for a value.");
571 return (String) properties.get(key);
575 * Returns the properties in a {@link java.util.Hashtable}. The table
576 * contains each of the properties as keys mapped to their value. The
577 * returned table is not unmodifiable, but changes made to it will not
578 * be reflected in the object name.
580 * @return a {@link java.util.Hashtable}, containing each of the object
583 public Hashtable<String,String> getKeyPropertyList()
585 return new Hashtable<String,String>(properties);
589 * Returns a {@link java.lang.String} representation of the property
590 * list. If the object name was created using {@link
591 * ObjectName(String)}, then this string will contain the properties
592 * in the same order they were given in at creation.
594 * @return the property list.
596 public String getKeyPropertyListString()
598 if (propertyListString != null)
599 return propertyListString;
600 return getCanonicalKeyPropertyListString();
604 * Returns a hash code for this object name. This is calculated as the
605 * summation of the hash codes of the domain and the properties.
607 * @return a hash code for this object name.
609 public int hashCode()
611 return domain.hashCode() + properties.hashCode();
615 * Returns true if the domain of this object name is a pattern.
616 * This is the case if it contains one or more wildcard characters
619 * @return true if the domain is a pattern.
621 public boolean isDomainPattern()
623 return domain.contains("?") || domain.contains("*");
627 * Returns true if this is an object name pattern. An object
628 * name pattern has a domain containing a wildcard character
629 * ('*' or '?') and/or a '*' in the list of properties.
630 * This method will return true if either {@link #isDomainPattern()}
631 * or {@link #isPropertyPattern()} does.
633 * @return true if this is an object name pattern.
635 public boolean isPattern()
637 return isDomainPattern() || isPropertyPattern();
641 * Returns true if this object name is a property pattern. This is
642 * the case if the list of properties contains an '*'.
644 * @return true if this is a property pattern.
646 public boolean isPropertyPattern()
648 return propertyPattern;
653 * Returns a quoted version of the supplied string. The string may
654 * contain any character. The resulting quoted version is guaranteed
655 * to be usable as the value of a property, so this method provides
656 * a good way of ensuring that a value is legal.
659 * The string is transformed as follows:
662 * <li>The string is prefixed with an opening quote character, '"'.
663 * <li>For each character, s:
665 * <li>If s is a quote ('"'), it is replaced by a backslash
666 * followed by a quote.</li>
667 * <li>If s is a star ('*'), it is replaced by a backslash followed
669 * <li>If s is a question mark ('?'), it is replaced by a backslash
670 * followed by a question mark.</li>
671 * <li>If s is a backslash ('\'), it is replaced by two backslashes.</li>
672 * <li>If s is a newline character, it is replaced by a backslash followed by
674 * <li>Otherwise, s is used verbatim.
676 * <li>The string is terminated with a closing quote character, '"'.</li>
679 * @param string the string to quote.
680 * @return a quoted version of the supplied string.
681 * @throws NullPointerException if <code>string</code> is <code>null</code>.
683 public static String quote(String string)
685 StringBuilder builder = new StringBuilder();
687 for (int a = 0; a < string.length(); ++a)
689 char s = string.charAt(a);
693 builder.append("\\\"");
696 builder.append("\\*");
699 builder.append("\\?");
702 builder.append("\\\\");
705 builder.append("\\\n");
712 return builder.toString();
716 * Changes the {@link MBeanServer} on which this query is performed.
718 * @param server the new server to use.
720 public void setMBeanServer(MBeanServer server)
722 this.server = server;
726 * Returns a textual representation of the object name.
728 * <p>The format is unspecified beyond that equivalent object
729 * names will return the same string from this method, but note
730 * that Tomcat depends on the string returned by this method
731 * being a valid textual representation of the object name and
732 * will fail to start if it is not.
734 * @return a textual representation of the object name.
736 public String toString()
738 return getCanonicalName();
742 * Unquotes the supplied string. The quotation marks are removed as
743 * are the backslashes preceding the escaped characters ('"', '?',
744 * '*', '\n', '\\'). A one-to-one mapping exists between quoted and
745 * unquoted values. As a result, a string <code>s</code> should be
746 * equal to <code>unquote(quote(s))</code>.
748 * @param q the quoted string to unquote.
749 * @return the unquoted string.
750 * @throws NullPointerException if <code>q</code> is <code>null</code>.
751 * @throws IllegalArgumentException if the string is not a valid
752 * quoted string i.e. it is not
753 * surrounded by quotation marks
754 * and/or characters are not properly
757 public static String unquote(String q)
759 if (q.charAt(0) != '"')
760 throw new IllegalArgumentException("The string does " +
761 "not start with a quote.");
762 if (q.charAt(q.length() - 1) != '"')
763 throw new IllegalArgumentException("The string does " +
764 "not end with a quote.");
765 StringBuilder builder = new StringBuilder();
766 for (int a = 1; a < (q.length() - 1); ++a)
768 char n = q.charAt(a);
772 if (n != '"' && n != '?' && n != '*' &&
773 n != '\n' && n != '\\')
774 throw new IllegalArgumentException("Illegal escaped character: "
780 return builder.toString();