How to use ServicedSession class of org.openqa.selenium.grid.session.remote package

Best Selenium code snippet using org.openqa.selenium.grid.session.remote.ServicedSession

Run Selenium automation tests on LambdaTest cloud grid

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

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.grid.session.remote;
19
20
21import static java.util.concurrent.TimeUnit.SECONDS;
22
23import org.openqa.selenium.Capabilities;
24import org.openqa.selenium.InvalidArgumentException;
25import org.openqa.selenium.SessionNotCreatedException;
26import org.openqa.selenium.grid.data.CreateSessionRequest;
27import org.openqa.selenium.grid.session.ActiveSession;
28import org.openqa.selenium.grid.web.CommandHandler;
29import org.openqa.selenium.net.PortProber;
30import org.openqa.selenium.remote.Dialect;
31import org.openqa.selenium.remote.SessionId;
32import org.openqa.selenium.remote.http.HttpMethod;
33import org.openqa.selenium.remote.http.HttpRequest;
34import org.openqa.selenium.remote.http.HttpResponse;
35import org.openqa.selenium.remote.server.jmx.JMXHelper;
36import org.openqa.selenium.remote.server.jmx.ManagedService;
37import org.openqa.selenium.remote.service.DriverService;
38
39import java.io.IOException;
40import java.lang.reflect.Method;
41import java.net.URL;
42import java.util.Map;
43import java.util.Objects;
44import java.util.Optional;
45import java.util.function.Function;
46import java.util.function.Predicate;
47import java.util.logging.Level;
48
49import javax.management.MalformedObjectNameException;
50import javax.management.ObjectName;
51
52@ManagedService
53public class ServicedSession extends RemoteSession {
54
55  private final DriverService service;
56
57  public ServicedSession(
58      DriverService service,
59      Dialect downstream,
60      Dialect upstream,
61      CommandHandler codec,
62      SessionId id,
63      Map<String, Object> capabilities) {
64    super(downstream, upstream, codec, id, capabilities);
65
66    this.service = service;
67
68    new JMXHelper().register(this);
69  }
70
71  @Override
72  public String toString() {
73    return getId().toString() + " (" + service.getClass().getName() + ")";
74  }
75
76  @Override
77  public void stop() {
78    // Try and kill the running session. Both W3C and OSS use the same quit endpoint
79    try {
80      HttpRequest request = new HttpRequest(HttpMethod.DELETE, "/session/" + getId());
81      HttpResponse ignored = new HttpResponse();
82      execute(request, ignored);
83    } catch (IOException e) {
84      // This is fine.
85    }
86
87    service.stop();
88  }
89
90  public static class Factory extends RemoteSession.Factory<DriverService> {
91
92    private final Predicate<Capabilities> key;
93    private final Function<Capabilities, ? extends DriverService> createService;
94    private final String serviceClassName;
95
96    public Factory(Predicate<Capabilities> key, String serviceClassName) {
97      this.key = key;
98
99      this.serviceClassName = serviceClassName;
100      try {
101        Class<? extends DriverService> driverClazz =
102            Class.forName(serviceClassName).asSubclass(DriverService.class);
103
104        Function<Capabilities, ? extends DriverService> factory =
105            get(driverClazz, Capabilities.class);
106        if (factory == null) {
107          factory = get(driverClazz);
108        }
109
110        if (factory == null) {
111          throw new IllegalArgumentException(
112              "DriverService has no mechanism to create a default instance");
113        }
114
115        this.createService = factory;
116      } catch (ReflectiveOperationException e) {
117        throw new IllegalArgumentException(
118            "DriverService class does not exist: " + serviceClassName);
119      }
120    }
121
122    private Function<Capabilities, ? extends DriverService> get(
123        Class<? extends DriverService> driverServiceClazz,
124        Class... args) {
125      try {
126        Method serviceMethod = driverServiceClazz.getDeclaredMethod("createDefaultService", args);
127        serviceMethod.setAccessible(true);
128        return caps -> {
129          try {
130            if (args.length > 0) {
131              return (DriverService) serviceMethod.invoke(null, caps);
132            } else {
133              return (DriverService) serviceMethod.invoke(null);
134            }
135          } catch (ReflectiveOperationException e) {
136            throw new SessionNotCreatedException(
137                "Unable to create new service: " + driverServiceClazz.getSimpleName(), e);
138          }
139        };
140      } catch (ReflectiveOperationException e) {
141        return null;
142      }
143    }
144
145    @Override
146    public boolean test(Capabilities capabilities) {
147      return key.test(capabilities);
148    }
149
150    @Override
151    public Optional<ActiveSession> apply(CreateSessionRequest sessionRequest) {
152      Objects.requireNonNull(sessionRequest);
153      DriverService service = createService.apply(sessionRequest.getCapabilities());
154
155      try {
156        service.start();
157
158        PortProber.waitForPortUp(service.getUrl().getPort(), 30, SECONDS);
159
160        URL url = service.getUrl();
161
162        return performHandshake(
163            service,
164            url,
165            sessionRequest.getDownstreamDialects(),
166            sessionRequest.getCapabilities());
167      } catch (IOException | IllegalStateException | NullPointerException | InvalidArgumentException e) {
168        log.log(Level.INFO, e.getMessage(), e);
169        service.stop();
170        return Optional.empty();
171      }
172    }
173
174    @Override
175    protected ServicedSession newActiveSession(
176        DriverService service,
177        Dialect downstream,
178        Dialect upstream,
179        CommandHandler codec,
180        SessionId id,
181        Map<String, Object> capabilities) {
182      return new ServicedSession(
183          service,
184          downstream,
185          upstream,
186          codec,
187          id,
188          capabilities);
189    }
190
191    @Override
192    public String toString() {
193      return getClass().getName() + " (provider: " + serviceClassName + ")";
194    }
195  }
196
197  public ObjectName getObjectName() throws MalformedObjectNameException {
198    return new ObjectName(String.format("org.seleniumhq.server:type=Session,browser=\"%s\",id=%s",
199                                        getCapabilities().get("browserName"), getId()));
200  }
201}
202
Full Screen
copy
1   public void forceClickElement(WebElement element){
2
3        jsExec.executeScript("arguments[0].click();", element);
4    }
5

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 used methods in ServicedSession

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)