Example usage for org.openqa.selenium.firefox FirefoxProfile addExtension

List of usage examples for org.openqa.selenium.firefox FirefoxProfile addExtension

Introduction

In this page you can find the example usage for org.openqa.selenium.firefox FirefoxProfile addExtension.

Prototype

public void addExtension(File extensionToInstall) 

Source Link

Document

Attempt to add an extension to install into this instance.

Usage

From source file:org.cerberus.serviceEngine.impl.SeleniumService.java

License:Open Source License

private DesiredCapabilities setFirefoxProfile(String executionUUID, boolean record, String country)
        throws CerberusException {
    FirefoxProfile profile = new FirefoxProfile();
    profile.setEnableNativeEvents(true);
    profile.setAcceptUntrustedCertificates(true);
    profile.setPreference("network.http.connection-timeout", "300");

    try {// ww w  .  ja  v  a 2  s. com
        Invariant invariant = this.invariantService.findInvariantByIdValue("COUNTRY", country);
        if (invariant.getGp2() == null) {
            MyLogger.log(Selenium.class.getName(), Level.WARN, "Country selected (" + country
                    + ") has no value of GP2 in Invariant table, default language set to English(en)");
            profile.setPreference("intl.accept_languages", "en");
        } else {
            profile.setPreference("intl.accept_languages", invariant.getGp2());
        }
    } catch (CerberusException ex) {
        MyLogger.log(Selenium.class.getName(), Level.WARN, "Country selected (" + country
                + ") not in Invariant table, default language set to English(en)");
        profile.setPreference("intl.accept_languages", "en");
    }

    if (record) {
        String firebugPath = parameterService
                .findParameterByKey("cerberus_selenium_firefoxextension_firebug", "").getValue();
        String netexportPath = parameterService
                .findParameterByKey("cerberus_selenium_firefoxextension_netexport", "").getValue();
        if (StringUtil.isNullOrEmpty(firebugPath)) {
            MessageGeneral mes = new MessageGeneral(MessageGeneralEnum.EXECUTION_FA_SELENIUM);
            mes.setDescription(mes.getDescription().replaceAll("%MES%",
                    "Mandatory parameter for network traffic 'cerberus_selenium_firefoxextension_firebug' not defined."));
            throw new CerberusException(mes);
        }
        if (StringUtil.isNullOrEmpty(netexportPath)) {
            MessageGeneral mes = new MessageGeneral(MessageGeneralEnum.EXECUTION_FA_SELENIUM);
            mes.setDescription(mes.getDescription().replaceAll("%MES%",
                    "Mandatory parameter for network traffic 'cerberus_selenium_firefoxextension_netexport' not defined."));
            throw new CerberusException(mes);
        }

        File firebug = new File(firebugPath);
        if (!firebug.canRead()) {
            MyLogger.log(Selenium.class.getName(), Level.WARN, "Can't read : " + firebugPath);
            MessageGeneral mes = new MessageGeneral(MessageGeneralEnum.EXECUTION_FA_SELENIUM);
            mes.setDescription(mes.getDescription().replaceAll("%MES%", "File not found : '" + firebugPath
                    + "' Change the Cerberus parameter : cerberus_selenium_firefoxextension_firebug"));
            throw new CerberusException(mes);

        }
        try {
            MyLogger.log(SeleniumService.class.getName(), Level.DEBUG,
                    "Adding firebug extension : " + firebugPath);
            profile.addExtension(firebug);
        } catch (IOException exception) {
            MyLogger.log(Selenium.class.getName(), Level.WARN, exception.toString());
            MessageGeneral mes = new MessageGeneral(MessageGeneralEnum.EXECUTION_FA_SELENIUM);
            mes.setDescription(mes.getDescription().replaceAll("%MES%", "File not found : " + firebugPath));
            throw new CerberusException(mes);
        }

        File netExport = new File(netexportPath);
        if (!netExport.canRead()) {
            MyLogger.log(Selenium.class.getName(), Level.WARN, "Can't read : " + netexportPath);
            MessageGeneral mes = new MessageGeneral(MessageGeneralEnum.EXECUTION_FA_SELENIUM);
            mes.setDescription(mes.getDescription().replaceAll("%MES%", "File not found : " + netexportPath
                    + "' Change the Cerberus parameter : cerberus_selenium_firefoxextension_netexport"));
            throw new CerberusException(mes);
        }
        try {
            MyLogger.log(SeleniumService.class.getName(), Level.DEBUG,
                    "Adding netexport extension : " + netexportPath);
            profile.addExtension(netExport);
        } catch (IOException exception) {
            MyLogger.log(Selenium.class.getName(), Level.WARN, exception.toString());
            MessageGeneral mes = new MessageGeneral(MessageGeneralEnum.EXECUTION_FA_SELENIUM);
            mes.setDescription(mes.getDescription().replaceAll("%MES%", "File not found : " + netexportPath));
            throw new CerberusException(mes);
        }

        String cerberusUrl = parameterService.findParameterByKey("cerberus_url", "").getValue();
        if (StringUtil.isNullOrEmpty(cerberusUrl)) {
            MessageGeneral mes = new MessageGeneral(MessageGeneralEnum.EXECUTION_FA_SELENIUM);
            mes.setDescription(mes.getDescription().replaceAll("%MES%",
                    "Mandatory parameter for network traffic 'cerberus_url' not defined."));
            throw new CerberusException(mes);
        }

        // Set default Firefox preferences
        profile.setPreference("app.update.enabled", false);

        // Set default Firebug preferences
        profile.setPreference("extensions.firebug.currentVersion", "1.11.4");
        profile.setPreference("extensions.firebug.allPagesActivation", "on");
        profile.setPreference("extensions.firebug.defaultPanelName", "net");
        profile.setPreference("extensions.firebug.net.enableSites", true);

        // Set default NetExport preferences
        profile.setPreference("extensions.firebug.netexport.alwaysEnableAutoExport", true);
        // Export to Server.
        String url = cerberusUrl + "/SaveStatistic?logId=" + executionUUID;
        profile.setPreference("extensions.firebug.netexport.autoExportToServer", true);
        profile.setPreference("extensions.firebug.netexport.beaconServerURL", url);
        MyLogger.log(SeleniumService.class.getName(), Level.DEBUG,
                "Selenium netexport.beaconServerURL : " + url);
        // Export to File. This only works on the selenium server side so should not be used as we don't know where to put the file and neither if Linux or Windows based.
        //            String cerberusHarPath = "logHar" + myFile.separator;
        //            String cerberusHarPath = "logHar" ;
        //            File dir = new File(cerberusHarPath + runId);
        //            dir.mkdirs();
        //            profile.setPreference("extensions.firebug.netexport.autoExportToFile", true);
        //            profile.setPreference("extensions.firebug.netexport.defaultLogDir", cerberusHarPath );
        //            MyLogger.log(SeleniumService.class.getName(), Level.DEBUG, "Selenium netexport.defaultLogDir : " + cerberusHarPath);
        profile.setPreference("extensions.firebug.netexport.sendToConfirmation", false);
        profile.setPreference("extensions.firebug.netexport.showPreview", false);

    }

    DesiredCapabilities dc = DesiredCapabilities.firefox();
    dc.setCapability(FirefoxDriver.PROFILE, profile);

    return dc;
}

