001/* 002 * ModeShape (http://www.modeshape.org) 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 */ 016package org.modeshape.common.collection; 017 018import static org.hamcrest.core.AllOf.allOf; 019import static org.hamcrest.core.IsEqual.equalTo; 020import java.util.ArrayList; 021import java.util.Collection; 022import java.util.Iterator; 023import org.hamcrest.Description; 024import org.hamcrest.Factory; 025import org.hamcrest.Matcher; 026import org.hamcrest.TypeSafeMatcher; 027 028/** 029 * @author Randall Hauch 030 * @param <T> 031 */ 032public class IsIteratorContaining<T> extends TypeSafeMatcher<Iterator<T>> { 033 private final Matcher<? extends T> elementMatcher; 034 035 public IsIteratorContaining( Matcher<? extends T> elementMatcher ) { 036 this.elementMatcher = elementMatcher; 037 } 038 039 @Override 040 public boolean matchesSafely( Iterator<T> iterator ) { 041 while (iterator.hasNext()) { 042 T item = iterator.next(); 043 if (elementMatcher.matches(item)) { 044 return true; 045 } 046 } 047 return false; 048 } 049 050 @Override 051 public void describeTo( Description description ) { 052 description.appendText("a iterator containing ").appendDescriptionOf(elementMatcher); 053 } 054 055 @Factory 056 public static <T> Matcher<Iterator<T>> hasItem( Matcher<? extends T> elementMatcher ) { 057 return new IsIteratorContaining<T>(elementMatcher); 058 } 059 060 @Factory 061 public static <T> Matcher<Iterator<T>> hasItem( T element ) { 062 return hasItem(equalTo(element)); 063 } 064 065 @Factory 066 @SafeVarargs 067 public static <T> Matcher<Iterator<T>> hasItems( Matcher<? extends T>... elementMatchers ) { 068 Collection<Matcher<? super Iterator<T>>> all = new ArrayList<>(elementMatchers.length); 069 for (Matcher<? extends T> elementMatcher : elementMatchers) { 070 all.add(hasItem(elementMatcher)); 071 } 072 return allOf(all); 073 } 074 075 @Factory 076 @SafeVarargs 077 public static <T> Matcher<Iterator<T>> hasItems( T... elements ) { 078 Collection<Matcher<? super Iterator<T>>> all = new ArrayList<>(elements.length); 079 for (T element : elements) { 080 all.add(hasItem(element)); 081 } 082 return allOf(all); 083 } 084}