1 /*
2 * EL4J, the Extension Library for the J2EE, adds incremental enhancements to
3 * the spring framework, http://el4j.sf.net
4 * Copyright (C) 2006 by ELCA Informatique SA, Av. de la Harpe 22-24,
5 * 1000 Lausanne, Switzerland, http://www.elca.ch
6 *
7 * EL4J is published under the GNU Lesser General Public License (LGPL)
8 * Version 2.1. See http://www.gnu.org/licenses/
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU Lesser General Public License for more details.
14 *
15 * For alternative licensing, please contact info@elca.ch
16 */
17 package ch.elca.el4j.util.observer.impl;
18
19 import java.util.Collection;
20
21 import ch.elca.el4j.util.observer.ObservableValue;
22
23 /**
24 * Convenience class providing a few standard LiveValues.
25 *
26 * @svnLink $Revision: 3880 $;$Date: 2009-08-04 15:17:52 +0200 (Di, 04. Aug 2009) $;$Author: swismer $;$URL: https://el4j.svn.sourceforge.net/svnroot/el4j/branches/el4j_3_1/el4j/framework/modules/core/src/main/java/ch/elca/el4j/util/observer/impl/LiveValueFactory.java $
27 *
28 * @author Adrian Moos (AMS)
29 */
30 public final class LiveValueFactory {
31 /** This class can not be instantiated. */
32 private LiveValueFactory() { }
33
34 /**
35 * Returns a LiveValue backed by a Collection that yields the collection's
36 * unique element or <code>null</code> if there is no such element.
37 *
38 * @param oc the backing collection
39 * @return see above.
40 */
41 public static
42 <T, OC extends ObservableValue<? extends Collection<? extends T>>>
43 LiveValue<T> theElementIn(final OC oc) {
44 return new LiveValue<T>(new Computable<T>() {
45 public T is() {
46 Collection<? extends T> c = oc.get();
47 if (c == null || c.size() != 1) {
48 return null;
49 } else {
50 return c.iterator().next();
51 }
52 }
53 });
54 }
55
56 /**
57 * Returns a LiveValue that yields the value of {@code upper}
58 * if it is not {@code null}, or the value of {@code lower} otherwise.
59 * @param lower .
60 * @param upper .
61 * @return .
62 */
63 public static <T>
64 LiveValue<T> shadow(final ObservableValue<? extends T> lower,
65 final ObservableValue<? extends T> upper) {
66 return new LiveValue<T>(new Computable<T>() {
67 public T is() {
68 if (upper.get() == null) {
69 return lower.get();
70 } else {
71 return upper.get();
72 }
73 }
74 });
75 }
76 }