From source file:org.eclipse.scout.rt.testing.ui.rap.RapMock.java

License:Open Source License

@Override
public void beforeTest() {
    if (m_service != null) {
        if (useChrome) {
            DesiredCapabilities chrome = DesiredCapabilities.chrome();
            m_driver = new RemoteWebDriver(m_service.getUrl(), chrome);
        }/* w  ww  .  ja v a  2 s . co m*/
    } else {
        if (useFirefox) {
            System.setProperty("webdriver.firefox.bin", "C:/FirefoxPortableTest_11/App/Firefox/firefox.exe");
            FirefoxProfile firefoxProfile = new FirefoxProfile();
            if (useFirebug) {
                try {
                    firefoxProfile.addExtension(new File("E:/Downloads/java/firebug-1.9.2-fx.xpi"));
                    firefoxProfile.setPreference("extensions.firebug.currentVersion", "1.9.2"); // Avoid startup screen

                    firefoxProfile.addExtension(new File("E:/Downloads/java/firepath-0.9.7-fx.xpi"));
                } catch (IOException e) {
                    throw new IllegalStateException("Could not add/find firefox extensions.", e);
                }
            }

            m_driver = new FirefoxDriver(firefoxProfile);
            //        m_driver = new FirefoxDriver(new FirefoxProfile(new File("C:/Temp/webdriver-profile")));
        }
    }
    if (m_driver == null) {
        throw new NullPointerException("no driver instantiated!");
    }
    m_bot = new RAPSelenium(m_driver, "http://localhost:8081");
    m_actionBuilder = new Actions(m_bot.getWrappedDriver());

    m_bot.open("http://localhost:8081/rap");
    m_bot.waitForElementPresent("w2");
}

