001    /*
002     * Copyright 2005 John G. Wilson
003     *
004     * Licensed under the Apache License, Version 2.0 (the "License");
005     * you may not use this file except in compliance with the License.
006     * You may obtain a copy of the License at
007     *
008     *     http://www.apache.org/licenses/LICENSE-2.0
009     *
010     * Unless required by applicable law or agreed to in writing, software
011     * distributed under the License is distributed on an "AS IS" BASIS,
012     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013     * See the License for the specific language governing permissions and
014     * limitations under the License.
015     *
016     */
017    
018    package groovy.util.slurpersupport;
019    
020    import java.util.Iterator;
021    import java.util.Map;
022    
023    import groovy.lang.Closure;
024    
025    /**
026     * @author John Wilson
027     *
028     */
029    
030    public class FilteredNodeChildren extends NodeChildren {
031      private final Closure closure;
032      
033      public FilteredNodeChildren(final GPathResult parent, final Closure closure, final Map namespaceTagHints) {
034        super(parent, parent.name, namespaceTagHints);
035        this.closure = closure;
036      }
037    
038      /* (non-Javadoc)
039       * @see org.codehaus.groovy.sandbox.util.slurpersupport.NodeChildren#iterator()
040       */
041      public Iterator nodeIterator() {
042        return new NodeIterator(this.parent.iterator()) {
043                  /* (non-Javadoc)
044                   * @see org.codehaus.groovy.sandbox.util.slurpersupport.NodeIterator#getNextNode(java.util.Iterator)
045                   */
046                  protected Object getNextNode(final Iterator iter) {
047                    while (iter.hasNext()) {
048                    final Object node = iter.next();
049                    final Boolean result = (Boolean)FilteredNodeChildren.this.closure.call(new Object[]{node});
050                    
051                      if (result != null && result.booleanValue()) {
052                        return node;
053                      }
054                    }
055                    
056                    return null;
057                  }   
058                };
059      }
060      
061    }