All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.ats.executor.drivers.engines.browsers.capabilities.ChromiumOptions Maven / Gradle / Ivy

The newest version!
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
 */

package com.ats.executor.drivers.engines.browsers.capabilities;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.openqa.selenium.MutableCapabilities;
import org.openqa.selenium.remote.CapabilityType;

import com.ats.driver.ApplicationProperties;
import com.ats.driver.AtsProxy;
import com.ats.executor.drivers.desktop.SystemDriver;
import com.ats.executor.drivers.engines.browsers.BrowserArgumentsParser;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ObjectArrays;

@SuppressWarnings("serial")


public class ChromiumOptions extends MutableCapabilities {

	protected static final String enableAutomationName = "enable-automation";
	private static final String enableLogging = "enable-logging";
	private final static String NO_SANDBOX = "--no-sandbox";
	private final static String DISABLE_GPU = "--disable-gpu";
	private final static String DISABLE_DEV_SHM_USAGE = "--disable-dev-shm-usage";

	private static final ImmutableList standardOptions =
			ImmutableList.of(
					new String[]{"test-type", "=webdriver"},
					new String[]{"no-default-browser-check", ""},
					new String[]{"no-first-run", ""},
					new String[]{"disable-search-engine-choice-screen", ""},
					new String[]{"no-service-autorun", ""},
					new String[]{"disable-sync", ""},
					new String[]{"allow-file-access-from-files", ""},
					new String[]{"allow-running-insecure-content", ""},
					new String[]{"allow-cross-origin-auth-prompt", ""},
					new String[]{"allow-file-access", ""},
					new String[]{"ignore-certificate-errors", ""});
	
	private String binary;
	private List args = new ArrayList<>();
	private Map experimentalOptions = new HashMap<>();

	private String capabilityName;

	public ChromiumOptions(
			BrowserArgumentsParser browserArgs,
			ApplicationProperties props,
			String capabilityName,
			String privateName,
			boolean enableAutomation,
			SystemDriver systemDriver,
			AtsProxy proxy) {

		this.capabilityName = capabilityName;

		if (this.capabilityName.equals("operaOptions")) {
			experimentalOptions.put("w3c", true);
			this.capabilityName = "goog:chromeOptions";
			enableAutomation=false;
		}

		final Map prefs = new HashMap<>();
		prefs.put("credentials_enable_service", false);

		final Map profile = new HashMap<>();
		profile.put("password_manager_enabled", false);

		prefs.put("profile", profile);

		experimentalOptions.put("prefs", prefs);

		binary = browserArgs.getBinaryPath();

		final Map optionsData = new HashMap<>();
		final String[] options = browserArgs.getMoreOptions();

		boolean logging = false;
		for (String s: options) {
			if(enableLogging.equals(s)) {
				logging = true;
				break;
			}
		}

		List excludedOptions = null;
		if(logging) {
			excludedOptions = Arrays.asList(props.getExcludedOptions());
		}else {
			excludedOptions = Arrays.asList(props.getExcludedOptions(enableLogging));
		}
		
		for (String s: options) {
			addOption(optionsData, s, excludedOptions);
			if(enableAutomationName.equals(s)) {
				enableAutomation = true;
			}
		}

		for (String[] s: standardOptions) {
			addOption(optionsData, s[0], s[1], excludedOptions);
		}

		optionsData.forEach((k, v) -> args.add("--" + k + v));

		final String docker = System.getenv("DOCKER");
		if("true".equalsIgnoreCase(docker)) {
			args.add(NO_SANDBOX);
			args.add(DISABLE_GPU);
			args.add(DISABLE_DEV_SHM_USAGE);
		}
					
		final String X11_ENABLED = System.getenv("X11_ENABLED");
		if("true".equalsIgnoreCase(X11_ENABLED)) {
			args.add("--user-agent=Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.119 Safari/537.36");
		}else if(browserArgs.isHeadless() || !systemDriver.isInteractive()) {
			args.add("--headless");
			args.add("--disable-gpu");
		}

		if(browserArgs.isIncognito()) {
			args.add("--" + privateName);
		}

		if(props.getDebugPort() > 0) {
			args.add("--remote-debugging-port=" + props.getDebugPort());
		}

		if(browserArgs.getUserDataPath() != null) {
			//removeMetricsData(browserArgs.getUserDataPath());
			args.add("--user-data-dir=" + browserArgs.getUserDataPath());
		}

		if(browserArgs.getLang() != null) {
			args.add("--lang=" + browserArgs.getLang());
		}

		if(enableAutomation) {
			args.add("--" + enableAutomationName);
		}else {
			excludedOptions = Arrays.asList(ObjectArrays.concat(props.getExcludedOptions(enableLogging), new String[]{enableAutomationName}, String.class));
		}
		experimentalOptions.put("excludeSwitches", excludedOptions);
		
		if(proxy.enabled()) {
			setCapability(CapabilityType.PROXY, proxy.getValue());
		}
	}

