View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.maven.surefire.its.fixture;
20  
21  import java.util.Iterator;
22  import java.util.Set;
23  
24  import org.hamcrest.BaseMatcher;
25  import org.hamcrest.Description;
26  import org.hamcrest.Matcher;
27  
28  import static java.util.Collections.singleton;
29  
30  /**
31   * Java Hamcrest Matcher with Regex.
32   */
33  public final class IsRegex extends BaseMatcher<Set<String>> {
34      public static Matcher<Set<String>> regex(Set<String> expectedRegex) {
35          return new IsRegex(expectedRegex);
36      }
37  
38      public static Matcher<Set<String>> regex(String expectedRegex) {
39          return new IsRegex(expectedRegex);
40      }
41  
42      private final Set<String> expectedRegex;
43  
44      private IsRegex(String expectedRegex) {
45          this.expectedRegex = singleton(expectedRegex);
46      }
47  
48      private IsRegex(Set<String> expectedRegex) {
49          this.expectedRegex = expectedRegex;
50      }
51  
52      @Override
53      public boolean matches(Object o) {
54          if (o != null && expectedRegex.size() == 1 ? isStringOrSet(o) : isSet(o)) {
55              //noinspection unchecked
56              Set<String> actual = isSet(o) ? (Set<String>) o : singleton((String) o);
57              boolean matches = actual.size() == expectedRegex.size();
58              Iterator<String> regex = expectedRegex.iterator();
59              for (String s : actual) {
60                  if (s == null || !regex.hasNext() || !s.matches(regex.next())) {
61                      matches = false;
62                  }
63              }
64              return matches;
65          } else {
66              return false;
67          }
68      }
69  
70      @Override
71      public void describeTo(Description description) {
72          description.appendValue(expectedRegex);
73      }
74  
75      private static boolean isStringOrSet(Object o) {
76          return o instanceof String || o instanceof Set;
77      }
78  
79      private static boolean isSet(Object o) {
80          return o instanceof Set;
81      }
82  }