1   /*
2    * Copyright (C) 2010 Atlassian
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package com.atlassian.jira.rest.client;
18  
19  import com.google.common.collect.Iterables;
20  import org.hamcrest.Description;
21  import org.junit.internal.matchers.TypeSafeMatcher;
22  
23  import java.util.Arrays;
24  import java.util.Collections;
25  import java.util.HashSet;
26  import java.util.Set;
27  
28  public class IterableMatcher<T> extends TypeSafeMatcher<Iterable<T>> {
29      private final Iterable<T> expected;
30  
31      public IterableMatcher(Iterable<T> expected) {
32          this.expected = expected;
33      }
34  
35  
36      public static <T> IterableMatcher<T> hasOnlyElements(T... elements) {
37          return new IterableMatcher<T>(Arrays.asList(elements));
38      }
39  
40  	public static <T> IterableMatcher<T> hasOnlyElements(Iterable<T> elements) {
41  		return new IterableMatcher<T>(elements);
42  	}
43  
44  	public static <T> IterableMatcher<T> isEmpty() {
45  		return new IterableMatcher<T>(Collections.<T>emptyList());
46  	}
47  
48  	public static <T> TypeSafeMatcher<Iterable<T>> contains(final T element) {
49  		return new TypeSafeMatcher<Iterable<T>>() {
50  			@Override
51  			public boolean matchesSafely(Iterable<T> given) {
52  				return Iterables.contains(given, element);
53  			}
54  
55  			@Override
56  			public void describeTo(Description description) {
57  				description.appendText("an iterable containing element " + element);
58  			}
59  
60  		};
61  	}
62  
63      @Override
64      public boolean matchesSafely(Iterable<T> given) {
65          final Set<T> s = asSet(expected);
66  
67  
68          for (T t : given) {
69              if (!s.remove(t)) {
70                  return false;
71              }
72          }
73          return s.isEmpty();
74      }
75  
76      private Set<T> asSet(Iterable<T> iterable) {
77          final Set<T> s = new HashSet<T>();
78  
79          for (T t : iterable) {
80              s.add(t);
81          }
82          return s;
83      }
84  
85      @Override
86      public void describeTo(Description description) {
87          description.appendText("an iterable containing just elements " + asSet(expected));
88      }
89  }