How to use credentials method of org.openqa.selenium.remote.http.ClientConfig class

Best Selenium code snippet using org.openqa.selenium.remote.http.ClientConfig.credentials

Source:RemoteWebDriverBuilder.java Github

copy

Full Screen

...119 };120 private ClientConfig clientConfig = ClientConfig.defaultConfig();121 private URI remoteHost = null;122 private DriverService driverService;123 private Credentials credentials = null;124 RemoteWebDriverBuilder() {125 // Access through RemoteWebDriver.builder126 }127 /**128 * Clears the current set of alternative browsers and instead sets the list of possible choices to129 * the arguments given to this method.130 */131 public RemoteWebDriverBuilder oneOf(Capabilities maybeThis, Capabilities... orOneOfThese) {132 Require.nonNull("Capabilities to use", maybeThis);133 if (!requestedCapabilities.isEmpty()) {134 LOG.log(getDebugLogLevel(), "Removing existing requested capabilities: " + requestedCapabilities);135 requestedCapabilities.clear();136 }137 addAlternative(maybeThis);138 for (Capabilities caps : orOneOfThese) {139 Require.nonNull("Capabilities to use", caps);140 addAlternative(caps);141 }142 return this;143 }144 /**145 * Add to the list of possible configurations that might be asked for. It is possible to ask for146 * more than one type of browser per session. For example, perhaps you have an extension that is147 * available for two different kinds of browser, and you'd like to test it).148 */149 public RemoteWebDriverBuilder addAlternative(Capabilities options) {150 Require.nonNull("Capabilities to use", options);151 requestedCapabilities.add(new ImmutableCapabilities(options));152 return this;153 }154 /**155 * Adds metadata to the outgoing new session request, which can be used by intermediary of end156 * nodes for any purpose they choose (commonly, this is used to request additional features from157 * cloud providers, such as video recordings or to set the timezone or screen size). Neither158 * parameter can be {@code null}.159 */160 public RemoteWebDriverBuilder addMetadata(String key, Object value) {161 Require.nonNull("Metadata key", key);162 Require.nonNull("Metadata value", value);163 if (ILLEGAL_METADATA_KEYS.contains(key)) {164 throw new IllegalArgumentException(String.format("Cannot add %s as metadata key", key));165 }166 Object previous = metadata.put(key, value);167 if (previous != null) {168 LOG.log(169 getDebugLogLevel(),170 String.format("Overwriting metadata %s. Previous value %s, new value %s", key, previous, value));171 }172 return this;173 }174 /**175 * Sets a capability for every single alternative when the session is created. These capabilities176 * are only set once the session is created, so this will be set on capabilities added via177 * {@link #addAlternative(Capabilities)} or {@link #oneOf(Capabilities, Capabilities...)} even178 * after this method call.179 */180 public RemoteWebDriverBuilder setCapability(String capabilityName, Object value) {181 Require.nonNull("Capability name", capabilityName);182 Require.nonNull("Capability value", value);183 Object previous = additionalCapabilities.put(capabilityName, value);184 if (previous != null) {185 LOG.log(186 getDebugLogLevel(),187 String.format("Overwriting capability %s. Previous value %s, new value %s", capabilityName, previous, value));188 }189 return this;190 }191 /**192 * @see #address(URI)193 */194 public RemoteWebDriverBuilder address(String uri) {195 Require.nonNull("Address", uri);196 try {197 return address(new URI(uri));198 } catch (URISyntaxException e) {199 throw new IllegalArgumentException("Unable to create URI from " + uri);200 }201 }202 /**203 * @see #address(URI)204 */205 public RemoteWebDriverBuilder address(URL url) {206 Require.nonNull("Address", url);207 try {208 return address(url.toURI());209 } catch (URISyntaxException e) {210 throw new IllegalArgumentException("Unable to create URI from " + url);211 }212 }213 /**214 * Set the URI of the remote server. If this URI is not set, then it assumed that a local running215 * remote webdriver session is needed. It is an error to call this method and also216 * {@link #withDriverService(DriverService)}.217 */218 public RemoteWebDriverBuilder address(URI uri) {219 Require.nonNull("URI", uri);220 if (driverService != null || (clientConfig.baseUri() != null && !clientConfig.baseUri().equals(uri))) {221 throw new IllegalArgumentException(222 "Attempted to set the base uri on both this builder and the http client config. " +223 "Please set in only one place. " + uri);224 }225 remoteHost = uri;226 return this;227 }228 public RemoteWebDriverBuilder authenticateAs(UsernameAndPassword usernameAndPassword) {229 Require.nonNull("User name and password", usernameAndPassword);230 this.credentials = usernameAndPassword;231 return this;232 }233 /**234 * Allows precise control of the {@link ClientConfig} to use with remote235 * instances. If {@link ClientConfig#baseUri(URI)} has been called, then236 * that will be used as the base URI for the session.237 */238 public RemoteWebDriverBuilder config(ClientConfig config) {239 Require.nonNull("HTTP client config", config);240 if (config.baseUri() != null) {241 if (remoteHost != null || driverService != null) {242 throw new IllegalArgumentException("Base URI has already been set. Cannot also set it via client config");243 }244 }245 this.clientConfig = config;246 return this;247 }248 /**249 * Use the given {@link DriverService} to set up the webdriver instance. It is an error to set250 * both this and also call {@link #address(URI)}.251 */252 public RemoteWebDriverBuilder withDriverService(DriverService service) {253 Require.nonNull("Driver service", service);254 if (clientConfig.baseUri() != null || remoteHost != null) {255 throw new IllegalArgumentException("Base URI has already been set. Cannot also set driver service.");256 }257 this.driverService = service;258 return this;259 }260 @VisibleForTesting261 RemoteWebDriverBuilder connectingWith(Function<ClientConfig, HttpHandler> handlerFactory) {262 Require.nonNull("Handler factory", handlerFactory);263 this.handlerFactory = handlerFactory;264 return this;265 }266 @VisibleForTesting267 WebDriver getLocalDriver() {268 if (remoteHost != null || clientConfig.baseUri() != null || driverService != null) {269 return null;270 }271 Set<WebDriverInfo> infos = StreamSupport.stream(272 ServiceLoader.load(WebDriverInfo.class).spliterator(),273 false)274 .filter(WebDriverInfo::isAvailable)275 .collect(Collectors.toSet());276 Capabilities additional = new ImmutableCapabilities(additionalCapabilities);277 Optional<Supplier<WebDriver>> first = requestedCapabilities.stream()278 .map(caps -> caps.merge(additional))279 .flatMap(caps ->280 infos.stream()281 .filter(WebDriverInfo::isAvailable)282 .filter(info -> info.isSupporting(caps))283 .map(info -> (Supplier<WebDriver>) () -> info.createDriver(caps)284 .orElseThrow(() -> new SessionNotCreatedException("Unable to create session with " + caps))))285 .findFirst();286 if (!first.isPresent()) {287 throw new SessionNotCreatedException("Unable to find matching driver for capabilities");288 }289 return first.get().get();290 }291 /**292 * Actually create a new WebDriver session. The returned webdriver is not guaranteed to be a293 * {@link RemoteWebDriver}.294 */295 public WebDriver build() {296 if (requestedCapabilities.isEmpty() && additionalCapabilities.isEmpty()) {297 throw new SessionNotCreatedException("One set of browser options must be specified");298 }299 Set<String> clobberedCapabilities = getClobberedCapabilities();300 if (!clobberedCapabilities.isEmpty()) {301 throw new IllegalArgumentException(String.format(302 "Unable to create session. Additional capabilities %s overwrite capabilities in requested options",303 clobberedCapabilities));304 }305 WebDriver driver = getLocalDriver();306 if (driver == null) {307 driver = getRemoteDriver();308 }309 return new Augmenter().augment(driver);310 }311 private WebDriver getRemoteDriver() {312 startDriverServiceIfNecessary();313 ClientConfig driverClientConfig = clientConfig;314 URI baseUri = getBaseUri();315 if (baseUri != null) {316 driverClientConfig = driverClientConfig.baseUri(baseUri);317 }318 if (credentials != null) {319 driverClientConfig = driverClientConfig.authenticateAs(credentials);320 }321 HttpHandler client = handlerFactory.apply(driverClientConfig);322 HttpHandler handler = Require.nonNull("Http handler", client)323 .with(new CloseHttpClientFilter(client)324 .andThen(new AddWebDriverSpecHeaders())325 .andThen(new ErrorFilter())326 .andThen(new DumpHttpExchangeFilter()));327 Either<SessionNotCreatedException, ProtocolHandshake.Result> result = null;328 try {329 result = new ProtocolHandshake().createSession(handler, getPayload());330 } catch (IOException e) {331 throw new SessionNotCreatedException("Unable to create new remote session.", e);332 }333 if (result.isRight()) {...

Full Screen

Full Screen

Source:ChromiumDriver.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.chromium;18import com.google.common.collect.ImmutableMap;19import org.openqa.selenium.BuildInfo;20import org.openqa.selenium.Capabilities;21import org.openqa.selenium.Credentials;22import org.openqa.selenium.HasAuthentication;23import org.openqa.selenium.ImmutableCapabilities;24import org.openqa.selenium.PersistentCapabilities;25import org.openqa.selenium.WebDriver;26import org.openqa.selenium.WebDriverException;27import org.openqa.selenium.devtools.CdpEndpointFinder;28import org.openqa.selenium.devtools.CdpInfo;29import org.openqa.selenium.devtools.CdpVersionFinder;30import org.openqa.selenium.devtools.Connection;31import org.openqa.selenium.devtools.DevTools;32import org.openqa.selenium.devtools.HasDevTools;33import org.openqa.selenium.devtools.noop.NoOpCdpInfo;34import org.openqa.selenium.html5.LocalStorage;35import org.openqa.selenium.html5.Location;36import org.openqa.selenium.html5.LocationContext;37import org.openqa.selenium.html5.SessionStorage;38import org.openqa.selenium.html5.WebStorage;39import org.openqa.selenium.interactions.HasTouchScreen;40import org.openqa.selenium.interactions.TouchScreen;41import org.openqa.selenium.internal.Require;42import org.openqa.selenium.logging.EventType;43import org.openqa.selenium.logging.HasLogEvents;44import org.openqa.selenium.mobile.NetworkConnection;45import org.openqa.selenium.remote.CommandExecutor;46import org.openqa.selenium.remote.FileDetector;47import org.openqa.selenium.remote.RemoteTouchScreen;48import org.openqa.selenium.remote.RemoteWebDriver;49import org.openqa.selenium.remote.html5.RemoteLocationContext;50import org.openqa.selenium.remote.html5.RemoteWebStorage;51import org.openqa.selenium.remote.http.ClientConfig;52import org.openqa.selenium.remote.http.HttpClient;53import org.openqa.selenium.remote.mobile.RemoteNetworkConnection;54import java.net.URI;55import java.util.Map;56import java.util.Optional;57import java.util.function.Predicate;58import java.util.function.Supplier;59import java.util.logging.Logger;60/**61 * A {@link WebDriver} implementation that controls a Chromium browser running on the local machine.62 * It is used as the base class for Chromium-based browser drivers (Chrome, Edgium).63 */64public class ChromiumDriver extends RemoteWebDriver implements65 HasAuthentication,66 HasDevTools,67 HasLogEvents,68 HasTouchScreen,69 LocationContext,70 NetworkConnection,71 WebStorage {72 private static final Logger LOG = Logger.getLogger(ChromiumDriver.class.getName());73 private final Capabilities capabilities;74 private final RemoteLocationContext locationContext;75 private final RemoteWebStorage webStorage;76 private final TouchScreen touchScreen;77 private final RemoteNetworkConnection networkConnection;78 private final Optional<Connection> connection;79 private final Optional<DevTools> devTools;80 protected ChromiumDriver(CommandExecutor commandExecutor, Capabilities capabilities, String capabilityKey) {81 super(commandExecutor, capabilities);82 locationContext = new RemoteLocationContext(getExecuteMethod());83 webStorage = new RemoteWebStorage(getExecuteMethod());84 touchScreen = new RemoteTouchScreen(getExecuteMethod());85 networkConnection = new RemoteNetworkConnection(getExecuteMethod());86 HttpClient.Factory factory = HttpClient.Factory.createDefault();87 Capabilities originalCapabilities = super.getCapabilities();88 Optional<URI> cdpUri = CdpEndpointFinder.getReportedUri(capabilityKey, originalCapabilities)89 .flatMap(uri -> CdpEndpointFinder.getCdpEndPoint(factory, uri));90 connection = cdpUri.map(uri -> new Connection(91 factory.createClient(ClientConfig.defaultConfig().baseUri(uri)),92 uri.toString()));93 CdpInfo cdpInfo = new CdpVersionFinder().match(originalCapabilities.getBrowserVersion())94 .orElseGet(() -> {95 LOG.warning(96 String.format(97 "Unable to find version of CDP to use for %s. You may need to " +98 "include a dependency on a specific version of the CDP using " +99 "something similar to " +100 "`org.seleniumhq.selenium:selenium-devtools-v86:%s` where the " +101 "version (\"v86\") matches the version of the chromium-based browser " +102 "you're using and the version number of the artifact is the same " +103 "as Selenium's.",104 capabilities.getBrowserVersion(),105 new BuildInfo().getReleaseLabel()));106 return new NoOpCdpInfo();107 });108 devTools = connection.map(conn -> new DevTools(cdpInfo::getDomains, conn));109 this.capabilities = cdpUri.map(uri -> new ImmutableCapabilities(110 new PersistentCapabilities(originalCapabilities)111 .setCapability("se:cdp", uri.toString())112 .setCapability(113 "se:cdpVersion", originalCapabilities.getBrowserVersion())))114 .orElse(new ImmutableCapabilities(originalCapabilities));115 }116 @Override117 public Capabilities getCapabilities() {118 return capabilities;119 }120 @Override121 public void setFileDetector(FileDetector detector) {122 throw new WebDriverException(123 "Setting the file detector only works on remote webdriver instances obtained " +124 "via RemoteWebDriver");125 }126 @Override127 public <X> void onLogEvent(EventType<X> kind) {128 Require.nonNull("Event type", kind);129 kind.initializeListener(this);130 }131 @Override132 public void register(Predicate<URI> whenThisMatches, Supplier<Credentials> useTheseCredentials) {133 Require.nonNull("Check to use to see how we should authenticate", whenThisMatches);134 Require.nonNull("Credentials to use when authenticating", useTheseCredentials);135 getDevTools().createSessionIfThereIsNotOne();136 getDevTools().getDomains().network().addAuthHandler(whenThisMatches, useTheseCredentials);137 }138 @Override139 public LocalStorage getLocalStorage() {140 return webStorage.getLocalStorage();141 }142 @Override143 public SessionStorage getSessionStorage() {144 return webStorage.getSessionStorage();145 }146 @Override147 public Location location() {148 return locationContext.location();149 }150 @Override151 public void setLocation(Location location) {152 locationContext.setLocation(location);153 }154 @Override155 public TouchScreen getTouch() {156 return touchScreen;157 }158 @Override159 public ConnectionType getNetworkConnection() {160 return networkConnection.getNetworkConnection();161 }162 @Override163 public ConnectionType setNetworkConnection(ConnectionType type) {164 return networkConnection.setNetworkConnection(type);165 }166 /**167 * Launches Chrome app specified by id.168 *169 * @param id Chrome app id.170 */171 public void launchApp(String id) {172 execute(ChromiumDriverCommand.LAUNCH_APP, ImmutableMap.of("id", id));173 }174 /**175 * Execute a Chrome Devtools Protocol command and get returned result. The176 * command and command args should follow177 * <a href="https://chromedevtools.github.io/devtools-protocol/">chrome178 * devtools protocol domains/commands</a>.179 */180 public Map<String, Object> executeCdpCommand(String commandName, Map<String, Object> parameters) {181 Require.nonNull("Command name", commandName);182 Require.nonNull("Parameters", parameters);183 @SuppressWarnings("unchecked")184 Map<String, Object> toReturn = (Map<String, Object>) getExecuteMethod().execute(185 ChromiumDriverCommand.EXECUTE_CDP_COMMAND,186 ImmutableMap.of("cmd", commandName, "params", parameters));187 return ImmutableMap.copyOf(toReturn);188 }189 @Override190 public DevTools getDevTools() {191 return devTools.orElseThrow(() -> new WebDriverException("Unable to create DevTools connection"));192 }193 public String getCastSinks() {194 Object response = getExecuteMethod().execute(ChromiumDriverCommand.GET_CAST_SINKS, null);195 return response.toString();196 }197 public String getCastIssueMessage() {198 Object response = getExecuteMethod().execute(ChromiumDriverCommand.GET_CAST_ISSUE_MESSAGE, null);199 return response.toString();200 }201 public void selectCastSink(String deviceName) {202 getExecuteMethod().execute(ChromiumDriverCommand.SET_CAST_SINK_TO_USE, ImmutableMap.of("sinkName", deviceName));203 }204 public void startTabMirroring(String deviceName) {205 getExecuteMethod().execute(ChromiumDriverCommand.START_CAST_TAB_MIRRORING, ImmutableMap.of("sinkName", deviceName));206 }207 public void stopCasting(String deviceName) {208 getExecuteMethod().execute(ChromiumDriverCommand.STOP_CASTING, ImmutableMap.of("sinkName", deviceName));209 }210 public void setPermission(String name, String value) {211 getExecuteMethod().execute(ChromiumDriverCommand.SET_PERMISSION,212 ImmutableMap.of("descriptor", ImmutableMap.of("name", name), "state", value));213 }214 @Override215 public void quit() {216 connection.ifPresent(Connection::close);217 super.quit();218 }219}...

Full Screen

Full Screen

Source:NettyWebSocket.java Github

copy

Full Screen

...111 Request nettyReq = NettyMessages.toNettyRequest(112 config.baseUri(),113 toClampedInt(config.readTimeout().toMillis()),114 toClampedInt(config.readTimeout().toMillis()),115 config.credentials(),116 filtered);117 return new NettyWebSocket(client, nettyReq, listener);118 };119 }120 @Override121 public WebSocket send(Message message) {122 if (message instanceof BinaryMessage) {123 socket.sendBinaryFrame(((BinaryMessage) message).data());124 } else if (message instanceof CloseMessage) {125 socket.sendCloseFrame(((CloseMessage) message).code(), ((CloseMessage) message).reason());126 } else if (message instanceof TextMessage) {127 socket.sendTextFrame(((TextMessage) message).text());128 }129 return this;...

Full Screen

Full Screen

Source:NettyClient.java Github

copy

Full Screen

...87 .setConnectTimeout(toClampedInt(config.connectionTimeout().toMillis()))88 .setReadTimeout(toClampedInt(config.readTimeout().toMillis()))89 .setUseProxyProperties(true)90 .setUseProxySelector(true);91 if (config.credentials() != null) {92 Credentials credentials = config.credentials();93 if (!(credentials instanceof UsernameAndPassword)) {94 throw new IllegalArgumentException("Credentials must be a username and password");95 }96 UsernameAndPassword uap = (UsernameAndPassword) credentials;97 builder.setRealm(new Realm.Builder(uap.username(), uap.password()).setUsePreemptiveAuth(true));98 }99 return Dsl.asyncHttpClient(builder);100 }101 @Override102 public HttpResponse execute(HttpRequest request) {103 return handler.execute(request);104 }105 @Override106 public WebSocket openSocket(HttpRequest request, WebSocket.Listener listener) {107 Require.nonNull("Request to send", request);108 Require.nonNull("WebSocket listener", listener);109 return toWebSocket.apply(request, listener);110 }...

