001/*
002 * Copyright 2002-2016 the original author or authors.
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 *      https://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 */
016
017package org.springframework.test.web.servlet.htmlunit;
018
019import java.util.regex.Pattern;
020
021import com.gargoylesoftware.htmlunit.WebRequest;
022
023/**
024 * A {@link WebRequestMatcher} that allows matching on
025 * {@code WebRequest#getUrl().toExternalForm()} using a regular expression.
026 *
027 * <p>For example, if you would like to match on the domain {@code code.jquery.com},
028 * you might want to use the following.
029 *
030 * <pre class="code">
031 * WebRequestMatcher cdnMatcher = new UrlRegexRequestMatcher(".*?//code.jquery.com/.*");
032 * </pre>
033 *
034 * @author Rob Winch
035 * @author Sam Brannen
036 * @since 4.2
037 * @see org.springframework.test.web.servlet.htmlunit.DelegatingWebConnection
038 */
039public final class UrlRegexRequestMatcher implements WebRequestMatcher {
040
041        private final Pattern pattern;
042
043
044        public UrlRegexRequestMatcher(String regex) {
045                this.pattern = Pattern.compile(regex);
046        }
047
048        public UrlRegexRequestMatcher(Pattern pattern) {
049                this.pattern = pattern;
050        }
051
052
053        @Override
054        public boolean matches(WebRequest request) {
055                String url = request.getUrl().toExternalForm();
056                return this.pattern.matcher(url).matches();
057        }
058
059}