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;
48 import java.io.IOException;
49 import java.io.InvalidObjectException;
50 import java.io.ObjectInputStream;
51 import java.io.ObjectOutputStream;
55 * An {@link ObjectName} instance represents the name of a management
56 * bean, or a pattern which may match the name of one or more
57 * management beans. Patterns are distinguished from names by the
58 * presence of the '?' and '*' characters (which match a single
59 * character and a series of zero or more characters, respectively).
62 * Each name begins with a domain element, which is terminated by
63 * a ':' character. The domain may be empty. If so, it will be
64 * replaced by the default domain of the bean server in certain
65 * contexts. The domain is a pattern, if it contains either '?'
66 * or '*'. To avoid collisions, it is usual to use reverse
67 * DNS names for the domain, as in Java package and property names.
70 * Following the ':' character is a series of properties. The list
71 * is separated by commas, and largely consists of unordered key-value
72 * pairs, separated by an equals sign ('='). At most one element may
73 * be an asterisk ('*'), which turns the {@link ObjectName} instance
74 * into a <emph>property pattern</emph>. In this situation, the pattern
75 * matches a name if the name contains at least those key-value pairs
76 * given and has the same domain.
79 * A <emph>key</emph> is a string of characters which doesn't include
80 * any of those used as delimiters or in patterns (':', '=', ',', '?'
81 * and '*'). Keys must be unique.
84 * A value may be <emph>quoted</emph> or <emph>unquoted</emph>. Unquoted
85 * values obey the same rules as given for keys above. Quoted values are
86 * surrounded by quotation marks ("), and use a backslash ('\') character
87 * to include quotes ('\"'), backslashes ('\\'), newlines ('\n'), and
88 * the pattern characters ('\?' and '\*'). The quotes and backslashes
89 * (after expansion) are considered part of the value.
92 * Spaces are maintained within the different parts of the name. Thus,
93 * '<code>domain: key1 = value1 </code>' has a key ' key1 ' with value
94 * ' value1 '. Newlines are disallowed, except where escaped in quoted
98 * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
101 public class ObjectName
102 implements Serializable, QueryExp
105 private static final long serialVersionUID = 1081892073854801359L;
108 * The domain of the name.
110 private transient String domain;
113 * The properties, as key-value pairs.
115 private transient TreeMap<String,String> properties;
118 * The properties as a string (stored for ordering).
120 private transient String propertyListString;
123 * True if this object name is a property pattern.
125 private transient boolean propertyPattern;
128 * The management server associated with this object name.
130 private transient MBeanServer server;
133 * Constructs an {@link ObjectName} instance from the given string,
134 * which should be of the form
135 * <domain>:<properties><wild>. <domain>
136 * represents the domain section of the name. <properties>
137 * represents the key-value pairs, as returned by {@link
138 * #getKeyPropertyListString()}. <wild> is the optional
139 * asterisk present in the property list. If the string doesn't
140 * represent a property pattern, it will be empty. If it does,
141 * it will be either ',*' or '*', depending on whether other
142 * properties are present or not, respectively.
144 * @param name the string to use to construct this instance.
145 * @throws MalformedObjectNameException if the string is of the
147 * @throws NullPointerException if <code>name</code> is
150 public ObjectName(String name)
151 throws MalformedObjectNameException
153 if (name.length() == 0)
159 * Parse the name in the same form as the constructor. Used by
163 private void parse(String name)
164 throws MalformedObjectNameException
166 int domainSep = name.indexOf(':');
168 throw new MalformedObjectNameException("No domain separator was found.");
169 domain = name.substring(0, domainSep);
170 String rest = name.substring(domainSep + 1);
171 properties = new TreeMap<String,String>();
172 if (rest.equals("*"))
173 propertyPattern = true;
176 if (rest.endsWith(",*"))
178 propertyPattern = true;
179 propertyListString = rest.substring(0, rest.length() - 2);
182 propertyListString = rest;
183 String[] pairs = propertyListString.split(",");
184 if (pairs.length == 0 && !isPattern())
185 throw new MalformedObjectNameException("A name that is not a " +
186 "pattern must contain at " +
187 "least one key-value pair.");
188 for (int a = 0; a < pairs.length; ++a)
190 int sep = pairs[a].indexOf('=');
191 String key = pairs[a].substring(0, sep);
192 if (properties.containsKey(key))
193 throw new MalformedObjectNameException("The same key occurs " +
195 properties.put(key, pairs[a].substring(sep + 1));
202 * Constructs an {@link ObjectName} instance using the given
203 * domain and the one specified property.
205 * @param domain the domain part of the object name.
206 * @param key the key of the property.
207 * @param value the value of the property.
208 * @throws MalformedObjectNameException the domain, key or value
209 * contains an illegal
210 * character or the value
211 * does not follow the quoting
213 * @throws NullPointerException if one of the parameters is
216 public ObjectName(String domain, String key, String value)
217 throws MalformedObjectNameException
219 this.domain = domain;
220 properties = new TreeMap<String,String>();
221 properties.put(key, value);
226 * Constructs an {@link ObjectName} instance using the given
227 * domain and properties.
229 * @param domain the domain part of the object name.
230 * @param properties the key-value property pairs.
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
236 * @throws NullPointerException if one of the parameters is
239 public ObjectName(String domain, Hashtable<String,String> properties)
240 throws MalformedObjectNameException
242 this.domain = domain;
243 this.properties = new TreeMap<String,String>();
244 this.properties.putAll(properties);
249 * Checks the legality of the domain and the properties.
251 * @throws MalformedObjectNameException the domain, a key or a value
252 * contains an illegal
253 * character or a value
254 * does not follow the quoting
257 private void checkComponents()
258 throws MalformedObjectNameException
260 if (domain.indexOf(':') != -1)
261 throw new MalformedObjectNameException("The domain includes a ':' " +
263 if (domain.indexOf('\n') != -1)
264 throw new MalformedObjectNameException("The domain includes a newline " +
266 char[] chars = new char[] { ':', ',', '*', '?', '=' };
267 Iterator i = properties.entrySet().iterator();
270 Map.Entry entry = (Map.Entry) i.next();
271 String key = (String) entry.getKey();
272 for (int a = 0; a < chars.length; ++a)
273 if (key.indexOf(chars[a]) != -1)
274 throw new MalformedObjectNameException("A key contains a '" +
277 String value = (String) entry.getValue();
278 int quote = value.indexOf('"');
285 catch (IllegalArgumentException e)
287 throw new MalformedObjectNameException("The quoted value is " +
291 else if (quote != -1)
292 throw new MalformedObjectNameException("A value contains " +
293 "a '\"' character.");
296 for (int a = 0; a < chars.length; ++a)
297 if (value.indexOf(chars[a]) != -1)
298 throw new MalformedObjectNameException("A value contains " +
299 "a '" + chars[a] + "' " +
307 * Attempts to find a match between this name and the one supplied.
308 * The following criteria are used:
311 * <li>If the supplied name is a pattern, <code>false</code> is
313 * <li>If this name is a pattern, this method returns <code>true</code>
314 * if the supplied name matches the pattern.</li>
315 * <li>If this name is not a pattern, the result of
316 * <code>equals(name)</code> is returned.
319 * @param name the name to find a match with.
320 * @return true if the name either matches this pattern or is
321 * equivalent to this name under the criteria of
322 * {@link #equals(java.lang.Object)}
323 * @throws NullPointerException if <code>name</code> is <code>null</code>.
325 public boolean apply(ObjectName name)
327 if (name.isPattern())
333 if (isDomainPattern())
335 if (!domainMatches(domain, 0, name.getDomain(), 0))
340 if (!domain.equals(name.getDomain()))
344 if (isPropertyPattern())
346 Hashtable oProps = name.getKeyPropertyList();
347 Iterator i = properties.entrySet().iterator();
350 Map.Entry entry = (Map.Entry) i.next();
351 String key = (String) entry.getKey();
352 if (!(oProps.containsKey(key)))
354 String val = (String) entry.getValue();
355 if (!(val.equals(oProps.get(key))))
361 if (!getCanonicalKeyPropertyListString().equals
362 (name.getCanonicalKeyPropertyListString()))
369 * Returns true if the domain matches the pattern.
371 * @param pattern the pattern to match against.
372 * @param patternindex the index into the pattern to start matching.
373 * @param domain the domain to match.
374 * @param domainindex the index into the domain to start matching.
375 * @return true if the domain matches the pattern.
377 private static boolean domainMatches(String pattern, int patternindex,
378 String domain, int domainindex)
380 while (patternindex < pattern.length())
382 char c = pattern.charAt(patternindex++);
386 for (int i = domain.length(); i >= domainindex; i--)
388 if (domainMatches(pattern, patternindex, domain, i))
394 if (domainindex >= domain.length())
397 if (c != '?' && c != domain.charAt(domainindex))
406 * Compares the specified object with this one. The two
407 * are judged to be equivalent if the given object is an
408 * instance of {@link ObjectName} and has an equal canonical
409 * form (as returned by {@link #getCanonicalName()}).
411 * @param obj the object to compare with this.
412 * @return true if the object is also an {@link ObjectName}
413 * with an equivalent canonical form.
415 public boolean equals(Object obj)
417 if (obj instanceof ObjectName)
419 ObjectName o = (ObjectName) obj;
420 return getCanonicalName().equals(o.getCanonicalName());
426 * Returns the property list in canonical form. The keys
427 * are ordered using the lexicographic ordering used by
428 * {@link java.lang.String#compareTo(java.lang.Object)}.
430 * @return the property list, with the keys in lexicographic
433 public String getCanonicalKeyPropertyListString()
435 StringBuilder builder = new StringBuilder();
436 Iterator i = properties.entrySet().iterator();
439 Map.Entry entry = (Map.Entry) i.next();
440 builder.append(entry.getKey() + "=" + entry.getValue());
444 return builder.toString();
449 * Returns the name as a string in canonical form. More precisely,
450 * this returns a string of the format
451 * <domain>:<properties><wild>. <properties>
452 * is the same value as returned by
453 * {@link #getCanonicalKeyPropertyListString()}. <wild>
457 * <li>an empty string, if the object name is not a property pattern.</li>
458 * <li>'*' if <properties> is empty.</li>
459 * <li>',*' if there is at least one key-value pair.</li>
462 * @return the canonical string form of the object name, as specified
465 public String getCanonicalName()
467 return domain + ":" +
468 getCanonicalKeyPropertyListString() +
469 (isPropertyPattern() ? (properties.isEmpty() ? "*" : ",*") : "");
473 * Returns the domain part of the object name.
475 * @return the domain.
477 public String getDomain()
483 * Returns an {@link ObjectName} instance that is substitutable for the
484 * one given. The instance returned may be a subclass of {@link ObjectName},
485 * but is not guaranteed to be of the same type as the given name, if that
486 * should also turn out to be a subclass. The returned instance may or may
487 * not be equivalent to the one given. The purpose of this method is to provide
488 * an instance of {@link ObjectName} with a well-defined semantics, such as may
489 * be used in cases where the given name is not trustworthy.
491 * @param name the {@link ObjectName} to provide a substitute for.
492 * @return a substitute for the given name, which may or may not be a subclass
493 * of {@link ObjectName}. In either case, the returned object is
494 * guaranteed to have the semantics defined here.
495 * @throws NullPointerException if <code>name</code> is <code>null</code>.
497 public static ObjectName getInstance(ObjectName name)
501 return new ObjectName(name.getCanonicalName());
503 catch (MalformedObjectNameException e)
505 throw (InternalError)
506 (new InternalError("The canonical name of " +
507 "the given name is invalid.").initCause(e));
512 * Returns an {@link ObjectName} instance for the specified name, represented
513 * as a {@link java.lang.String}. 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 string.
517 * @param name the {@link ObjectName} to provide an instance of.
518 * @return a instance for the given name, which may or may not be a subclass
519 * of {@link ObjectName}.
520 * @throws MalformedObjectNameException the domain, a key or a value
521 * contains an illegal
522 * character or a value
523 * does not follow the quoting
525 * @throws NullPointerException if <code>name</code> is <code>null</code>.
527 public static ObjectName getInstance(String name)
528 throws MalformedObjectNameException
530 return new ObjectName(name);
534 * Returns an {@link ObjectName} instance for the specified name, represented
535 * as a series of {@link java.lang.String} objects for the domain and a single
536 * property, as a key-value pair. The instance returned may be a subclass of
537 * {@link ObjectName} and may or may not be equivalent to earlier instances
538 * returned by this method for the same parameters.
540 * @param domain the domain part of the object name.
541 * @param key the key of the property.
542 * @param value the value of the property.
543 * @return a instance for the given name, which may or may not be a subclass
544 * of {@link ObjectName}.
545 * @throws MalformedObjectNameException the domain, a key or a value
546 * contains an illegal
547 * character or a value
548 * does not follow the quoting
550 * @throws NullPointerException if <code>name</code> is <code>null</code>.
552 public static ObjectName getInstance(String domain, String key, String value)
553 throws MalformedObjectNameException
555 return new ObjectName(domain, key, value);
559 * Returns an {@link ObjectName} instance for the specified name, represented
560 * as a domain {@link java.lang.String} and a table of properties. The
561 * instance returned may be a subclass of {@link ObjectName} and may or may
562 * not be equivalent to earlier instances returned by this method for the
565 * @param domain the domain part of the object name.
566 * @param properties the key-value property pairs.
567 * @return a instance for the given name, which may or may not be a subclass
568 * of {@link ObjectName}.
569 * @throws MalformedObjectNameException the domain, a key or a value
570 * contains an illegal
571 * character or a value
572 * does not follow the quoting
574 * @throws NullPointerException if <code>name</code> is <code>null</code>.
576 public static ObjectName getInstance(String domain,
577 Hashtable<String,String> properties)
578 throws MalformedObjectNameException
580 return new ObjectName(domain, properties);
584 * Returns the property value corresponding to the given key.
586 * @param key the key of the property to be obtained.
587 * @return the value of the specified property.
588 * @throws NullPointerException if <code>key</code> is <code>null</code>.
590 public String getKeyProperty(String key)
593 throw new NullPointerException("Null key given in request for a value.");
594 return (String) properties.get(key);
598 * Returns the properties in a {@link java.util.Hashtable}. The table
599 * contains each of the properties as keys mapped to their value. The
600 * returned table is not unmodifiable, but changes made to it will not
601 * be reflected in the object name.
603 * @return a {@link java.util.Hashtable}, containing each of the object
606 public Hashtable<String,String> getKeyPropertyList()
608 return new Hashtable<String,String>(properties);
612 * Returns a {@link java.lang.String} representation of the property
613 * list. If the object name was created using {@link
614 * ObjectName(String)}, then this string will contain the properties
615 * in the same order they were given in at creation.
617 * @return the property list.
619 public String getKeyPropertyListString()
621 if (propertyListString != null)
622 return propertyListString;
623 return getCanonicalKeyPropertyListString();
627 * Returns a hash code for this object name. This is calculated as the
628 * summation of the hash codes of the domain and the properties.
630 * @return a hash code for this object name.
632 public int hashCode()
634 return domain.hashCode() + properties.hashCode();
638 * Returns true if the domain of this object name is a pattern.
639 * This is the case if it contains one or more wildcard characters
642 * @return true if the domain is a pattern.
644 public boolean isDomainPattern()
646 return domain.contains("?") || domain.contains("*");
650 * Returns true if this is an object name pattern. An object
651 * name pattern has a domain containing a wildcard character
652 * ('*' or '?') and/or a '*' in the list of properties.
653 * This method will return true if either {@link #isDomainPattern()}
654 * or {@link #isPropertyPattern()} does.
656 * @return true if this is an object name pattern.
658 public boolean isPattern()
660 return isDomainPattern() || isPropertyPattern();
664 * Returns true if this object name is a property pattern. This is
665 * the case if the list of properties contains an '*'.
667 * @return true if this is a property pattern.
669 public boolean isPropertyPattern()
671 return propertyPattern;
676 * Returns a quoted version of the supplied string. The string may
677 * contain any character. The resulting quoted version is guaranteed
678 * to be usable as the value of a property, so this method provides
679 * a good way of ensuring that a value is legal.
682 * The string is transformed as follows:
685 * <li>The string is prefixed with an opening quote character, '"'.
686 * <li>For each character, s:
688 * <li>If s is a quote ('"'), it is replaced by a backslash
689 * followed by a quote.</li>
690 * <li>If s is a star ('*'), it is replaced by a backslash followed
692 * <li>If s is a question mark ('?'), it is replaced by a backslash
693 * followed by a question mark.</li>
694 * <li>If s is a backslash ('\'), it is replaced by two backslashes.</li>
695 * <li>If s is a newline character, it is replaced by a backslash followed by
697 * <li>Otherwise, s is used verbatim.
699 * <li>The string is terminated with a closing quote character, '"'.</li>
702 * @param string the string to quote.
703 * @return a quoted version of the supplied string.
704 * @throws NullPointerException if <code>string</code> is <code>null</code>.
706 public static String quote(String string)
708 StringBuilder builder = new StringBuilder();
710 for (int a = 0; a < string.length(); ++a)
712 char s = string.charAt(a);
716 builder.append("\\\"");
719 builder.append("\\*");
722 builder.append("\\?");
725 builder.append("\\\\");
728 builder.append("\\\n");
735 return builder.toString();
739 * Changes the {@link MBeanServer} on which this query is performed.
741 * @param server the new server to use.
743 public void setMBeanServer(MBeanServer server)
745 this.server = server;
749 * Returns a textual representation of the object name.
751 * <p>The format is unspecified beyond that equivalent object
752 * names will return the same string from this method, but note
753 * that Tomcat depends on the string returned by this method
754 * being a valid textual representation of the object name and
755 * will fail to start if it is not.
757 * @return a textual representation of the object name.
759 public String toString()
761 return getCanonicalName();
766 * Serialization methods. The serialized form is the same as the
767 * string parsed by the constructor.
770 private void writeObject(ObjectOutputStream out)
773 out.defaultWriteObject();
774 StringBuffer buffer = new StringBuffer(getDomain());
776 String properties = getKeyPropertyListString();
777 buffer.append(properties);
778 if (isPropertyPattern())
780 if (properties.length() == 0)
785 out.writeObject(buffer.toString());
788 private void readObject(ObjectInputStream in)
789 throws IOException, ClassNotFoundException
791 in.defaultReadObject();
792 String objectName = (String)in.readObject();
797 catch (MalformedObjectNameException x)
799 throw new InvalidObjectException(x.toString());
805 * Unquotes the supplied string. The quotation marks are removed as
806 * are the backslashes preceding the escaped characters ('"', '?',
807 * '*', '\n', '\\'). A one-to-one mapping exists between quoted and
808 * unquoted values. As a result, a string <code>s</code> should be
809 * equal to <code>unquote(quote(s))</code>.
811 * @param q the quoted string to unquote.
812 * @return the unquoted string.
813 * @throws NullPointerException if <code>q</code> is <code>null</code>.
814 * @throws IllegalArgumentException if the string is not a valid
815 * quoted string i.e. it is not
816 * surrounded by quotation marks
817 * and/or characters are not properly
820 public static String unquote(String q)
822 if (q.charAt(0) != '"')
823 throw new IllegalArgumentException("The string does " +
824 "not start with a quote.");
825 if (q.charAt(q.length() - 1) != '"')
826 throw new IllegalArgumentException("The string does " +
827 "not end with a quote.");
828 StringBuilder builder = new StringBuilder();
829 for (int a = 1; a < (q.length() - 1); ++a)
831 char n = q.charAt(a);
835 if (n != '"' && n != '?' && n != '*' &&
836 n != '\n' && n != '\\')
837 throw new IllegalArgumentException("Illegal escaped character: "
843 return builder.toString();