From source file:org.eclipse.skalli.selenium.utils.DriverProvider.java

License:Open Source License

/**
 * Starts the driver, adds a shutdown hook to stop the driver and navigates to {@link #getHTTPBaseUrl()}
 *///from   w  w  w  . j a va 2s .  c  o  m
private static void startDriver() {
    FirefoxProfile profile = new FirefoxProfile();

    //load the browser plugins
    if (BROWSER_PLUGINS_FOLDER.exists()) {
        File[] plugins = BROWSER_PLUGINS_FOLDER.listFiles();

        for (int i = 0; i < plugins.length; i++) {
            File plugin = plugins[i];
            String name = plugin.getName();

            if (!name.toLowerCase().contains(".xpi")) {
                System.err.println("\"" + name + "\" is not a plugin -> remove from " + BROWSER_PLUGINS_FOLDER);
                continue;
            }

            //pluginName = "firebug-" + FIREBUG_VERSION + ".xpi"
            //pluginName = "firepath-" + FIREPATH_VERSION + "-fx.xpi"

            //set up the plugin if needed
            if (name.toLowerCase().contains("firebug")) {
                //pluginName = "firebug-" + FIREBUG_VERSION + ".xpi"
                String version = name.substring("firebug-".length());
                version = version.substring(0, version.length() - ".xpi".length());

                //avoids that the first run page is shown
                profile.setPreference("extensions.firebug.currentVersion", version);
            }

            //add the plugin
            try {
                profile.addExtension(plugin);
            } catch (IOException e) {
                System.err.println("could not add extension \"" + name + "\" to the profile\n" + e);
                e.printStackTrace();
            }
        }
    }

    driver = new FirefoxDriver(profile);
    registerShutdownHook();
    driver.get(getHTTPBaseUrl());

    copyTestContent();
}

From source file:org.kurento.test.browser.Browser.java

License:Apache License

private void createFirefoxBrowser(DesiredCapabilities capabilities) throws MalformedURLException {
    FirefoxProfile profile = new FirefoxProfile();
    // This flag avoids granting the access to the camera
    profile.setPreference("media.navigator.permission.disabled", true);

    capabilities.setCapability(FirefoxDriver.PROFILE, profile);
    capabilities.setBrowserName(DesiredCapabilities.firefox().getBrowserName());

    // Firefox extensions
    if (extensions != null && !extensions.isEmpty()) {
        for (Map<String, String> extension : extensions) {
            InputStream is = getExtensionAsInputStream(extension.values().iterator().next());
            if (is != null) {
                try {
                    File xpi = File.createTempFile(extension.keySet().iterator().next(), ".xpi");
                    FileUtils.copyInputStreamToFile(is, xpi);
                    profile.addExtension(xpi);
                } catch (Throwable t) {
                    log.error("Error loading Firefox extension {} ({} : {})", extension, t.getClass(),
                            t.getMessage());
                }/*from w w w  . ja v a 2s. co  m*/
            }
        }
    }

    createDriver(capabilities, profile);
}

From source file:org.kurento.test.client.BrowserClient.java

License:Open Source License

