How to use Interface Extension class of org.openqa.selenium.firefox package

Best Selenium code snippet using org.openqa.selenium.firefox.Interface Extension

Source:XpiDriverService.java Github

copy

Full Screen

1// Licensed to the Software Freedom Conservancy (SFC) under one2// or more contributor license agreements. See the NOTICE file3// distributed with this work for additional information4// regarding copyright ownership. The SFC licenses this file5// to you under the Apache License, Version 2.0 (the6// "License"); you may not use this file except in compliance7// with the License. You may obtain a copy of the License at8//9// http://www.apache.org/licenses/LICENSE-2.010//11// Unless required by applicable law or agreed to in writing,12// software distributed under the License is distributed on an13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY14// KIND, either express or implied. See the License for the15// specific language governing permissions and limitations16// under the License.17package org.openqa.selenium.firefox;18import static java.util.concurrent.TimeUnit.SECONDS;19import static org.openqa.selenium.firefox.FirefoxOptions.FIREFOX_OPTIONS;20import static org.openqa.selenium.firefox.FirefoxProfile.PORT_PREFERENCE;21import com.google.auto.service.AutoService;22import com.google.common.base.Preconditions;23import com.google.common.collect.ImmutableList;24import com.google.common.collect.ImmutableMap;25import com.google.common.io.ByteStreams;26import org.openqa.selenium.Capabilities;27import org.openqa.selenium.WebDriverException;28import org.openqa.selenium.firefox.internal.ClasspathExtension;29import org.openqa.selenium.firefox.internal.Extension;30import org.openqa.selenium.firefox.internal.FileExtension;31import org.openqa.selenium.net.UrlChecker;32import org.openqa.selenium.remote.BrowserType;33import org.openqa.selenium.remote.service.DriverService;34import java.io.File;35import java.io.FileOutputStream;36import java.io.IOException;37import java.net.MalformedURLException;38import java.net.URL;39import java.util.Map;40import java.util.Objects;41import java.util.Optional;42import java.util.concurrent.locks.Lock;43import java.util.concurrent.locks.ReentrantLock;44import java.util.function.Supplier;45import java.util.stream.Stream;46public class XpiDriverService extends DriverService {47 private final Lock lock = new ReentrantLock();48 private final int port;49 private final FirefoxBinary binary;50 private final FirefoxProfile profile;51 private File profileDir;52 private XpiDriverService(53 File executable,54 int port,55 ImmutableList<String> args,56 ImmutableMap<String, String> environment,57 FirefoxBinary binary,58 FirefoxProfile profile,59 File logFile)60 throws IOException {61 super(executable, port, args, environment);62 Preconditions.checkState(port > 0, "Port must be set");63 this.port = port;64 this.binary = binary;65 this.profile = profile;66 String firefoxLogFile = System.getProperty(FirefoxDriver.SystemProperty.BROWSER_LOGFILE);67 if (firefoxLogFile != null) { // System property has higher precedence68 if ("/dev/stdout".equals(firefoxLogFile)) {69 sendOutputTo(System.out);70 } else if ("/dev/stderr".equals(firefoxLogFile)) {71 sendOutputTo(System.err);72 } else if ("/dev/null".equals(firefoxLogFile)) {73 sendOutputTo(ByteStreams.nullOutputStream());74 } else {75 // TODO: This stream is leaked.76 sendOutputTo(new FileOutputStream(firefoxLogFile));77 }78 } else {79 if (logFile != null) {80 // TODO: This stream is leaked.81 sendOutputTo(new FileOutputStream(logFile));82 } else {83 sendOutputTo(ByteStreams.nullOutputStream());84 }85 }86 }87 @Override88 protected URL getUrl(int port) throws MalformedURLException {89 return new URL("http", "localhost", port, "/hub");90 }91 @Override92 public void start() throws IOException {93 lock.lock();94 try {95 profile.setPreference(PORT_PREFERENCE, port);96 addWebDriverExtension(profile);97 profileDir = profile.layoutOnDisk();98 binary.setOutputWatcher(getOutputStream());99 binary.startProfile(profile, profileDir, "-foreground");100 waitUntilAvailable();101 } finally {102 lock.unlock();103 }104 }105 @Override106 protected void waitUntilAvailable() throws MalformedURLException {107 try {108 // Use a longer timeout, because 45 seconds was the default timeout in the predecessor to109 // XpiDriverService. This has to wait for Firefox to start, not just a service, and some users110 // may be running tests on really slow machines.111 URL status = new URL(getUrl(port).toString() + "/status");112 new UrlChecker().waitUntilAvailable(45, SECONDS, status);113 } catch (UrlChecker.TimeoutException e) {114 throw new WebDriverException("Timed out waiting 45 seconds for Firefox to start.", e);115 }116 }117 @Override118 public void stop() {119 lock.lock();120 try {121 binary.quit();122 profile.cleanTemporaryModel();123 profile.clean(profileDir);124 } finally {125 lock.unlock();126 }127 }128 private void addWebDriverExtension(FirefoxProfile profile) {129 if (profile.containsWebDriverExtension()) {130 return;131 }132 profile.addExtension("webdriver", loadCustomExtension().orElse(loadDefaultExtension()));133 }134 private Optional<Extension> loadCustomExtension() {135 String xpiProperty = System.getProperty(FirefoxDriver.SystemProperty.DRIVER_XPI_PROPERTY);136 if (xpiProperty != null) {137 File xpi = new File(xpiProperty);138 return Optional.of(new FileExtension(xpi));139 }140 return Optional.empty();141 }142 private static Extension loadDefaultExtension() {143 return new ClasspathExtension(144 FirefoxProfile.class,145 "/" + FirefoxProfile.class.getPackage().getName().replace(".", "/") + "/webdriver.xpi");146 }147 /**148 * Configures and returns a new {@link XpiDriverService} using the default configuration. In149 * this configuration, the service will use the firefox executable identified by the150 * {@link FirefoxDriver.SystemProperty#BROWSER_BINARY} system property on a free port.151 *152 * @return A new XpiDriverService using the default configuration.153 */154 public static XpiDriverService createDefaultService() {155 try {156 return new Builder().build();157 } catch (WebDriverException e) {158 throw new IllegalStateException(e.getMessage(), e.getCause());159 }160 }161 @SuppressWarnings("unchecked")162 static XpiDriverService createDefaultService(Capabilities caps) {163 Builder builder = new Builder().usingAnyFreePort();164 FirefoxProfile profile = Stream.<ThrowingSupplier<FirefoxProfile>>of(165 () -> (FirefoxProfile) caps.getCapability(FirefoxDriver.PROFILE),166 () -> FirefoxProfile.fromJson((String) caps.getCapability(FirefoxDriver.PROFILE)),167 () -> ((FirefoxOptions) caps).getProfile(),168 () -> (FirefoxProfile) ((Map<String, Object>) caps.getCapability(FIREFOX_OPTIONS)).get("profile"),169 () -> FirefoxProfile.fromJson((String) ((Map<String, Object>) caps.getCapability(FIREFOX_OPTIONS)).get("profile")),170 () -> {171 Map<String, Object> options = (Map<String, Object>) caps.getCapability(FIREFOX_OPTIONS);172 FirefoxProfile toReturn = new FirefoxProfile();173 ((Map<String, Object>) options.get("prefs")).forEach((key, value) -> {174 if (value instanceof Boolean) { toReturn.setPreference(key, (Boolean) value); }175 if (value instanceof Integer) { toReturn.setPreference(key, (Integer) value); }176 if (value instanceof String) { toReturn.setPreference(key, (String) value); }177 });178 return toReturn;179 })180 .map(supplier -> {181 try {182 return supplier.get();183 } catch (Exception e) {184 return null;185 }186 })187 .filter(Objects::nonNull)188 .findFirst()189 .orElse(null);190 if (profile != null) {191 builder.withProfile(profile);192 }193 Object binary = caps.getCapability(FirefoxDriver.BINARY);194 if (binary != null) {195 FirefoxBinary actualBinary;196 if (binary instanceof FirefoxBinary) {197 actualBinary = (FirefoxBinary) binary;198 } else if (binary instanceof String) {199 actualBinary = new FirefoxBinary(new File(String.valueOf(binary)));200 } else {201 throw new IllegalArgumentException(202 "Expected binary to be a string or a binary: " + binary);203 }204 builder.withBinary(actualBinary);205 }206 return builder.build();207 }208 public static Builder builder() {209 return new Builder();210 }211 @AutoService(DriverService.Builder.class)212 public static class Builder extends DriverService.Builder<XpiDriverService, XpiDriverService.Builder> {213 private FirefoxBinary binary = null;214 private FirefoxProfile profile = null;215 @Override216 public int score(Capabilities capabilites) {217 int score = 0;218 if (BrowserType.FIREFOX.equals(capabilites.getBrowserName())) {219 score++;220 }221 if (capabilites.getCapability(FirefoxOptions.FIREFOX_OPTIONS) != null) {222 score++;223 }224 // This is the legacy firefox driver that they've asked for. Bind very strongly.225 if (capabilites.getCapability(FirefoxDriver.MARIONETTE) == Boolean.FALSE) {226 score += 5;227 }228 return score;229 }230 public Builder withBinary(FirefoxBinary binary) {231 this.binary = Preconditions.checkNotNull(binary);232 return this;233 }234 public Builder withProfile(FirefoxProfile profile) {235 this.profile = Preconditions.checkNotNull(profile);236 return this;237 }238 @Override239 protected File findDefaultExecutable() {240 if (binary == null) {241 return new FirefoxBinary().getFile();242 }243 return binary.getFile();244 }245 @Override246 protected ImmutableList<String> createArgs() {247 return ImmutableList.of("-foreground");248 }249 @Override250 protected XpiDriverService createDriverService(251 File exe,252 int port,253 ImmutableList<String> args,254 ImmutableMap<String, String> environment) {255 try {256 return new XpiDriverService(257 exe,258 port,259 args,260 environment,261 binary == null ? new FirefoxBinary() : binary,262 profile == null ? new FirefoxProfile() : profile,263 getLogFile());264 } catch (IOException e) {265 throw new WebDriverException(e);266 }267 }268 }269 @FunctionalInterface270 private interface ThrowingSupplier<V> extends Supplier<V> {271 V throwingGet() throws Exception;272 @Override273 default V get() {274 try {275 return throwingGet();276 } catch (Exception e) {277 if (e instanceof RuntimeException) {278 throw (RuntimeException) e;279 } else {280 throw new RuntimeException(e);281 }282 }283 }284 }285}...

