How to use getPrivateFieldValue method of io.appium.java_client.remote.AppiumCommandExecutor class

Best io.appium code snippet using io.appium.java_client.remote.AppiumCommandExecutor.getPrivateFieldValue

Run io.appium automation tests on LambdaTest cloud grid

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

AppiumCommandExecutor.java

Source: AppiumCommandExecutor.java Github

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 static com.google.common.base.Preconditions.checkNotNull;
20import static com.google.common.base.Throwables.throwIfUnchecked;
21import static java.lang.String.format;
22import static java.nio.charset.StandardCharsets.UTF_8;
23import static java.util.Optional.ofNullable;
24import static java.util.logging.Logger.getLogger;
25import static org.openqa.selenium.remote.DriverCommand.NEW_SESSION;
26
27import com.google.common.base.Supplier;
28import com.google.common.base.Throwables;
29
30import com.google.common.io.CountingOutputStream;
31import com.google.common.io.FileBackedOutputStream;
32
33import io.appium.java_client.internal.Config;
34import org.openqa.selenium.Capabilities;
35import org.openqa.selenium.ImmutableCapabilities;
36import org.openqa.selenium.SessionNotCreatedException;
37import org.openqa.selenium.WebDriverException;
38import org.openqa.selenium.remote.Command;
39import org.openqa.selenium.remote.CommandCodec;
40import org.openqa.selenium.remote.CommandInfo;
41import org.openqa.selenium.remote.Dialect;
42import org.openqa.selenium.remote.DriverCommand;
43import org.openqa.selenium.remote.HttpCommandExecutor;
44import org.openqa.selenium.remote.ProtocolHandshake;
45import org.openqa.selenium.remote.Response;
46import org.openqa.selenium.remote.ResponseCodec;
47import org.openqa.selenium.remote.http.HttpClient;
48import org.openqa.selenium.remote.http.HttpRequest;
49import org.openqa.selenium.remote.http.HttpResponse;
50import org.openqa.selenium.remote.http.W3CHttpCommandCodec;
51import org.openqa.selenium.remote.service.DriverService;
52
53import java.io.BufferedInputStream;
54import java.io.IOException;
55import java.io.InputStream;
56import java.io.OutputStreamWriter;
57import java.io.Writer;
58import java.lang.reflect.Field;
59import java.lang.reflect.InvocationTargetException;
60import java.lang.reflect.Method;
61import java.net.ConnectException;
62import java.net.URL;
63import java.util.Map;
64import java.util.Optional;
65
66public class AppiumCommandExecutor extends HttpCommandExecutor {
67
68    private final Optional<DriverService> serviceOptional;
69
70    private AppiumCommandExecutor(Map<String, CommandInfo> additionalCommands, DriverService service,
71                                  URL addressOfRemoteServer,
72                                  HttpClient.Factory httpClientFactory) {
73        super(additionalCommands,
74                ofNullable(service)
75                        .map(DriverService::getUrl)
76                        .orElse(addressOfRemoteServer), httpClientFactory);
77        serviceOptional = ofNullable(service);
78    }
79
80    public AppiumCommandExecutor(Map<String, CommandInfo> additionalCommands, DriverService service,
81                                 HttpClient.Factory httpClientFactory) {
82        this(additionalCommands, checkNotNull(service), null, httpClientFactory);
83    }
84
85    public AppiumCommandExecutor(Map<String, CommandInfo> additionalCommands,
86                                 URL addressOfRemoteServer, HttpClient.Factory httpClientFactory) {
87        this(additionalCommands, null, checkNotNull(addressOfRemoteServer), httpClientFactory);
88    }
89
90
91    public AppiumCommandExecutor(Map<String, CommandInfo> additionalCommands,
92                                 URL addressOfRemoteServer) {
93        this(additionalCommands, addressOfRemoteServer, HttpClient.Factory.createDefault());
94    }
95
96    public AppiumCommandExecutor(Map<String, CommandInfo> additionalCommands,
97                                 DriverService service) {
98        this(additionalCommands, service, HttpClient.Factory.createDefault());
99    }
100
101    protected <B> B getPrivateFieldValue(String fieldName, Class<B> fieldType) {
102        Class<?> superclass = getClass().getSuperclass();
103        Throwable recentException = null;
104        while (superclass != Object.class) {
105            try {
106                final Field f = superclass.getDeclaredField(fieldName);
107                f.setAccessible(true);
108                return fieldType.cast(f.get(this));
109            } catch (NoSuchFieldException | IllegalAccessException e) {
110                recentException = e;
111            }
112            superclass = superclass.getSuperclass();
113        }
114        throw new WebDriverException(recentException);
115    }
116
117    protected void setPrivateFieldValue(String fieldName, Object newValue) {
118        Class<?> superclass = getClass().getSuperclass();
119        Throwable recentException = null;
120        while (superclass != Object.class) {
121            try {
122                final Field f = superclass.getDeclaredField(fieldName);
123                f.setAccessible(true);
124                f.set(this, newValue);
125                return;
126            } catch (NoSuchFieldException | IllegalAccessException e) {
127                recentException = e;
128            }
129            superclass = superclass.getSuperclass();
130        }
131        throw new WebDriverException(recentException);
132    }
133
134    protected Map<String, CommandInfo> getAdditionalCommands() {
135        //noinspection unchecked
136        return getPrivateFieldValue("additionalCommands", Map.class);
137    }
138
139    protected CommandCodec<HttpRequest> getCommandCodec() {
140        //noinspection unchecked
141        return getPrivateFieldValue("commandCodec", CommandCodec.class);
142    }
143
144    protected void setCommandCodec(CommandCodec<HttpRequest> newCodec) {
145        setPrivateFieldValue("commandCodec", newCodec);
146    }
147
148    protected void setResponseCodec(ResponseCodec<HttpResponse> codec) {
149        setPrivateFieldValue("responseCodec", codec);
150    }
151
152    protected HttpClient getClient() {
153        //noinspection unchecked
154        return getPrivateFieldValue("client", HttpClient.class);
155    }
156
157    private Response createSession(Command command) throws IOException {
158        if (getCommandCodec() != null) {
159            throw new SessionNotCreatedException("Session already exists");
160        }
161        ProtocolHandshake handshake = new ProtocolHandshake() {
162            @SuppressWarnings("unchecked")
163            public Result createSession(HttpClient client, Command command)
164                    throws IOException {
165                Capabilities desiredCapabilities = (Capabilities) command.getParameters().get("desiredCapabilities");
166                Capabilities desired = desiredCapabilities == null ? new ImmutableCapabilities() : desiredCapabilities;
167
168                //the number of bytes before the stream should switch to buffering to a file
169                int threshold = (int) Math.min(Runtime.getRuntime().freeMemory() / 10, Integer.MAX_VALUE);
170                FileBackedOutputStream os = new FileBackedOutputStream(threshold);
171                try {
172
173                    CountingOutputStream counter = new CountingOutputStream(os);
174                    Writer writer = new OutputStreamWriter(counter, UTF_8);
175                    NewAppiumSessionPayload payload = NewAppiumSessionPayload.create(desired);
176                    payload.writeTo(writer);
177
178                    try (InputStream rawIn = os.asByteSource().openBufferedStream();
179                         BufferedInputStream contentStream = new BufferedInputStream(rawIn)) {
180
181                        Method createSessionMethod = this.getClass().getSuperclass()
182                                .getDeclaredMethod("createSession", HttpClient.class, InputStream.class, long.class);
183                        createSessionMethod.setAccessible(true);
184
185                        Optional<Result> result = (Optional<Result>) createSessionMethod
186                                .invoke(this, client, contentStream, counter.getCount());
187
188                        return result.map(result1 -> {
189                            Result toReturn = result.get();
190                            getLogger(ProtocolHandshake.class.getName())
191                                    .info(format("Detected dialect: %s", toReturn.getDialect()));
192                            return toReturn;
193                        }).orElseThrow(() -> new SessionNotCreatedException(
194                                format("Unable to create a new remote session. Desired capabilities = %s", desired)));
195                    } catch (NoSuchMethodException | IllegalAccessException e) {
196                        throw new SessionNotCreatedException(format("Unable to create a new remote session. "
197                                        + "Make sure your project dependencies config does not override "
198                                        + "Selenium API version %s used by java-client library.",
199                                Config.main().getValue("selenium.version", String.class)), e);
200                    } catch (InvocationTargetException e) {
201                        String message = "Unable to create a new remote session.";
202                        if (e.getCause() != null) {
203                            if (e.getCause() instanceof WebDriverException) {
204                                message += " Please check the server log for more details.";
205                            }
206                            message += format(" Original error: %s", e.getCause().getMessage());
207                        }
208                        throw new SessionNotCreatedException(message, e);
209                    }
210                } finally {
211                    os.reset();
212                }
213            }
214        };
215
216        ProtocolHandshake.Result result = handshake
217                .createSession(getClient(), command);
218        Dialect dialect = result.getDialect();
219        setCommandCodec(dialect.getCommandCodec());
220        getAdditionalCommands().forEach(this::defineCommand);
221        setResponseCodec(dialect.getResponseCodec());
222        return result.createResponse();
223    }
224
225    @Override
226    public Response execute(Command command) throws WebDriverException {
227        if (DriverCommand.NEW_SESSION.equals(command.getName())) {
228            serviceOptional.ifPresent(driverService -> {
229                try {
230                    driverService.start();
231                } catch (IOException e) {
232                    throw new WebDriverException(e.getMessage(), e);
233                }
234            });
235        }
236
237        Response response;
238        try {
239            response = NEW_SESSION.equals(command.getName()) ? createSession(command) : super.execute(command);
240        } catch (Throwable t) {
241            Throwable rootCause = Throwables.getRootCause(t);
242            if (rootCause instanceof ConnectException
243                    && rootCause.getMessage().contains("Connection refused")) {
244                throw serviceOptional.map(service -> {
245                    if (service.isRunning()) {
246                        return new WebDriverException("The session is closed!", rootCause);
247                    }
248
249                    return new WebDriverException("The appium server has accidentally died!", rootCause);
250                }).orElseGet((Supplier<WebDriverException>) () ->
251                        new WebDriverException(rootCause.getMessage(), rootCause));
252            }
253            throwIfUnchecked(t);
254            throw new WebDriverException(t);
255        } finally {
256            if (DriverCommand.QUIT.equals(command.getName())) {
257                serviceOptional.ifPresent(DriverService::stop);
258            }
259        }
260
261        if (DriverCommand.NEW_SESSION.equals(command.getName())
262                && getCommandCodec() instanceof W3CHttpCommandCodec) {
263            setCommandCodec(new AppiumW3CHttpCommandCodec());
264            getAdditionalCommands().forEach(this::defineCommand);
265        }
266
267        return response;
268    }
269}
270
Full Screen