Full Screen

Full Screen

Source:ClientConfig.java Github

copy

Full Screen

...30 private final Duration connectionTimeout;31 private final Duration readTimeout;32 private final Filter filters;33 private final Proxy proxy;34 private final Credentials credentials;35 private ClientConfig(36 URI baseUri,37 Duration connectionTimeout,38 Duration readTimeout,39 Filter filters,40 Proxy proxy,41 Credentials credentials) {42 this.baseUri = baseUri;43 this.connectionTimeout = Require.nonNegative("Connection timeout", connectionTimeout);44 this.readTimeout = Require.nonNegative("Read timeout", readTimeout);45 this.filters = Require.nonNull("Filters", filters);46 this.proxy = proxy;47 this.credentials = credentials;48 }49 public static ClientConfig defaultConfig() {50 return new ClientConfig(51 null,52 Duration.ofSeconds(10),53 Duration.ofMinutes(3),54 new AddSeleniumUserAgent(),55 null,56 null);57 }58 public ClientConfig baseUri(URI baseUri) {59 return new ClientConfig(60 Require.nonNull("Base URI", baseUri),61 connectionTimeout,62 readTimeout,63 filters,64 proxy,65 credentials);66 }67 public ClientConfig baseUrl(URL baseUrl) {68 try {69 return baseUri(Require.nonNull("Base URL", baseUrl).toURI());70 } catch (URISyntaxException e) {71 throw new RuntimeException(e);72 }73 }74 public URI baseUri() {75 return baseUri;76 }77 public URL baseUrl() {78 try {79 return baseUri().toURL();80 } catch (MalformedURLException e) {81 throw new UncheckedIOException(e);82 }83 }84 public ClientConfig connectionTimeout(Duration timeout) {85 return new ClientConfig(86 baseUri,87 Require.nonNull("Connection timeout", timeout),88 readTimeout,89 filters,90 proxy,91 credentials);92 }93 public Duration connectionTimeout() {94 return connectionTimeout;95 }96 public ClientConfig readTimeout(Duration timeout) {97 return new ClientConfig(98 baseUri,99 connectionTimeout,100 Require.nonNull("Read timeout", timeout),101 filters,102 proxy,103 credentials);104 }105 public Duration readTimeout() {106 return readTimeout;107 }108 public ClientConfig withFilter(Filter filter) {109 return new ClientConfig(110 baseUri,111 connectionTimeout,112 readTimeout,113 filter == null ? DEFAULT_FILTER : filter.andThen(DEFAULT_FILTER),114 proxy,115 credentials);116 }117 public Filter filter() {118 return filters;119 }120 public ClientConfig proxy(Proxy proxy) {121 return new ClientConfig(122 baseUri,123 connectionTimeout,124 readTimeout,125 filters,126 Require.nonNull("Proxy", proxy),127 credentials);128 }129 public Proxy proxy() {130 return proxy;131 }132 public ClientConfig authenticateAs(Credentials credentials) {133 return new ClientConfig(134 baseUri,135 connectionTimeout,136 readTimeout,137 filters,138 proxy,139 Require.nonNull("Credentials", credentials));140 }141 public Credentials credentials() {142 return credentials;143 }144 @Override145 public String toString() {146 return "ClientConfig{" +147 "baseUri=" + baseUri +148 ", connectionTimeout=" + connectionTimeout +149 ", readTimeout=" + readTimeout +150 ", filters=" + filters +151 ", proxy=" + proxy +152 ", credentials=" + credentials +153 '}';154 }155}...

