001/*
002 * (C) Copyright 2011-2015 Nuxeo SA (http://nuxeo.com/) and contributors.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the GNU Lesser General Public License
006 * (LGPL) version 2.1 which accompanies this distribution, and is available at
007 * http://www.gnu.org/licenses/lgpl-2.1.html
008 *
009 * This library is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 *
014 * Contributors:
015 *     Sun Seng David TAN
016 *     Florent Guillaume
017 *     Benoit Delbosc
018 *     Antoine Taillefer
019 *     Anahide Tchertchian
020 *     Guillaume Renard
021 *     Mathieu Guillaume
022 *     Julien Carsique
023 */
024package org.nuxeo.functionaltests.proxy;
025
026import java.io.File;
027
028import org.browsermob.proxy.ProxyServer;
029import org.nuxeo.common.Environment;
030import org.openqa.selenium.Proxy;
031
032/**
033 * Proxy server manager.
034 *
035 * @since 8.3
036 */
037public class ProxyManager {
038
039    private static final int PROXY_PORT = 4444;
040
041    private static final String HAR_NAME = "http-headers.json";
042
043    protected ProxyServer proxyServer = null;
044
045    public Proxy startProxy() throws Exception {
046        if (Boolean.TRUE.equals(Boolean.valueOf(System.getProperty("useProxy", "false")))) {
047            proxyServer = new ProxyServer(PROXY_PORT);
048            proxyServer.start();
049            proxyServer.setCaptureHeaders(true);
050            // Block access to tracking sites
051            proxyServer.blacklistRequests("https?://www\\.nuxeo\\.com/embedded/wizard.*", 410);
052            proxyServer.blacklistRequests("https?://.*\\.mktoresp\\.com/.*", 410);
053            proxyServer.blacklistRequests(".*_mchId.*", 410);
054            proxyServer.blacklistRequests("https?://.*\\.google-analytics\\.com/.*", 410);
055            proxyServer.newHar("webdriver-test");
056            Proxy proxy = proxyServer.seleniumProxy();
057            return proxy;
058        } else {
059            return null;
060        }
061    }
062
063    public void stopProxy() throws Exception {
064        if (proxyServer != null) {
065            String target = System.getProperty(Environment.NUXEO_LOG_DIR);
066            File harFile;
067            if (target == null) {
068                harFile = new File(HAR_NAME);
069            } else {
070                harFile = new File(target, HAR_NAME);
071            }
072            proxyServer.getHar().writeTo(harFile);
073            proxyServer.stop();
074        }
075    }
076
077}