001/*
002 * Copyright 2012-2017 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 *      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 */
016
017package org.springframework.boot.test.web.htmlunit;
018
019import java.io.IOException;
020import java.net.MalformedURLException;
021
022import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
023import com.gargoylesoftware.htmlunit.Page;
024import com.gargoylesoftware.htmlunit.WebClient;
025
026import org.springframework.core.env.Environment;
027import org.springframework.util.Assert;
028
029/**
030 * {@link WebClient} will automatically prefix relative URLs with
031 * <code>localhost:$&#123;local.server.port&#125;</code>.
032 *
033 * @author Phillip Webb
034 * @since 1.4.0
035 */
036public class LocalHostWebClient extends WebClient {
037
038        private final Environment environment;
039
040        public LocalHostWebClient(Environment environment) {
041                Assert.notNull(environment, "Environment must not be null");
042                this.environment = environment;
043        }
044
045        @Override
046        public <P extends Page> P getPage(String url)
047                        throws IOException, FailingHttpStatusCodeException, MalformedURLException {
048                if (url.startsWith("/")) {
049                        String port = this.environment.getProperty("local.server.port", "8080");
050                        url = "http://localhost:" + port + url;
051                }
052                return super.getPage(url);
053        }
054
055}