AbstractPreferences.java |
1 /* 2 * %W% %E% 3 * 4 * Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved. 5 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. 6 */ 7 8 package java.util.prefs; 9 10 import java.util.*; 11 import java.io.*; 12 import java.security.AccessController; 13 import java.security.PrivilegedAction; 14 // These imports needed only as a workaround for a JavaDoc bug 15 import java.lang.Integer; 16 import java.lang.Long; 17 import java.lang.Float; 18 import java.lang.Double; 19 20 /** 21 * This class provides a skeletal implementation of the {@link Preferences} 22 * class, greatly easing the task of implementing it. 23 * 24 * <p><strong>This class is for <tt>Preferences</tt> implementers only. 25 * Normal users of the <tt>Preferences</tt> facility should have no need to 26 * consult this documentation. The {@link Preferences} documentation 27 * should suffice.</strong> 28 * 29 * <p>Implementors must override the nine abstract service-provider interface 30 * (SPI) methods: {@link #getSpi(String)}, {@link #putSpi(String,String)}, 31 * {@link #removeSpi(String)}, {@link #childSpi(String)}, {@link 32 * #removeNodeSpi()}, {@link #keysSpi()}, {@link #childrenNamesSpi()}, {@link 33 * #syncSpi()} and {@link #flushSpi()}. All of the concrete methods specify 34 * precisely how they are implemented atop these SPI methods. The implementor 35 * may, at his discretion, override one or more of the concrete methods if the 36 * default implementation is unsatisfactory for any reason, such as 37 * performance. 38 * 39 * <p>The SPI methods fall into three groups concerning exception 40 * behavior. The <tt>getSpi</tt> method should never throw exceptions, but it 41 * doesn't really matter, as any exception thrown by this method will be 42 * intercepted by {@link #get(String,String)}, which will return the specified 43 * default value to the caller. The <tt>removeNodeSpi, keysSpi, 44 * childrenNamesSpi, syncSpi</tt> and <tt>flushSpi</tt> methods are specified 45 * to throw {@link BackingStoreException}, and the implementation is required 46 * to throw this checked exception if it is unable to perform the operation. 47 * The exception propagates outward, causing the corresponding API method 48 * to fail. 49 * 50 * <p>The remaining SPI methods {@link #putSpi(String,String)}, {@link 51 * #removeSpi(String)} and {@link #childSpi(String)} have more complicated 52 * exception behavior. They are not specified to throw 53 * <tt>BackingStoreException</tt>, as they can generally obey their contracts 54 * even if the backing store is unavailable. This is true because they return 55 * no information and their effects are not required to become permanent until 56 * a subsequent call to {@link Preferences#flush()} or 57 * {@link Preferences#sync()}. Generally speaking, these SPI methods should not 58 * throw exceptions. In some implementations, there may be circumstances 59 * under which these calls cannot even enqueue the requested operation for 60 * later processing. Even under these circumstances it is generally better to 61 * simply ignore the invocation and return, rather than throwing an 62 * exception. Under these circumstances, however, all subsequent invocations 63 * of <tt>flush()</tt> and <tt>sync</tt> should return <tt>false</tt>, as 64 * returning <tt>true</tt> would imply that all previous operations had 65 * successfully been made permanent. 66 * 67 * <p>There is one circumstance under which <tt>putSpi, removeSpi and 68 * childSpi</tt> <i>should</i> throw an exception: if the caller lacks 69 * sufficient privileges on the underlying operating system to perform the 70 * requested operation. This will, for instance, occur on most systems 71 * if a non-privileged user attempts to modify system preferences. 72 * (The required privileges will vary from implementation to 73 * implementation. On some implementations, they are the right to modify the 74 * contents of some directory in the file system; on others they are the right 75 * to modify contents of some key in a registry.) Under any of these 76 * circumstances, it would generally be undesirable to let the program 77 * continue executing as if these operations would become permanent at a later 78 * time. While implementations are not required to throw an exception under 79 * these circumstances, they are encouraged to do so. A {@link 80 * SecurityException} would be appropriate. 81 * 82 * <p>Most of the SPI methods require the implementation to read or write 83 * information at a preferences node. The implementor should beware of the 84 * fact that another VM may have concurrently deleted this node from the 85 * backing store. It is the implementation's responsibility to recreate the 86 * node if it has been deleted. 87 * 88 * <p>Implementation note: In Sun's default <tt>Preferences</tt> 89 * implementations, the user's identity is inherited from the underlying 90 * operating system and does not change for the lifetime of the virtual 91 * machine. It is recognized that server-side <tt>Preferences</tt> 92 * implementations may have the user identity change from request to request, 93 * implicitly passed to <tt>Preferences</tt> methods via the use of a 94 * static {@link ThreadLocal} instance. Authors of such implementations are 95 * <i>strongly</i> encouraged to determine the user at the time preferences 96 * are accessed (for example by the {@link #get(String,String)} or {@link 97 * #put(String,String)} method) rather than permanently associating a user 98 * with each <tt>Preferences</tt> instance. The latter behavior conflicts 99 * with normal <tt>Preferences</tt> usage and would lead to great confusion. 100 * 101 * @author Josh Bloch 102 * @version %I%, %G% 103 * @see Preferences 104 * @since 1.4 105 */ 106 public abstract class AbstractPreferences extends Preferences { 107 /** 108 * Our name relative to parent. 109 */ 110 private final String name; 111 112 /** 113 * Our absolute path name. 114 */ 115 private final String absolutePath; 116 117 /** 118 * Our parent node. 119 */ 120 final AbstractPreferences parent; 121 122 /** 123 * Our root node. 124 */ 125 private final AbstractPreferences root; // Relative to this node 126 127 /** 128 * This field should be <tt>true</tt> if this node did not exist in the 129 * backing store prior to the creation of this object. The field 130 * is initialized to false, but may be set to true by a subclass 131 * constructor (and should not be modified thereafter). This field 132 * indicates whether a node change event should be fired when 133 * creation is complete. 134 */ 135 protected boolean newNode = false; 136 137 /** 138 * All known unremoved children of this node. (This "cache" is consulted 139 * prior to calling childSpi() or getChild(). 140 */ 141 private Map kidCache = new HashMap(); 142 143 /** 144 * This field is used to keep track of whether or not this node has 145 * been removed. Once it's set to true, it will never be reset to false. 146 */ 147 private boolean removed = false; 148 149 /** 150 * Registered preference change listeners. 151 */ 152 private PreferenceChangeListener[] prefListeners = 153 new PreferenceChangeListener[0]; 154 155 /** 156 * Registered node change listeners. 157 */ 158 private NodeChangeListener[] nodeListeners = new NodeChangeListener[0]; 159 160 /** 161 * An object whose monitor is used to lock this node. This object 162 * is used in preference to the node itself to reduce the likelihood of 163 * intentional or unintentional denial of service due to a locked node. 164 * To avoid deadlock, a node is <i>never</i> locked by a thread that 165 * holds a lock on a descendant of that node. 166 */ 167 protected final Object lock = new Object(); 168 169 /** 170 * Creates a preference node with the specified parent and the specified 171 * name relative to its parent. 172 * 173 * @param parent the parent of this preference node, or null if this 174 * is the root. 175 * @param name the name of this preference node, relative to its parent, 176 * or <tt>""</tt> if this is the root. 177 * @throws IllegalArgumentException if <tt>name</tt> contains a slash 178 * (<tt>'/'</tt>), or <tt>parent</tt> is <tt>null</tt> and 179 * name isn't <tt>""</tt>. 180 */ 181 protected AbstractPreferences(AbstractPreferences parent, String name) { 182 if (parent==null) { 183 if (!name.equals("")) 184 throw new IllegalArgumentException("Root name '"+name+ 185 "' must be \"\""); 186 this.absolutePath = "/"; 187 root = this; 188 } else { 189 if (name.indexOf('/') != -1) 190 throw new IllegalArgumentException("Name '" + name + 191 "' contains '/'"); 192 if (name.equals("")) 193 throw new IllegalArgumentException("Illegal name: empty string"); 194 195 root = parent.root; 196 absolutePath = (parent==root ? "/" + name 197 : parent.absolutePath() + "/" + name); 198 } 199 this.name = name; 200 this.parent = parent; 201 } 202 203 /** 204 * Implements the <tt>put</tt> method as per the specification in 205 * {@link Preferences#put(String,String)}. 206 * 207 * <p>This implementation checks that the key and value are legal, 208 * obtains this preference node's lock, checks that the node 209 * has not been removed, invokes {@link #putSpi(String,String)}, and if 210 * there are any preference change listeners, enqueues a notification 211 * event for processing by the event dispatch thread. 212 * 213 * @param key key with which the specified value is to be associated. 214 * @param value value to be associated with the specified key. 215 * @throws NullPointerException if key or value is <tt>null</tt>. 216 * @throws IllegalArgumentException if <tt>key.length()</tt> exceeds 217 * <tt>MAX_KEY_LENGTH</tt> or if <tt>value.length</tt> exceeds 218 * <tt>MAX_VALUE_LENGTH</tt>. 219 * @throws IllegalStateException if this node (or an ancestor) has been 220 * removed with the {@link #removeNode()} method. 221 */ 222 public void put(String key, String value) { 223 if (key==null || value==null) 224 throw new NullPointerException(); 225 if (key.length() > MAX_KEY_LENGTH) 226 throw new IllegalArgumentException("Key too long: "+key); 227 if (value.length() > MAX_VALUE_LENGTH) 228 throw new IllegalArgumentException("Value too long: "+value); 229 230 synchronized(lock) { 231 if (removed) 232 throw new IllegalStateException("Node has been removed."); 233 234 putSpi(key, value); 235 enqueuePreferenceChangeEvent(key, value); 236 } 237 } 238 239 /** 240 * Implements the <tt>get</tt> method as per the specification in 241 * {@link Preferences#get(String,String)}. 242 * 243 * <p>This implementation first checks to see if <tt>key</tt> is 244 * <tt>null</tt> throwing a <tt>NullPointerException</tt> if this is 245 * the case. Then it obtains this preference node's lock, 246 * checks that the node has not been removed, invokes {@link 247 * #getSpi(String)}, and returns the result, unless the <tt>getSpi</tt> 248 * invocation returns <tt>null</tt> or throws an exception, in which case 249 * this invocation returns <tt>def</tt>. 250 * 251 * @param key key whose associated value is to be returned. 252 * @param def the value to be returned in the event that this 253 * preference node has no value associated with <tt>key</tt>. 254 * @return the value associated with <tt>key</tt>, or <tt>def</tt> 255 * if no value is associated with <tt>key</tt>. 256 * @throws IllegalStateException if this node (or an ancestor) has been 257 * removed with the {@link #removeNode()} method. 258 * @throws NullPointerException if key is <tt>null</tt>. (A 259 * <tt>null</tt> default <i>is</i> permitted.) 260 */ 261 public String get(String key, String def) { 262 if (key==null) 263 throw new NullPointerException("Null key"); 264 synchronized(lock) { 265 if (removed) 266 throw new IllegalStateException("Node has been removed."); 267 268 String result = null; 269 try { 270 result = getSpi(key); 271 } catch (Exception e) { 272 // Ignoring exception causes default to be returned 273 } 274 return (result==null ? def : result); 275 } 276 } 277 278 /** 279 * Implements the <tt>remove(String)</tt> method as per the specification 280 * in {@link Preferences#remove(String)}. 281 * 282 * <p>This implementation obtains this preference node's lock, 283 * checks that the node has not been removed, invokes 284 * {@link #removeSpi(String)} and if there are any preference 285 * change listeners, enqueues a notification event for processing by the 286 * event dispatch thread. 287 * 288 * @param key key whose mapping is to be removed from the preference node. 289 * @throws IllegalStateException if this node (or an ancestor) has been 290 * removed with the {@link #removeNode()} method. 291 */ 292 public void remove(String key) { 293 synchronized(lock) { 294 if (removed) 295 throw new IllegalStateException("Node has been removed."); 296 297 removeSpi(key); 298 enqueuePreferenceChangeEvent(key, null); 299 } 300 } 301 302 /** 303 * Implements the <tt>clear</tt> method as per the specification in 304 * {@link Preferences#clear()}. 305 * 306 * <p>This implementation obtains this preference node's lock, 307 * invokes {@link #keys()} to obtain an array of keys, and 308 * iterates over the array invoking {@link #remove(String)} on each key. 309 * 310 * @throws BackingStoreException if this operation cannot be completed 311 * due to a failure in the backing store, or inability to 312 * communicate with it. 313 * @throws IllegalStateException if this node (or an ancestor) has been 314 * removed with the {@link #removeNode()} method. 315 */ 316 public void clear() throws BackingStoreException { 317 synchronized(lock) { 318 String[] keys = keys(); 319 for (int i=0; i<keys.length; i++) 320 remove(keys[i]); 321 } 322 } 323 324 /** 325 * Implements the <tt>putInt</tt> method as per the specification in 326 * {@link Preferences#putInt(String,int)}. 327 * 328 * <p>This implementation translates <tt>value</tt> to a string with 329 * {@link Integer#toString(int)} and invokes {@link #put(String,String)} 330 * on the result. 331 * 332 * @param key key with which the string form of value is to be associated. 333 * @param value value whose string form is to be associated with key. 334 * @throws NullPointerException if key is <tt>null</tt>. 335 * @throws IllegalArgumentException if <tt>key.length()</tt> exceeds 336 * <tt>MAX_KEY_LENGTH</tt>. 337 * @throws IllegalStateException if this node (or an ancestor) has been 338 * removed with the {@link #removeNode()} method. 339 */ 340 public void putInt(String key, int value) { 341 put(key, Integer.toString(value)); 342 } 343 344 /** 345 * Implements the <tt>getInt</tt> method as per the specification in 346 * {@link Preferences#getInt(String,int)}. 347 * 348 * <p>This implementation invokes {@link #get(String,String) <tt>get(key, 349 * null)</tt>}. If the return value is non-null, the implementation 350 * attempts to translate it to an <tt>int</tt> with 351 * {@link Integer#parseInt(String)}. If the attempt succeeds, the return 352 * value is returned by this method. Otherwise, <tt>def</tt> is returned. 353 * 354 * @param key key whose associated value is to be returned as an int. 355 * @param def the value to be returned in the event that this 356 * preference node has no value associated with <tt>key</tt> 357 * or the associated value cannot be interpreted as an int. 358 * @return the int value represented by the string associated with 359 * <tt>key</tt> in this preference node, or <tt>def</tt> if the 360 * associated value does not exist or cannot be interpreted as 361 * an int. 362 * @throws IllegalStateException if this node (or an ancestor) has been 363 * removed with the {@link #removeNode()} method. 364 * @throws NullPointerException if <tt>key</tt> is <tt>null</tt>. 365 */ 366 public int getInt(String key, int def) { 367 int result = def; 368 try { 369 String value = get(key, null); 370 if (value != null) 371 result = Integer.parseInt(value); 372 } catch (NumberFormatException e) { 373 // Ignoring exception causes specified default to be returned 374 } 375 376 return result; 377 } 378 379 /** 380 * Implements the <tt>putLong</tt> method as per the specification in 381 * {@link Preferences#putLong(String,long)}. 382 * 383 * <p>This implementation translates <tt>value</tt> to a string with 384 * {@link Long#toString(long)} and invokes {@link #put(String,String)} 385 * on the result. 386 * 387 * @param key key with which the string form of value is to be associated. 388 * @param value value whose string form is to be associated with key. 389 * @throws NullPointerException if key is <tt>null</tt>. 390 * @throws IllegalArgumentException if <tt>key.length()</tt> exceeds 391 * <tt>MAX_KEY_LENGTH</tt>. 392 * @throws IllegalStateException if this node (or an ancestor) has been 393 * removed with the {@link #removeNode()} method. 394 */ 395 public void putLong(String key, long value) { 396 put(key, Long.toString(value)); 397 } 398 399 /** 400 * Implements the <tt>getLong</tt> method as per the specification in 401 * {@link Preferences#getLong(String,long)}. 402 * 403 * <p>This implementation invokes {@link #get(String,String) <tt>get(key, 404 * null)</tt>}. If the return value is non-null, the implementation 405 * attempts to translate it to a <tt>long</tt> with 406 * {@link Long#parseLong(String)}. If the attempt succeeds, the return 407 * value is returned by this method. Otherwise, <tt>def</tt> is returned. 408 * 409 * @param key key whose associated value is to be returned as a long. 410 * @param def the value to be returned in the event that this 411 * preference node has no value associated with <tt>key</tt> 412 * or the associated value cannot be interpreted as a long. 413 * @return the long value represented by the string associated with 414 * <tt>key</tt> in this preference node, or <tt>def</tt> if the 415 * associated value does not exist or cannot be interpreted as 416 * a long. 417 * @throws IllegalStateException if this node (or an ancestor) has been 418 * removed with the {@link #removeNode()} method. 419 * @throws NullPointerException if <tt>key</tt> is <tt>null</tt>. 420 */ 421 public long getLong(String key, long def) { 422 long result = def; 423 try { 424 String value = get(key, null); 425 if (value != null) 426 result = Long.parseLong(value); 427 } catch (NumberFormatException e) { 428 // Ignoring exception causes specified default to be returned 429 } 430 431 return result; 432 } 433 434 /** 435 * Implements the <tt>putBoolean</tt> method as per the specification in 436 * {@link Preferences#putBoolean(String,boolean)}. 437 * 438 * <p>This implementation translates <tt>value</tt> to a string with 439 * {@link String#valueOf(boolean)} and invokes {@link #put(String,String)} 440 * on the result. 441 * 442 * @param key key with which the string form of value is to be associated. 443 * @param value value whose string form is to be associated with key. 444 * @throws NullPointerException if key is <tt>null</tt>. 445 * @throws IllegalArgumentException if <tt>key.length()</tt> exceeds 446 * <tt>MAX_KEY_LENGTH</tt>. 447 * @throws IllegalStateException if this node (or an ancestor) has been 448 * removed with the {@link #removeNode()} method. 449 */ 450 public void putBoolean(String key, boolean value) { 451 put(key, String.valueOf(value)); 452 } 453 454 /** 455 * Implements the <tt>getBoolean</tt> method as per the specification in 456 * {@link Preferences#getBoolean(String,boolean)}. 457 * 458 * <p>This implementation invokes {@link #get(String,String) <tt>get(key, 459 * null)</tt>}. If the return value is non-null, it is compared with 460 * <tt>"true"</tt> using {@link String#equalsIgnoreCase(String)}. If the 461 * comparison returns <tt>true</tt>, this invocation returns 462 * <tt>true</tt>. Otherwise, the original return value is compared with 463 * <tt>"false"</tt>, again using {@link String#equalsIgnoreCase(String)}. 464 * If the comparison returns <tt>true</tt>, this invocation returns 465 * <tt>false</tt>. Otherwise, this invocation returns <tt>def</tt>. 466 * 467 * @param key key whose associated value is to be returned as a boolean. 468 * @param def the value to be returned in the event that this 469 * preference node has no value associated with <tt>key</tt> 470 * or the associated value cannot be interpreted as a boolean. 471 * @return the boolean value represented by the string associated with 472 * <tt>key</tt> in this preference node, or <tt>def</tt> if the 473 * associated value does not exist or cannot be interpreted as 474 * a boolean. 475 * @throws IllegalStateException if this node (or an ancestor) has been 476 * removed with the {@link #removeNode()} method. 477 * @throws NullPointerException if <tt>key</tt> is <tt>null</tt>. 478 */ 479 public boolean getBoolean(String key, boolean def) { 480 boolean result = def; 481 String value = get(key, null); 482 if (value != null) { 483 if (value.equalsIgnoreCase("true")) 484 result = true; 485 else if (value.equalsIgnoreCase("false")) 486 result = false; 487 } 488 489 return result; 490 } 491 492 /** 493 * Implements the <tt>putFloat</tt> method as per the specification in 494 * {@link Preferences#putFloat(String,float)}. 495 * 496 * <p>This implementation translates <tt>value</tt> to a string with 497 * {@link Float#toString(float)} and invokes {@link #put(String,String)} 498 * on the result. 499 * 500 * @param key key with which the string form of value is to be associated. 501 * @param value value whose string form is to be associated with key. 502 * @throws NullPointerException if key is <tt>null</tt>. 503 * @throws IllegalArgumentException if <tt>key.length()</tt> exceeds 504 * <tt>MAX_KEY_LENGTH</tt>. 505 * @throws IllegalStateException if this node (or an ancestor) has been 506 * removed with the {@link #removeNode()} method. 507 */ 508 public void putFloat(String key, float value) { 509 put(key, Float.toString(value)); 510 } 511 512 /** 513 * Implements the <tt>getFloat</tt> method as per the specification in 514 * {@link Preferences#getFloat(String,float)}. 515 * 516 * <p>This implementation invokes {@link #get(String,String) <tt>get(key, 517 * null)</tt>}. If the return value is non-null, the implementation 518 * attempts to translate it to an <tt>float</tt> with 519 * {@link Float#parseFloat(String)}. If the attempt succeeds, the return 520 * value is returned by this method. Otherwise, <tt>def</tt> is returned. 521 * 522 * @param key key whose associated value is to be returned as a float. 523 * @param def the value to be returned in the event that this 524 * preference node has no value associated with <tt>key</tt> 525 * or the associated value cannot be interpreted as a float. 526 * @return the float value represented by the string associated with 527 * <tt>key</tt> in this preference node, or <tt>def</tt> if the 528 * associated value does not exist or cannot be interpreted as 529 * a float. 530 * @throws IllegalStateException if this node (or an ancestor) has been 531 * removed with the {@link #removeNode()} method. 532 * @throws NullPointerException if <tt>key</tt> is <tt>null</tt>. 533 */ 534 public float getFloat(String key, float def) { 535 float result = def; 536 try { 537 String value = get(key, null); 538 if (value != null) 539 result = Float.parseFloat(value); 540 } catch (NumberFormatException e) { 541 // Ignoring exception causes specified default to be returned 542 } 543 544 return result; 545 } 546 547 /** 548 * Implements the <tt>putDouble</tt> method as per the specification in 549 * {@link Preferences#putDouble(String,double)}. 550 * 551 * <p>This implementation translates <tt>value</tt> to a string with 552 * {@link Double#toString(double)} and invokes {@link #put(String,String)} 553 * on the result. 554 * 555 * @param key key with which the string form of value is to be associated. 556 * @param value value whose string form is to be associated with key. 557 * @throws NullPointerException if key is <tt>null</tt>. 558 * @throws IllegalArgumentException if <tt>key.length()</tt> exceeds 559 * <tt>MAX_KEY_LENGTH</tt>. 560 * @throws IllegalStateException if this node (or an ancestor) has been 561 * removed with the {@link #removeNode()} method. 562 */ 563 public void putDouble(String key, double value) { 564 put(key, Double.toString(value)); 565 } 566 567 /** 568 * Implements the <tt>getDouble</tt> method as per the specification in 569 * {@link Preferences#getDouble(String,double)}. 570 * 571 * <p>This implementation invokes {@link #get(String,String) <tt>get(key, 572 * null)</tt>}. If the return value is non-null, the implementation 573 * attempts to translate it to an <tt>double</tt> with 574 * {@link Double#parseDouble(String)}. If the attempt succeeds, the return 575 * value is returned by this method. Otherwise, <tt>def</tt> is returned. 576 * 577 * @param key key whose associated value is to be returned as a double. 578 * @param def the value to be returned in the event that this 579 * preference node has no value associated with <tt>key</tt> 580 * or the associated value cannot be interpreted as a double. 581 * @return the double value represented by the string associated with 582 * <tt>key</tt> in this preference node, or <tt>def</tt> if the 583 * associated value does not exist or cannot be interpreted as 584 * a double. 585 * @throws IllegalStateException if this node (or an ancestor) has been 586 * removed with the {@link #removeNode()} method. 587 * @throws NullPointerException if <tt>key</tt> is <tt>null</tt>. 588 */ 589 public double getDouble(String key, double def) { 590 double result = def; 591 try { 592 String value = get(key, null); 593 if (value != null) 594 result = Double.parseDouble(value); 595 } catch (NumberFormatException e) { 596 // Ignoring exception causes specified default to be returned 597 } 598 599 return result; 600 } 601 602 /** 603 * Implements the <tt>putByteArray</tt> method as per the specification in 604 * {@link Preferences#putByteArray(String,byte[])}. 605 * 606 * @param key key with which the string form of value is to be associated. 607 * @param value value whose string form is to be associated with key. 608 * @throws NullPointerException if key or value is <tt>null</tt>. 609 * @throws IllegalArgumentException if key.length() exceeds MAX_KEY_LENGTH 610 * or if value.length exceeds MAX_VALUE_LENGTH*3/4. 611 * @throws IllegalStateException if this node (or an ancestor) has been 612 * removed with the {@link #removeNode()} method. 613 */ 614 public void putByteArray(String key, byte[] value) { 615 put(key, Base64.byteArrayToBase64(value)); 616 } 617 618 /** 619 * Implements the <tt>getByteArray</tt> method as per the specification in 620 * {@link Preferences#getByteArray(String,byte[])}. 621 * 622 * @param key key whose associated value is to be returned as a byte array. 623 * @param def the value to be returned in the event that this 624 * preference node has no value associated with <tt>key</tt> 625 * or the associated value cannot be interpreted as a byte array. 626 * @return the byte array value represented by the string associated with 627 * <tt>key</tt> in this preference node, or <tt>def</tt> if the 628 * associated value does not exist or cannot be interpreted as 629 * a byte array. 630 * @throws IllegalStateException if this node (or an ancestor) has been 631 * removed with the {@link #removeNode()} method. 632 * @throws NullPointerException if <tt>key</tt> is <tt>null</tt>. (A 633 * <tt>null</tt> value for <tt>def</tt> <i>is</i> permitted.) 634 */ 635 public byte[] getByteArray(String key, byte[] def) { 636 byte[] result = def; 637 String value = get(key, null); 638 try { 639 if (value != null) 640 result = Base64.base64ToByteArray(value); 641 } 642 catch (RuntimeException e) { 643 // Ignoring exception causes specified default to be returned 644 } 645 646 return result; 647 } 648 649 /** 650 * Implements the <tt>keys</tt> method as per the specification in 651 * {@link Preferences#keys()}. 652 * 653 * <p>This implementation obtains this preference node's lock, checks that 654 * the node has not been removed and invokes {@link #keysSpi()}. 655 * 656 * @return an array of the keys that have an associated value in this 657 * preference node. 658 * @throws BackingStoreException if this operation cannot be completed 659 * due to a failure in the backing store, or inability to 660 * communicate with it. 661 * @throws IllegalStateException if this node (or an ancestor) has been 662 * removed with the {@link #removeNode()} method. 663 */ 664 public String[] keys() throws BackingStoreException { 665 synchronized(lock) { 666 if (removed) 667 throw new IllegalStateException("Node has been removed."); 668 669 return keysSpi(); 670 } 671 } 672 673 /** 674 * Implements the <tt>children</tt> method as per the specification in 675 * {@link Preferences#childrenNames()}. 676 * 677 * <p>This implementation obtains this preference node's lock, checks that 678 * the node has not been removed, constructs a <tt>TreeSet</tt> initialized 679 * to the names of children already cached (the children in this node's 680 * "child-cache"), invokes {@link #childrenNamesSpi()}, and adds all of the 681 * returned child-names into the set. The elements of the tree set are 682 * dumped into a <tt>String</tt> array using the <tt>toArray</tt> method, 683 * and this array is returned. 684 * 685 * @return the names of the children of this preference node. 686 * @throws BackingStoreException if this operation cannot be completed 687 * due to a failure in the backing store, or inability to 688 * communicate with it. 689 * @throws IllegalStateException if this node (or an ancestor) has been 690 * removed with the {@link #removeNode()} method. 691 * @see #cachedChildren() 692 */ 693 public String[] childrenNames() throws BackingStoreException { 694 synchronized(lock) { 695 if (removed) 696 throw new IllegalStateException("Node has been removed."); 697 698 Set s = new TreeSet(kidCache.keySet()); 699 String[] kids = childrenNamesSpi(); 700 for(int i=0; i<kids.length; i++) 701 s.add(kids[i]); 702 return (String[]) s.toArray(EMPTY_STRING_ARRAY); 703 } 704 } 705 706 private static final String[] EMPTY_STRING_ARRAY = new String[0]; 707 708 /** 709 * Returns all known unremoved children of this node. 710 * 711 * @return all known unremoved children of this node. 712 */ 713 protected final AbstractPreferences[] cachedChildren() { 714 return (AbstractPreferences[]) kidCache.values(). 715 toArray(EMPTY_ABSTRACT_PREFS_ARRAY); 716 } 717 718 private static final AbstractPreferences[] EMPTY_ABSTRACT_PREFS_ARRAY 719 = new AbstractPreferences[0]; 720 721 /** 722 * Implements the <tt>parent</tt> method as per the specification in 723 * {@link Preferences#parent()}. 724 * 725 * <p>This implementation obtains this preference node's lock, checks that 726 * the node has not been removed and returns the parent value that was 727 * passed to this node's constructor. 728 * 729 * @return the parent of this preference node. 730 * @throws IllegalStateException if this node (or an ancestor) has been 731 * removed with the {@link #removeNode()} method. 732 */ 733 public Preferences parent() { 734 synchronized(lock) { 735 if (removed) 736 throw new IllegalStateException("Node has been removed."); 737 738 return parent; 739 } 740 } 741 742 /** 743 * Implements the <tt>node</tt> method as per the specification in 744 * {@link Preferences#node(String)}. 745 * 746 * <p>This implementation obtains this preference node's lock and checks 747 * that the node has not been removed. If <tt>path</tt> is <tt>""</tt>, 748 * this node is returned; if <tt>path</tt> is <tt>"/"</tt>, this node's 749 * root is returned. If the first character in <tt>path</tt> is 750 * not <tt>'/'</tt>, the implementation breaks <tt>path</tt> into 751 * tokens and recursively traverses the path from this node to the 752 * named node, "consuming" a name and a slash from <tt>path</tt> at 753 * each step of the traversal. At each step, the current node is locked 754 * and the node's child-cache is checked for the named node. If it is 755 * not found, the name is checked to make sure its length does not 756 * exceed <tt>MAX_NAME_LENGTH</tt>. Then the {@link #childSpi(String)} 757 * method is invoked, and the result stored in this node's child-cache. 758 * If the newly created <tt>Preferences</tt> object's {@link #newNode} 759 * field is <tt>true</tt> and there are any node change listeners, 760 * a notification event is enqueued for processing by the event dispatch 761 * thread. 762 * 763 * <p>When there are no more tokens, the last value found in the 764 * child-cache or returned by <tt>childSpi</tt> is returned by this 765 * method. If during the traversal, two <tt>"/"</tt> tokens occur 766 * consecutively, or the final token is <tt>"/"</tt> (rather than a name), 767 * an appropriate <tt>IllegalArgumentException</tt> is thrown. 768 * 769 * <p> If the first character of <tt>path</tt> is <tt>'/'</tt> 770 * (indicating an absolute path name) this preference node's 771 * lock is dropped prior to breaking <tt>path</tt> into tokens, and 772 * this method recursively traverses the path starting from the root 773 * (rather than starting from this node). The traversal is otherwise 774 * identical to the one described for relative path names. Dropping 775 * the lock on this node prior to commencing the traversal at the root 776 * node is essential to avoid the possibility of deadlock, as per the 777 * {@link #lock locking invariant}. 778 * 779 * @param path the path name of the preference node to return. 780 * @return the specified preference node. 781 * @throws IllegalArgumentException if the path name is invalid (i.e., 782 * it contains multiple consecutive slash characters, or ends 783 * with a slash character and is more than one character long). 784 * @throws IllegalStateException if this node (or an ancestor) has been 785 * removed with the {@link #removeNode()} method. 786 */ 787 public Preferences node(String path) { 788 synchronized(lock) { 789 if (removed) 790 throw new IllegalStateException("Node has been removed."); 791 if (path.equals("")) 792 return this; 793 if (path.equals("/")) 794 return root; 795 if (path.charAt(0) != '/') 796 return node(new StringTokenizer(path, "/", true)); 797 } 798 799 // Absolute path. Note that we've dropped our lock to avoid deadlock 800 return root.node(new StringTokenizer(path.substring(1), "/", true)); 801 } 802 803 /** 804 * tokenizer contains <name> {'/' <name>}* 805 */ 806 private Preferences node(StringTokenizer path) { 807 String token = path.nextToken(); 808 if (token.equals("/")) // Check for consecutive slashes 809 throw new IllegalArgumentException("Consecutive slashes in path"); 810 synchronized(lock) { 811 AbstractPreferences child=(AbstractPreferences)kidCache.get(token); 812 if (child == null) { 813 if (token.length() > MAX_NAME_LENGTH) 814 throw new IllegalArgumentException( 815 "Node name " + token + " too long"); 816 child = childSpi(token); 817 if (child.newNode) 818 enqueueNodeAddedEvent(child); 819 kidCache.put(token, child); 820 } 821 if (!path.hasMoreTokens()) 822 return child; 823 path.nextToken(); // Consume slash 824 if (!path.hasMoreTokens()) 825 throw new IllegalArgumentException("Path ends with slash"); 826 return child.node(path); 827 } 828 } 829 830 /** 831 * Implements the <tt>nodeExists</tt> method as per the specification in 832 * {@link Preferences#nodeExists(String)}. 833 * 834 * <p>This implementation is very similar to {@link #node(String)}, 835 * except that {@link #getChild(String)} is used instead of {@link 836 * #childSpi(String)}. 837 * 838 * @param path the path name of the node whose existence is to be checked. 839 * @return true if the specified node exists. 840 * @throws BackingStoreException if this operation cannot be completed 841 * due to a failure in the backing store, or inability to 842 * communicate with it. 843 * @throws IllegalArgumentException if the path name is invalid (i.e., 844 * it contains multiple consecutive slash characters, or ends 845 * with a slash character and is more than one character long). 846 * @throws IllegalStateException if this node (or an ancestor) has been 847 * removed with the {@link #removeNode()} method and 848 * <tt>pathname</tt> is not the empty string (<tt>""</tt>). 849 */ 850 public boolean nodeExists(String path) 851 throws BackingStoreException 852 { 853 synchronized(lock) { 854 if (path.equals("")) 855 return !removed; 856 if (removed) 857 throw new IllegalStateException("Node has been removed."); 858 if (path.equals("/")) 859 return true; 860 if (path.charAt(0) != '/') 861 return nodeExists(new StringTokenizer(path, "/", true)); 862 } 863 864 // Absolute path. Note that we've dropped our lock to avoid deadlock 865 return root.nodeExists(new StringTokenizer(path.substring(1), "/", 866 true)); 867 } 868 869 /** 870 * tokenizer contains <name> {'/' <name>}* 871 */ 872 private boolean nodeExists(StringTokenizer path) 873 throws BackingStoreException 874 { 875 String token = path.nextToken(); 876 if (token.equals("/")) // Check for consecutive slashes 877 throw new IllegalArgumentException("Consecutive slashes in path"); 878 synchronized(lock) { 879 AbstractPreferences child=(AbstractPreferences)kidCache.get(token); 880 if (child == null) 881 child = getChild(token); 882 if (child==null) 883 return false; 884 if (!path.hasMoreTokens()) 885 return true; 886 path.nextToken(); // Consume slash 887 if (!path.hasMoreTokens()) 888 throw new IllegalArgumentException("Path ends with slash"); 889 return child.nodeExists(path); 890 } 891 } 892 893 /** 894 895 * Implements the <tt>removeNode()</tt> method as per the specification in 896 * {@link Preferences#removeNode()}. 897 * 898 * <p>This implementation checks to see that this node is the root; if so, 899 * it throws an appropriate exception. Then, it locks this node's parent, 900 * and calls a recursive helper method that traverses the subtree rooted at 901 * this node. The recursive method locks the node on which it was called, 902 * checks that it has not already been removed, and then ensures that all 903 * of its children are cached: The {@link #childrenNamesSpi()} method is 904 * invoked and each returned child name is checked for containment in the 905 * child-cache. If a child is not already cached, the {@link 906 * #childSpi(String)} method is invoked to create a <tt>Preferences</tt> 907 * instance for it, and this instance is put into the child-cache. Then 908 * the helper method calls itself recursively on each node contained in its 909 * child-cache. Next, it invokes {@link #removeNodeSpi()}, marks itself 910 * as removed, and removes itself from its parent's child-cache. Finally, 911 * if there are any node change listeners, it enqueues a notification 912 * event for processing by the event dispatch thread. 913 * 914 * <p>Note that the helper method is always invoked with all ancestors up 915 * to the "closest non-removed ancestor" locked. 916 * 917 * @throws IllegalStateException if this node (or an ancestor) has already 918 * been removed with the {@link #removeNode()} method. 919 * @throws UnsupportedOperationException if this method is invoked on 920 * the root node. 921 * @throws BackingStoreException if this operation cannot be completed 922 * due to a failure in the backing store, or inability to 923 * communicate with it. 924 */ 925 public void removeNode() throws BackingStoreException { 926 if (this==root) 927 throw new UnsupportedOperationException("Can't remove the root!"); 928 synchronized(parent.lock) { 929 removeNode2(); 930 parent.kidCache.remove(name); 931 } 932 } 933 934 /* 935 * Called with locks on all nodes on path from parent of "removal root" 936 * to this (including the former but excluding the latter). 937 */ 938 private void removeNode2() throws BackingStoreException { 939 synchronized(lock) { 940 if (removed) 941 throw new IllegalStateException("Node already removed."); 942 943 // Ensure that all children are cached 944 String[] kidNames = childrenNamesSpi(); 945 for (int i=0; i<kidNames.length; i++) 946 if (!kidCache.containsKey(kidNames[i])) 947 kidCache.put(kidNames[i], childSpi(kidNames[i])); 948 949 // Recursively remove all cached children 950 for (Iterator i = kidCache.values().iterator(); i.hasNext();) { 951 try { 952 ((AbstractPreferences)i.next()).removeNode2(); 953 i.remove(); 954 } catch (BackingStoreException x) { } 955 } 956 957 // Now we have no descendants - it's time to die! 958 removeNodeSpi(); 959 removed = true; 960 parent.enqueueNodeRemovedEvent(this); 961 } 962 } 963 964 /** 965 * Implements the <tt>name</tt> method as per the specification in 966 * {@link Preferences#name()}. 967 * 968 * <p>This implementation merely returns the name that was 969 * passed to this node's constructor. 970 * 971 * @return this preference node's name, relative to its parent. 972 */ 973 public String name() { 974 return name; 975 } 976 977 /** 978 * Implements the <tt>absolutePath</tt> method as per the specification in 979 * {@link Preferences#absolutePath()}. 980 * 981 * <p>This implementation merely returns the absolute path name that 982 * was computed at the time that this node was constructed (based on 983 * the name that was passed to this node's constructor, and the names 984 * that were passed to this node's ancestors' constructors). 985 * 986 * @return this preference node's absolute path name. 987 */ 988 public String absolutePath() { 989 return absolutePath; 990 } 991 992 /** 993 * Implements the <tt>isUserNode</tt> method as per the specification in 994 * {@link Preferences#isUserNode()}. 995 * 996 * <p>This implementation compares this node's root node (which is stored 997 * in a private field) with the value returned by 998 * {@link Preferences#userRoot()}. If the two object references are 999 * identical, this method returns true. 1000 * 1001 * @return <tt>true</tt> if this preference node is in the user 1002 * preference tree, <tt>false</tt> if it's in the system 1003 * preference tree. 1004 */ 1005 public boolean isUserNode() { 1006 Boolean result = (Boolean) 1007 AccessController.doPrivileged( new PrivilegedAction() { 1008 public Object run() { 1009 return new Boolean(root == Preferences.userRoot()); 1010 } 1011 }); 1012 return result.booleanValue(); 1013 } 1014 1015 public void addPreferenceChangeListener(PreferenceChangeListener pcl) { 1016 if (pcl==null) 1017 throw new NullPointerException("Change listener is null."); 1018 synchronized(lock) { 1019 if (removed) 1020 throw new IllegalStateException("Node has been removed."); 1021 1022 // Copy-on-write 1023 PreferenceChangeListener[] old = prefListeners; 1024 prefListeners = new PreferenceChangeListener[old.length + 1]; 1025 System.arraycopy(old, 0, prefListeners, 0, old.length); 1026 prefListeners[old.length] = pcl; 1027 } 1028 startEventDispatchThreadIfNecessary(); 1029 } 1030 1031 public void removePreferenceChangeListener(PreferenceChangeListener pcl) { 1032 synchronized(lock) { 1033 if (removed) 1034 throw new IllegalStateException("Node has been removed."); 1035 if ((prefListeners == null) || (prefListeners.length == 0)) 1036 throw new IllegalArgumentException("Listener not registered."); 1037 1038 // Copy-on-write 1039 PreferenceChangeListener[] newPl = 1040 new PreferenceChangeListener[prefListeners.length - 1]; 1041 int i = 0; 1042 while (i < newPl.length && prefListeners[i] != pcl) 1043 newPl[i] = prefListeners[i++]; 1044 1045 if (i == newPl.length && prefListeners[i] != pcl) 1046 throw new IllegalArgumentException("Listener not registered."); 1047 while (i < newPl.length) 1048 newPl[i] = prefListeners[++i]; 1049 prefListeners = newPl; 1050 } 1051 } 1052 1053 public void addNodeChangeListener(NodeChangeListener ncl) { 1054 if (ncl==null) 1055 throw new NullPointerException("Change listener is null."); 1056 synchronized(lock) { 1057 if (removed) 1058 throw new IllegalStateException("Node has been removed."); 1059 1060 // Copy-on-write 1061 if (nodeListeners == null) { 1062 nodeListeners = new NodeChangeListener[1]; 1063 nodeListeners[0] = ncl; 1064 } else { 1065 NodeChangeListener[] old = nodeListeners; 1066 nodeListeners = new NodeChangeListener[old.length + 1]; 1067 System.arraycopy(old, 0, nodeListeners, 0, old.length); 1068 nodeListeners[old.length] = ncl; 1069 } 1070 } 1071 startEventDispatchThreadIfNecessary(); 1072 } 1073 1074 public void removeNodeChangeListener(NodeChangeListener ncl) { 1075 synchronized(lock) { 1076 if (removed) 1077 throw new IllegalStateException("Node has been removed."); 1078 if ((nodeListeners == null) || (nodeListeners.length == 0)) 1079 throw new IllegalArgumentException("Listener not registered."); 1080 1081 // Copy-on-write 1082 int i = 0; 1083 while (i < nodeListeners.length && nodeListeners[i] != ncl) 1084 i++; 1085 if (i == nodeListeners.length) 1086 throw new IllegalArgumentException("Listener not registered."); 1087 NodeChangeListener[] newNl = 1088 new NodeChangeListener[nodeListeners.length - 1]; 1089 if (i != 0) 1090 System.arraycopy(nodeListeners, 0, newNl, 0, i); 1091 if (i != newNl.length) 1092 System.arraycopy(nodeListeners, i + 1, 1093 newNl, i, newNl.length - i); 1094 nodeListeners = newNl; 1095 } 1096 } 1097 1098 // "SPI" METHODS 1099 1100 /** 1101 * Put the given key-value association into this preference node. It is 1102 * guaranteed that <tt>key</tt> and <tt>value</tt> are non-null and of 1103 * legal length. Also, it is guaranteed that this node has not been 1104 * removed. (The implementor needn't check for any of these things.) 1105 * 1106 * <p>This method is invoked with the lock on this node held. 1107 */ 1108 protected abstract void putSpi(String key, String value); 1109 1110 /** 1111 * Return the value associated with the specified key at this preference 1112 * node, or <tt>null</tt> if there is no association for this key, or the 1113 * association cannot be determined at this time. It is guaranteed that 1114 * <tt>key</tt> is non-null. Also, it is guaranteed that this node has 1115 * not been removed. (The implementor needn't check for either of these 1116 * things.) 1117 * 1118 * <p> Generally speaking, this method should not throw an exception 1119 * under any circumstances. If, however, if it does throw an exception, 1120 * the exception will be intercepted and treated as a <tt>null</tt> 1121 * return value. 1122 * 1123 * <p>This method is invoked with the lock on this node held. 1124 * 1125 * @return the value associated with the specified key at this preference 1126 * node, or <tt>null</tt> if there is no association for this 1127 * key, or the association cannot be determined at this time. 1128 */ 1129 protected abstract String getSpi(String key); 1130 1131 /** 1132 * Remove the association (if any) for the specified key at this 1133 * preference node. It is guaranteed that <tt>key</tt> is non-null. 1134 * Also, it is guaranteed that this node has not been removed. 1135 * (The implementor needn't check for either of these things.) 1136 * 1137 * <p>This method is invoked with the lock on this node held. 1138 */ 1139 protected abstract void removeSpi(String key); 1140 1141 /** 1142 * Removes this preference node, invalidating it and any preferences that 1143 * it contains. The named child will have no descendants at the time this 1144 * invocation is made (i.e., the {@link Preferences#removeNode()} method 1145 * invokes this method repeatedly in a bottom-up fashion, removing each of 1146 * a node's descendants before removing the node itself). 1147 * 1148 * <p>This method is invoked with the lock held on this node and its 1149 * parent (and all ancestors that are being removed as a 1150 * result of a single invocation to {@link Preferences#removeNode()}). 1151 * 1152 * <p>The removal of a node needn't become persistent until the 1153 * <tt>flush</tt> method is invoked on this node (or an ancestor). 1154 * 1155 * <p>If this node throws a <tt>BackingStoreException</tt>, the exception 1156 * will propagate out beyond the enclosing {@link #removeNode()} 1157 * invocation. 1158 * 1159 * @throws BackingStoreException if this operation cannot be completed 1160 * due to a failure in the backing store, or inability to 1161 * communicate with it. 1162 */ 1163 protected abstract void removeNodeSpi() throws BackingStoreException; 1164 1165 /** 1166 * Returns all of the keys that have an associated value in this 1167 * preference node. (The returned array will be of size zero if 1168 * this node has no preferences.) It is guaranteed that this node has not 1169 * been removed. 1170 * 1171 * <p>This method is invoked with the lock on this node held. 1172 * 1173 * <p>If this node throws a <tt>BackingStoreException</tt>, the exception 1174 * will propagate out beyond the enclosing {@link #keys()} invocation. 1175 * 1176 * @return an array of the keys that have an associated value in this 1177 * preference node. 1178 * @throws BackingStoreException if this operation cannot be completed 1179 * due to a failure in the backing store, or inability to 1180 * communicate with it. 1181 */ 1182 protected abstract String[] keysSpi() throws BackingStoreException; 1183 1184 /** 1185 * Returns the names of the children of this preference node. (The 1186 * returned array will be of size zero if this node has no children.) 1187 * This method need not return the names of any nodes already cached, 1188 * but may do so without harm. 1189 * 1190 * <p>This method is invoked with the lock on this node held. 1191 * 1192 * <p>If this node throws a <tt>BackingStoreException</tt>, the exception 1193 * will propagate out beyond the enclosing {@link #childrenNames()} 1194 * invocation. 1195 * 1196 * @return an array containing the names of the children of this 1197 * preference node. 1198 * @throws BackingStoreException if this operation cannot be completed 1199 * due to a failure in the backing store, or inability to 1200 * communicate with it. 1201 */ 1202 protected abstract String[] childrenNamesSpi() 1203 throws BackingStoreException; 1204 1205 /** 1206 * Returns the named child if it exists, or <tt>null</tt> if it does not. 1207 * It is guaranteed that <tt>nodeName</tt> is non-null, non-empty, 1208 * does not contain the slash character ('/'), and is no longer than 1209 * {@link #MAX_NAME_LENGTH} characters. Also, it is guaranteed 1210 * that this node has not been removed. (The implementor needn't check 1211 * for any of these things if he chooses to override this method.) 1212 * 1213 * <p>Finally, it is guaranteed that the named node has not been returned 1214 * by a previous invocation of this method or {@link #childSpi} after the 1215 * last time that it was removed. In other words, a cached value will 1216 * always be used in preference to invoking this method. (The implementor 1217 * needn't maintain his own cache of previously returned children if he 1218 * chooses to override this method.) 1219 * 1220 * <p>This implementation obtains this preference node's lock, invokes 1221 * {@link #childrenNames()} to get an array of the names of this node's 1222 * children, and iterates over the array comparing the name of each child 1223 * with the specified node name. If a child node has the correct name, 1224 * the {@link #childSpi(String)} method is invoked and the resulting 1225 * node is returned. If the iteration completes without finding the 1226 * specified name, <tt>null</tt> is returned. 1227 * 1228 * @param nodeName name of the child to be searched for. 1229 * @return the named child if it exists, or null if it does not. 1230 * @throws BackingStoreException if this operation cannot be completed 1231 * due to a failure in the backing store, or inability to 1232 * communicate with it. 1233 */ 1234 protected AbstractPreferences getChild(String nodeName) 1235 throws BackingStoreException { 1236 synchronized(lock) { 1237 // assert kidCache.get(nodeName)==null; 1238 String[] kidNames = childrenNames(); 1239 for (int i=0; i<kidNames.length; i++) 1240 if (kidNames[i].equals(nodeName)) 1241 return childSpi(kidNames[i]); 1242 } 1243 return null; 1244 } 1245 1246 /** 1247 * Returns the named child of this preference node, creating it if it does 1248 * not already exist. It is guaranteed that <tt>name</tt> is non-null, 1249 * non-empty, does not contain the slash character ('/'), and is no longer 1250 * than {@link #MAX_NAME_LENGTH} characters. Also, it is guaranteed that 1251 * this node has not been removed. (The implementor needn't check for any 1252 * of these things.) 1253 * 1254 * <p>Finally, it is guaranteed that the named node has not been returned 1255 * by a previous invocation of this method or {@link #getChild(String)} 1256 * after the last time that it was removed. In other words, a cached 1257 * value will always be used in preference to invoking this method. 1258 * Subclasses need not maintain their own cache of previously returned 1259 * children. 1260 * 1261 * <p>The implementer must ensure that the returned node has not been 1262 * removed. If a like-named child of this node was previously removed, the 1263 * implementer must return a newly constructed <tt>AbstractPreferences</tt> 1264 * node; once removed, an <tt>AbstractPreferences</tt> node 1265 * cannot be "resuscitated." 1266 * 1267 * <p>If this method causes a node to be created, this node is not 1268 * guaranteed to be persistent until the <tt>flush</tt> method is 1269 * invoked on this node or one of its ancestors (or descendants). 1270 * 1271 * <p>This method is invoked with the lock on this node held. 1272 * 1273 * @param name The name of the child node to return, relative to 1274 * this preference node. 1275 * @return The named child node. 1276 */ 1277 protected abstract AbstractPreferences childSpi(String name); 1278 1279 /** 1280 * Returns the absolute path name of this preferences node. 1281 */ 1282 public String toString() { 1283 return (this.isUserNode() ? "User" : "System") + 1284 " Preference Node: " + this.absolutePath(); 1285 } 1286 1287 /** 1288 * Implements the <tt>sync</tt> method as per the specification in 1289 * {@link Preferences#sync()}. 1290 * 1291 * <p>This implementation calls a recursive helper method that locks this 1292 * node, invokes syncSpi() on it, unlocks this node, and recursively 1293 * invokes this method on each "cached child." A cached child is a child 1294 * of this node that has been created in this VM and not subsequently 1295 * removed. In effect, this method does a depth first traversal of the 1296 * "cached subtree" rooted at this node, calling syncSpi() on each node in 1297 * the subTree while only that node is locked. Note that syncSpi() is 1298 * invoked top-down. 1299 * 1300 * @throws BackingStoreException if this operation cannot be completed 1301 * due to a failure in the backing store, or inability to 1302 * communicate with it. 1303 * @throws IllegalStateException if this node (or an ancestor) has been 1304 * removed with the {@link #removeNode()} method. 1305 * @see #flush() 1306 */ 1307 public void sync() throws BackingStoreException { 1308 sync2(); 1309 } 1310 1311 private void sync2() throws BackingStoreException { 1312 AbstractPreferences[] cachedKids; 1313 1314 synchronized(lock) { 1315 if (removed) 1316 throw new IllegalStateException("Node has been removed"); 1317 syncSpi(); 1318 cachedKids = cachedChildren(); 1319 } 1320 1321 for (int i=0; i<cachedKids.length; i++) 1322 cachedKids[i].sync2(); 1323 } 1324 1325 /** 1326 * This method is invoked with this node locked. The contract of this 1327 * method is to synchronize any cached preferences stored at this node 1328 * with any stored in the backing store. (It is perfectly possible that 1329 * this node does not exist on the backing store, either because it has 1330 * been deleted by another VM, or because it has not yet been created.) 1331 * Note that this method should <i>not</i> synchronize the preferences in 1332 * any subnodes of this node. If the backing store naturally syncs an 1333 * entire subtree at once, the implementer is encouraged to override 1334 * sync(), rather than merely overriding this method. 1335 * 1336 * <p>If this node throws a <tt>BackingStoreException</tt>, the exception 1337 * will propagate out beyond the enclosing {@link #sync()} invocation. 1338 * 1339 * @throws BackingStoreException if this operation cannot be completed 1340 * due to a failure in the backing store, or inability to 1341 * communicate with it. 1342 */ 1343 protected abstract void syncSpi() throws BackingStoreException; 1344 1345 /** 1346 * Implements the <tt>flush</tt> method as per the specification in 1347 * {@link Preferences#flush()}. 1348 * 1349 * <p>This implementation calls a recursive helper method that locks this 1350 * node, invokes flushSpi() on it, unlocks this node, and recursively 1351 * invokes this method on each "cached child." A cached child is a child 1352 * of this node that has been created in this VM and not subsequently 1353 * removed. In effect, this method does a depth first traversal of the 1354 * "cached subtree" rooted at this node, calling flushSpi() on each node in 1355 * the subTree while only that node is locked. Note that flushSpi() is 1356 * invoked top-down. 1357 * 1358 * <p> If this method is invoked on a node that has been removed with 1359 * the {@link #removeNode()} method, flushSpi() is invoked on this node, 1360 * but not on others. 1361 * 1362 * @throws BackingStoreException if this operation cannot be completed 1363 * due to a failure in the backing store, or inability to 1364 * communicate with it. 1365 * @see #flush() 1366 */ 1367 public void flush() throws BackingStoreException { 1368 flush2(); 1369 } 1370 1371 private void flush2() throws BackingStoreException { 1372 AbstractPreferences[] cachedKids; 1373 1374 synchronized(lock) { 1375 flushSpi(); 1376 if(removed) 1377 return; 1378 cachedKids = cachedChildren(); 1379 } 1380 1381 for (int i = 0; i < cachedKids.length; i++) 1382 cachedKids[i].flush2(); 1383 } 1384 1385 /** 1386 * This method is invoked with this node locked. The contract of this 1387 * method is to force any cached changes in the contents of this 1388 * preference node to the backing store, guaranteeing their persistence. 1389 * (It is perfectly possible that this node does not exist on the backing 1390 * store, either because it has been deleted by another VM, or because it 1391 * has not yet been created.) Note that this method should <i>not</i> 1392 * flush the preferences in any subnodes of this node. If the backing 1393 * store naturally flushes an entire subtree at once, the implementer is 1394 * encouraged to override flush(), rather than merely overriding this 1395 * method. 1396 * 1397 * <p>If this node throws a <tt>BackingStoreException</tt>, the exception 1398 * will propagate out beyond the enclosing {@link #flush()} invocation. 1399 * 1400 * @throws BackingStoreException if this operation cannot be completed 1401 * due to a failure in the backing store, or inability to 1402 * communicate with it. 1403 */ 1404 protected abstract void flushSpi() throws BackingStoreException; 1405 1406 /** 1407 * Returns <tt>true</tt> iff this node (or an ancestor) has been 1408 * removed with the {@link #removeNode()} method. This method 1409 * locks this node prior to returning the contents of the private 1410 * field used to track this state. 1411 * 1412 * @return <tt>true</tt> iff this node (or an ancestor) has been 1413 * removed with the {@link #removeNode()} method. 1414 */ 1415 protected boolean isRemoved() { 1416 synchronized(lock) { 1417 return removed; 1418 } 1419 } 1420 1421 /** 1422 * Queue of pending notification events. When a preference or node 1423 * change event for which there are one or more listeners occurs, 1424 * it is placed on this queue and the queue is notified. A background 1425 * thread waits on this queue and delivers the events. This decouples 1426 * event delivery from preference activity, greatly simplifying 1427 * locking and reducing opportunity for deadlock. 1428 */ 1429 private static final List eventQueue = new LinkedList(); 1430 1431 /** 1432 * These two classes are used to distinguish NodeChangeEvents on 1433 * eventQueue so the event dispatch thread knows whether to call 1434 * childAdded or childRemoved. 1435 */ 1436 private class NodeAddedEvent extends NodeChangeEvent { 1437 private static final long serialVersionUID = -6743557530157328528L; 1438 NodeAddedEvent(Preferences parent, Preferences child) { 1439 super(parent, child); 1440 } 1441 } 1442 private class NodeRemovedEvent extends NodeChangeEvent { 1443 private static final long serialVersionUID = 8735497392918824837L; 1444 NodeRemovedEvent(Preferences parent, Preferences child) { 1445 super(parent, child); 1446 } 1447 } 1448 1449 /** 1450 * A single background thread ("the event notification thread") monitors 1451 * the event queue and delivers events that are placed on the queue. 1452 */ 1453 private static class EventDispatchThread extends Thread { 1454 public void run() { 1455 while(true) { 1456 // Wait on eventQueue till an event is present 1457 EventObject event = null; 1458 synchronized(eventQueue) { 1459 try { 1460 while (eventQueue.isEmpty()) 1461 eventQueue.wait(); 1462 event = (EventObject) eventQueue.remove(0); 1463 } catch (InterruptedException e) { 1464 // XXX Log "Event dispatch thread interrupted. Exiting" 1465 return; 1466 } 1467 } 1468 1469 // Now we have event & hold no locks; deliver evt to listeners 1470 AbstractPreferences src=(AbstractPreferences)event.getSource(); 1471 if (event instanceof PreferenceChangeEvent) { 1472 PreferenceChangeEvent pce = (PreferenceChangeEvent)event; 1473 PreferenceChangeListener[] listeners = src.prefListeners(); 1474 for (int i=0; i<listeners.length; i++) 1475 listeners[i].preferenceChange(pce); 1476 } else { 1477 NodeChangeEvent nce = (NodeChangeEvent)event; 1478 NodeChangeListener[] listeners = src.nodeListeners(); 1479 if (nce instanceof NodeAddedEvent) { 1480 for (int i=0; i<listeners.length; i++) 1481 listeners[i].childAdded(nce); 1482 } else { 1483 // assert nce instanceof NodeRemovedEvent; 1484 for (int i=0; i<listeners.length; i++) 1485 listeners[i].childRemoved(nce); 1486 } 1487 } 1488 } 1489 } 1490 } 1491 1492 private static Thread eventDispatchThread = null; 1493 1494 /** 1495 * This method starts the event dispatch thread the first time it 1496 * is called. The event dispatch thread will be started only 1497 * if someone registers a listener. 1498 */ 1499 private static synchronized void startEventDispatchThreadIfNecessary() { 1500 if (eventDispatchThread == null) { 1501 // XXX Log "Starting event dispatch thread" 1502 eventDispatchThread = new EventDispatchThread(); 1503 eventDispatchThread.setDaemon(true); 1504 eventDispatchThread.start(); 1505 } 1506 } 1507 1508 /** 1509 * Return this node's preference/node change listeners. Even though 1510 * we're using a copy-on-write lists, we use synchronized accessors to 1511 * ensure information transmission from the writing thread to the 1512 * reading thread. 1513 */ 1514 PreferenceChangeListener[] prefListeners() { 1515 synchronized(lock) { 1516 return prefListeners; 1517 } 1518 } 1519 NodeChangeListener[] nodeListeners() { 1520 synchronized(lock) { 1521 return nodeListeners; 1522 } 1523 } 1524 1525 /** 1526 * Enqueue a preference change event for delivery to registered 1527 * preference change listeners unless there are no registered 1528 * listeners. Invoked with this.lock held. 1529 */ 1530 private void enqueuePreferenceChangeEvent(String key, String newValue) { 1531 if (prefListeners.length != 0) { 1532 synchronized(eventQueue) { 1533 eventQueue.add(new PreferenceChangeEvent(this, key, newValue)); 1534 eventQueue.notify(); 1535 } 1536 } 1537 } 1538 1539 /** 1540 * Enqueue a "node added" event for delivery to registered node change 1541 * listeners unless there are no registered listeners. Invoked with 1542 * this.lock held. 1543 */ 1544 private void enqueueNodeAddedEvent(Preferences child) { 1545 if (nodeListeners.length != 0) { 1546 synchronized(eventQueue) { 1547 eventQueue.add(new NodeAddedEvent(this, child)); 1548 eventQueue.notify(); 1549 } 1550 } 1551 } 1552 1553 /** 1554 * Enqueue a "node removed" event for delivery to registered node change 1555 * listeners unless there are no registered listeners. Invoked with 1556 * this.lock held. 1557 */ 1558 private void enqueueNodeRemovedEvent(Preferences child) { 1559 if (nodeListeners.length != 0) { 1560 synchronized(eventQueue) { 1561 eventQueue.add(new NodeRemovedEvent(this, child)); 1562 eventQueue.notify(); 1563 } 1564 } 1565 } 1566 1567 /** 1568 * Implements the <tt>exportNode</tt> method as per the specification in 1569 * {@link Preferences#exportNode(OutputStream)}. 1570 * 1571 * @param os the output stream on which to emit the XML document. 1572 * @throws IOException if writing to the specified output stream 1573 * results in an <tt>IOException</tt>. 1574 * @throws BackingStoreException if preference data cannot be read from 1575 * backing store. 1576 */ 1577 public void exportNode(OutputStream os) 1578 throws IOException, BackingStoreException 1579 { 1580 XmlSupport.export(os, this, false); 1581 } 1582 1583 /** 1584 * Implements the <tt>exportSubtree</tt> method as per the specification in 1585 * {@link Preferences#exportSubtree(OutputStream)}. 1586 * 1587 * @param os the output stream on which to emit the XML document. 1588 * @throws IOException if writing to the specified output stream 1589 * results in an <tt>IOException</tt>. 1590 * @throws BackingStoreException if preference data cannot be read from 1591 * backing store. 1592 */ 1593 public void exportSubtree(OutputStream os) 1594 throws IOException, BackingStoreException 1595 { 1596 XmlSupport.export(os, this, true); 1597 } 1598} 1599