Full Screen

Full Screen

Source:NettyHttpHandler.java Github

copy

Full Screen

...48 NettyMessages.toNettyRequest(49 getConfig().baseUri(),50 toClampedInt(getConfig().readTimeout().toMillis()),51 toClampedInt(getConfig().readTimeout().toMillis()),52 getConfig().credentials(),53 request));54 try {55 Response response = whenResponse.get(getConfig().readTimeout().toMillis(), TimeUnit.MILLISECONDS);56 return NettyMessages.toSeleniumResponse(response);57 } catch (InterruptedException e) {58 Thread.currentThread().interrupt();59 throw new RuntimeException("NettyHttpHandler request interrupted", e);60 } catch (TimeoutException e) {61 throw new org.openqa.selenium.TimeoutException(e);62 } catch (ExecutionException e) {63 Throwable cause = e.getCause();64 if (cause instanceof UncheckedIOException) {65 throw (UncheckedIOException) cause;66 }...

Full Screen

Full Screen

Source:CreateOkClient.java Github

copy

Full Screen

...38 if (!Strings.isNullOrEmpty(info)) {39 String[] parts = info.split(":", 2);40 String user = parts[0];41 String pass = parts.length > 1 ? parts[1] : null;42 String credentials = Credentials.basic(user, pass);43 client.authenticator((route, response) -> {44 if (response.request().header("Authorization") != null) {45 return null; // Give up, we've already attempted to authenticate.46 }47 return response.request().newBuilder()48 .header("Authorization", credentials)49 .build();50 });51 }52 client.addNetworkInterceptor(chain -> {53 Request request = chain.request();54 Response response = chain.proceed(request);55 return response.code() == 40856 ? response.newBuilder().code(500).message("Server-Side Timeout").build()57 : response;58 });59 return client.build();60 }61}...

Full Screen

Full Screen

Source:OkHandler.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.remote.http.okhttp;18import static java.util.concurrent.TimeUnit.MILLISECONDS;19import com.google.common.base.Strings;20import org.openqa.selenium.remote.http.ClientConfig;21import org.openqa.selenium.remote.http.HttpHandler;22import org.openqa.selenium.remote.http.HttpRequest;23import org.openqa.selenium.remote.http.HttpResponse;24import org.openqa.selenium.remote.http.RemoteCall;25import okhttp3.Credentials;26import okhttp3.OkHttpClient;27import okhttp3.Request;28import okhttp3.Response;29import java.io.IOException;30import java.io.UncheckedIOException;31import java.util.Objects;32public class OkHandler extends RemoteCall {33 private final OkHttpClient client;34 private final HttpHandler handler;35 public OkHandler(ClientConfig config) {36 super(config);37 this.client = new CreateOkClient().apply(config);38 this.handler = config.filter().andFinally(this::makeCall);39 }40 @Override41 public HttpResponse execute(HttpRequest request) {42 return handler.execute(request);43 }44 private HttpResponse makeCall(HttpRequest request) {45 Objects.requireNonNull(request, "Request must be set.");46 try {47 Request okReq = OkMessages.toOkHttpRequest(getConfig().baseUri(), request);48 Response response = client.newCall(okReq).execute();49 return OkMessages.toSeleniumResponse(response);50 } catch (IOException e) {51 throw new UncheckedIOException(e);52 }53 }54}...

Full Screen

Full Screen

credentials

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.remote.http.ClientConfig;2import org.openqa.selenium.remote.http.HttpClient;3import org.openqa.selenium.remote.http.HttpRequest;4import org.openqa.selenium.remote.http.HttpResponse;5import org.openqa.selenium.remote.http.W3CHttpCommandCodec;6import org.openqa.selenium.remote.http.W3CHttpResponseCodec;7import java.io.IOException;8import java.net.URI;9import java.util.Base64;10import java.util.HashMap;11import java.util.Map;12public class CredentialsExample {13 public static void main(String[] args) throws IOException {14 HttpClient client = HttpClient.Factory.createDefault().createClient(new ClientConfig().setCredentials("username", "password"));15 HttpRequest request = new HttpRequest("POST", "/session");16 request.setContent(W3CHttpCommandCodec.encode(new HashMap<String, Object>() {{17 put("capabilities", new HashMap<String, Object>() {{18 put("alwaysMatch", new HashMap<String, Object>() {{19 put("browserName", "chrome");20 }});21 }});22 }}));23 Map<String, Object> decoded = W3CHttpResponseCodec.decode(response);24 System.out.println(decoded);25 }26}27{value={sessionId=9d9e0d1f-5b7a-4c0d-a0f6-8a6c7f6d0c9a, capabilities={acceptInsecureCerts=false, browserName=chrome, browserVersion=91.0.4472.114, chrome={chromedriverVersion=91.0.4472.101 (2b4f4c4b4d4e4c3f3e8b8d4afdf6b3d9c7b6f1c6-refs/branch-heads/4472@{#1008}), userDataDir=/tmp/.com.google.Chrome.7PvFjK}, goog:chromeOptions={debuggerAddress=localhost:44901}, networkConnectionEnabled=false, pageLoadStrategy=normal, platformName=linux, proxy={}, setWindowRect=true, strictFileInteractability=false, timeouts={implicit=0, pageLoad=300000, script=30000}, unhandledPromptBehavior=dismiss and notify, webauthn:extension:largeBlob=true, webauthn:virtualAuthenticators=true}}}

Full Screen

Full Screen

credentials

Using AI Code Generation

copy

Full Screen

1package com.test;2import java.net.MalformedURLException;3import java.net.URL;4import org.openqa.selenium.WebDriver;5import org.openqa.selenium.remote.CapabilityType;6import org.openqa.selenium.remote.DesiredCapabilities;7import org.openqa.selenium.remote.http.ClientConfig;8import org.openqa.selenium.remote.http.HttpClient;9import org.openqa.selenium.remote.http.HttpClient.Factory;10import org.openqa.selenium.remote.http.HttpRequest;11import org.openqa.selenium.remote.http.HttpResponse;12import org.openqa.selenium.remote.http.WebSocket;13import org.openqa.selenium.remote.http.WebSocket.Factory;14import org.openqa.selenium.remote.http.WebSocket.Listener;15import org.openqa.selenium.remote.http.WebSocketClient;16import org.openqa.selenium.remote.http.WebSocketClient.Factory;17import org.openqa.selenium.remote.http.WebSocketMessage;18import org.openqa.selenium.remote.http.WebSocketMessage.Text;19import org.openqa.selenium.remote.http.WebSocketMessage.Type;20import org.openqa.selenium.remote.http.WebSocketMessage.Type;21import io.appium.java_client.android.AndroidDriver;22import io.appium.java_client.remote.MobileCapabilityType;23public class Test {24 public static void main(String[] args) throws MalformedURLException {25 DesiredCapabilities capabilities = new DesiredCapabilities();26 capabilities.setCapability(MobileCapabilityType.PLATFORM_NAME, "Android");27 capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "Android Emulator");28 capabilities.setCapability(MobileCapabilityType.BROWSER_NAME, "Chrome");29 capabilities.setCapability(MobileCapabilityType.NEW_COMMAND_TIMEOUT, "100");30 capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);31 capabilities.setCapability(MobileCapabilityType.VERSION, "6.0");32 capabilities.setCapability("chromedriverExecutable", "C:\\Users\\user\\Desktop\\chromedriver.exe");33 capabilities.setCapability("appium:chromeOptions", "{args:[--ignore-certificate-errors]}");34 capabilities.setCapability("appium:chromeOptions", "{args:[--disable-popup-blocking]}");35 capabilities.setCapability("appium:chromeOptions", "{args:[--disable-notifications]}");36 capabilities.setCapability("appium:chromeOptions", "{args:[--disable-infobars]}");37 capabilities.setCapability("appium:chromeOptions", "{args:[--disable-extensions]}");38 capabilities.setCapability("appium:chromeOptions", "{args:[--disable-dev-shm

Full Screen

Full Screen

credentials

Using AI Code Generation

copy

Full Screen

1import java.net.InetSocketAddress2import java.net.Proxy3import java.net.ProxySelector4import java.net.URI5import java.util.Collections6import java.util.List7import java.util.stream.Collectors8import org.openqa.selenium.Proxy9import org.openqa.selenium.remote.http.ClientConfig10import org.openqa.selenium.remote.http.HttpClient11import org.openqa.selenium.remote.http.HttpMethod12import org.openqa.selenium.remote.http.HttpRequest13import org.openqa.selenium.remote.http.HttpResponse14import org.openqa.selenium.remote.http.WebSocket15import org.openqa.selenium.remote.http.WebSocketClient16import org.openqa.selenium.remote.http.WebSocketFactory17import org.openqa.selenium.remote.http.WebSocketListener18import org.openqa.selenium.remote.http.WebSocketMessage19import org.openqa.selenium.remote.http.WebSocketMessageType20import org.openqa.selenium.remote.http.WrappingClient21import org.openqa.selenium.remote.http.WrappingWebSocketFactory22import org.openqa.selenium.remote.http.WrappingWebSocketListener23class ProxyClientConfig extends ClientConfig {24 ProxyClientConfig(Proxy proxy) {25 }26 HttpClient toHttpClient() {27 return new ProxyClient(super.toHttpClient(), proxy)28 }29 WebSocketFactory toWebSocketFactory() {30 return new WrappingWebSocketFactory(super.toWebSocketFactory()) {31 WebSocket createSocket(URI uri, WebSocketListener listener) {32 return new ProxyWebSocket(super.createSocket(uri, listener), proxy)33 }34 }35 }36}37class ProxyClient extends WrappingClient {38 ProxyClient(HttpClient client, Proxy proxy) {39 super(client)40 }41 HttpResponse execute(HttpRequest req) {42 return super.execute(req, proxy)43 }44}45class ProxyWebSocket extends WebSocket {46 ProxyWebSocket(WebSocket delegate, Proxy proxy) {47 }48 void sendText(CharSequence data) {49 delegate.sendText(data)50 }51 void sendBinary(byte[] data) {52 delegate.sendBinary(data)53 }54 void sendPing(byte[] data) {55 delegate.sendPing(data)56 }57 void sendPong(byte[] data) {58 delegate.sendPong(data)59 }

Full Screen

Full Screen

credentials

Using AI Code Generation

copy

Full Screen

1driverManagerType . setDriverVersion ( "2.16" );2driverManagerType . setBrowserVersion ( "2.16" );3driverManagerType . setDriverManagerClass ( "io.github.bonigarcia.wdm.ChromeDriverManager" );4driverManagerType . setDriverManagerVersion ( "1.4.1" );5driverManagerType . setDriverManagerClass ( "io.github.bonigarcia.wdm.ChromeDriverManager" );6driverManagerType . setDriverManagerVersion ( "1.4.1" );7driverManagerType . setBrowserVersion ( "2.16" );8driverManagerType . setDriverManagerClass ( "io.github.bonigarcia.wdm.ChromeDriverManager" );9driverManagerType . setDriverManagerVersion ( "1.4.1" );10driverManagerType . setBrowserVersion ( "2.16" );11driverManagerType . setDriverManagerClass ( "io.github.bonigarcia.wdm.ChromeDriverManager" );12driverManagerType . setDriverManagerVersion ( "1.4.1" );13driverManagerType . setBrowserVersion ( "2.16" );14driverManagerType . setDriverManagerClass ( "io.github.bonigarcia.wdm.ChromeDriverManager" );15driverManagerType . setDriverManagerVersion ( "1.4.1" );16driverManagerType . setBrowserVersion ( "2.16" );17driverManagerType . setDriverManagerClass ( "io.github.bonigarcia.wdm.ChromeDriverManager" );18driverManagerType . setDriverManagerVersion ( "1.4.1" );19driverManagerType . setBrowserVersion ( "2.16" );20driverManagerType . setDriverManagerClass ( "io.github.bonigarcia.wdm.ChromeDriverManager" );21driverManagerType . setDriverManagerVersion ( "1.4.1" );22driverManagerType . setBrowserVersion ( "2.16" );23driverManagerType . setDriverManagerClass ( "io.github.bonigarcia.wdm.ChromeDriverManager" );

Full Screen

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.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful