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