001    /*
002    @license.text@
003     */
004    
005    package biz.hammurapi.util;
006    
007    import java.util.Collection;
008    import java.util.LinkedList;
009    
010    import biz.hammurapi.RuntimeException;
011    
012    /**
013     * @author Pavel Vlasov 
014     * @version $Revision: 1.3 $
015     */
016    public abstract class AbstractSearchable implements Visitable, Searchable {
017    
018            public Object find(final Acceptor acceptor) {
019                    /**
020                     * Doesn't indicate problem, but carries found object.
021                     */
022                    class ReturnException extends RuntimeException {
023                            /**
024                             * Comment for <code>serialVersionUID</code>
025                             */
026                            private static final long serialVersionUID = 358344825019870509L;
027                            Object found;
028                            
029                            ReturnException(Object found) {
030                                    this.found=found;
031                            }
032                    }
033                    
034                    try {
035                            accept(new Visitor() {
036                                    public boolean visit(Object target) {
037                                            if (acceptor.accept(target)) {
038                                                    throw new ReturnException(target);
039                                            }
040                                            return true;
041                                    }                       
042                            });
043                            return null;
044                    } catch (ReturnException e) {
045                            return e.found;
046                    }
047            }
048    
049            public Collection findAll(final Acceptor acceptor) {
050                    final Collection ret=new LinkedList();
051                    accept(new Visitor() {
052                            public boolean visit(Object target) {
053                                    if (acceptor.accept(target)) {
054                                            ret.add(target);
055                                    }
056                                    return true;
057                            }                       
058                    });
059                    return ret;
060            }
061    }