public void init() {

    Class<? extends WebDriver> driverClass = browserType.getDriverClass();

    try {/*from www.  java2 s.  c om*/
        DesiredCapabilities capabilities = new DesiredCapabilities();

        if (driverClass.equals(FirefoxDriver.class)) {
            FirefoxProfile profile = new FirefoxProfile();
            // This flag avoids granting the access to the camera
            profile.setPreference("media.navigator.permission.disabled", true);

            capabilities.setCapability(FirefoxDriver.PROFILE, profile);
            capabilities.setBrowserName(DesiredCapabilities.firefox().getBrowserName());

            // Firefox extensions
            if (extensions != null && !extensions.isEmpty()) {
                for (Map<String, String> extension : extensions) {
                    InputStream is = getExtensionAsInputStream(extension.values().iterator().next());
                    if (is != null) {
                        try {
                            File xpi = File.createTempFile(extension.keySet().iterator().next(), ".xpi");
                            FileUtils.copyInputStreamToFile(is, xpi);
                            profile.addExtension(xpi);
                        } catch (Throwable t) {
                            log.error("Error loading Firefox extension {} ({} : {})", extension, t.getClass(),
                                    t.getMessage());
                        }
                    }
                }
            }

            if (scope == BrowserScope.SAUCELABS) {
                createSaucelabsDriver(capabilities);
            } else if (scope == BrowserScope.REMOTE) {
                createRemoteDriver(capabilities);
            } else {
                driver = new FirefoxDriver(profile);
            }

        } else if (driverClass.equals(ChromeDriver.class)) {
            // Chrome driver
            ChromeDriverManager.getInstance().setup();

            // Chrome options
            ChromeOptions options = new ChromeOptions();

            // Chrome extensions
            if (extensions != null && !extensions.isEmpty()) {
                for (Map<String, String> extension : extensions) {
                    InputStream is = getExtensionAsInputStream(extension.values().iterator().next());
                    if (is != null) {
                        try {
                            File crx = File.createTempFile(extension.keySet().iterator().next(), ".crx");
                            FileUtils.copyInputStreamToFile(is, crx);
                            options.addExtensions(crx);
                        } catch (Throwable t) {
                            log.error("Error loading Chrome extension {} ({} : {})", extension, t.getClass(),
                                    t.getMessage());
                        }
                    }
                }
            }

            if (enableScreenCapture) {
                // This flag enables the screen sharing
                options.addArguments("--enable-usermedia-screen-capturing");

                String windowTitle = TEST_SCREEN_SHARE_TITLE_DEFAULT;
                if (platform != null && (platform == Platform.WINDOWS || platform == Platform.XP
                        || platform == Platform.VISTA || platform == Platform.WIN8
                        || platform == Platform.WIN8_1)) {

                    windowTitle = TEST_SCREEN_SHARE_TITLE_DEFAULT_WIN;
                }
                options.addArguments("--auto-select-desktop-capture-source="
                        + getProperty(TEST_SCREEN_SHARE_TITLE_PROPERTY, windowTitle));

            } else {
                // This flag avoids grant the camera
                options.addArguments("--use-fake-ui-for-media-stream");
            }

            // This flag avoids warning in Chrome. See:
            // https://code.google.com/p/chromedriver/issues/detail?id=799
            options.addArguments("--test-type");

            if (protocol == Protocol.FILE) {
                // This flag allows reading local files in video tags
                options.addArguments("--allow-file-access-from-files");
            }

            if (!usePhysicalCam) {
                // This flag makes using a synthetic video (green with
                // spinner) in WebRTC. Or it is needed to combine with
                // use-file-for-fake-video-capture to use a file faking the
                // cam
                options.addArguments("--use-fake-device-for-media-stream");

                if (video != null && isLocal()) {
                    options.addArguments("--use-file-for-fake-video-capture=" + video);
                }
            }

            capabilities.setCapability(ChromeOptions.CAPABILITY, options);
            capabilities.setBrowserName(DesiredCapabilities.chrome().getBrowserName());

            if (scope == BrowserScope.SAUCELABS) {
                createSaucelabsDriver(capabilities);
            } else if (scope == BrowserScope.REMOTE) {
                createRemoteDriver(capabilities);
            } else {
                driver = new ChromeDriver(options);
            }
        } else if (driverClass.equals(InternetExplorerDriver.class)) {

            if (scope == BrowserScope.SAUCELABS) {
                capabilities.setBrowserName(DesiredCapabilities.internetExplorer().getBrowserName());
                capabilities.setCapability("ignoreProtectedModeSettings", true);
                createSaucelabsDriver(capabilities);
            }

        } else if (driverClass.equals(SafariDriver.class)) {

            if (scope == BrowserScope.SAUCELABS) {
                capabilities.setBrowserName(DesiredCapabilities.safari().getBrowserName());
                createSaucelabsDriver(capabilities);
            }

        }

        // Timeouts
        changeTimeout(timeout);

        if (protocol == Protocol.FILE) {
            String clientPage = client.toString();
            File clientPageFile = new File(
                    this.getClass().getClassLoader().getResource("static" + clientPage).getFile());
            url = protocol.toString() + clientPageFile.getAbsolutePath();
        } else {
            String hostName = host != null ? host : node;
            url = protocol.toString() + hostName + ":" + serverPort + client.toString();
        }
        log.info("*** Browsing URL with WebDriver: {}", url);
        driver.get(url);

    } catch (MalformedURLException e) {
        log.error("MalformedURLException in BrowserClient.initDriver", e);
    }

    // startPing();
}

From source file:org.nuxeo.functionaltests.AbstractTest.java

License:Open Source License

