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