EventFiringAppiumCommandExecutor.java

Source: EventFiringAppiumCommandExecutor.java Github

copy
1/*******************************************************************************
2 * Copyright 2013-2018 QaProSoft (http://www.qaprosoft.com).
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
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 *******************************************************************************/
16package com.qaprosoft.carina.core.foundation.webdriver.listener;
17
18import static com.google.common.base.Preconditions.checkNotNull;
19import static java.util.Optional.ofNullable;
20
21import java.io.IOException;
22import java.lang.reflect.Field;
23import java.net.ConnectException;
24import java.net.URL;
25import java.util.ArrayList;
26import java.util.List;
27import java.util.Map;
28import java.util.Optional;
29
30import org.openqa.selenium.WebDriverException;
31import org.openqa.selenium.remote.Command;
32import org.openqa.selenium.remote.CommandCodec;
33import org.openqa.selenium.remote.CommandInfo;
34import org.openqa.selenium.remote.DriverCommand;
35import org.openqa.selenium.remote.HttpCommandExecutor;
36import org.openqa.selenium.remote.Response;
37import org.openqa.selenium.remote.http.HttpClient;
38import org.openqa.selenium.remote.http.HttpRequest;
39import org.openqa.selenium.remote.http.W3CHttpCommandCodec;
40import org.openqa.selenium.remote.service.DriverService;
41
42import com.google.common.base.Supplier;
43import com.google.common.base.Throwables;
44
45import io.appium.java_client.MobileCommand;
46import io.appium.java_client.remote.AppiumCommandExecutor;
47import io.appium.java_client.remote.AppiumW3CHttpCommandCodec;
48
49/**
50 * EventFiringAppiumCommandExecutor triggers event listener before/after execution of the command.
51 * Please track {@link AppiumCommandExecutor} for latest changes.
52 * 
53 * @author akhursevich
54 */
55@SuppressWarnings({ "unchecked" })
56public class EventFiringAppiumCommandExecutor extends HttpCommandExecutor {
57
58    private final Optional<DriverService> serviceOptional;
59
60    private List<IDriverCommandListener> listeners = new ArrayList<>();
61
62    private EventFiringAppiumCommandExecutor(Map<String, CommandInfo> additionalCommands, DriverService service,
63            URL addressOfRemoteServer,
64            HttpClient.Factory httpClientFactory) {
65        super(additionalCommands,
66                ofNullable(service)
67                        .map(DriverService::getUrl)
68                        .orElse(addressOfRemoteServer),
69                httpClientFactory);
70        serviceOptional = ofNullable(service);
71    }
72
73    public EventFiringAppiumCommandExecutor(Map<String, CommandInfo> additionalCommands, DriverService service,
74            HttpClient.Factory httpClientFactory) {
75        this(additionalCommands, checkNotNull(service), null, httpClientFactory);
76    }
77
78    public EventFiringAppiumCommandExecutor(Map<String, CommandInfo> additionalCommands,
79            URL addressOfRemoteServer, HttpClient.Factory httpClientFactory) {
80        this(additionalCommands, null, checkNotNull(addressOfRemoteServer), httpClientFactory);
81    }
82
83    public EventFiringAppiumCommandExecutor(Map<String, CommandInfo> additionalCommands,
84            URL addressOfRemoteServer) {
85        this(additionalCommands, addressOfRemoteServer, HttpClient.Factory.createDefault());
86    }
87
88    public EventFiringAppiumCommandExecutor(Map<String, CommandInfo> additionalCommands,
89            DriverService service) {
90        this(additionalCommands, service, HttpClient.Factory.createDefault());
91    }
92
93    public EventFiringAppiumCommandExecutor(URL addressOfRemoteServer) {
94        this(MobileCommand.commandRepository, addressOfRemoteServer, HttpClient.Factory.createDefault());
95    }
96
97    private <B> B getPrivateFieldValue(String fieldName, Class<B> fieldType) {
98        try {
99            final Field f = getClass().getSuperclass().getDeclaredField(fieldName);
100            f.setAccessible(true);
101            return fieldType.cast(f.get(this));
102        } catch (NoSuchFieldException | IllegalAccessException e) {
103            throw new WebDriverException(e);
104        }
105    }
106
107    private void setPrivateFieldValue(String fieldName, Object newValue) {
108        try {
109            final Field f = getClass().getSuperclass().getDeclaredField(fieldName);
110            f.setAccessible(true);
111            f.set(this, newValue);
112        } catch (NoSuchFieldException | IllegalAccessException e) {
113            throw new WebDriverException(e);
114        }
115    }
116
117    private Map<String, CommandInfo> getAdditionalCommands() {
118        // noinspection unchecked
119        return getPrivateFieldValue("additionalCommands", Map.class);
120    }
121
122    private CommandCodec<HttpRequest> getCommandCodec() {
123        // noinspection unchecked
124        return getPrivateFieldValue("commandCodec", CommandCodec.class);
125    }
126
127    private void setCommandCodec(CommandCodec<HttpRequest> newCodec) {
128        setPrivateFieldValue("commandCodec", newCodec);
129    }
130
131    @Override
132    public Response execute(Command command) throws WebDriverException {
133        if (DriverCommand.NEW_SESSION.equals(command.getName())) {
134            serviceOptional.ifPresent(driverService -> {
135                try {
136                    driverService.start();
137                } catch (IOException e) {
138                    throw new WebDriverException(e.getMessage(), e);
139                }
140            });
141        }
142
143        Response response;
144        try {
145
146            for (IDriverCommandListener listener : listeners) {
147                listener.beforeEvent(command);
148            }
149
150            response = super.execute(command);
151
152            for (IDriverCommandListener listener : listeners) {
153                listener.afterEvent(command);
154            }
155        } catch (Throwable t) {
156            Throwable rootCause = Throwables.getRootCause(t);
157            if (rootCause instanceof ConnectException
158                    && rootCause.getMessage().contains("Connection refused")) {
159                throw serviceOptional.map(service -> {
160                    if (service.isRunning()) {
161                        return new WebDriverException("The session is closed!", rootCause);
162                    }
163
164                    return new WebDriverException("The appium server has accidentally died!", rootCause);
165                }).orElseGet((Supplier<WebDriverException>) () -> new WebDriverException(rootCause.getMessage(), rootCause));
166            }
167            // [VD] never enable throwIfUnchecked as it generates RuntimeException and corrupt TestNG main thread!   
168            // throwIfUnchecked(t);
169            throw new WebDriverException(t);
170        } finally {
171            if (DriverCommand.QUIT.equals(command.getName())) {
172                serviceOptional.ifPresent(DriverService::stop);
173            }
174        }
175
176        if (DriverCommand.NEW_SESSION.equals(command.getName())
177                && getCommandCodec() instanceof W3CHttpCommandCodec) {
178            setCommandCodec(new AppiumW3CHttpCommandCodec());
179            getAdditionalCommands().forEach(this::defineCommand);
180        }
181
182        return response;
183    }
184
185    public List<IDriverCommandListener> getListeners() {
186        return listeners;
187    }
188
189    public void setListeners(List<IDriverCommandListener> listeners) {
190        this.listeners = listeners;
191    }
192}
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

Trigger getPrivateFieldValue code on LambdaTest Cloud Grid

Execute automation tests with getPrivateFieldValue on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

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)