protected static void addFireBug(FirefoxProfile profile) throws Exception {
    // this is preventing from running tests in eclipse
    // profile.addExtension(AbstractTest.class, "/firebug.xpi");

    File xpi = null;//from  w w  w  .  j  a va2s  . com
    List<String> clf = getClassLoaderFiles();
    for (String f : clf) {
        if (f.endsWith("/" + FIREBUG_XPI)) {
            xpi = new File(f);
        }
    }
    if (xpi == null) {
        String customM2Repo = System.getProperty("M2_REPO", M2_REPO).replaceAll("/$", "");
        // try to guess the location in the M2 repo
        for (String f : clf) {
            if (f.contains(customM2Repo)) {
                String m2 = f.substring(0, f.indexOf(customM2Repo) + customM2Repo.length());
                xpi = new File(m2 + "/" + FIREBUG_M2 + "/" + FIREBUG_XPI);
                break;
            }
        }
    }
    if (xpi == null || !xpi.exists()) {
        log.warn(FIREBUG_XPI + " not found in classloader or local M2 repository");
        return;
    }
    profile.addExtension(xpi);

    // avoid "first run" page
    profile.setPreference("extensions.firebug.currentVersion", FIREBUG_VERSION);
}

From source file:org.orcid.integration.blackbox.web.shibboleth.ShibbolethTest.java

License:Open Source License

private void createFireFoxDriverWithModifyHeaders() throws IOException {
    FirefoxProfile fireFoxProfile = new FirefoxProfile();
    File modifyHeaders = new File(
            System.getProperty("user.dir") + "/src/test/resources/modify-headers-0.7.1.1.xpi");
    fireFoxProfile.setEnableNativeEvents(false);
    fireFoxProfile.addExtension(modifyHeaders);

    fireFoxProfile.setPreference("modifyheaders.headers.count", 2);
    fireFoxProfile.setPreference("modifyheaders.headers.action0", "Add");
    fireFoxProfile.setPreference("modifyheaders.headers.name0", "persistent-id");
    fireFoxProfile.setPreference("modifyheaders.headers.value0",
            "integration-test-" + System.currentTimeMillis() + "@orcid.org");
    fireFoxProfile.setPreference("modifyheaders.headers.enabled0", true);
    fireFoxProfile.setPreference("modifyheaders.headers.action1", "Add");
    fireFoxProfile.setPreference("modifyheaders.headers.name1", "Shib-Identity-Provider");
    fireFoxProfile.setPreference("modifyheaders.headers.value1",
            "https://integrationtest.orcid.org/idp/shibboleth");
    fireFoxProfile.setPreference("modifyheaders.headers.enabled1", true);
    fireFoxProfile.setPreference("modifyheaders.config.active", true);
    fireFoxProfile.setPreference("modifyheaders.config.alwaysOn", true);

    DesiredCapabilities capabilities = new DesiredCapabilities();
    capabilities.setBrowserName("firefox");
    capabilities.setPlatform(org.openqa.selenium.Platform.ANY);
    capabilities.setCapability(FirefoxDriver.PROFILE, fireFoxProfile);
    webDriver = new FirefoxDriver(capabilities);
}

From source file:wsattacker.sso.openid.attacker.evaluation.SeleniumBrowser.java

License:Open Source License

public static WebDriver getWebDriver() {

    if (INSTANCE == null || hasQuit(INSTANCE) || INSTANCE.getWindowHandles().isEmpty()) {
        // create chrome profile
        //ChromeOptions options = new ChromeOptions();
        //options.addExtensions(new File("adblock.crx"));

        FirefoxProfile profile = new FirefoxProfile();

        // install adblock plus
        File tmpFile = new File("adblock.xpi");
        try {/*  ww w  .j av  a  2s .  c o  m*/
            InputStream inputStream = SeleniumBrowser.class.getResourceAsStream("/adblock_firefox.xpi");
            FileUtils.copyInputStreamToFile(inputStream, tmpFile);
            profile.addExtension(tmpFile);
        } catch (IOException ex) {
            Logger.getLogger(EvaluationGui.class.getName()).log(Level.SEVERE, null, ex);
        }

        // disable local and session storage
        // some websites (e.g. stackoverflow) use those storages in addition
        // to session cookies
        profile.setPreference("dom.storage.enabled", false);

        // start new Firefox instance
        INSTANCE = new FirefoxDriver(profile);

        // screen size
        GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
        int width = gd.getDisplayMode().getWidth();
        int height = gd.getDisplayMode().getHeight();

        width = width > 1440 ? 1440 : width;
        height = height > 900 ? 900 : height;

        INSTANCE.manage().window().setPosition(new Point(0, 0));
        INSTANCE.manage().window().setSize(new Dimension(width, height));

        tmpFile.delete();
    }

    return INSTANCE;
}