001    // Copyright 2007 Waterken Inc. under the terms of the MIT X license
002    // found at http://www.opensource.org/licenses/mit-license.html
003    package org.ref_send.test;
004    
005    import static org.ref_send.promise.Eventual.ref;
006    
007    import java.io.Serializable;
008    
009    import org.ref_send.promise.Deferred;
010    import org.ref_send.promise.Do;
011    import org.ref_send.promise.Eventual;
012    import org.ref_send.promise.Promise;
013    import org.ref_send.promise.Resolver;
014    
015    /**
016     * Test condition operations.
017     */
018    public final class
019    Logic {
020        private Logic() {}
021    
022        /**
023         * Creates a when block that compares against an expected value.
024         * @param <T> referent type
025         * @param expected  expected value
026         */
027        static public <T> Do<T,Promise<?>>
028        was(final T expected) {
029            class Was extends Do<T,Promise<?>> implements Serializable {
030                static private final long serialVersionUID = 1L;
031    
032                public Promise<?>
033                fulfill(final T value) throws Exception {
034                    if (expected.equals(value)) { return ref(true); }
035                    throw new Exception();
036                }
037            }
038            return new Was();
039        }
040    
041        /**
042         * Fulfills a promise after each listed promise is fulfilled.
043         * @param _ eventual operator
044         * @param tests each promise to test
045         * @return promise that is fulfilled if each of the listed promises is
046         *         fulfilled; otherwise, the promise is rejected
047         */
048        static public Promise<?>
049        join(final Eventual _, final Object... tests) {
050            if (0 == tests.length) { return ref(true); }
051            final Deferred<Boolean> answer = _.defer();
052            final int[] todo = { tests.length };
053            final Resolver<Boolean> resolver = answer.resolver;
054            for (final Object test : tests) {
055                class Join extends Do<Object,Void> implements Serializable {
056                    static private final long serialVersionUID = 1L;
057    
058                    public Void
059                    fulfill(final Object value) {
060                        if (0 == --todo[0]) {
061                            resolver.apply(true);
062                        } else {
063                            resolver.progress();
064                        }
065                        return null;
066                    }
067                    public Void
068                    reject(final Exception e) {
069                        resolver.reject(e);
070                        return null;
071                    }
072                }
073                _.when(test, new Join());
074            }
075            return answer.promise;
076        }
077    }