	protected void addExperimentalOption(String name, Object value) {
		experimentalOptions.put(name, value);
	}

	private void addOption(Map optionsData, String optionName, List excludedOptions) {
		addOption(optionsData, optionName, "", excludedOptions);
	}

	private void addOption(Map optionsData, String optionName, String optionValue, List excludedOptions) {
		if(!excludedOptions.contains(optionName) && !enableLogging.equals(optionName)) {
			optionsData.putIfAbsent(optionName, optionValue);
		}
	}

	@Override
	public Map asMap() {
		Map toReturn = new TreeMap<>(super.asMap());

		Map options = new TreeMap<>();
		experimentalOptions.forEach(options::put);

		if (binary != null) {
			options.put("binary", binary);
		}

		options.put("args", ImmutableList.copyOf(args));
		options.put("extensions", Collections.EMPTY_LIST);

		toReturn.put(capabilityName, options);

		return Collections.unmodifiableMap(toReturn);
	}

	/*private JsonObject readDataFile(Path path) {

		try {
			return JsonParser.parseString(Files.readString(path, StandardCharsets.ISO_8859_1)).getAsJsonObject();
		} catch (Exception e) {}

		try {
			return JsonParser.parseString(Files.readString(path, StandardCharsets.UTF_8)).getAsJsonObject();
		} catch (Exception e) {}

		path.toFile().delete(); // preferences file is no more usable, have to delete

		return null;
	}*/

	/*private void removeMetricsData(String profileFolder) {

		final Path atsProfilePath = Paths.get(profileFolder);
		if(atsProfilePath.toFile().exists()) {
			final Path localStatePath = atsProfilePath.resolve("Local State");
			if(localStatePath.toFile().exists()) {

				final JsonObject localStateObject = readDataFile(localStatePath);

				if(localStateObject != null) {
					try {

						final JsonObject metrics = localStateObject.get("user_experience_metrics").getAsJsonObject();

						if(metrics != null) {
							final JsonObject stability = metrics.get("stability").getAsJsonObject();
							if(stability != null) {
								if(!stability.get("exited_cleanly").getAsBoolean()) {
									stability.remove("exited_cleanly");
									stability.addProperty("exited_cleanly", true);

									metrics.remove("stability");
									metrics.add("stability", stability);

									localStateObject.remove("user_experience_metrics");
									localStateObject.add("user_experience_metrics", metrics);

									Files.writeString(localStatePath, new Gson().toJson(localStateObject), StandardCharsets.UTF_8);
								}
							}
						}
					} catch (Exception e) {}
				}
			}

			final Path preferencesPath = atsProfilePath.resolve("Default").resolve("Preferences");
			if(preferencesPath.toFile().exists()) {

				final JsonObject PreferencesObject = readDataFile(preferencesPath);

				if(PreferencesObject != null) {
					try {

						final JsonObject profile = PreferencesObject.get("profile").getAsJsonObject();

						if(profile != null) {

							final JsonElement exitType = profile.get("exit_type");

							if(exitType != null) {
								profile.remove("exit_type");
							}

							profile.addProperty("exit_type", "Normal");

							PreferencesObject.remove("profile");
							PreferencesObject.add("profile", profile);

							Files.writeString(preferencesPath, new Gson().toJson(PreferencesObject), StandardCharsets.UTF_8);

						}
					} catch (Exception e) {}
				}
			}
		}
	}*/
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy