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 properties;
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 properties = new TreeMap();
168 for (int a = 0; a < pairs.length; ++a)
170 int sep = pairs[a].indexOf('=');
171 String key = pairs[a].substring(0, sep);
172 if (properties.containsKey(key))
173 throw new MalformedObjectNameException("The same key occurs " +
175 properties.put(key, pairs[a].substring(sep + 1));
182 * Constructs an {@link ObjectName} instance using the given
183 * domain and the one specified property.
185 * @param domain the domain part of the object name.
186 * @param key the key of the property.
187 * @param value the value of the property.
188 * @throws MalformedObjectNameException the domain, key or value
189 * contains an illegal
190 * character or the value
191 * does not follow the quoting
193 * @throws NullPointerException if one of the parameters is
196 public ObjectName(String domain, String key, String value)
197 throws MalformedObjectNameException
199 this.domain = domain;
200 properties = new TreeMap();
201 properties.put(key, value);
206 * Constructs an {@link ObjectName} instance using the given
207 * domain and properties.
209 * @param domain the domain part of the object name.
210 * @param properties the key-value property pairs.
211 * @throws MalformedObjectNameException the domain, a key or a value
212 * contains an illegal
213 * character or a value
214 * does not follow the quoting
216 * @throws NullPointerException if one of the parameters is
219 public ObjectName(String domain, Hashtable properties)
220 throws MalformedObjectNameException
222 this.domain = domain;
223 this.properties.putAll(properties);
228 * Checks the legality of the domain and the properties.
230 * @throws MalformedObjectNameException the domain, a key or a value
231 * contains an illegal
232 * character or a value
233 * does not follow the quoting
236 private void checkComponents()
237 throws MalformedObjectNameException
239 if (domain.indexOf(':') != -1)
240 throw new MalformedObjectNameException("The domain includes a ':' " +
242 if (domain.indexOf('\n') != -1)
243 throw new MalformedObjectNameException("The domain includes a newline " +
245 char[] chars = new char[] { ':', ',', '*', '?', '=' };
246 Iterator i = properties.entrySet().iterator();
249 Map.Entry entry = (Map.Entry) i.next();
250 String key = (String) entry.getKey();
251 for (int a = 0; a < chars.length; ++a)
252 if (key.indexOf(chars[a]) != -1)
253 throw new MalformedObjectNameException("A key contains a '" +
256 String value = (String) entry.getValue();
257 int quote = value.indexOf('"');
264 catch (IllegalArgumentException e)
266 throw new MalformedObjectNameException("The quoted value is " +
270 else if (quote != -1)
271 throw new MalformedObjectNameException("A value contains " +
272 "a '\"' character.");
275 for (int a = 0; a < chars.length; ++a)
276 if (value.indexOf(chars[a]) != -1)
277 throw new MalformedObjectNameException("A value contains " +
278 "a '" + chars[a] + "' " +
286 * Attempts to find a match between this name and the one supplied.
287 * The following criteria are used:
290 * <li>If the supplied name is a pattern, <code>false</code> is
292 * <li>If this name is a pattern, this method returns <code>true</code>
293 * if the supplied name matches the pattern.</li>
294 * <li>If this name is not a pattern, the result of
295 * <code>equals(name)</code> is returned.
298 * @param name the name to find a match with.
299 * @return true if the name either matches this pattern or is
300 * equivalent to this name under the criteria of
301 * {@link #equals(java.lang.Object)}
302 * @throws NullPointerException if <code>name</code> is <code>null</code>.
304 public boolean apply(ObjectName name)
306 if (name.isPattern())
310 boolean domainMatch, propMatch;
311 if (isDomainPattern())
313 String oDomain = name.getDomain();
314 int oLength = oDomain.length();
315 for (int a = 0; a < domain.length(); ++a)
317 char n = domain.charAt(a);
318 if (oLength == a && n != '*')
323 if ((a + 1) < domain.length())
330 next = domain.charAt(a + 1);
331 } while (next == '*');
335 while (oDomain.charAt(pos) != next)
342 if (n != oDomain.charAt(a))
348 domainMatch = domain.equals(name.getDomain());
349 if (isPropertyPattern())
351 Hashtable oProps = name.getKeyPropertyList();
352 Iterator i = properties.entrySet().iterator();
355 Map.Entry entry = (Map.Entry) i.next();
356 String key = (String) entry.getKey();
357 if (!(oProps.containsKey(key)))
359 String val = (String) entry.getValue();
360 if (!(val.equals(oProps.get(key))))
367 getCanonicalKeyPropertyListString().equals
368 (name.getCanonicalKeyPropertyListString());
369 return domainMatch && propMatch;
375 * Compares the specified object with this one. The two
376 * are judged to be equivalent if the given object is an
377 * instance of {@link ObjectName} and has an equal canonical
378 * form (as returned by {@link #getCanonicalName()}).
380 * @param obj the object to compare with this.
381 * @return true if the object is also an {@link ObjectName}
382 * with an equivalent canonical form.
384 public boolean equals(Object obj)
386 if (obj instanceof ObjectName)
388 ObjectName o = (ObjectName) obj;
389 return getCanonicalName().equals(o.getCanonicalName());
395 * Returns the property list in canonical form. The keys
396 * are ordered using the lexicographic ordering used by
397 * {@link java.lang.String#compareTo(java.lang.Object)}.
399 * @return the property list, with the keys in lexicographic
402 public String getCanonicalKeyPropertyListString()
404 StringBuilder builder = new StringBuilder();
405 Iterator i = properties.entrySet().iterator();
408 Map.Entry entry = (Map.Entry) i.next();
409 builder.append(entry.getKey() + "=" + entry.getValue());
413 return builder.toString();
418 * Returns the name as a string in canonical form. More precisely,
419 * this returns a string of the format
420 * <domain>:<properties><wild>. <properties>
421 * is the same value as returned by
422 * {@link #getCanonicalKeyPropertyListString()}. <wild>
426 * <li>an empty string, if the object name is not a property pattern.</li>
427 * <li>'*' if <properties> is empty.</li>
428 * <li>',*' if there is at least one key-value pair.</li>
431 * @return the canonical string form of the object name, as specified
434 public String getCanonicalName()
436 return domain + ":" +
437 getCanonicalKeyPropertyListString() +
438 (isPropertyPattern() ? (properties.isEmpty() ? "*" : ",*") : "");
442 * Returns the domain part of the object name.
444 * @return the domain.
446 public String getDomain()
452 * Returns an {@link ObjectName} instance that is substitutable for the
453 * one given. The instance returned may be a subclass of {@link ObjectName},
454 * but is not guaranteed to be of the same type as the given name, if that
455 * should also turn out to be a subclass. The returned instance may or may
456 * not be equivalent to the one given. The purpose of this method is to provide
457 * an instance of {@link ObjectName} with a well-defined semantics, such as may
458 * be used in cases where the given name is not trustworthy.
460 * @param name the {@link ObjectName} to provide a substitute for.
461 * @return a substitute for the given name, which may or may not be a subclass
462 * of {@link ObjectName}. In either case, the returned object is
463 * guaranteed to have the semantics defined here.
464 * @throws NullPointerException if <code>name</code> is <code>null</code>.
466 public static ObjectName getInstance(ObjectName name)
470 return new ObjectName(name.getCanonicalName());
472 catch (MalformedObjectNameException e)
474 throw (InternalError)
475 (new InternalError("The canonical name of " +
476 "the given name is invalid.").initCause(e));
481 * Returns an {@link ObjectName} instance for the specified name, represented
482 * as a {@link java.lang.String}. The instance returned may be a subclass of
483 * {@link ObjectName} and may or may not be equivalent to earlier instances
484 * returned by this method for the same string.
486 * @param name the {@link ObjectName} to provide an instance of.
487 * @return a instance for the given name, which may or may not be a subclass
488 * of {@link ObjectName}.
489 * @throws MalformedObjectNameException the domain, a key or a value
490 * contains an illegal
491 * character or a value
492 * does not follow the quoting
494 * @throws NullPointerException if <code>name</code> is <code>null</code>.
496 public static ObjectName getInstance(String name)
497 throws MalformedObjectNameException
499 return new ObjectName(name);
503 * Returns an {@link ObjectName} instance for the specified name, represented
504 * as a series of {@link java.lang.String} objects for the domain and a single
505 * property, as a key-value pair. The instance returned may be a subclass of
506 * {@link ObjectName} and may or may not be equivalent to earlier instances
507 * returned by this method for the same parameters.
509 * @param domain the domain part of the object name.
510 * @param key the key of the property.
511 * @param value the value of the property.
512 * @return a instance for the given name, which may or may not be a subclass
513 * of {@link ObjectName}.
514 * @throws MalformedObjectNameException the domain, a key or a value
515 * contains an illegal
516 * character or a value
517 * does not follow the quoting
519 * @throws NullPointerException if <code>name</code> is <code>null</code>.
521 public static ObjectName getInstance(String domain, String key, String value)
522 throws MalformedObjectNameException
524 return new ObjectName(domain, key, value);
528 * Returns an {@link ObjectName} instance for the specified name, represented
529 * as a domain {@link java.lang.String} and a table of properties. The
530 * instance returned may be a subclass of {@link ObjectName} and may or may
531 * not be equivalent to earlier instances returned by this method for the
534 * @param domain the domain part of the object name.
535 * @param properties the key-value property pairs.
536 * @return a instance for the given name, which may or may not be a subclass
537 * of {@link ObjectName}.
538 * @throws MalformedObjectNameException the domain, a key or a value
539 * contains an illegal
540 * character or a value
541 * does not follow the quoting
543 * @throws NullPointerException if <code>name</code> is <code>null</code>.
545 public static ObjectName getInstance(String domain, Hashtable properties)
546 throws MalformedObjectNameException
548 return new ObjectName(domain, properties);
552 * Returns the property value corresponding to the given key.
554 * @param key the key of the property to be obtained.
555 * @return the value of the specified property.
556 * @throws NullPointerException if <code>key</code> is <code>null</code>.
558 public String getKeyProperty(String key)
561 throw new NullPointerException("Null key given in request for a value.");
562 return (String) properties.get(key);
566 * Returns the properties in a {@link java.util.Hashtable}. The table
567 * contains each of the properties as keys mapped to their value. The
568 * returned table is not unmodifiable, but changes made to it will not
569 * be reflected in the object name.
571 * @return a {@link java.util.Hashtable}, containing each of the object
574 public Hashtable getKeyPropertyList()
576 return new Hashtable(properties);
580 * Returns a {@link java.lang.String} representation of the property
581 * list. If the object name was created using {@link
582 * ObjectName(String)}, then this string will contain the properties
583 * in the same order they were given in at creation.
585 * @return the property list.
587 public String getKeyPropertyListString()
589 if (propertyListString != null)
590 return propertyListString;
591 return getCanonicalKeyPropertyListString();
595 * Returns a hash code for this object name. This is calculated as the
596 * summation of the hash codes of the domain and the properties.
598 * @return a hash code for this object name.
600 public int hashCode()
602 return domain.hashCode() + properties.hashCode();
606 * Returns true if the domain of this object name is a pattern.
607 * This is the case if it contains one or more wildcard characters
610 * @return true if the domain is a pattern.
612 public boolean isDomainPattern()
614 return domain.contains("?") || domain.contains("*");
618 * Returns true if this is an object name pattern. An object
619 * name pattern has a domain containing a wildcard character
620 * ('*' or '?') and/or a '*' in the list of properties.
621 * This method will return true if either {@link #isDomainPattern()}
622 * or {@link #isPropertyPattern()} does.
624 * @return true if this is an object name pattern.
626 public boolean isPattern()
628 return isDomainPattern() || isPropertyPattern();
632 * Returns true if this object name is a property pattern. This is
633 * the case if the list of properties contains an '*'.
635 * @return true if this is a property pattern.
637 public boolean isPropertyPattern()
639 return propertyPattern;
644 * Returns a quoted version of the supplied string. The string may
645 * contain any character. The resulting quoted version is guaranteed
646 * to be usable as the value of a property, so this method provides
647 * a good way of ensuring that a value is legal.
650 * The string is transformed as follows:
653 * <li>The string is prefixed with an opening quote character, '"'.
654 * <li>For each character, s:
656 * <li>If s is a quote ('"'), it is replaced by a backslash
657 * followed by a quote.</li>
658 * <li>If s is a star ('*'), it is replaced by a backslash followed
660 * <li>If s is a question mark ('?'), it is replaced by a backslash
661 * followed by a question mark.</li>
662 * <li>If s is a backslash ('\'), it is replaced by two backslashes.</li>
663 * <li>If s is a newline character, it is replaced by a backslash followed by
665 * <li>Otherwise, s is used verbatim.
667 * <li>The string is terminated with a closing quote character, '"'.</li>
670 * @param string the string to quote.
671 * @return a quoted version of the supplied string.
672 * @throws NullPointerException if <code>string</code> is <code>null</code>.
674 public static String quote(String string)
676 StringBuilder builder = new StringBuilder();
678 for (int a = 0; a < string.length(); ++a)
680 char s = string.charAt(a);
684 builder.append("\\\"");
687 builder.append("\\*");
690 builder.append("\\?");
693 builder.append("\\\\");
696 builder.append("\\\n");
703 return builder.toString();
707 * Changes the {@link MBeanServer} on which this query is performed.
709 * @param server the new server to use.
711 public void setMBeanServer(MBeanServer server)
713 this.server = server;
717 * Returns a textual representation of the object name.
719 * <p>The format is unspecified beyond that equivalent object
720 * names will return the same string from this method, but note
721 * that Tomcat depends on the string returned by this method
722 * being a valid textual representation of the object name and
723 * will fail to start if it is not.
725 * @return a textual representation of the object name.
727 public String toString()
729 return getCanonicalName();
733 * Unquotes the supplied string. The quotation marks are removed as
734 * are the backslashes preceding the escaped characters ('"', '?',
735 * '*', '\n', '\\'). A one-to-one mapping exists between quoted and
736 * unquoted values. As a result, a string <code>s</code> should be
737 * equal to <code>unquote(quote(s))</code>.
739 * @param q the quoted string to unquote.
740 * @return the unquoted string.
741 * @throws NullPointerException if <code>q</code> is <code>null</code>.
742 * @throws IllegalArgumentException if the string is not a valid
743 * quoted string i.e. it is not
744 * surrounded by quotation marks
745 * and/or characters are not properly
748 public static String unquote(String q)
750 if (q.charAt(0) != '"')
751 throw new IllegalArgumentException("The string does " +
752 "not start with a quote.");
753 if (q.charAt(q.length() - 1) != '"')
754 throw new IllegalArgumentException("The string does " +
755 "not end with a quote.");
756 StringBuilder builder = new StringBuilder();
757 for (int a = 1; a < (q.length() - 1); ++a)
759 char n = q.charAt(a);
763 if (n != '"' && n != '?' && n != '*' &&
764 n != '\n' && n != '\\')
765 throw new IllegalArgumentException("Illegal escaped character: "
771 return builder.toString();