Full Screen

Full Screen

Source:FirefoxDriver.java Github

copy

Full Screen

1/*2Copyright 2007-2009 WebDriver committers3Copyright 2007-2009 Google Inc.4Portions copyright 2007 ThoughtWorks, Inc5Licensed under the Apache License, Version 2.0 (the "License");6you may not use this file except in compliance with the License.7You may obtain a copy of the License at8 http://www.apache.org/licenses/LICENSE-2.09Unless required by applicable law or agreed to in writing, software10distributed under the License is distributed on an "AS IS" BASIS,11WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12See the License for the specific language governing permissions and13limitations under the License.14*/15package org.openqa.selenium.firefox;16import java.io.File;17import java.io.IOException;18import java.net.BindException;19import java.net.InetSocketAddress;20import java.net.Socket;21import java.util.HashSet;22import java.util.List;23import java.util.Map;24import java.util.Set;25import com.google.common.collect.ImmutableMap;26import org.openqa.selenium.Alert;27import org.openqa.selenium.NoAlertPresentException;28import org.openqa.selenium.OutputType;29import org.openqa.selenium.Platform;30import org.openqa.selenium.TakesScreenshot;31import org.openqa.selenium.UnhandledAlertException;32import org.openqa.selenium.WebDriverException;33import org.openqa.selenium.WebElement;34import org.openqa.selenium.firefox.internal.Lock;35import org.openqa.selenium.firefox.internal.NewProfileExtensionConnection;36import org.openqa.selenium.firefox.internal.ProfilesIni;37import org.openqa.selenium.firefox.internal.SocketLock;38import org.openqa.selenium.internal.FileHandler;39import org.openqa.selenium.internal.FindsByCssSelector;40import org.openqa.selenium.remote.Command;41import org.openqa.selenium.remote.CommandExecutor;42import org.openqa.selenium.remote.DesiredCapabilities;43import org.openqa.selenium.remote.DriverCommand;44import org.openqa.selenium.remote.RemoteWebDriver;45import org.openqa.selenium.remote.Response;46import static org.openqa.selenium.OutputType.FILE;47/**48 * An implementation of the {#link WebDriver} interface that drives Firefox. This works through a firefox extension,49 * which gets installed automatically if necessary. Important system variables are:50 * <ul>51 * <li><b>webdriver.firefox.bin</b> - Which firefox binary to use (normally "firefox" on the PATH).</li>52 * <li><b>webdriver.firefox.profile</b> - The name of the profile to use (normally "WebDriver").</li>53 * </ul>54 * <p/>55 * When the driver starts, it will make a copy of the profile it is using, rather than using that profile directly.56 * This allows multiple instances of firefox to be started.57 */58public class FirefoxDriver extends RemoteWebDriver implements TakesScreenshot, FindsByCssSelector {59 public static final int DEFAULT_PORT = 7055;60 // For now, only enable native events on Windows61 public static final boolean DEFAULT_ENABLE_NATIVE_EVENTS =62 Platform.getCurrent()63 .is(Platform.WINDOWS);64 // Accept untrusted SSL certificates.65 public static final boolean ACCEPT_UNTRUSTED_CERTIFICATES = true;66 // Assume that the untrusted certificates will come from untrusted issuers67 // or will be self signed.68 public static final boolean ASSUME_UNTRUSTED_ISSUER = true;69 // Commands we can execute with needing to dismiss an active alert70 private final Set<DriverCommand> alertWhiteListedCommands = new HashSet<DriverCommand>() {{71 add(DriverCommand.DISMISS_ALERT);72 }};73 private FirefoxAlert currentAlert;74 private final LazyCommandExecutor executor;75 protected FirefoxBinary binary;76 protected FirefoxProfile profile;77 public FirefoxDriver() {78 this(new FirefoxBinary(), null);79 }80 public FirefoxDriver(FirefoxProfile profile) {81 this(new FirefoxBinary(), profile);82 }83 public FirefoxDriver(FirefoxBinary binary, FirefoxProfile profile) {84 super(new LazyCommandExecutor(binary, profile), DesiredCapabilities.firefox());85 this.binary = binary;86 this.profile = profile;87 executor = (LazyCommandExecutor) getCommandExecutor();88 }89 @Override90 protected void startClient() {91 LazyCommandExecutor executor = (LazyCommandExecutor) getCommandExecutor();92 FirefoxProfile profileToUse = getProfile(executor.profile);93 profileToUse.addWebDriverExtensionIfNeeded(false);94 // TODO(simon): Make this not sinfully ugly95 ExtensionConnection connection = connectTo(executor.binary, profileToUse, "localhost");96 executor.setConnection(connection);97 try {98 connection.start();99 } catch (IOException e) {100 throw new WebDriverException("An error occurred while connecting to Firefox", e);101 }102 }103 private FirefoxProfile getProfile(FirefoxProfile profile) {104 FirefoxProfile profileToUse = profile;105 String suggestedProfile = System.getProperty("webdriver.firefox.profile");106 if (profileToUse == null && suggestedProfile != null) {107 profileToUse = new ProfilesIni().getProfile(suggestedProfile);108 } else if (profileToUse == null) {109 profileToUse = new FirefoxProfile();110 }111 return profileToUse;112 }113 protected ExtensionConnection connectTo(FirefoxBinary binary, FirefoxProfile profile,114 String host) {115 int profilePort = profile.getPort() == 0 ? DEFAULT_PORT : profile.getPort();116 Lock lock = new SocketLock(profilePort - 1);117 try {118 FirefoxBinary bin = binary == null ? new FirefoxBinary() : binary;119 120 return new NewProfileExtensionConnection(lock, bin, profile, host);121 } catch (Exception e) {122 throw new WebDriverException(e);123 } finally {124 lock.unlock();125 }126 }127 @Override128 protected void stopClient() {129 ((LazyCommandExecutor) this.getCommandExecutor()).quit();130 }131 @Override132 protected FirefoxWebElement newRemoteWebElement() {133 return new FirefoxWebElement(this);134 }135 public WebElement findElementByCssSelector(String using) {136 if (using == null) {137 throw new IllegalArgumentException("Cannot find elements when the css selector is null.");138 }139 return findElement("css selector", using);140 }141 public List<WebElement> findElementsByCssSelector(String using) {142 if (using == null) {143 throw new IllegalArgumentException("Cannot find elements when the css selector is null.");144 }145 return findElements("css selector", using);146 }147 @Override148 public TargetLocator switchTo() {149 return new FirefoxTargetLocator();150 }151 @Override152 protected Response execute(DriverCommand driverCommand, Map<String, ?> parameters) {153 if (currentAlert != null) {154 if (!alertWhiteListedCommands.contains(driverCommand)) {155 ((FirefoxTargetLocator) switchTo()).alert()156 .dismiss();157 throw new UnhandledAlertException(driverCommand.toString());158 }159 }160 Response response = super.execute(driverCommand, parameters);161 Object rawResponse = response.getValue();162 if (rawResponse instanceof Map) {163 Map map = (Map) rawResponse;164 if (map.containsKey("__webdriverType")) {165 // Looks like have an alert. construct it166 currentAlert = new FirefoxAlert((String) map.get("text"));167 response.setValue(null);168 }169 }170 return response;171 }172 @Override173 public boolean isJavascriptEnabled() {174 return true;175 }176 private class FirefoxTargetLocator extends RemoteTargetLocator {177 // TODO: this needs to be on an interface178 public Alert alert() {179 if (currentAlert != null) {180 return currentAlert;181 }182 throw new NoAlertPresentException();183 }184 }185 public <X> X getScreenshotAs(OutputType<X> target) {186 // Get the screenshot as base64.187 String base64 = execute(DriverCommand.SCREENSHOT).getValue().toString();188 // ... and convert it.189 return target.convertFromBase64Png(base64);190 }191 /**192 * Saves a screenshot of the current page into the given file.193 *194 * @deprecated Use getScreenshotAs(file), which returns a temporary file.195 */196 @Deprecated197 public void saveScreenshot(File pngFile) {198 if (pngFile == null) {199 throw new IllegalArgumentException("Method parameter pngFile must not be null");200 }201 File tmpfile = getScreenshotAs(FILE);202 File dir = pngFile.getParentFile();203 if (dir != null && !dir.exists() && !dir.mkdirs()) {204 throw new WebDriverException("Could not create directory " + dir.getAbsolutePath());205 }206 try {207 FileHandler.copy(tmpfile, pngFile);208 } catch (IOException e) {209 throw new WebDriverException(e);210 }211 }212 private class FirefoxAlert implements Alert {213 private String text;214 public FirefoxAlert(String text) {215 this.text = text;216 }217 public void dismiss() {218 execute(DriverCommand.DISMISS_ALERT, ImmutableMap.of("text", text));219 currentAlert = null;220 }221 public void accept() {222 }223 public String getText() {224 return text;225 }226 }227 private static class LazyCommandExecutor implements CommandExecutor {228 private ExtensionConnection connection;229 private final FirefoxBinary binary;230 private final FirefoxProfile profile;231 private LazyCommandExecutor(FirefoxBinary binary, FirefoxProfile profile) {232 this.binary = binary;233 this.profile = profile;234 }235 public void setConnection(ExtensionConnection connection) {236 this.connection = connection;237 }238 public void quit() {239 connection.quit();240 }241 public Response execute(Command command) throws Exception {242 return connection.execute(command);243 }244 }245}...

Full Screen

Full Screen

Source:AbstractExtensionConnection.java Github

copy

Full Screen

1/*2Copyright 2007-2009 WebDriver committers3Copyright 2007-2009 Google Inc.4Licensed under the Apache License, Version 2.0 (the "License");5you may not use this file except in compliance with the License.6You may obtain a copy of the License at7 http://www.apache.org/licenses/LICENSE-2.08Unless required by applicable law or agreed to in writing, software9distributed under the License is distributed on an "AS IS" BASIS,10WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.11See the License for the specific language governing permissions and12limitations under the License.13*/14package org.openqa.selenium.firefox.internal;15import java.io.BufferedInputStream;16import java.io.IOException;17import java.io.OutputStreamWriter;18import java.io.UnsupportedEncodingException;19import java.net.ConnectException;20import java.net.InetAddress;21import java.net.InetSocketAddress;22import java.net.NetworkInterface;23import java.net.Socket;24import java.net.SocketAddress;25import java.net.SocketException;26import java.net.UnknownHostException;27import java.util.Collections;28import java.util.Enumeration;29import java.util.HashSet;30import java.util.Set;31import org.json.JSONArray;32import org.json.JSONException;33import org.json.JSONObject;34import org.openqa.selenium.Platform;35import org.openqa.selenium.WebDriverException;36import org.openqa.selenium.firefox.Command;37import org.openqa.selenium.firefox.ExtensionConnection;38import org.openqa.selenium.firefox.NotConnectedException;39import org.openqa.selenium.firefox.Response;40public abstract class AbstractExtensionConnection implements ExtensionConnection {41 private Socket socket;42 private Set<SocketAddress> addresses;43 private OutputStreamWriter out;44 private BufferedInputStream in;45 protected void setAddress(String host, int port) {46 if ("localhost".equals(host)) {47 addresses = obtainLoopbackAddresses(port);48 } else {49 try {50 SocketAddress hostAddress = new InetSocketAddress(InetAddress.getByName(host), port);51 addresses = Collections.singleton(hostAddress);52 } catch (UnknownHostException e) {53 throw new WebDriverException(e);54 }55 }56 }57 private Set<SocketAddress> obtainLoopbackAddresses(int port) {58 Set<SocketAddress> localhosts = new HashSet<SocketAddress>();59 try {60 Enumeration<NetworkInterface> allInterfaces = NetworkInterface.getNetworkInterfaces();61 while (allInterfaces.hasMoreElements()) {62 NetworkInterface iface = allInterfaces.nextElement();63 Enumeration<InetAddress> allAddresses = iface.getInetAddresses();64 while (allAddresses.hasMoreElements()) {65 InetAddress addr = allAddresses.nextElement();66 if (addr.isLoopbackAddress()) {67 SocketAddress socketAddress = new InetSocketAddress(addr, port);68 localhosts.add(socketAddress);69 }70 }71 }72 // On linux, loopback addresses are named "lo". See if we can find that. We do this73 // craziness because sometimes the loopback device is given an IP range that falls outside74 // of 127/2475 if (Platform.getCurrent().is(Platform.UNIX)) {76 NetworkInterface linuxLoopback = NetworkInterface.getByName("lo");77 if (linuxLoopback != null) {78 Enumeration<InetAddress> possibleLoopbacks = linuxLoopback.getInetAddresses();79 while (possibleLoopbacks.hasMoreElements()) {80 InetAddress inetAddress = possibleLoopbacks.nextElement();81 SocketAddress socketAddress = new InetSocketAddress(inetAddress, port);82 localhosts.add(socketAddress);83 }84 }85 }86 } catch (SocketException e) {87 throw new WebDriverException(e);88 }89 if (!localhosts.isEmpty()) {90 return localhosts;91 }92 // Nothing found. Grab the first address we can find93 NetworkInterface firstInterface;94 try {95 firstInterface = NetworkInterface.getNetworkInterfaces().nextElement();96 } catch (SocketException e) {97 throw new WebDriverException(e);98 }99 InetAddress firstAddress = null;100 if (firstInterface != null) {101 firstAddress = firstInterface.getInetAddresses().nextElement();102 }103 if (firstAddress != null) {104 SocketAddress socketAddress = new InetSocketAddress(firstAddress, port);105 return Collections.singleton(socketAddress);106 }107 throw new WebDriverException("Unable to find loopback address for localhost");108 }109 protected void connectToBrowser(long timeToWaitInMilliSeconds) throws IOException {110 long waitUntil = System.currentTimeMillis() + timeToWaitInMilliSeconds;111 while (!isConnected() && waitUntil > System.currentTimeMillis()) {112 for (SocketAddress addr : addresses) {113 try {114 connect(addr);115 break;116 } catch (ConnectException e) {117 try {118 Thread.sleep(250);119 } catch (InterruptedException ie) {120 throw new WebDriverException(ie);121 }122 }123 }124 }125 if (!isConnected()) {126 throw new NotConnectedException(socket, timeToWaitInMilliSeconds);127 }128 }129 private void connect(SocketAddress addr) throws IOException {130 socket = new Socket();131 socket.connect(addr);132 in = new BufferedInputStream(socket.getInputStream());133 out = new OutputStreamWriter(socket.getOutputStream(), "UTF-8");134 }135 public boolean isConnected() {136 return socket != null && socket.isConnected();137 }138 public Response sendMessageAndWaitForResponse(Class<? extends RuntimeException> throwOnFailure,139 Command command) {140 sendMessage(command);141 return waitForResponseFor(command.getCommandName());142 }143 protected void sendMessage(Command command) {144 String converted = convert(command);145 // Make this look like an HTTP request146 StringBuilder message = new StringBuilder();147 message.append("GET / HTTP/1.1\n");148 message.append("Host: localhost\n");149 message.append("Content-Length: ");150 message.append(converted.length()).append("\n\n");151 message.append(converted).append("\n");152 try {153 out.write(message.toString());154 out.flush();155 } catch (IOException e) {156 throw new WebDriverException(e);157 }158 }159 private String convert(Command command) {160 JSONObject json = new JSONObject();161 try {162 json.put("commandName", command.getCommandName());163 json.put("context", String.valueOf(command.getContext()));164 json.put("elementId", command.getElementId());165 JSONArray params = new JSONArray();166 for (Object o : command.getParameters()) {167 params.put(o);168 }169 json.put("parameters", params);170 } catch (JSONException e) {171 throw new WebDriverException(e);172 }173 try {174 // Force encoding as UTF-8.175 byte[] bytes = json.toString().getBytes("UTF-8");176 return new String(bytes, "UTF-8");177 } catch (UnsupportedEncodingException e) {178 // If UTF-8 is missing from Java, we've got problems179 throw new IllegalStateException("Cannot convert string to UTF-8");180 }181 }182 private Response waitForResponseFor(String command) {183 try {184 return readLoop(command);185 } catch (IOException e) {186 throw new WebDriverException(e);187 }188 }189 private Response readLoop(String command) throws IOException {190 Response response = nextResponse();191 if (command.equals(response.getCommand())) {192 return response;193 }194 throw new WebDriverException(195 "Expected response to " + command + " but actually got: " + response.getCommand() + " ("196 + response.getCommand() + ")");197 }198 private Response nextResponse() throws IOException {199 String line = readLine();200 // Expected input will be of the form:201 // Header: Value202 // \n203 // JSON object204 //205 // The only expected header is "Length"206 // Read headers207 int count = 0;208 String[] parts = line.split(":", 2);209 if ("Length".equals(parts[0])) {210 count = Integer.parseInt(parts[1].trim());211 }212 // Wait for the blank line213 while (line.length() != 0) {214 line = readLine();215 }216 // Read the rest of the response.217 byte[] remaining = new byte[count];218 for (int i = 0; i < count; i++) {219 remaining[i] = (byte) in.read();220 }221 return new Response(new String(remaining, "UTF-8"));222 }223 private String readLine() throws IOException {224 int size = 4096;225 int growBy = 1024;226 byte[] raw = new byte[size];227 int count = 0;228 for (; ;) {229 int b = in.read();230 if (b == -1 || (char) b == '\n') {231 break;232 }233 raw[count++] = (byte) b;234 if (count == size) {235 size += growBy;236 byte[] temp = new byte[size];237 System.arraycopy(raw, 0, temp, 0, count);238 raw = temp;239 }240 }241 return new String(raw, 0, count, "UTF-8");242 }243}...

Full Screen

Full Screen

Source:FirefoxCapabilitiesFactory.java Github

copy

Full Screen

1/**2 * Orignal work: Copyright 2015 www.seleniumtests.com3 * Modified work: Copyright 2016 www.infotel.com4 * Copyright 2017-2019 B.Hecquet5 *6 * Licensed under the Apache License, Version 2.0 (the "License");7 * you may not use this file except in compliance with the License.8 * You may obtain a copy of the License at9 *10 * http://www.apache.org/licenses/LICENSE-2.011 *12 * Unless required by applicable law or agreed to in writing, software13 * distributed under the License is distributed on an "AS IS" BASIS,14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.15 * See the License for the specific language governing permissions and16 * limitations under the License.17 */18package com.seleniumtests.browserfactory;1920import java.io.File;21import java.io.IOException;22import java.util.List;23import java.util.Map.Entry;2425import org.apache.commons.io.FileUtils;26import org.openqa.selenium.MutableCapabilities;27import org.openqa.selenium.firefox.FirefoxDriver;28import org.openqa.selenium.firefox.FirefoxDriverLogLevel;29import org.openqa.selenium.firefox.FirefoxOptions;30import org.openqa.selenium.firefox.FirefoxProfile;31import org.openqa.selenium.firefox.GeckoDriverService;32import org.openqa.selenium.firefox.ProfilesIni;3334import com.seleniumtests.browserfactory.customprofile.FireFoxProfileMarker;35import com.seleniumtests.driver.BrowserType;36import com.seleniumtests.driver.DriverConfig;37import com.seleniumtests.driver.DriverMode;38import com.seleniumtests.util.FileUtility;39import com.seleniumtests.util.logging.DebugMode;4041public class FirefoxCapabilitiesFactory extends IDesktopCapabilityFactory {42 43 public FirefoxCapabilitiesFactory(DriverConfig webDriverConfig) {44 super(webDriverConfig);45 }4647 public static final String ALL_ACCESS = "allAccess";48 private static boolean isProfileCreated = false;49 private static Object lockProfile = new Object();50 51 @Override52 protected MutableCapabilities getDriverOptions() {53 FirefoxOptions options = new FirefoxOptions();54 55 if (webDriverConfig.isHeadlessBrowser()) {56 logger.info("setting firefox in headless mode. Supported for firefox version >= 56");57 options.addArguments("-headless");58 options.addArguments("--window-size=1280,1024");59 options.addArguments("--width=1280");60 options.addArguments("--height=1024");61 }6263 options.setLogLevel(FirefoxDriverLogLevel.ERROR);64 options.setPageLoadStrategy(webDriverConfig.getPageLoadStrategy());65 66 if (webDriverConfig.getDebug().contains(DebugMode.DRIVER)) {67 options.setLogLevel(FirefoxDriverLogLevel.TRACE);68 }69 70 // handle https://bugzilla.mozilla.org/show_bug.cgi?id=1429338#c4 and https://github.com/mozilla/geckodriver/issues/78971 options.setCapability("moz:useNonSpecCompliantPointerOrigin", true);72 return options;73 }74 75 @Override76 protected String getDriverPath() {77 return webDriverConfig.getGeckoDriverPath();78 }79 80 @Override81 protected String getBrowserBinaryPath() {82 return webDriverConfig.getFirefoxBinPath();83 }84 85 @Override86 protected BrowserType getBrowserType() {87 return BrowserType.FIREFOX;88 }89 90 @Override91 protected String getDriverExeProperty() {92 return GeckoDriverService.GECKO_DRIVER_EXE_PROPERTY;93 }94 95 @Override96 protected void updateOptionsWithSelectedBrowserInfo(MutableCapabilities options) {97 options.setCapability(FirefoxDriver.MARIONETTE, !BrowserInfo.useLegacyFirefoxVersion(selectedBrowserInfo.getVersion()));98 99 ((FirefoxOptions)options).setBinary(selectedBrowserInfo.getPath());100 101 FirefoxProfile profile = getFirefoxProfile();102 configProfile(profile, webDriverConfig);103 options.setCapability(FirefoxDriver.PROFILE, profile);104 105 // extensions106 List<BrowserExtension> extensions = BrowserExtension.getExtensions(webDriverConfig.getTestContext().getConfiguration());107 if (!extensions.isEmpty()) {108 for (BrowserExtension ext: extensions) {109 profile.addExtension(ext.getExtensionPath());110 for (Entry<String, String> entry: ext.getOptions().entrySet()) {111 profile.setPreference(entry.getKey(), entry.getValue());112 }113 }114 115 }116 }117 118119 protected void configProfile(final FirefoxProfile profile, final DriverConfig webDriverConfig) {120 profile.setAcceptUntrustedCertificates(webDriverConfig.isSetAcceptUntrustedCertificates());121 profile.setAssumeUntrustedCertificateIssuer(webDriverConfig.isSetAssumeUntrustedCertificateIssuer());122123 if (webDriverConfig.getUserAgentOverride() != null) {124 profile.setPreference("general.useragent.override", webDriverConfig.getUserAgentOverride());125 }126127 if (webDriverConfig.getNtlmAuthTrustedUris() != null) {128 profile.setPreference("network.automatic-ntlm-auth.trusted-uris", webDriverConfig.getNtlmAuthTrustedUris());129 }130131 if (webDriverConfig.getBrowserDownloadDir() != null && webDriverConfig.getMode() == DriverMode.LOCAL) {132 profile.setPreference("browser.download.dir", webDriverConfig.getBrowserDownloadDir());133 profile.setPreference("browser.download.folderList", 2);134 profile.setPreference("browser.download.manager.showWhenStarting", false);135 profile.setPreference("browser.helperApps.neverAsk.saveToDisk",136 "application/octet-stream,text/plain,application/pdf,application/zip,text/csv,text/html");137 }138139 // fix permission denied issues140 profile.setPreference("capability.policy.default.Window.QueryInterface", ALL_ACCESS);141 profile.setPreference("capability.policy.default.Window.frameElement.get", ALL_ACCESS);142 profile.setPreference("capability.policy.default.HTMLDocument.compatMode.get", ALL_ACCESS);143 profile.setPreference("capability.policy.default.Document.compatMode.get", ALL_ACCESS);144 profile.setPreference("dom.max_chrome_script_run_time", 0);145 profile.setPreference("dom.max_script_run_time", 0);146 }147148 /**149 * extractDefaultProfile to a folder.150 *151 * @param profilePath The folder to store the profile152 *153 * @throws IOException when profile file is not found154 */155 protected void extractDefaultProfile(final String profilePath) throws IOException {156 synchronized (lockProfile) {157 try {158 if (!isProfileCreated) {159 logger.info("start create profile");160 FileUtils.deleteDirectory(new File(profilePath));161 FileUtility.extractJar(profilePath, FireFoxProfileMarker.class);162 }163 } catch (Exception ex) {164 logger.error(ex);165 }166 isProfileCreated = true;167 }168169 170 }171172 protected synchronized FirefoxProfile getFirefoxProfile() {173174 if (webDriverConfig.getFirefoxProfilePath() != null) {175 if (!BrowserInfo.DEFAULT_BROWSER_PRODFILE.equals(webDriverConfig.getFirefoxProfilePath()) && (webDriverConfig.getFirefoxProfilePath().contains("/") || webDriverConfig.getFirefoxProfilePath().contains("\\"))) {176 return new FirefoxProfile(new File(webDriverConfig.getFirefoxProfilePath()));177 } else if (BrowserInfo.DEFAULT_BROWSER_PRODFILE.equals(webDriverConfig.getFirefoxProfilePath())) {178 ProfilesIni init=new ProfilesIni();179 return init.getProfile("default");180 } else {181 logger.warn(String.format("Firefox profile %s could not be set", webDriverConfig.getFirefoxProfilePath()));182 }183 }184 return new FirefoxProfile();185 }186187 /**188 * Creates a default profile that may be overriden on selenium grid side if we specify a path or "default"189 */190 @Override191 protected void updateGridOptionsWithSelectedBrowserInfo(MutableCapabilities options) {192 FirefoxProfile profile = new FirefoxProfile();193 if (webDriverConfig.getFirefoxProfilePath() != null) {194 if (BrowserInfo.DEFAULT_BROWSER_PRODFILE.equals(webDriverConfig.getFirefoxProfilePath()) || webDriverConfig.getFirefoxProfilePath().contains("/") || webDriverConfig.getFirefoxProfilePath().contains("\\")) {195 options.setCapability("firefoxProfile", webDriverConfig.getFirefoxProfilePath());196 } else {197 logger.warn(String.format("Firefox profile %s could not be set", webDriverConfig.getFirefoxProfilePath()));198 }199 } 200 201 configProfile(profile, webDriverConfig);202 options.setCapability(FirefoxDriver.PROFILE, profile);203 204 }205206} ...

Full Screen

Full Screen

Source:NewProfileExtensionConnection.java Github

copy

Full Screen

1/*2Copyright 2007-2009 WebDriver committers3Copyright 2007-2009 Google Inc.4Portions copyright 2007 ThoughtWorks, Inc5Licensed under the Apache License, Version 2.0 (the "License");6you may not use this file except in compliance with the License.7You may obtain a copy of the License at8 http://www.apache.org/licenses/LICENSE-2.09Unless required by applicable law or agreed to in writing, software10distributed under the License is distributed on an "AS IS" BASIS,11WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12See the License for the specific language governing permissions and13limitations under the License.14*/15package org.openqa.selenium.firefox.internal;16import java.io.File;17import java.io.IOException;18import java.net.BindException;19import java.net.InetAddress;20import java.net.InetSocketAddress;21import java.net.MalformedURLException;22import java.net.NetworkInterface;23import java.net.Socket;24import java.net.SocketException;25import java.net.URL;26import java.util.Collections;27import java.util.Enumeration;28import java.util.HashSet;29import java.util.Set;30import org.openqa.selenium.Platform;31import org.openqa.selenium.WebDriverException;32import org.openqa.selenium.firefox.ExtensionConnection;33import org.openqa.selenium.firefox.FirefoxBinary;34import org.openqa.selenium.firefox.FirefoxProfile;35import org.openqa.selenium.firefox.NotConnectedException;36import org.openqa.selenium.remote.Command;37import org.openqa.selenium.remote.CommandExecutor;38import org.openqa.selenium.remote.HttpCommandExecutor;39import org.openqa.selenium.remote.Response;40import org.openqa.selenium.remote.internal.CircularOutputStream;41public class NewProfileExtensionConnection implements CommandExecutor, ExtensionConnection {42 private final HttpCommandExecutor delegate;43 private final long connectTimeout;44 private final FirefoxBinary process;45 private final FirefoxProfile profile;46 private final Lock lock;47 private final int bufferSize = 4096;48 public NewProfileExtensionConnection(Lock lock, FirefoxBinary binary, FirefoxProfile profile,49 String host) throws Exception {50 delegate = new HttpCommandExecutor(buildUrl(host, determineNextFreePort(profile.getPort())));51 this.connectTimeout = binary.getTimeout();52 this.lock = lock;53 this.profile = profile;54 this.process = binary;55 }56 public void start() throws IOException {57 lock.lock(connectTimeout);58 try {59 String firefoxLogFile = System.getProperty("webdriver.firefox.logfile");60 File logFile = firefoxLogFile == null ? null : new File(firefoxLogFile);61 this.process.setOutputWatcher(new CircularOutputStream(logFile, bufferSize));62 profile.setPort(delegate.getAddressOfRemoteServer().getPort());63 profile.updateUserPrefs();64 this.process.clean(profile);65 this.process.startProfile(profile);66 long waitUntil = System.currentTimeMillis() + connectTimeout;67 while (!isConnected() && waitUntil > System.currentTimeMillis()) {68 // Do nothing69 }70 if (!isConnected()) {71 throw new NotConnectedException(72 delegate.getAddressOfRemoteServer(), connectTimeout);73 }74 } catch (IOException e) {75 throw new WebDriverException(76 String.format("Failed to connect to binary %s on port %d; process output follows: \n%s",77 process.toString(), profile.getPort(), process.getConsoleOutput()), e);78 } catch (WebDriverException e) {79 throw new WebDriverException(80 String.format("Failed to connect to binary %s on port %d; process output follows: \n%s",81 process.toString(), profile.getPort(), process.getConsoleOutput()), e);82 } finally {83 lock.unlock();84 }85 }86 public Response execute(Command command) throws Exception {87 return delegate.execute(command);88 }89 protected static int determineNextFreePort(int port) throws IOException {90 // Attempt to connect to the given port on the host91 // If we can't connect, then we're good to use it92 int newport;93 for (newport = port; newport < port + 200; newport++) {94 Socket socket = new Socket();95 InetSocketAddress address = new InetSocketAddress("localhost", newport);96 try {97 socket.bind(address);98 return newport;99 } catch (BindException e) {100 // Port is already bound. Skip it and continue101 } finally {102 socket.close();103 }104 }105 throw new WebDriverException(106 String.format("Cannot find free port in the range %d to %d ", port, newport));107 }108 public void quit() {109 // This should only be called after the QUIT command has been sent,110 // so go ahead and clean up our process and profile.111 process.quit();112 profile.clean();113 }114 /**115 * Builds the URL for the Firefox extension running on the given host and116 * port. If the host is {@code localhost}, an attempt will be made to find the117 * correct loopback address.118 *119 * @param host The hostname the extension is running on.120 * @param port The port the extension is listening on.121 * @return The URL of the Firefox extension.122 */123 private static URL buildUrl(String host, int port) {124 if ("localhost".equals(host)) {125 for (InetSocketAddress address : obtainLoopbackAddresses(port)) {126 try {127 return new URL("http", address.getHostName(), address.getPort(), "/hub");128 } catch (MalformedURLException ignored) {129 // Do nothing; loop and try next address.130 }131 }132 throw new WebDriverException("Unable to find loopback address for localhost");133 } else {134 try {135 return new URL("http", host, port, "/hub");136 } catch (MalformedURLException e) {137 throw new WebDriverException(e);138 }139 }140 }141 private static Set<InetSocketAddress> obtainLoopbackAddresses(int port) {142 Set<InetSocketAddress> localhosts = new HashSet<InetSocketAddress>();143 try {144 Enumeration<NetworkInterface> allInterfaces = NetworkInterface.getNetworkInterfaces();145 while (allInterfaces.hasMoreElements()) {146 NetworkInterface iface = allInterfaces.nextElement();147 Enumeration<InetAddress> allAddresses = iface.getInetAddresses();148 while (allAddresses.hasMoreElements()) {149 InetAddress addr = allAddresses.nextElement();150 if (addr.isLoopbackAddress()) {151 InetSocketAddress socketAddress = new InetSocketAddress(addr, port);152 localhosts.add(socketAddress);153 }154 }155 }156 // On linux, loopback addresses are named "lo". See if we can find that. We do this157 // craziness because sometimes the loopback device is given an IP range that falls outside158 // of 127/24159 if (Platform.getCurrent()160 .is(Platform.UNIX)) {161 NetworkInterface linuxLoopback = NetworkInterface.getByName("lo");162 if (linuxLoopback != null) {163 Enumeration<InetAddress> possibleLoopbacks = linuxLoopback.getInetAddresses();164 while (possibleLoopbacks.hasMoreElements()) {165 InetAddress inetAddress = possibleLoopbacks.nextElement();166 InetSocketAddress socketAddress = new InetSocketAddress(inetAddress, port);167 localhosts.add(socketAddress);168 }169 }170 }171 } catch (SocketException e) {172 throw new WebDriverException(e);173 }174 if (!localhosts.isEmpty()) {175 return localhosts;176 }177 // Nothing found. Grab the first address we can find178 NetworkInterface firstInterface;179 try {180 firstInterface = NetworkInterface.getNetworkInterfaces().nextElement();181 } catch (SocketException e) {182 throw new WebDriverException(e);183 }184 InetAddress firstAddress = null;185 if (firstInterface != null) {186 firstAddress = firstInterface.getInetAddresses().nextElement();187 }188 if (firstAddress != null) {189 InetSocketAddress socketAddress = new InetSocketAddress(firstAddress, port);190 return Collections.singleton(socketAddress);191 }192 throw new WebDriverException("Unable to find loopback address for localhost");193 }194 public boolean isConnected() {195 try {196 // TODO: use a more intelligent way of testing if the server is ready.197 delegate.getAddressOfRemoteServer().openConnection().connect();198 return true;199 } catch (IOException e) {200 // Cannot connect yet.201 return false;202 }203 }204}...

Full Screen

Full Screen

Source:DriverManager.java Github

copy

Full Screen

1package com.miniiinstabot.manager;2import com.miniiinstabot.interfaces.ResponseInterface;3import java.io.File;4import org.openqa.selenium.WebDriver;5import org.openqa.selenium.chrome.ChromeDriver;6import org.openqa.selenium.firefox.FirefoxBinary;7import org.openqa.selenium.firefox.FirefoxDriver;8import org.openqa.selenium.firefox.FirefoxOptions;9import org.openqa.selenium.firefox.FirefoxProfile;10public class DriverManager {11 private FirefoxDriver firefoxDriver;12 private ChromeDriver chromeDriver;13 private ResponseInterface responseInterface;14 public void setDriverInterface(ResponseInterface responseInterface) {15 this.responseInterface = responseInterface;16 }17 public DriverManager() {18 FirefoxProfile firefoxProfile = new FirefoxProfile();19 firefoxProfile.setPreference("permissions.default.image", 2);20 //firefoxProfile.addExtension(new File("addons\\multifox.xpi"));21 FirefoxOptions opt = new FirefoxOptions();22 opt.setProfile(firefoxProfile);23 FirefoxBinary firefoxBinary = new FirefoxBinary();24 firefoxBinary.addCommandLineOptions("--headless");25 //opt.setBinary(firefoxBinary);26 this.firefoxDriver = new FirefoxDriver(opt);27 //this.chromeDriver = new ChromeDriver();28 }29 public WebDriver getFirefoxDriver() {30 if (responseInterface != null) {31 responseInterface.onResponse("Driver Called...");32 }33 return firefoxDriver;34 }35 public WebDriver getChromeDriver() {36 if (responseInterface != null) {37 responseInterface.onResponse("Driver Called...");38 }39 return chromeDriver;40 }41}...

Full Screen

Full Screen

Source:OpenBrowser.java Github

copy

Full Screen

1package SeleniumPrograms;2import org.openqa.selenium.WebDriver;3import org.openqa.selenium.chrome.ChromeDriver;4import org.openqa.selenium.firefox.FirefoxDriver;5import org.openqa.selenium.firefox.GeckoDriverInfo;6public class OpenBrowser {7 public static void main(String[] args) throws Exception {8 9 //use alwas exception its a parent method10 // TODO Auto-generated method stub11 //System is a predefined class, .Set property is an extension method12 System.setProperty("webdriver.chrome.driver", "C:\\Driver\\chromedriver1.exe");13 14 /*System.setProperty("webdriver.gecko.driver", "C://Users//pavthrc//Desktop//Software//geckodriver//geckodriver.exe");15 WebDriver driver=new FirefoxDriver();*/16 17 //To Launch the chrome browser instance18 WebDriver driver=new ChromeDriver();19 20 //Manage is WebDriver method21 driver.manage().window().maximize();22 23 Thread.sleep(4000);24 25 //get is a Webelement operational methods which is used to open url .driver is a reference of webdriver interface26 driver.get("https://m.facebook.com/");27 28 //Sleep for 2 seconds29 Thread.sleep(3000);30 31 //To navigate to different Browser32 33 driver.navigate().to("https://www.google.com/");34 35 Thread.sleep(3000);36 37 //Refresh the page38 driver.navigate().refresh();39 40 //navigate backward41 driver.navigate().back();42 //navigate forward43 driver.navigate().forward();44 45 //To get Current URL46 String d=driver.getCurrentUrl();47 System.out.println(d);48 49 System.out.println(driver.getTitle());50 51 //when u want to close current window52 driver.close();53 54 //when u want to close all window instance55 driver.quit();56 }57}...

Full Screen

Full Screen

Interface Extension

Using AI Code Generation

copy

Full Screen

1package com.selenium;2import org.openqa.selenium.By;3import org.openqa.selenium.WebDriver;4import org.openqa.selenium.WebElement;5import org.openqa.selenium.firefox.FirefoxDriver;6import org.openqa.selenium.firefox.FirefoxProfile;7import org.openqa.selenium.internal.FindsByCssSelector;8import org.openqa.selenium.remote.RemoteWebDriver;9public class SeleniumTest {10 public static void main(String[] args) {11 FirefoxProfile profile = new FirefoxProfile();12 profile.setPreference("network.proxy.type", 1);13 profile.setPreference("network.proxy.http", "proxy.example.com");14 profile.setPreference("network.proxy.http_port", 8080);15 profile.setPreference("network.proxy.ssl", "proxy.example.com");16 profile.setPreference("network.proxy.ssl_port", 8080);17 WebDriver driver = new FirefoxDriver(profile);18 WebElement element = driver.findElement(By.cssSelector("input"));19 ((FindsByCssSelector) driver).findElementByCssSelector("input");20 }21}22 at com.selenium.SeleniumTest.main(SeleniumTest.java:27)23FirefoxDriver driver = new FirefoxDriver(profile);24Your name to display (optional):

Full Screen

Full Screen

Interface Extension

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.firefox.FirefoxDriver;2import org.openqa.selenium.firefox.FirefoxProfile;3import org.openqa.selenium.firefox.internal.ProfilesIni;4import org.openqa.selenium.remote.DesiredCapabilities;5public class FirefoxDriverExtension extends FirefoxDriver {6 public FirefoxDriverExtension(FirefoxProfile profile) {7 super(profile);8 }9 public FirefoxDriverExtension(DesiredCapabilities capabilities) {10 super(capabilities);11 }12}13ProfilesIni profile = new ProfilesIni();14FirefoxProfile myprofile = profile.getProfile("default");15FirefoxDriverExtension driver = new FirefoxDriverExtension(myprofile);

Full Screen

Full Screen

Interface Extension

Using AI Code Generation

copy

Full Screen

1package com.seleniumtest;2import org.openqa.selenium.WebDriver;3import org.openqa.selenium.firefox.FirefoxDriver;4import org.openqa.selenium.firefox.FirefoxProfile;5import org.openqa.selenium.firefox.internal.ProfilesIni;6public class FirefoxProfileTest {7 public static void main(String[] args) {8 ProfilesIni allProfiles=new ProfilesIni();9 FirefoxProfile profile=allProfiles.getProfile("default");10 WebDriver driver=new FirefoxDriver(profile);11 driver.quit();12 }13}14In the above code, we have used the FirefoxProfile class to create an object of FirefoxProfile class. Then, we have created an object of the ProfilesIni class and passed the FirefoxProfile object to the getProfile() method. This method takes a String argument that is the name of the profile. We have passed the default profile and then created an object of the Firefox

Full Screen

Full Screen

Interface Extension

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.firefox.FirefoxProfile;2import org.openqa.selenium.firefox.internal.ProfilesIni;3import org.openqa.selenium.firefox.FirefoxDriver;4import org.openqa.selenium.firefox.FirefoxDriver.SystemProperty;5import org.openqa.selenium.firefox.FirefoxOptions;6import org.openqa.selenium.Proxy;7import org.openqa.selenium.WebDriver;8public class FirefoxProxy {9 public static void main(String[] args) {10 ProfilesIni profile = new ProfilesIni();11 FirefoxProfile myprofile = profile.getProfile("default");12 myprofile.setPreference("network.proxy.type", 1);13 myprofile.setPreference("network.proxy.http", "localhost");14 myprofile.setPreference("network.proxy.http_port", 8888);15 myprofile.setPreference("network.proxy.ssl", "localhost");16 myprofile.setPreference("network.proxy.ssl_port", 8888);17 System.setProperty("webdriver.gecko.driver", "C:\\geckodriver.exe");18 FirefoxOptions options = new FirefoxOptions();19 options.setProfile(myprofile);20 WebDriver driver = new FirefoxDriver(options);21 driver.quit();22 }23}

Full Screen

Full Screen

Interface Extension

Using AI Code Generation

copy

Full Screen

1FirefoxProfile profile = new FirefoxProfile();2profile.setPreference("browser.download.folderList", 2);3profile.setPreference("browser.download.manager.showWhenStarting", false);4profile.setPreference("browser.download.dir", "C:\\Users\\Downloads");5profile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/zip");6FirefoxOptions options = new FirefoxOptions();7options.setProfile(profile);8WebDriver driver = new FirefoxDriver(options);9FirefoxProfile profile = new FirefoxProfile();10profile.setPreference("browser.download.folderList", 2);11profile.setPreference("browser.download.manager.showWhenStarting", false);12profile.setPreference("browser.download.dir", "C:\\Users\\Downloads");13profile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/zip");14WebDriver driver = new FirefoxDriver(profile);15FirefoxProfile profile = new FirefoxProfile();16profile.setPreference("browser.download.folderList", 2);17profile.setPreference("browser.download.manager.showWhenStarting", false);18profile.setPreference("browser.download.dir", "C:\\Users\\Downloads");19profile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/zip");20WebDriver driver = new FirefoxDriver(profile);21FirefoxProfile profile = new FirefoxProfile();22profile.setPreference("browser.download.folderList", 2);23profile.setPreference("browser.download.manager.showWhenStarting", false);24profile.setPreference("browser.download.dir", "C:\\Users\\Downloads");25profile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/

Full Screen

Full Screen
copy
1Objects.requireNonNull(someObject);2someObject.doCalc();3
Full Screen

Selenium 4 Tutorial:

LambdaTest’s Selenium 4 tutorial is covering every aspects of Selenium 4 testing with examples and best practices. Here you will learn basics, such as how to upgrade from Selenium 3 to Selenium 4, to some advanced concepts, such as Relative locators and Selenium Grid 4 for Distributed testing. Also will learn new features of Selenium 4, such as capturing screenshots of specific elements, opening a new tab or window on the browser, and new protocol adoptions.

Chapters:

  1. Upgrading From Selenium 3 To Selenium 4?: In this chapter, learn in detail how to update Selenium 3 to Selenium 4 for Java binding. Also, learn how to upgrade while using different build tools such as Maven or Gradle and get comprehensive guidance for upgrading Selenium.

  2. What’s New In Selenium 4 & What’s Being Deprecated? : Get all information about new implementations in Selenium 4, such as W3S protocol adaption, Optimized Selenium Grid, and Enhanced Selenium IDE. Also, learn what is deprecated for Selenium 4, such as DesiredCapabilites and FindsBy methods, etc.

  3. Selenium 4 With Python: Selenium supports all major languages, such as Python, C#, Ruby, and JavaScript. In this chapter, learn how to install Selenium 4 for Python and the features of Python in Selenium 4, such as Relative locators, Browser manipulation, and Chrom DevTool protocol.

  4. Selenium 4 Is Now W3C Compliant: JSON Wireframe protocol is retiring from Selenium 4, and they are adopting W3C protocol to learn in detail about the advantages and impact of these changes.

  5. How To Use Selenium 4 Relative Locator? : Selenium 4 came with new features such as Relative Locators that allow constructing locators with reference and easily located constructors nearby. Get to know its different use cases with examples.

  6. Selenium Grid 4 Tutorial For Distributed Testing: Selenium Grid 4 allows you to perform tests over different browsers, OS, and device combinations. It also enables parallel execution browser testing, reads up on various features of Selenium Grid 4 and how to download it, and runs a test on Selenium Grid 4 with best practices.

  7. Selenium Video Tutorials: Binge on video tutorials on Selenium by industry experts to get step-by-step direction from automating basic to complex test scenarios with Selenium.

Selenium 101 certifications:

LambdaTest also provides certification for Selenium testing to accelerate your career in Selenium automation testing.

Run Selenium automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

...Most popular Stackoverflow questions on Interface-Extension

Most used methods in Interface-Extension

Test Your Web Or Mobile Apps On 3000+ Browsers

Signup for free

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful