summaryrefslogtreecommitdiff
path: root/javax/management/ObjectName.java
blob: a3f30efffb42df307fa8bc215a2bf98a01238324 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
/* ObjectName.java -- Represent the name of a bean, or a pattern for a name.
   Copyright (C) 2006, 2007 Free Software Foundation, Inc.

This file is part of GNU Classpath.

GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.

GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING.  If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.

Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.

As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module.  An independent module is a module which is not derived from
or based on this library.  If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so.  If you do not wish to do so, delete this
exception statement from your version. */

package javax.management;

import java.io.Serializable;

import java.util.Collections;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * <p>
 * An {@link ObjectName} instance represents the name of a management
 * bean, or a pattern which may match the name of one or more
 * management beans.  Patterns are distinguished from names by the
 * presence of the '?' and '*' characters (which match a single
 * character and a series of zero or more characters, respectively).
 * </p>
 * <p>
 * Each name begins with a domain element, which is terminated by
 * a ':' character.  The domain may be empty.  If so, it will be
 * replaced by the default domain of the bean server in certain
 * contexts.  The domain is a pattern, if it contains either '?'
 * or '*'.  To avoid collisions, it is usual to use reverse
 * DNS names for the domain, as in Java package and property names.
 * </p>
 * <p>
 * Following the ':' character is a series of properties.  The list
 * is separated by commas, and largely consists of unordered key-value
 * pairs, separated by an equals sign ('=').  At most one element may
 * be an asterisk ('*'), which turns the {@link ObjectName} instance
 * into a <emph>property pattern</emph>.  In this situation, the pattern
 * matches a name if the name contains at least those key-value pairs
 * given and has the same domain.
 * </p>
 * <p>
 * A <emph>key</emph> is a string of characters which doesn't include
 * any of those used as delimiters or in patterns (':', '=', ',', '?'
 * and '*').  Keys must be unique.
 * </p>
 * <p>
 * A value may be <emph>quoted</emph> or <emph>unquoted</emph>.  Unquoted
 * values obey the same rules as given for keys above.  Quoted values are
 * surrounded by quotation marks ("), and use a backslash ('\') character
 * to include quotes ('\"'), backslashes ('\\'), newlines ('\n'), and
 * the pattern characters ('\?' and '\*').  The quotes and backslashes
 * (after expansion) are considered part of the value.
 * </p>
 * <p>
 * Spaces are maintained within the different parts of the name.  Thus,
 * '<code>domain: key1 = value1 </code>' has a key ' key1 ' with value
 * ' value1 '.  Newlines are disallowed, except where escaped in quoted
 * values.
 * </p> 
 *
 * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
 * @since 1.5
 */
public class ObjectName
  implements Serializable, QueryExp
{

  private static final long serialVersionUID = 1081892073854801359L;

  /**
   * The wildcard {@link ObjectName} {@code "*:*"}
   *
   * @since 1.6
   */
  public static final ObjectName WILDCARD;

  /**
   * The domain of the name.
   */
  private transient String domain;

  /**
   * The properties, as key-value pairs.
   */
  private transient TreeMap<String,String> properties;

  /**
   * The properties as a string (stored for ordering).
   */
  private transient String propertyListString;

  /**
   * True if this object name is a property pattern.
   */
  private transient boolean propertyPattern;

  /**
   * The management server associated with this object name.
   */
  private transient MBeanServer server;

  /**
   * Static initializer to set up the wildcard.
   */
  static
  {
    try
      {
	WILDCARD = new ObjectName("");
      }
    catch (MalformedObjectNameException e)
      {
	throw (InternalError) (new InternalError("A problem occurred " +
						 "initializing the ObjectName " +
						 "wildcard.").initCause(e));
      }
  }

  /**
   * Constructs an {@link ObjectName} instance from the given string,
   * which should be of the form
   * &lt;domain&gt;:&lt;properties&gt;&lt;wild&gt;.  &lt;domain&gt;
   * represents the domain section of the name.  &lt;properties&gt;
   * represents the key-value pairs, as returned by {@link
   * #getKeyPropertyListString()}.  &lt;wild&gt; is the optional
   * asterisk present in the property list.  If the string doesn't
   * represent a property pattern, it will be empty.  If it does,
   * it will be either ',*' or '*', depending on whether other
   * properties are present or not, respectively.
   *
   * @param name the string to use to construct this instance.
   * @throws MalformedObjectNameException if the string is of the
   *                                      wrong format.
   * @throws NullPointerException if <code>name</code> is
   *                              <code>null</code>.
   */
  public ObjectName(String name)
    throws MalformedObjectNameException
  {
    if (name.length() == 0)
      name = "*:*";
    parse(name);
  }

  /**
   * Parse the name in the same form as the constructor.  Used by
   * readObject().
   */
  private void parse(String name)
    throws MalformedObjectNameException
  {
    int domainSep = name.indexOf(':');
    if (domainSep == -1)
      throw new MalformedObjectNameException("No domain separator was found.");
    domain = name.substring(0, domainSep);
    String rest = name.substring(domainSep + 1);
    properties = new TreeMap<String,String>();
    String[] pairs = rest.split(",");
    if (pairs.length == 0 && !isPattern())
      throw new MalformedObjectNameException("A name that is not a " +
					     "pattern must contain at " +
					     "least one key-value pair.");
    propertyListString = "";
    for (int a = 0; a < pairs.length; ++a)
      {
	if (pairs[a].equals("*"))
	  {
	    if (propertyPattern)
	      throw new MalformedObjectNameException("Multiple wildcards " +
						     "in properties.");
	    propertyPattern = true;
	    continue;
	  }
	int sep = pairs[a].indexOf('=');
	if (sep == -1)
	  throw new MalformedObjectNameException("A key must be " +
						 "followed by a value.");
	String key = pairs[a].substring(0, sep);
	if (properties.containsKey(key))
	  throw new MalformedObjectNameException("The same key occurs " +
						 "more than once.");
	String value = pairs[a].substring(sep+1);
	properties.put(key, value);
	propertyListString += key + "=" + value + ",";
      }
    if (propertyListString.length() > 0)
      propertyListString =
	propertyListString.substring(0, propertyListString.length() - 1);
    checkComponents();
  }

  /**
   * Constructs an {@link ObjectName} instance using the given
   * domain and the one specified property.
   *
   * @param domain the domain part of the object name.
   * @param key the key of the property.
   * @param value the value of the property.
   * @throws MalformedObjectNameException the domain, key or value
   *                                      contains an illegal
   *                                      character or the value
   *                                      does not follow the quoting
   *                                      specifications.
   * @throws NullPointerException if one of the parameters is
   *                              <code>null</code>.
   */
  public ObjectName(String domain, String key, String value)
    throws MalformedObjectNameException
  {
    this.domain = domain;
    properties = new TreeMap<String,String>();
    properties.put(key, value);
    checkComponents();
  }

  /**
   * Constructs an {@link ObjectName} instance using the given
   * domain and properties.
   *
   * @param domain the domain part of the object name.
   * @param properties the key-value property pairs.
   * @throws MalformedObjectNameException the domain, a key or a value
   *                                      contains an illegal
   *                                      character or a value
   *                                      does not follow the quoting
   *                                      specifications.
   * @throws NullPointerException if one of the parameters is
   *                              <code>null</code>.
   */
  public ObjectName(String domain, Hashtable<String,String> properties)
    throws MalformedObjectNameException
  {
    this.domain = domain;
    this.properties = new TreeMap<String,String>();
    this.properties.putAll(properties);
    checkComponents();
  }

  /**
   * Checks the legality of the domain and the properties.
   *
   * @throws MalformedObjectNameException the domain, a key or a value
   *                                      contains an illegal
   *                                      character or a value
   *                                      does not follow the quoting
   *                                      specifications.
   */
  private void checkComponents()
    throws MalformedObjectNameException
  {
    if (domain.indexOf(':') != -1)
      throw new MalformedObjectNameException("The domain includes a ':' " +
					     "character.");
    if (domain.indexOf('\n') != -1)
      throw new MalformedObjectNameException("The domain includes a newline " +
					     "character.");
    char[] chars = new char[] { '\n', ':', ',', '*', '?', '=' };
    Iterator i = properties.entrySet().iterator();
    while (i.hasNext())
      {
	Map.Entry entry = (Map.Entry) i.next();
	String key = (String) entry.getKey();
	for (int a = 0; a < chars.length; ++a)
	  if (key.indexOf(chars[a]) != -1)
	    throw new MalformedObjectNameException("A key contains a '" +
						   chars[a] + "' " +
						   "character.");
	String value = (String) entry.getValue();
	int quote = value.indexOf('"');
	if (quote == 0)
	  {
	    try
	      {
		unquote(value);
	      }
	    catch (IllegalArgumentException e)
	      {
		throw (MalformedObjectNameException)
		  new MalformedObjectNameException("The quoted value is " +
						   "invalid.").initCause(e);
	      }
	  }
	else if (quote != -1)
	  throw new MalformedObjectNameException("A value contains " +
						 "a '\"' character.");
	else
	  {
	    for (int a = 0; a < chars.length; ++a)
	      if (value.indexOf(chars[a]) != -1)
		throw new MalformedObjectNameException("A value contains " +
						       "a '" + chars[a] + "' " +
						       "character.");
	  }
      }
  }

  /**
   * <p>
   * Attempts to find a match between this name and the one supplied.
   * The following criteria are used:
   * </p>
   * <ul>
   * <li>If the supplied name is a pattern, <code>false</code> is
   * returned.</li>
   * <li>If this name is a pattern, this method returns <code>true</code>
   * if the supplied name matches the pattern.</li>
   * <li>If this name is not a pattern, the result of
   * <code>equals(name)</code> is returned.
   * </ul>
   *
   * @param name the name to find a match with.
   * @return true if the name either matches this pattern or is
   *         equivalent to this name under the criteria of
   *         {@link #equals(java.lang.Object)}
   * @throws NullPointerException if <code>name</code> is <code>null</code>.
   */
  public boolean apply(ObjectName name)
  {
    if (name.isPattern())
      return false;

    if (!isPattern())
      return equals(name);

    if (isDomainPattern())
      {
	if (!domainMatches(domain, 0, name.getDomain(), 0))
	  return false;
      }
    else
      {
	if (!domain.equals(name.getDomain()))
	  return false;
      }

    if (isPropertyPattern())
      {
	Hashtable oProps = name.getKeyPropertyList();
	Iterator i = properties.entrySet().iterator();
	while (i.hasNext())
	  {
	    Map.Entry entry = (Map.Entry) i.next();
	    String key = (String) entry.getKey();
	    if (!(oProps.containsKey(key)))
	      return false;
	    String val = (String) entry.getValue();
	    if (!(val.equals(oProps.get(key))))
	      return false;
	  }
      }
    else
      {
	if (!getCanonicalKeyPropertyListString().equals
	    (name.getCanonicalKeyPropertyListString()))
	  return false;
      }
    return true;
  }

  /**
   * Returns true if the domain matches the pattern.
   *
   * @param pattern the pattern to match against.
   * @param patternindex the index into the pattern to start matching.
   * @param domain the domain to match.
   * @param domainindex the index into the domain to start matching.
   * @return true if the domain matches the pattern.
   */
  private static boolean domainMatches(String pattern, int patternindex,
				       String domain, int domainindex)
  {
    while (patternindex < pattern.length())
      {
	char c = pattern.charAt(patternindex++);
	
	if (c == '*')
	  {
	    for (int i = domain.length(); i >= domainindex; i--)
	      {
		if (domainMatches(pattern, patternindex, domain, i))
		  return true;
	      }
	    return false;
	  }

	if (domainindex >= domain.length())
	  return false;
	
	if (c != '?' && c != domain.charAt(domainindex))
	  return false;

	domainindex++;
      }
    return true;
  }

  /**
   * Compares the specified object with this one.  The two
   * are judged to be equivalent if the given object is an
   * instance of {@link ObjectName} and has an equal canonical
   * form (as returned by {@link #getCanonicalName()}).
   *
   * @param obj the object to compare with this.
   * @return true if the object is also an {@link ObjectName}
   *         with an equivalent canonical form.
   */
  public boolean equals(Object obj)
  {
    if (obj instanceof ObjectName)
      {
	ObjectName o = (ObjectName) obj;
	return getCanonicalName().equals(o.getCanonicalName());
      }
    return false;
  }

  /**
   * Returns the property list in canonical form.  The keys
   * are ordered using the lexicographic ordering used by
   * {@link java.lang.String#compareTo(java.lang.Object)}.
   * 
   * @return the property list, with the keys in lexicographic
   *         order.
   */
  public String getCanonicalKeyPropertyListString()
  {
    StringBuilder builder = new StringBuilder();
    Iterator i = properties.entrySet().iterator();
    while (i.hasNext())
      {
	Map.Entry entry = (Map.Entry) i.next();
	builder.append(entry.getKey() + "=" + entry.getValue());
	if (i.hasNext())
	  builder.append(",");
      }
    return builder.toString();
  }

  /**
   * <p>
   * Returns the name as a string in canonical form.  More precisely,
   * this returns a string of the format 
   * &lt;domain&gt;:&lt;properties&gt;&lt;wild&gt;.  &lt;properties&gt;
   * is the same value as returned by
   * {@link #getCanonicalKeyPropertyListString()}.  &lt;wild&gt;
   * is:
   * </p>
   * <ul>
   * <li>an empty string, if the object name is not a property pattern.</li>
   * <li>'*' if &lt;properties&gt; is empty.</li>
   * <li>',*' if there is at least one key-value pair.</li>
   * </ul>
   * 
   * @return the canonical string form of the object name, as specified
   *         above.
   */
  public String getCanonicalName()
  {
    return domain + ":" +
      getCanonicalKeyPropertyListString() +
      (isPropertyPattern() ? (properties.isEmpty() ? "*" : ",*") : "");
  }

  /**
   * Returns the domain part of the object name.
   *
   * @return the domain.
   */
  public String getDomain()
  {
    return domain;
  }

  /**
   * Returns an {@link ObjectName} instance that is substitutable for the
   * one given.  The instance returned may be a subclass of {@link ObjectName},
   * but is not guaranteed to be of the same type as the given name, if that
   * should also turn out to be a subclass.  The returned instance may or may
   * not be equivalent to the one given.  The purpose of this method is to provide
   * an instance of {@link ObjectName} with a well-defined semantics, such as may
   * be used in cases where the given name is not trustworthy.
   *
   * @param name the {@link ObjectName} to provide a substitute for.
   * @return a substitute for the given name, which may or may not be a subclass
   *         of {@link ObjectName}.  In either case, the returned object is
   *         guaranteed to have the semantics defined here.
   * @throws NullPointerException if <code>name</code> is <code>null</code>.
   */
  public static ObjectName getInstance(ObjectName name)
  {
    try
      {
	return new ObjectName(name.getCanonicalName());
      }
    catch (MalformedObjectNameException e)
      {
	throw (InternalError)
	  (new InternalError("The canonical name of " +
			     "the given name is invalid.").initCause(e));
      }
  }

  /**
   * Returns an {@link ObjectName} instance for the specified name, represented
   * as a {@link java.lang.String}.  The instance returned may be a subclass of
   * {@link ObjectName} and may or may not be equivalent to earlier instances
   * returned by this method for the same string.
   *
   * @param name the {@link ObjectName} to provide an instance of.
   * @return a instance for the given name, which may or may not be a subclass
   *         of {@link ObjectName}.  
   * @throws MalformedObjectNameException the domain, a key or a value
   *                                      contains an illegal
   *                                      character or a value
   *                                      does not follow the quoting
   *                                      specifications.
   * @throws NullPointerException if <code>name</code> is <code>null</code>.
   */
  public static ObjectName getInstance(String name)
    throws MalformedObjectNameException
  {
    return new ObjectName(name);
  }

  /**
   * Returns an {@link ObjectName} instance for the specified name, represented
   * as a series of {@link java.lang.String} objects for the domain and a single
   * property, as a key-value pair.  The instance returned may be a subclass of
   * {@link ObjectName} and may or may not be equivalent to earlier instances
   * returned by this method for the same parameters.
   *
   * @param domain the domain part of the object name.
   * @param key the key of the property.
   * @param value the value of the property.
   * @return a instance for the given name, which may or may not be a subclass
   *         of {@link ObjectName}.  
   * @throws MalformedObjectNameException the domain, a key or a value
   *                                      contains an illegal
   *                                      character or a value
   *                                      does not follow the quoting
   *                                      specifications.
   * @throws NullPointerException if <code>name</code> is <code>null</code>.
   */
  public static ObjectName getInstance(String domain, String key, String value)
    throws MalformedObjectNameException
  {
    return new ObjectName(domain, key, value);
  }

  /**
   * Returns an {@link ObjectName} instance for the specified name, represented
   * as a domain {@link java.lang.String} and a table of properties.  The
   * instance returned may be a subclass of {@link ObjectName} and may or may
   * not be equivalent to earlier instances returned by this method for the
   * same string.
   *
   * @param domain the domain part of the object name.
   * @param properties the key-value property pairs.
   * @return a instance for the given name, which may or may not be a subclass
   *         of {@link ObjectName}.  
   * @throws MalformedObjectNameException the domain, a key or a value
   *                                      contains an illegal
   *                                      character or a value
   *                                      does not follow the quoting
   *                                      specifications.
   * @throws NullPointerException if <code>name</code> is <code>null</code>.
   */
  public static ObjectName getInstance(String domain,
				       Hashtable<String,String> properties)
    throws MalformedObjectNameException
  {
    return new ObjectName(domain, properties);
  }

  /**
   * Returns the property value corresponding to the given key.
   *
   * @param key the key of the property to be obtained.
   * @return the value of the specified property.
   * @throws NullPointerException if <code>key</code> is <code>null</code>.
   */
  public String getKeyProperty(String key)
  {
    if (key == null)
      throw new NullPointerException("Null key given in request for a value.");
    return (String) properties.get(key);
  }

  /**
   * Returns the properties in a {@link java.util.Hashtable}.  The table
   * contains each of the properties as keys mapped to their value.  The
   * returned table is not unmodifiable, but changes made to it will not
   * be reflected in the object name.
   *
   * @return a {@link java.util.Hashtable}, containing each of the object
   *         name's properties.
   */
  public Hashtable<String,String> getKeyPropertyList()
  {
    return new Hashtable<String,String>(properties);
  }

  /**
   * Returns a {@link java.lang.String} representation of the property
   * list.  If the object name was created using {@link
   * ObjectName(String)}, then this string will contain the properties
   * in the same order they were given in at creation.
   * 
   * @return the property list.
   */
  public String getKeyPropertyListString()
  {
    if (propertyListString != null)
      return propertyListString;
    return getCanonicalKeyPropertyListString();
  }

  /**
   * Returns a hash code for this object name.  This is calculated as the
   * summation of the hash codes of the domain and the properties.
   *
   * @return a hash code for this object name.
   */
  public int hashCode()
  {
    return domain.hashCode() + properties.hashCode();
  }

  /**
   * Returns true if the domain of this object name is a pattern.
   * This is the case if it contains one or more wildcard characters
   * ('*' or '?').
   *
   * @return true if the domain is a pattern.
   */
  public boolean isDomainPattern()
  {
    return domain.contains("?") || domain.contains("*");
  }

  /**
   * Returns true if this is an object name pattern.  An object
   * name pattern has a domain containing a wildcard character
   * ('*' or '?') and/or a '*' in the list of properties.
   * This method will return true if either {@link #isDomainPattern()}
   * or {@link #isPropertyPattern()} does.
   *
   * @return true if this is an object name pattern.
   */
  public boolean isPattern()
  {
    return isDomainPattern() || isPropertyPattern();
  }

  /**
   * Returns true if this object name is a property pattern.  This is
   * the case if the list of properties contains an '*'.
   *
   * @return true if this is a property pattern.
   */
  public boolean isPropertyPattern()
  {
    return propertyPattern;
  }

  /**
   * <p>
   * Returns a quoted version of the supplied string.  The string may
   * contain any character.  The resulting quoted version is guaranteed
   * to be usable as the value of a property, so this method provides
   * a good way of ensuring that a value is legal.
   * </p>
   * <p>
   * The string is transformed as follows:
   * </p>
   * <ul>
   * <li>The string is prefixed with an opening quote character, '"'.
   * <li>For each character, s:
   * <ul>
   * <li>If s is a quote ('"'), it is replaced by a backslash
   * followed by a quote.</li>
   * <li>If s is a star ('*'), it is replaced by a backslash followed
   * by a star.</li>
   * <li>If s is a question mark ('?'), it is replaced by a backslash
   * followed by a question mark.</li>
   * <li>If s is a backslash ('\'), it is replaced by two backslashes.</li>
   * <li>If s is a newline character, it is replaced by a backslash followed by
   * a '\n'.</li>
   * <li>Otherwise, s is used verbatim.
   * </ul></li>
   * <li>The string is terminated with a closing quote character, '"'.</li>
   * </ul> 
   * 
   * @param string the string to quote.
   * @return a quoted version of the supplied string.
   * @throws NullPointerException if <code>string</code> is <code>null</code>.
   */
  public static String quote(String string)
  {
    StringBuilder builder = new StringBuilder();
    builder.append('"');
    for (int a = 0; a < string.length(); ++a)
      {
	char s = string.charAt(a);
	switch (s)
	  {
	  case '"':
	    builder.append("\\\"");
	    break;
	  case '*':
	    builder.append("\\*");
	    break;
	  case '?':
	    builder.append("\\?");
	    break;
	  case '\\':
	    builder.append("\\\\");
	    break;
	  case '\n':
	    builder.append("\\\n");
	    break;
	  default:
	    builder.append(s);
	  }
      }
    builder.append('"');
    return builder.toString();
  }

  /**
   * Changes the {@link MBeanServer} on which this query is performed.
   *
   * @param server the new server to use.
   */
  public void setMBeanServer(MBeanServer server)
  {
    this.server = server;
  }

  /**
   * Returns a textual representation of the object name.
   *
   * <p>The format is unspecified beyond that equivalent object
   * names will return the same string from this method, but note
   * that Tomcat depends on the string returned by this method
   * being a valid textual representation of the object name and
   * will fail to start if it is not.
   *
   * @return a textual representation of the object name.
   */
  public String toString()
  {
    return getCanonicalName();
  }


  /**
   * Serialize this {@link ObjectName}.  The serialized
   * form is the same as the string parsed by the constructor.
   *
   * @param out the output stream to write to.
   * @throws IOException if an I/O error occurs.
   */
  private void writeObject(ObjectOutputStream out)
    throws IOException
  {
    out.defaultWriteObject();
    StringBuffer buffer = new StringBuffer(getDomain());
    buffer.append(':');
    String properties = getKeyPropertyListString();
    buffer.append(properties);
    if (isPropertyPattern())
      {
       if (properties.length() == 0)
         buffer.append("*");
       else
         buffer.append(",*");
      }
    out.writeObject(buffer.toString());
  }

  /**
   * Reads the serialized form, which is that used
   * by the constructor.
   *
   * @param in the input stream to read from.
   * @throws IOException if an I/O error occurs.
   */
  private void readObject(ObjectInputStream in) 
    throws IOException, ClassNotFoundException
   {
     in.defaultReadObject();
     String objectName = (String)in.readObject();
     try
       {
         parse(objectName);
       }
     catch (MalformedObjectNameException x)
       {
         throw new InvalidObjectException(x.toString());
       }
   }


  /**
   * Unquotes the supplied string.  The quotation marks are removed as
   * are the backslashes preceding the escaped characters ('"', '?',
   * '*', '\n', '\\').  A one-to-one mapping exists between quoted and
   * unquoted values.  As a result, a string <code>s</code> should be
   * equal to <code>unquote(quote(s))</code>.
   *
   * @param q the quoted string to unquote.
   * @return the unquoted string.
   * @throws NullPointerException if <code>q</code> is <code>null</code>.
   * @throws IllegalArgumentException if the string is not a valid
   *                                  quoted string i.e. it is not 
   *                                  surrounded by quotation marks
   *                                  and/or characters are not properly
   *                                  escaped.
   */
  public static String unquote(String q)
  {
    if (q.charAt(0) != '"')
      throw new IllegalArgumentException("The string does " +
					 "not start with a quote.");
    if (q.charAt(q.length() - 1) != '"')
      throw new IllegalArgumentException("The string does " +
					 "not end with a quote.");
    StringBuilder builder = new StringBuilder();
    for (int a = 1; a < (q.length() - 1); ++a)
      {
	char n = q.charAt(a);
	if (n == '\\')
	  {
	    n = q.charAt(++a);
	    if (n != '"' && n != '?' && n != '*' &&
		n != 'n' && n != '\\')
	      throw new IllegalArgumentException("Illegal escaped character: "
						 + n);
	  }
	else if (n == '"' || n == '\n') 
	  throw new IllegalArgumentException("Illegal character: " + n);
	builder.append(n);
      }

    return builder.toString();
  }

}