View Javadoc

1   /*
2    * Copyright (C) 2013 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.test.matchers;
18  
19  import org.hamcrest.Description;
20  import org.junit.internal.matchers.TypeSafeMatcher;
21  
22  import java.net.URI;
23  import java.util.regex.Pattern;
24  
25  public class UriRegularExpressionMatcher extends TypeSafeMatcher<URI> {
26      private final URI baseUri;
27      private final Pattern pattern;
28  
29      public UriRegularExpressionMatcher(final URI baseUri, final Pattern pattern) {
30          this.baseUri = baseUri;
31          this.pattern = pattern;
32      }
33  
34      public static UriRegularExpressionMatcher uriMatchesRegexp(final URI baseUri, final Pattern pattern) {
35          return new UriRegularExpressionMatcher(baseUri, pattern);
36      }
37  
38      public static UriRegularExpressionMatcher uriMatchesRegexp(final URI baseUri, final String pattern) {
39          return new UriRegularExpressionMatcher(baseUri, Pattern.compile(pattern));
40      }
41  
42      @Override
43      public boolean matchesSafely(URI given) {
44          return checkBaseUri(given) && checkPattern(given);
45      }
46  
47      private boolean checkPattern(URI given) {
48          final URI relativeUrl = baseUri.relativize(given);
49          return pattern.matcher(relativeUrl.toString()).matches();
50      }
51  
52      private boolean checkBaseUri(URI given) {
53          return given.toString().startsWith(baseUri.toString());
54      }
55  
56      @Override
57      public void describeTo(Description description) {
58          description.appendText(String.format("url with base %s and matching regular expression %s", baseUri, pattern));
59      }
60  }