View Javadoc

    1   package org.owasp.dependencycheck.utils;
    2
    3   import java.util.Iterator;
    4   import java.util.NoSuchElementException;
    5
    6   /*
    7    * This is an abstract filter that can be used to filter iterable list.
    8    *
    9    * This Filter class was copied from:
    10   * http://erikras.com/2008/01/18/the-filter-pattern-java-conditional-abstraction-with-iterables/
    11   *
    12   * Erik Rasmussen - © 2006 - 2012 All Rights Reserved. @author Erik Rasmussen
    13   * https://plus.google.com/115403795880834599019/?rel=author
    14   */
    15  public abstract class Filter<T> {
    16
    17      public abstract boolean passes(T object);
    18
    19      public Iterator<T> filter(Iterator<T> iterator) {
    20          return new FilterIterator(iterator);
    21      }
    22
    23      public Iterable<T> filter(final Iterable<T> iterable) {
    24          return new Iterable<T>() {
    25
    26              public Iterator<T> iterator() {
    27                  return filter(iterable.iterator());
    28              }
    29          };
    30      }
    31
    32      private class FilterIterator implements Iterator<T> {
    33
    34          private final Iterator<T> iterator;
    35          private T next;
    36
    37          private FilterIterator(Iterator<T> iterator) {
    38              this.iterator = iterator;
    39              toNext();
    40          }
    41
    42          public boolean hasNext() {
    43              return next != null;
    44          }
    45
    46          public T next() {
    47              if (next == null) {
    48                  throw new NoSuchElementException();
    49              }
    50              T returnValue = next;
    51              toNext();
    52              return returnValue;
    53          }
    54
    55          public void remove() {
    56              throw new UnsupportedOperationException();
    57          }
    58
    59          private void toNext() {
    60              next = null;
    61              while (iterator.hasNext()) {
    62                  T item = iterator.next();
    63                  if (item != null && passes(item)) {
    64                      next = item;
    65                      break;
    66                  }
    67              }
    68          }
    69      }
    70  }