How to use AcceptedW3CCapabilityKeys class of org.openqa.selenium.remote package

Best Selenium code snippet using org.openqa.selenium.remote.AcceptedW3CCapabilityKeys

Run Selenium automation tests on LambdaTest cloud grid

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

copy
1/*
2 * Licensed under the Apache License, Version 2.0 (the "License");
3 * you may not use this file except in compliance with the License.
4 * See the NOTICE file distributed with this work for additional
5 * information regarding copyright ownership.
6 * You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package io.appium.java_client.remote;
18
19import com.google.common.collect.ImmutableMap;
20import com.google.common.collect.ImmutableSet;
21import org.openqa.selenium.Capabilities;
22import org.openqa.selenium.internal.Require;
23import org.openqa.selenium.remote.AcceptedW3CCapabilityKeys;
24import org.openqa.selenium.remote.CommandPayload;
25
26import java.util.Map;
27
28import static io.appium.java_client.internal.CapabilityHelpers.APPIUM_PREFIX;
29import static org.openqa.selenium.remote.DriverCommand.NEW_SESSION;
30
31public class AppiumNewSessionCommandPayload extends CommandPayload {
32    private static final AcceptedW3CCapabilityKeys ACCEPTED_W3C_PATTERNS = new AcceptedW3CCapabilityKeys();
33
34    /**
35     * Appends "appium:" prefix to all non-prefixed non-standard capabilities.
36     *
37     * @param possiblyInvalidCapabilities user-provided capabilities mapping.
38     * @return Fixed capabilities mapping.
39     */
40    private static Map<String, Object> makeW3CSafe(Capabilities possiblyInvalidCapabilities) {
41        return Require.nonNull("Capabilities", possiblyInvalidCapabilities)
42                .asMap().entrySet().stream()
43                .collect(ImmutableMap.toImmutableMap(entry -> ACCEPTED_W3C_PATTERNS.test(entry.getKey())
44                                ? entry.getKey()
45                                : APPIUM_PREFIX + entry.getKey(),
46                        Map.Entry::getValue));
47    }
48
49    /**
50     * Overrides the default new session behavior to
51     * only handle W3C capabilities.
52     *
53     * @param capabilities User-provided capabilities.
54     */
55    public AppiumNewSessionCommandPayload(Capabilities capabilities) {
56        super(NEW_SESSION, ImmutableMap.of(
57                "capabilities", ImmutableSet.of(makeW3CSafe(capabilities)),
58                "desiredCapabilities", capabilities
59        ));
60    }
61}
62
Full Screen
copy
1/*
2 * Licensed under the Apache License, Version 2.0 (the "License");
3 * you may not use this file except in compliance with the License.
4 * See the NOTICE file distributed with this work for additional
5 * information regarding copyright ownership.
6 * You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package io.appium.java_client.remote.options;
18
19import org.openqa.selenium.Capabilities;
20import org.openqa.selenium.MutableCapabilities;
21import org.openqa.selenium.Platform;
22import org.openqa.selenium.WebDriverException;
23import org.openqa.selenium.internal.Require;
24import org.openqa.selenium.remote.AcceptedW3CCapabilityKeys;
25import org.openqa.selenium.remote.CapabilityType;
26
27import javax.annotation.Nullable;
28import java.lang.reflect.Constructor;
29import java.lang.reflect.InvocationTargetException;
30import java.util.Map;
31import java.util.Optional;
32import java.util.stream.Collectors;
33
34import static io.appium.java_client.internal.CapabilityHelpers.APPIUM_PREFIX;
35import static java.util.Collections.unmodifiableMap;
36
37/**
38 * This class represents capabilities that are available in the base driver,
39 * e.g. are acceptable by any Appium driver
40 *
41 * @param <T> The child class for a proper chaining.
42 */
43@SuppressWarnings({"unused", "UnusedReturnValue"})
44public class BaseOptions<T extends BaseOptions<T>> extends MutableCapabilities implements
45        CanSetCapability<T>,
46        SupportsAutomationNameOption<T>,
47        SupportsEventTimingsOption<T>,
48        SupportsPrintPageSourceOnFindFailureOption<T>,
49        SupportsNoResetOption<T>,
50        SupportsFullResetOption<T>,
51        SupportsNewCommandTimeoutOption<T>,
52        SupportsBrowserNameOption<T>,
53        SupportsPlatformVersionOption<T> {
54    private static final AcceptedW3CCapabilityKeys W3C_KEY_PATTERNS = new AcceptedW3CCapabilityKeys();
55
56    /**
57     * Creates new instance with no preset capabilities.
58     */
59    public BaseOptions() {
60    }
61
62    /**
63     * Creates new instance with provided capabilities.
64     *
65     * @param source Capabilities map to merge into new instance
66     */
67    public BaseOptions(Map<String, ?> source) {
68        super(source);
69    }
70
71    /**
72     * Creates new instance with provided capabilities.
73     *
74     * @param source is Capabilities instance to merge into new instance
75     */
76    public BaseOptions(Capabilities source) {
77        super(source);
78    }
79
80    /**
81     * Set the kind of mobile device or emulator to use.
82     *
83     * @param platform the kind of mobile device or emulator to use.
84     * @return self instance for chaining.
85     * @see CapabilityType#PLATFORM_NAME
86     */
87    public T setPlatformName(String platform) {
88        return amend(CapabilityType.PLATFORM_NAME, platform);
89    }
90
91    @Override
92    @Nullable
93    public Platform getPlatformName() {
94        return Optional.ofNullable(getCapability(CapabilityType.PLATFORM_NAME))
95                .map(cap -> {
96                    if (cap instanceof Platform) {
97                        return (Platform) cap;
98                    }
99
100                    try {
101                        return Platform.fromString((String.valueOf(cap)));
102                    } catch (WebDriverException e) {
103                        return null;
104                    }
105                })
106                .orElse(null);
107    }
108
109    @Override
110    public Map<String, Object> asMap() {
111        return unmodifiableMap(super.asMap().entrySet().stream()
112                .collect(Collectors.toMap(entry -> W3C_KEY_PATTERNS.test(entry.getKey())
113                        ? entry.getKey() : APPIUM_PREFIX + entry.getKey(), Map.Entry::getValue)
114                ));
115    }
116
117    @Override
118    public T merge(Capabilities extraCapabilities) {
119        T result = this.clone();
120        extraCapabilities.asMap().forEach((key, value) -> {
121            if (value != null) {
122                result.setCapability(key, value);
123            }
124        });
125        return result;
126    }
127
128    /**
129     * Makes a deep clone of the current Options instance.
130     *
131     * @return A deep instance clone.
132     */
133    @SuppressWarnings("MethodDoesntCallSuperMethod")
134    public T clone() {
135        try {
136            Constructor<?> constructor = getClass().getConstructor(Capabilities.class);
137            //noinspection unchecked
138            return (T) constructor.newInstance(this);
139        } catch (InvocationTargetException | NoSuchMethodException
140                | InstantiationException | IllegalAccessException e) {
141            throw new IllegalStateException(e);
142        }
143    }
144
145    @Override
146    public void setCapability(String key, @Nullable Object value) {
147        Require.nonNull("Capability name", key);
148        super.setCapability(W3C_KEY_PATTERNS.test(key) ? key : APPIUM_PREFIX + key, value);
149    }
150
151    @Override
152    @Nullable
153    public Object getCapability(String capabilityName) {
154        Object value = super.getCapability(capabilityName);
155        if (value == null) {
156            value = super.getCapability(APPIUM_PREFIX + capabilityName);
157        }
158        return value;
159    }
160}
Full Screen
copy
1// Licensed to the Software Freedom Conservancy (SFC) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The SFC licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18package org.openqa.selenium.remote;
19
20import static com.google.common.net.MediaType.JSON_UTF_8;
21import static java.nio.charset.StandardCharsets.UTF_8;
22import static org.openqa.selenium.remote.http.HttpMethod.POST;
23
24import com.google.common.annotations.VisibleForTesting;
25import com.google.common.collect.ImmutableMap;
26import com.google.common.collect.ImmutableSet;
27
28import org.openqa.selenium.Beta;
29import org.openqa.selenium.Capabilities;
30import org.openqa.selenium.ImmutableCapabilities;
31import org.openqa.selenium.SessionNotCreatedException;
32import org.openqa.selenium.json.Json;
33import org.openqa.selenium.json.JsonOutput;
34import org.openqa.selenium.remote.http.HttpClient;
35import org.openqa.selenium.remote.http.HttpRequest;
36import org.openqa.selenium.remote.http.HttpResponse;
37import org.openqa.selenium.remote.http.W3CHttpCommandCodec;
38import org.openqa.selenium.remote.http.W3CHttpResponseCodec;
39import org.openqa.selenium.remote.service.DriverService;
40
41import java.io.IOException;
42import java.io.UncheckedIOException;
43import java.net.MalformedURLException;
44import java.net.URL;
45import java.util.ArrayList;
46import java.util.HashMap;
47import java.util.List;
48import java.util.Map;
49import java.util.Objects;
50import java.util.ServiceLoader;
51import java.util.Set;
52import java.util.TreeMap;
53import java.util.concurrent.atomic.AtomicReference;
54import java.util.function.Consumer;
55import java.util.function.Supplier;
56import java.util.stream.StreamSupport;
57
58@Beta
59class RemoteWebDriverBuilder {
60
61  private final static Set<String> ILLEGAL_METADATA_KEYS = ImmutableSet.of(
62      "alwaysMatch",
63      "capabilities",
64      "firstMatch");
65  private final static AcceptedW3CCapabilityKeys OK_KEYS = new AcceptedW3CCapabilityKeys();
66  private final List<Map<String, Object>> options = new ArrayList<>();
67  private final Map<String, Object> metadata = new TreeMap<>();
68  private final Map<String, Object> additionalCapabilities = new TreeMap<>();
69  private URL remoteHost;
70  private DriverService service;
71
72  public RemoteWebDriverBuilder oneOf(Capabilities... oneOfTheseOptions) {
73    options.clear();
74    for (int i = 0; i < oneOfTheseOptions.length; i++) {
75      addAlternative(oneOfTheseOptions[i]);
76    }
77    return this;
78  }
79
80  public RemoteWebDriverBuilder addAlternative(Capabilities options) {
81    Map<String, Object> serialized = validate(Objects.requireNonNull(options));
82    this.options.add(serialized);
83    return this;
84  }
85
86  public RemoteWebDriverBuilder addMetadata(String key, Object value) {
87    if (ILLEGAL_METADATA_KEYS.contains(key)) {
88      throw new IllegalArgumentException(key + " is a reserved key");
89    }
90    metadata.put(Objects.requireNonNull(key), Objects.requireNonNull(value));
91    return this;
92  }
93
94  public RemoteWebDriverBuilder setCapability(String capabilityName, String value) {
95    if (!OK_KEYS.test(capabilityName)) {
96      throw new IllegalArgumentException("Capability is not valid");
97    }
98    if (value == null) {
99      throw new IllegalArgumentException("Null values are not allowed");
100    }
101
102    additionalCapabilities.put(capabilityName, value);
103    return this;
104  }
105
106  public RemoteWebDriverBuilder url(String url) {
107    try {
108      return url(new URL(url));
109    } catch (MalformedURLException e) {
110      throw new UncheckedIOException(e);
111    }
112  }
113
114  public RemoteWebDriverBuilder url(URL url) {
115    this.remoteHost = Objects.requireNonNull(url);
116    validateDriverServiceAndUrlConstraint();
117    return this;
118  }
119
120  public RemoteWebDriver build() {
121    if (options.isEmpty()) {
122      throw new SessionNotCreatedException("Refusing to create session without any capabilities");
123    }
124
125    Plan plan = getPlan();
126
127    CommandExecutor executor;
128    if (plan.isUsingDriverService()) {
129      AtomicReference<DriverService> serviceRef = new AtomicReference<>();
130
131      executor = new SpecCompliantExecutor(
132          () -> {
133            if (serviceRef.get() != null && serviceRef.get().isRunning()) {
134              throw new SessionNotCreatedException(
135                  "Attempt to start the underlying service more than once");
136            }
137            try {
138              serviceRef.set(plan.getDriverService());
139              serviceRef.get().start();
140              return serviceRef.get().getUrl();
141            } catch (IOException e) {
142              throw new SessionNotCreatedException(e.getMessage(), e);
143            }
144          },
145          plan::writePayload,
146          () -> serviceRef.get().stop());
147    } else {
148      executor = new SpecCompliantExecutor(() -> remoteHost, plan::writePayload, () -> {});
149    }
150
151    return new RemoteWebDriver(executor, new ImmutableCapabilities());
152  }
153
154  private Map<String, Object> validate(Capabilities options) {
155    return options.asMap().entrySet().stream()
156        // Ensure that the keys are ok
157        .peek(
158            entry -> {
159              if (!OK_KEYS.test(entry.getKey())) {
160                throw new IllegalArgumentException(
161                    "Capability key is not a valid w3c key: " + entry.getKey());
162              }
163            })
164        // And remove null values, as these are ignored.
165        .filter(entry -> entry.getValue() != null)
166        .collect(ImmutableMap.toImmutableMap(Map.Entry::getKey, Map.Entry::getValue));
167  }
168
169  @VisibleForTesting
170  Plan getPlan() {
171    return new Plan();
172  }
173
174  public RemoteWebDriverBuilder withDriverService(DriverService service) {
175    this.service = Objects.requireNonNull(service);
176    validateDriverServiceAndUrlConstraint();
177    return this;
178  }
179
180  private void validateDriverServiceAndUrlConstraint() {
181    if (remoteHost != null && service != null) {
182      throw new IllegalArgumentException(
183          "You may only set one of the remote url or the driver service to use.");
184    }
185  }
186
187  @VisibleForTesting
188  class Plan {
189
190    private Plan() {
191      // Not for public consumption
192    }
193
194    boolean isUsingDriverService() {
195      return remoteHost == null;
196    }
197
198    @VisibleForTesting
199    URL getRemoteHost() {
200      return remoteHost;
201    }
202
203    DriverService getDriverService() {
204      if (service != null) {
205        return service;
206      }
207
208      ServiceLoader<DriverService.Builder> allLoaders =
209          ServiceLoader.load(DriverService.Builder.class);
210
211      // We need to extract each of the capabilities from the payload.
212      return options
213          .stream()
214          .map(HashMap::new) // Make a copy so we don't alter the original values
215          .map(
216              map -> {
217                map.putAll(additionalCapabilities);
218                return map;
219              })
220          .map(ImmutableCapabilities::new)
221          .map(
222              caps ->
223                  StreamSupport.stream(allLoaders.spliterator(), true)
224                      .filter(builder -> builder.score(caps) > 0)
225                      .findFirst()
226                      .orElse(null))
227          .filter(Objects::nonNull)
228          .map(
229              bs -> {
230                try {
231                  return bs.build();
232                } catch (Throwable e) {
233                  return null;
234                }
235              })
236          .filter(Objects::nonNull)
237          .findFirst()
238          .orElseThrow(() -> new IllegalStateException("Unable to find a driver service"));
239    }
240
241
242    @VisibleForTesting
243    void writePayload(JsonOutput out) {
244      out.beginObject();
245
246      out.name("capabilities");
247      out.beginObject();
248      // Try and minimise payload by finding keys that have the same value in every option. This isn't
249      // terribly efficient, but we expect the number of entries to be very low in almost every case,
250      // so this should be fine.
251      Map<String, Object> always = new HashMap<>(options.get(0));
252      for (Map<String, Object> option : options) {
253        for (Map.Entry<String, Object> entry : option.entrySet()) {
254          if (!always.containsKey(entry.getKey())) {
255            continue;
256          }
257
258          if (!always.get(entry.getKey()).equals(entry.getValue())) {
259            always.remove(entry.getKey());
260          }
261        }
262      }
263      always.putAll(additionalCapabilities);
264
265      out.name("alwaysMatch");
266      out.beginObject();
267      always.forEach((key, value) -> {
268        out.name(key);
269        out.write(value);
270      });
271      out.endObject();
272
273      out.name("firstMatch");
274      out.beginArray();
275      options.forEach(option -> {
276        out.beginObject();
277        option.entrySet().stream()
278            .filter(entry -> !always.containsKey(entry.getKey()))
279            .filter(entry -> !additionalCapabilities.containsKey(entry.getKey()))
280            .forEach(entry -> {
281              out.name(entry.getKey());
282              out.write(entry.getValue());
283            });
284        out.endObject();
285      });
286      out.endArray();
287      out.endObject();  // Close the "capabilities" entry
288
289      metadata.forEach((key, value) -> {
290        out.name(key);
291        out.write(value);
292      });
293
294      out.endObject();
295    }
296  }
297
298  private static class SpecCompliantExecutor implements CommandExecutor {
299
300    private final CommandCodec<HttpRequest> commandCodec = new W3CHttpCommandCodec();
301    private final ResponseCodec<HttpResponse> responseCodec = new W3CHttpResponseCodec();
302
303    private final Supplier<URL> onStart;
304    private final Consumer<JsonOutput> writePayload;
305    private final Runnable onQuit;
306    private HttpClient client;
307
308    public SpecCompliantExecutor(
309        Supplier<URL> onStart,
310        Consumer<JsonOutput> writePayload,
311        Runnable onQuit) {
312      this.onStart = onStart;
313      this.writePayload = writePayload;
314      this.onQuit = onQuit;
315    }
316
317    @Override
318    public Response execute(Command command) throws IOException {
319      HttpRequest request;
320
321      if (DriverCommand.NEW_SESSION.equals(command.getName())) {
322        URL url = onStart.get();
323        this.client = HttpClient.Factory.createDefault().createClient(url);
324
325        request = new HttpRequest(POST, "/session");
326        request.setHeader("Cache-Control", "none");
327        request.setHeader("Content-Type", JSON_UTF_8.toString());
328        StringBuilder payload = new StringBuilder();
329        try (JsonOutput jsonOutput = new Json().newOutput(payload)) {
330          writePayload.accept(jsonOutput);
331        }
332        request.setContent(payload.toString().getBytes(UTF_8));
333      } else {
334        request = commandCodec.encode(command);
335      }
336
337      try {
338        HttpResponse response = client.execute(request);
339        Response decodedResponse = responseCodec.decode(response);
340
341        if (decodedResponse.getSessionId() == null && decodedResponse.getValue() instanceof Map) {
342          Map<?, ?> value = (Map<?, ?>) decodedResponse.getValue();
343          if (value.get("sessionId") instanceof String) {
344            decodedResponse.setSessionId((String) value.get("sessionId"));
345          }
346        }
347
348        if (decodedResponse.getSessionId() == null && response.getTargetHost() != null) {
349          decodedResponse.setSessionId(HttpSessionId.getSessionId(response.getTargetHost()));
350        }
351
352        return decodedResponse;
353      } finally {
354        if (DriverCommand.QUIT.equals(command.getName())) {
355          onQuit.run();
356        }
357      }
358    }
359  }
360}
361
Full Screen
copy
1<dependency>
2  <groupId>io.appium</groupId>
3  <artifactId>java-client</artifactId>
4  <version>7.0.0</version>
5</dependency>
6
Full Screen
copy
1<dependency>
2  <groupId>org.seleniumhq.selenium</groupId>
3  <artifactId>selenium-java</artifactId>
4  <version>3.12.0</version>
5</dependency>
6
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

...Most popular Stackoverflow questions on AcceptedW3CCapabilityKeys

Most used methods in AcceptedW3CCapabilityKeys

Run Selenium Automation Tests on LambdaTest Cloud Grid

Trigger Selenium automation tests on a cloud-based Grid of 3000+ real browsers and operating systems.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)