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

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

AppiumDriver_4.1.2.java

Source:AppiumDriver_4.1.2.java Github

copy

Full Screen

...84 private static final ErrorHandler errorHandler = new ErrorHandler(new ErrorCodesMobile(), true);85 // frequently used command parameters86 private URL remoteAddress;87 private RemoteLocationContext locationContext;88 private ExecuteMethod executeMethod;89 /**90 * @param executor is an instance of {@link org.openqa.selenium.remote.HttpCommandExecutor}91 * or class that extends it. Default commands or another vendor-specific92 * commands may be specified there.93 * @param capabilities take a look94 * at {@link org.openqa.selenium.Capabilities}95 * @param converterClazz is an instance of a class that extends96 * {@link org.openqa.selenium.remote.internal.JsonToWebElementConverter}. It converts97 * JSON response to an instance of98 * {@link org.openqa.selenium.WebElement}99 */100 protected AppiumDriver(HttpCommandExecutor executor, Capabilities capabilities,101 Class<? extends JsonToWebElementConverter> converterClazz) {102 super(executor, capabilities);103 this.executeMethod = new AppiumExecutionMethod(this);104 locationContext = new RemoteLocationContext(executeMethod);105 super.setErrorHandler(errorHandler);106 this.remoteAddress = executor.getAddressOfRemoteServer();107 try {108 Constructor<? extends JsonToWebElementConverter> constructor =109 converterClazz.getConstructor(RemoteWebDriver.class);110 this.setElementConverter(constructor.newInstance(this));111 } catch (NoSuchMethodException | IllegalAccessException | InstantiationException112 | InvocationTargetException e) {113 throw new RuntimeException(e);114 }115 }116 public AppiumDriver(URL remoteAddress, Capabilities desiredCapabilities,117 Class<? extends JsonToWebElementConverter> converterClazz) {118 this(new AppiumCommandExecutor(MobileCommand.commandRepository, remoteAddress),119 desiredCapabilities, converterClazz);120 }121 public AppiumDriver(URL remoteAddress, HttpClient.Factory httpClientFactory,122 Capabilities desiredCapabilities,123 Class<? extends JsonToWebElementConverter> converterClazz) {124 this(new AppiumCommandExecutor(MobileCommand.commandRepository, remoteAddress,125 httpClientFactory), desiredCapabilities, converterClazz);126 }127 public AppiumDriver(AppiumDriverLocalService service, Capabilities desiredCapabilities,128 Class<? extends JsonToWebElementConverter> converterClazz) {129 this(new AppiumCommandExecutor(MobileCommand.commandRepository, service),130 desiredCapabilities, converterClazz);131 }132 public AppiumDriver(AppiumDriverLocalService service, HttpClient.Factory httpClientFactory,133 Capabilities desiredCapabilities,134 Class<? extends JsonToWebElementConverter> converterClazz) {135 this(new AppiumCommandExecutor(MobileCommand.commandRepository, service, httpClientFactory),136 desiredCapabilities, converterClazz);137 }138 public AppiumDriver(AppiumServiceBuilder builder, Capabilities desiredCapabilities,139 Class<? extends JsonToWebElementConverter> converterClazz) {140 this(builder.build(), desiredCapabilities, converterClazz);141 }142 public AppiumDriver(AppiumServiceBuilder builder, HttpClient.Factory httpClientFactory,143 Capabilities desiredCapabilities,144 Class<? extends JsonToWebElementConverter> converterClazz) {145 this(builder.build(), httpClientFactory, desiredCapabilities, converterClazz);146 }147 public AppiumDriver(HttpClient.Factory httpClientFactory, Capabilities desiredCapabilities,148 Class<? extends JsonToWebElementConverter> converterClazz) {149 this(AppiumDriverLocalService.buildDefaultService(), httpClientFactory,150 desiredCapabilities, converterClazz);151 }152 public AppiumDriver(Capabilities desiredCapabilities,153 Class<? extends JsonToWebElementConverter> converterClazz) {154 this(AppiumDriverLocalService.buildDefaultService(), desiredCapabilities, converterClazz);155 }156 /**157 * @param originalCapabilities the given {@link Capabilities}.158 * @param newPlatform a {@link MobileCapabilityType#PLATFORM_NAME} value which has159 * to be set up160 * @return {@link Capabilities} with changed mobile platform value161 */162 protected static Capabilities substituteMobilePlatform(Capabilities originalCapabilities,163 String newPlatform) {164 DesiredCapabilities dc = new DesiredCapabilities(originalCapabilities);165 dc.setCapability(MobileCapabilityType.PLATFORM_NAME, newPlatform);166 return dc;167 }168 @Override public List<T> findElements(By by) {169 return super.findElements(by);170 }171 @Override public List<T> findElements(String by, String using) {172 return super.findElements(by, using);173 }174 @Override public List<T> findElementsById(String id) {175 return super.findElementsById(id);176 }177 public List<T> findElementsByLinkText(String using) {178 return super.findElementsByLinkText(using);179 }180 public List<T> findElementsByPartialLinkText(String using) {181 return super.findElementsByPartialLinkText(using);182 }183 public List<T> findElementsByTagName(String using) {184 return super.findElementsByTagName(using);185 }186 public List<T> findElementsByName(String using) {187 return super.findElementsByName(using);188 }189 public List<T> findElementsByClassName(String using) {190 return super.findElementsByClassName(using);191 }192 public List<T> findElementsByCssSelector(String using) {193 return super.findElementsByCssSelector(using);194 }195 public List<T> findElementsByXPath(String using) {196 return super.findElementsByXPath(using);197 }198 @Override public List<T> findElementsByAccessibilityId(String using) {199 return super.findElementsByAccessibilityId(using);200 }201 @Override protected Response execute(String command) {202 return super.execute(command, ImmutableMap.<String, Object>of());203 }204 @Override public ExecuteMethod getExecuteMethod() {205 return executeMethod;206 }207 /**208 * @see InteractsWithApps#resetApp().209 */210 @Override public void resetApp() {211 execute(MobileCommand.RESET);212 }213 /**214 * @see InteractsWithApps#isAppInstalled(String).215 */216 @Override public boolean isAppInstalled(String bundleId) {217 Response response = execute(IS_APP_INSTALLED, ImmutableMap.of("bundleId", bundleId));218 return Boolean.parseBoolean(response.getValue().toString());219 }220 /**221 * @see InteractsWithApps#installApp(String).222 */223 @Override public void installApp(String appPath) {224 execute(INSTALL_APP, ImmutableMap.of("appPath", appPath));225 }226 /**227 * @see InteractsWithApps#removeApp(String).228 */229 @Override public void removeApp(String bundleId) {230 execute(REMOVE_APP, ImmutableMap.of("bundleId", bundleId));231 }232 /**233 * @see InteractsWithApps#launchApp().234 */235 @Override public void launchApp() {236 execute(LAUNCH_APP);237 }238 /**239 * @see InteractsWithApps#closeApp().240 */241 @Override public void closeApp() {242 execute(CLOSE_APP);243 }244 /**245 * @see InteractsWithApps#runAppInBackground(int).246 */247 @Override public void runAppInBackground(int seconds) {248 execute(RUN_APP_IN_BACKGROUND, ImmutableMap.of("seconds", seconds));249 }250 /**251 * @see DeviceActionShortcuts#getDeviceTime().252 */253 @Override public String getDeviceTime() {254 Response response = execute(GET_DEVICE_TIME);255 return response.getValue().toString();256 }257 /**258 * @see DeviceActionShortcuts#hideKeyboard().259 */260 @Override public void hideKeyboard() {261 execute(HIDE_KEYBOARD);262 }263 /**264 * @see InteractsWithFiles#pullFile(String).265 */266 @Override public byte[] pullFile(String remotePath) {267 Response response = execute(PULL_FILE, ImmutableMap.of("path", remotePath));268 String base64String = response.getValue().toString();269 return DatatypeConverter.parseBase64Binary(base64String);270 }271 /**272 * @see InteractsWithFiles#pullFolder(String).273 */274 @Override275 public byte[] pullFolder(String remotePath) {276 Response response = execute(PULL_FOLDER, ImmutableMap.of("path", remotePath));277 String base64String = response.getValue().toString();278 return DatatypeConverter.parseBase64Binary(base64String);279 }280 /**281 * @see PerformsTouchActions#performTouchAction(TouchAction).282 */283 @SuppressWarnings("rawtypes")284 @Override public TouchAction performTouchAction(285 TouchAction touchAction) {286 ImmutableMap<String, ImmutableList> parameters = touchAction.getParameters();287 execute(PERFORM_TOUCH_ACTION, parameters);288 return touchAction;289 }290 /**291 * @see PerformsTouchActions#performMultiTouchAction(MultiTouchAction).292 */293 @Override294 @SuppressWarnings({"rawtypes"})295 public void performMultiTouchAction(296 MultiTouchAction multiAction) {297 ImmutableMap<String, ImmutableList> parameters = multiAction.getParameters();298 execute(PERFORM_MULTI_TOUCH, parameters);299 }300 /**301 * @see TouchShortcuts#tap(int, WebElement, int).302 */303 @Override public void tap(int fingers, WebElement element, int duration) {304 MultiTouchAction multiTouch = new MultiTouchAction(this);305 for (int i = 0; i < fingers; i++) {306 multiTouch.add(createTap(element, duration));307 }308 multiTouch.perform();309 }310 /**311 * @see TouchShortcuts#tap(int, int, int, int).312 */313 @Override public void tap(int fingers, int x, int y, int duration) {314 MultiTouchAction multiTouch = new MultiTouchAction(this);315 for (int i = 0; i < fingers; i++) {316 multiTouch.add(createTap(x, y, duration));317 }318 multiTouch.perform();319 }320 protected void doSwipe(int startx, int starty, int endx, int endy, int duration) {321 TouchAction touchAction = new TouchAction(this);322 // appium converts press-wait-moveto-release to a swipe action323 touchAction.press(startx, starty).waitAction(duration).moveTo(endx, endy).release();324 touchAction.perform();325 }326 /**327 * @see TouchShortcuts#swipe(int, int, int, int, int).328 */329 @Override public abstract void swipe(int startx, int starty, int endx, int endy, int duration);330 /**331 * Convenience method for pinching an element on the screen.332 * "pinching" refers to the action of two appendages pressing the333 * screen and sliding towards each other.334 * NOTE:335 * This convenience method places the initial touches around the element, if this would336 * happen to place one of them off the screen, appium with return an outOfBounds error.337 * In this case, revert to using the MultiTouchAction api instead of this method.338 *339 * @param el The element to pinch.340 */341 public void pinch(WebElement el) {342 MultiTouchAction multiTouch = new MultiTouchAction(this);343 Dimension dimensions = el.getSize();344 Point upperLeft = el.getLocation();345 Point center = new Point(upperLeft.getX() + dimensions.getWidth() / 2,346 upperLeft.getY() + dimensions.getHeight() / 2);347 int yOffset = center.getY() - upperLeft.getY();348 TouchAction action0 =349 new TouchAction(this).press(el, center.getX(), center.getY() - yOffset).moveTo(el)350 .release();351 TouchAction action1 =352 new TouchAction(this).press(el, center.getX(), center.getY() + yOffset).moveTo(el)353 .release();354 multiTouch.add(action0).add(action1);355 multiTouch.perform();356 }357 /**358 * Convenience method for pinching an element on the screen.359 * "pinching" refers to the action of two appendages pressing the screen and360 * sliding towards each other.361 * NOTE:362 * This convenience method places the initial touches around the element at a distance,363 * if this would happen to place one of them off the screen, appium will return an364 * outOfBounds error. In this case, revert to using the MultiTouchAction api instead of this365 * method.366 *367 * @param x x coordinate to terminate the pinch on.368 * @param y y coordinate to terminate the pinch on.369 */370 public void pinch(int x, int y) {371 MultiTouchAction multiTouch = new MultiTouchAction(this);372 int scrHeight = manage().window().getSize().getHeight();373 int yOffset = 100;374 if (y - 100 < 0) {375 yOffset = y;376 } else if (y + 100 > scrHeight) {377 yOffset = scrHeight - y;378 }379 TouchAction action0 = new TouchAction(this).press(x, y - yOffset).moveTo(x, y).release();380 TouchAction action1 = new TouchAction(this).press(x, y + yOffset).moveTo(x, y).release();381 multiTouch.add(action0).add(action1);382 multiTouch.perform();383 }384 /**385 * Convenience method for "zooming in" on an element on the screen.386 * "zooming in" refers to the action of two appendages pressing the screen and sliding387 * away from each other.388 * NOTE:389 * This convenience method slides touches away from the element, if this would happen390 * to place one of them off the screen, appium will return an outOfBounds error.391 * In this case, revert to using the MultiTouchAction api instead of this method.392 *393 * @param el The element to pinch.394 */395 public void zoom(WebElement el) {396 MultiTouchAction multiTouch = new MultiTouchAction(this);397 Dimension dimensions = el.getSize();398 Point upperLeft = el.getLocation();399 Point center = new Point(upperLeft.getX() + dimensions.getWidth() / 2,400 upperLeft.getY() + dimensions.getHeight() / 2);401 int yOffset = center.getY() - upperLeft.getY();402 TouchAction action0 = new TouchAction(this).press(center.getX(), center.getY())403 .moveTo(el, center.getX(), center.getY() - yOffset).release();404 TouchAction action1 = new TouchAction(this).press(center.getX(), center.getY())405 .moveTo(el, center.getX(), center.getY() + yOffset).release();406 multiTouch.add(action0).add(action1);407 multiTouch.perform();408 }409 /**410 * Convenience method for "zooming in" on an element on the screen.411 * "zooming in" refers to the action of two appendages pressing the screen412 * and sliding away from each other.413 * NOTE:414 * This convenience method slides touches away from the element, if this would happen to415 * place one of them off the screen, appium will return an outOfBounds error. In this case,416 * revert to using the MultiTouchAction api instead of this method.417 *418 * @param x x coordinate to start zoom on.419 * @param y y coordinate to start zoom on.420 */421 public void zoom(int x, int y) {422 MultiTouchAction multiTouch = new MultiTouchAction(this);423 int scrHeight = manage().window().getSize().getHeight();424 int yOffset = 100;425 if (y - 100 < 0) {426 yOffset = y;427 } else if (y + 100 > scrHeight) {428 yOffset = scrHeight - y;429 }430 TouchAction action0 = new TouchAction(this).press(x, y).moveTo(0, -yOffset).release();431 TouchAction action1 = new TouchAction(this).press(x, y).moveTo(0, yOffset).release();432 multiTouch.add(action0).add(action1);433 multiTouch.perform();434 }435 /**436 * Get settings stored for this test session It's probably better to use a437 * convenience function, rather than use this function directly. Try finding438 * the method for the specific setting you want to read.439 *440 * @return JsonObject, a straight-up hash of settings.441 */442 public JsonObject getSettings() {443 Response response = execute(GET_SETTINGS);444 JsonParser parser = new JsonParser();445 return (JsonObject) parser.parse(response.getValue().toString());446 }447 /**448 * Set settings for this test session It's probably better to use a449 * convenience function, rather than use this function directly. Try finding450 * the method for the specific setting you want to change.451 *452 * @param settings Map of setting keys and values.453 */454 private void setSettings(ImmutableMap<?, ?> settings) {455 execute(SET_SETTINGS, prepareArguments("settings", settings));456 }457 /**458 * Set a setting for this test session It's probably better to use a459 * convenience function, rather than use this function directly. Try finding460 * the method for the specific setting you want to change.461 *462 * @param setting AppiumSetting you wish to set.463 * @param value value of the setting.464 */465 protected void setSetting(AppiumSetting setting, Object value) {466 setSettings(prepareArguments(setting.toString(), value));467 }468 @Override public WebDriver context(String name) {469 checkNotNull(name, "Must supply a context name");470 execute(DriverCommand.SWITCH_TO_CONTEXT, ImmutableMap.of("name", name));471 return this;472 }473 @Override public Set<String> getContextHandles() {474 Response response = execute(DriverCommand.GET_CONTEXT_HANDLES);475 Object value = response.getValue();476 try {477 List<String> returnedValues = (List<String>) value;478 return new LinkedHashSet<>(returnedValues);479 } catch (ClassCastException ex) {480 throw new WebDriverException(481 "Returned value cannot be converted to List<String>: " + value, ex);482 }483 }484 @Override public String getContext() {485 String contextName =486 String.valueOf(execute(DriverCommand.GET_CURRENT_CONTEXT_HANDLE).getValue());487 if (contextName.equals("null")) {488 return null;489 }490 return contextName;491 }492 @Override public void rotate(ScreenOrientation orientation) {493 execute(DriverCommand.SET_SCREEN_ORIENTATION,494 ImmutableMap.of("orientation", orientation.value().toUpperCase()));495 }496 @Override public ScreenOrientation getOrientation() {497 Response response = execute(DriverCommand.GET_SCREEN_ORIENTATION);498 String orientation = response.getValue().toString().toLowerCase();499 if (orientation.equals(ScreenOrientation.LANDSCAPE.value())) {500 return ScreenOrientation.LANDSCAPE;501 } else if (orientation.equals(ScreenOrientation.PORTRAIT.value())) {502 return ScreenOrientation.PORTRAIT;503 } else {504 throw new WebDriverException("Unexpected orientation returned: " + orientation);505 }506 }507 @Override public Location location() {508 return locationContext.location();509 }510 @Override public void setLocation(Location location) {511 locationContext.setLocation(location);512 }513 /**514 * @return a map with localized strings defined in the app.515 * @see HasAppStrings#getAppStringMap().516 */517 @Override public Map<String, String> getAppStringMap() {518 Response response = execute(GET_STRINGS);519 return (Map<String, String>) response.getValue();520 }521 /**522 * @param language strings language code.523 * @return a map with localized strings defined in the app.524 * @see HasAppStrings#getAppStringMap(String).525 */526 @Override public Map<String, String> getAppStringMap(String language) {527 Response response = execute(GET_STRINGS, prepareArguments("language", language));528 return (Map<String, String>) response.getValue();529 }530 /**531 * @param language strings language code.532 * @param stringFile strings filename.533 * @return a map with localized strings defined in the app.534 * @see HasAppStrings#getAppStringMap(String, String).535 */536 @Override public Map<String, String> getAppStringMap(String language, String stringFile) {537 String[] parameters = new String[] {"language", "stringFile"};538 Object[] values = new Object[] {language, stringFile};539 Response response = execute(GET_STRINGS, prepareArguments(parameters, values));540 return (Map<String, String>) response.getValue();541 }542 private TouchAction createTap(WebElement element, int duration) {543 TouchAction tap = new TouchAction(this);544 return tap.press(element).waitAction(duration).release();545 }546 private TouchAction createTap(int x, int y, int duration) {547 TouchAction tap = new TouchAction(this);548 return tap.press(x, y).waitAction(duration).release();549 }550 public URL getRemoteAddress() {551 return remoteAddress;552 }553 /**554 * @return a map with values that hold session details.555 *556 */557 public Map<String, Object> getSessionDetails() {558 Response response = execute(GET_SESSION);559 return (Map<String, Object>) response.getValue();560 }561}...

Full Screen

Full Screen

AppiumDriver.java

Source:AppiumDriver.java Github

copy

Full Screen

...58 private static final ErrorHandler errorHandler = new ErrorHandler(new ErrorCodesMobile(), true);59 // frequently used command parameters60 private final URL remoteAddress;61 protected final RemoteLocationContext locationContext;62 private final ExecuteMethod executeMethod;63 /**64 * Creates a new instance based on command {@code executor} and {@code capabilities}.65 *66 * @param executor is an instance of {@link HttpCommandExecutor}67 * or class that extends it. Default commands or another vendor-specific68 * commands may be specified there.69 * @param capabilities take a look at {@link Capabilities}70 */71 public AppiumDriver(HttpCommandExecutor executor, Capabilities capabilities) {72 super(executor, capabilities);73 this.executeMethod = new AppiumExecutionMethod(this);74 locationContext = new RemoteLocationContext(executeMethod);75 super.setErrorHandler(errorHandler);76 this.remoteAddress = executor.getAddressOfRemoteServer();77 }78 public AppiumDriver(URL remoteAddress, Capabilities capabilities) {79 this(new AppiumCommandExecutor(MobileCommand.commandRepository, remoteAddress),80 capabilities);81 }82 public AppiumDriver(URL remoteAddress, HttpClient.Factory httpClientFactory,83 Capabilities capabilities) {84 this(new AppiumCommandExecutor(MobileCommand.commandRepository, remoteAddress,85 httpClientFactory), capabilities);86 }87 public AppiumDriver(AppiumDriverLocalService service, Capabilities capabilities) {88 this(new AppiumCommandExecutor(MobileCommand.commandRepository, service),89 capabilities);90 }91 public AppiumDriver(AppiumDriverLocalService service, HttpClient.Factory httpClientFactory,92 Capabilities capabilities) {93 this(new AppiumCommandExecutor(MobileCommand.commandRepository, service, httpClientFactory),94 capabilities);95 }96 public AppiumDriver(AppiumServiceBuilder builder, Capabilities capabilities) {97 this(builder.build(), capabilities);98 }99 public AppiumDriver(AppiumServiceBuilder builder, HttpClient.Factory httpClientFactory,100 Capabilities capabilities) {101 this(builder.build(), httpClientFactory, capabilities);102 }103 public AppiumDriver(HttpClient.Factory httpClientFactory, Capabilities capabilities) {104 this(AppiumDriverLocalService.buildDefaultService(), httpClientFactory,105 capabilities);106 }107 public AppiumDriver(Capabilities capabilities) {108 this(AppiumDriverLocalService.buildDefaultService(), capabilities);109 }110 /**111 * Changes platform name if it is not set and returns merged capabilities.112 *113 * @param originalCapabilities the given {@link Capabilities}.114 * @param defaultName a {@link MobileCapabilityType#PLATFORM_NAME} value which has115 * to be set up116 * @return {@link Capabilities} with changed platform name value or the original capabilities117 */118 protected static Capabilities ensurePlatformName(119 Capabilities originalCapabilities, String defaultName) {120 String currentName = (String) originalCapabilities.getCapability(PLATFORM_NAME);121 return isBlank(currentName)122 ? originalCapabilities.merge(new ImmutableCapabilities(PLATFORM_NAME, defaultName))123 : originalCapabilities;124 }125 /**126 * Changes automation name if it is not set and returns merged capabilities.127 *128 * @param originalCapabilities the given {@link Capabilities}.129 * @param defaultName a {@link MobileCapabilityType#AUTOMATION_NAME} value which has130 * to be set up131 * @return {@link Capabilities} with changed mobile automation name value or the original capabilities132 */133 protected static Capabilities ensureAutomationName(134 Capabilities originalCapabilities, String defaultName) {135 String currentAutomationName = CapabilityHelpers.getCapability(136 originalCapabilities, AUTOMATION_NAME, String.class);137 if (isBlank(currentAutomationName)) {138 String capabilityName = originalCapabilities.getCapabilityNames()139 .contains(AUTOMATION_NAME) ? AUTOMATION_NAME : APPIUM_PREFIX + AUTOMATION_NAME;140 return originalCapabilities.merge(new ImmutableCapabilities(capabilityName, defaultName));141 }142 return originalCapabilities;143 }144 /**145 * Changes platform and automation names if they are not set146 * and returns merged capabilities.147 *148 * @param originalCapabilities the given {@link Capabilities}.149 * @param defaultPlatformName a {@link MobileCapabilityType#PLATFORM_NAME} value which has150 * to be set up151 * @param defaultAutomationName The default automation name to set up for this class152 * @return {@link Capabilities} with changed platform/automation name value or the original capabilities153 */154 protected static Capabilities ensurePlatformAndAutomationNames(155 Capabilities originalCapabilities, String defaultPlatformName, String defaultAutomationName) {156 Capabilities capsWithPlatformFixed = ensurePlatformName(originalCapabilities, defaultPlatformName);157 return ensureAutomationName(capsWithPlatformFixed, defaultAutomationName);158 }159 @Override160 public ExecuteMethod getExecuteMethod() {161 return executeMethod;162 }163 /**164 * This method is used to get build version status of running Appium server.165 *166 * @return map containing version details167 */168 public Map<String, Object> getStatus() {169 //noinspection unchecked170 return (Map<String, Object>) execute(DriverCommand.STATUS).getValue();171 }172 /**173 * This method is used to add custom appium commands in Appium 2.0.174 *175 * @param httpMethod the available {@link HttpMethod}.176 * @param url The url to URL template as https://www.w3.org/TR/webdriver/#endpoints.177 * @param methodName The name of custom appium command.178 */179 public void addCommand(HttpMethod httpMethod, String url, String methodName) {180 switch (httpMethod) {181 case GET:182 MobileCommand.commandRepository.put(methodName, MobileCommand.getC(url));183 break;184 case POST:185 MobileCommand.commandRepository.put(methodName, MobileCommand.postC(url));186 break;187 case DELETE:188 MobileCommand.commandRepository.put(methodName, MobileCommand.deleteC(url));189 break;190 default:191 throw new WebDriverException(String.format("Unsupported HTTP Method: %s. Only %s methods are supported",192 httpMethod,193 Arrays.toString(HttpMethod.values())));194 }195 ((AppiumCommandExecutor) getCommandExecutor()).refreshAdditionalCommands();196 }197 public URL getRemoteAddress() {198 return remoteAddress;199 }200 @Override201 protected void startSession(Capabilities capabilities) {202 Response response = execute(new AppiumNewSessionCommandPayload(capabilities));203 if (response == null) {204 throw new SessionNotCreatedException(205 "The underlying command executor returned a null response.");206 }207 Object responseValue = response.getValue();208 if (responseValue == null) {209 throw new SessionNotCreatedException(210 "The underlying command executor returned a response without payload: "211 + response);212 }213 if (!(responseValue instanceof Map)) {214 throw new SessionNotCreatedException(215 "The underlying command executor returned a response with a non well formed payload: "216 + response);217 }218 @SuppressWarnings("unchecked") Map<String, Object> rawCapabilities = (Map<String, Object>) responseValue;219 // A workaround for Selenium API enforcing some legacy capability values220 rawCapabilities.remove(CapabilityType.PLATFORM);221 if (rawCapabilities.containsKey(CapabilityType.BROWSER_NAME)222 && isBlank((String) rawCapabilities.get(CapabilityType.BROWSER_NAME))) {223 rawCapabilities.remove(CapabilityType.BROWSER_NAME);224 }225 MutableCapabilities returnedCapabilities = new BaseOptions<>(rawCapabilities);226 try {227 Field capsField = RemoteWebDriver.class.getDeclaredField("capabilities");228 capsField.setAccessible(true);229 capsField.set(this, returnedCapabilities);230 } catch (NoSuchFieldException | IllegalAccessException e) {231 throw new WebDriverException(e);232 }233 setSessionId(response.getSessionId());234 }235 @Override236 public Response execute(String driverCommand, Map<String, ?> parameters) {237 return super.execute(driverCommand, parameters);238 }239 @Override240 public Response execute(String command) {241 return super.execute(command, Collections.emptyMap());242 }243}...

Full Screen

Full Screen

AppiumSteps.java

Source:AppiumSteps.java Github

copy

Full Screen

...180 HttpCommandExecutor executor = (HttpCommandExecutor) ((QAFExtendedWebDriver) driver)181 .getCommandExecutor();182 AppiumCommandExecutor appiumCommandExecutor = new AppiumCommandExecutor(MobileCommand.commandRepository,183 executor.getAddressOfRemoteServer()) {184 public Response execute(Command command) throws WebDriverException {185 if (DriverCommand.NEW_SESSION.equals(command.getName())) {186 setCommandCodec((CommandCodec<HttpRequest>) ClassUtil.getField("commandCodec", executor));187 setResponseCodec((ResponseCodec<HttpResponse>) ClassUtil.getField("responseCodec", executor));188 getAdditionalCommands().forEach(this::defineCommand);189 Response response = new Response(((QAFExtendedWebDriver) driver).getSessionId());190 response.setValue(JSONUtil.toMap(JSONUtil.toString(capabilities.asMap())));191 response.setStatus(ErrorCodes.SUCCESS);192 response.setState(ErrorCodes.SUCCESS_STRING);193 return response;194 } else {195 return super.execute(command);196 }197 }198 };199 if (capabilities.getPlatform().is(Platform.ANDROID)) {200 return new AndroidDriver<WebElement>(appiumCommandExecutor, capabilities);201 }202 if (capabilities.getPlatform().is(Platform.IOS)) {203 return new IOSDriver<WebElement>(appiumCommandExecutor, capabilities);204 }205 if (capabilities.getPlatform().is(Platform.WINDOWS)) {206 return new WindowsDriver<WebElement>(executor, capabilities);207 }208 } catch (Exception e) {209 throw new AutomationError("Unable to build AppiumDriver from " + driver.getClass(), e);...

Full Screen

Full Screen

IOSDriver.java

Source:IOSDriver.java Github

copy

Full Screen

...150 */151 @Override public void runAppInBackground(Duration duration) {152 // timeout parameter is expected to be in milliseconds153 // float values are allowed154 execute(RUN_APP_IN_BACKGROUND,155 prepareArguments("seconds", prepareArguments("timeout", duration.toMillis())));156 }157 @Override public TargetLocator switchTo() {158 return new InnerTargetLocator();159 }160 private class InnerTargetLocator extends RemoteTargetLocator {161 @Override public Alert alert() {162 return new IOSAlert(super.alert());163 }164 }165 class IOSAlert implements Alert {166 private final Alert alert;167 IOSAlert(Alert alert) {168 this.alert = alert;169 }170 @Override public void dismiss() {171 execute(DriverCommand.DISMISS_ALERT);172 }173 @Override public void accept() {174 execute(DriverCommand.ACCEPT_ALERT);175 }176 @Override public String getText() {177 Response response = execute(DriverCommand.GET_ALERT_TEXT);178 return response.getValue().toString();179 }180 @Override public void sendKeys(String keysToSend) {181 execute(DriverCommand.SET_ALERT_VALUE, prepareArguments("value", keysToSend));182 }183 @Override public void setCredentials(Credentials credentials) {184 alert.setCredentials(credentials);185 }186 @Override public void authenticateUsing(Credentials credentials) {187 alert.authenticateUsing(credentials);188 }189 }190}...

Full Screen

Full Screen

AndroidDriver.java

Source:AndroidDriver.java Github

copy

Full Screen

...142 * @param intent intent to broadcast.143 * @param path path to .ec file.144 */145 public void endTestCoverage(String intent, String path) {146 CommandExecutionHelper.execute(this, endTestCoverageCommand(intent, path));147 }148 /**149 * Open the notification shade, on Android devices.150 */151 public void openNotifications() {152 CommandExecutionHelper.execute(this, openNotificationsCommand());153 }154 public void toggleLocationServices() {155 CommandExecutionHelper.execute(this, toggleLocationServicesCommand());156 }157}...

Full Screen

Full Screen

EventFiringAppiumCommandExecutor.java

Source:EventFiringAppiumCommandExecutor.java Github

copy

Full Screen

...108 private void setCommandCodec(CommandCodec<HttpRequest> newCodec) {109 setPrivateFieldValue("commandCodec", newCodec);110 }111 @Override112 public Response execute(Command command) throws WebDriverException {113 if (DriverCommand.NEW_SESSION.equals(command.getName())) {114 serviceOptional.ifPresent(driverService -> {115 try {116 driverService.start();117 } catch (IOException e) {118 throw new WebDriverException(e.getMessage(), e);119 }120 });121 }122 Response response;123 try {124 for (IDriverCommandListener listener : listeners) {125 listener.beforeEvent(command);126 }127 response = super.execute(command);128 for (IDriverCommandListener listener : listeners) {129 listener.afterEvent(command);130 }131 } catch (Throwable t) {132 Throwable rootCause = Throwables.getRootCause(t);133 if (rootCause instanceof ConnectException134 && rootCause.getMessage().contains("Connection refused")) {135 throw serviceOptional.map(service -> {136 if (service.isRunning()) {137 return new WebDriverException("The session is closed!", rootCause);138 }139 return new WebDriverException("The appium server has accidentally died!", rootCause);140 }).orElseGet((Supplier<WebDriverException>) () -> new WebDriverException(rootCause.getMessage(), rootCause));141 }...

Full Screen

Full Screen

AppiumCommandExecutor.java

Source:AppiumCommandExecutor.java Github

copy

Full Screen

...111 "No command or response codec has been defined. Unable to proceed");112 }113 HttpRequest httpRequest = commandCodec.encode(command);114 try {115 HttpResponse httpResponse = client.execute(httpRequest, true);116 Response response = responseCodec.decode(httpResponse);117 if (response.getSessionId() == null) {118 if (httpResponse.getTargetHost() != null) {119 response.setSessionId(HttpSessionId.getSessionId(httpResponse.getTargetHost()));120 } else {121 response.setSessionId(command.getSessionId().toString());122 }123 }124 if (QUIT.equals(command.getName())) {125 client.close();126 }127 return response;128 } catch (UnsupportedCommandException e) {129 if (e.getMessage() == null || "".equals(e.getMessage())) {130 throw new UnsupportedOperationException(131 "No information from server. Command name was: " + command.getName(),132 e.getCause());133 }134 throw e;135 }136 }137 @Override public Response execute(Command command) throws IOException, WebDriverException {138 if (DriverCommand.NEW_SESSION.equals(command.getName()) && service != null) {139 service.start();140 }141 try {142 return doExecute(command);143 } catch (Throwable t) {144 Throwable rootCause = getRootCause(t);145 if (rootCause instanceof ConnectException146 && rootCause.getMessage().contains("Connection refused")147 && service != null) {148 if (service.isRunning()) {149 throw new WebDriverException("The session is closed!", t);150 }151 if (!service.isRunning()) {...

Full Screen

Full Screen

CustomAppiumCommandExecutor.java

Source:CustomAppiumCommandExecutor.java Github

copy

Full Screen

...31import static io.testproject.sdk.internal.helpers.DriverHelper.FIELD_RESPONSE_CODEC;32/**33 * A custom Appium commands executor for Appium drivers.34 * Extends the original functionality by restoring driver session initiated by the Agent.35 * Reports commands executed to Agent.36 */37public final class CustomAppiumCommandExecutor38 extends io.appium.java_client.remote.AppiumCommandExecutor39 implements ReportingCommandsExecutor {40 /**41 * Agent client cached instance.42 */43 private final AgentClient agentClient;44 /**45 * Commands and responses stash to keep FluentWait attempts before reporting them.46 */47 private final StashedCommands stashedCommands = new StashedCommands();48 /**49 * Flag to enable/disable any reports.50 */51 private boolean reportsDisabled;52 /**53 * Flag to enable/disable command reports.54 */55 private boolean commandReportsDisabled;56 /**57 * Flag to enable/disable test reports.58 */59 private boolean testReportsDisabled;60 /**61 * Flag to enable/disable commands reports redaction.62 */63 private boolean redactionDisabled;64 /**65 * Current Test name tracking object.66 */67 private final AtomicReference<String> currentTest = new AtomicReference<>(null);68 /**69 * Initializes a new instance of this an Executor restoring command/response codecs.70 *71 * @param agentClient an instance of {@link AgentClient} used to pen the original driver session.72 * @param addressOfRemoteServer URL of the remote Appium server managed by the Agent73 */74 public CustomAppiumCommandExecutor(final AgentClient agentClient, final URL addressOfRemoteServer) {75 super(MobileCommand.commandRepository, addressOfRemoteServer);76 this.agentClient = agentClient;77 // Usually this is happening when the NEW_SESSION command is handled78 // Here we mimic the same logic using reflection, setting missing codecs and commands79 CommandCodec<HttpRequest> commandCodec = agentClient.getSession().getDialect().getCommandCodec();80 if (commandCodec instanceof W3CHttpCommandCodec) {81 commandCodec = new AppiumW3CHttpCommandCodec();82 }83 DriverHelper.setPrivateFieldValue(this, FIELD_COMMAND_CODEC, commandCodec);84 DriverHelper.setPrivateFieldValue(this, FIELD_RESPONSE_CODEC,85 agentClient.getSession().getDialect().getResponseCodec());86 getAdditionalCommands().forEach(this::defineCommand);87 }88 @Override89 public Response execute(final Command command) throws WebDriverException {90 return execute(command, false);91 }92 /**93 * Extended command execution method.94 * Allows skipping reporting for "internal" commands, for example:95 * - Taking screenshot for manual step reporting.96 * - Inspecting element type to determine whether redaction is required.97 * @param command Command to execute98 * @param skipReporting Flag to control reporting99 * @return Command execution response.100 */101 @Override102 public Response execute(final Command command, final boolean skipReporting) {103 Response response = null;104 if (!command.getName().equals(DriverCommand.QUIT)) {105 // Preserve the mobile session, agent got /change custom Appium endpoint106 response = super.execute(command);107 }108 if (!skipReporting) {109 reportCommand(command, response);110 }111 return response;112 }113 @Override114 public AgentClient getAgentClient() {115 return this.agentClient;116 }117 @Override118 public StashedCommands getStashedCommands() {119 return stashedCommands;120 }...

Full Screen

Full Screen

execute

Using AI Code Generation

copy

Full Screen

1public static void main(String[] args) {2 DesiredCapabilities capabilities = new DesiredCapabilities();3 capabilities.setCapability("deviceName", "Android Emulator");4 capabilities.setCapability("platformName", "Android");5 capabilities.setCapability("platformVersion", "4.4");6 capabilities.setCapability("appPackage", "com.android.calculator2");7 capabilities.setCapability("appActivity", ".Calculator");8 capabilities.setCapability("app", "C:\\Users\\sudheer\\Desktop\\apk\\Calculator.apk");

Full Screen

Full Screen

execute

Using AI Code Generation

copy

Full Screen

1package appium.java;2import java.net.URL;3import org.openqa.selenium.remote.DesiredCapabilities;4import io.appium.java_client.AppiumDriver;5import io.appium.java_client.remote.AppiumCommandExecutor;6public class App {7 public static void main(String[] args) throws Exception {8 DesiredCapabilities capabilities = new DesiredCapabilities();9 capabilities.setCapability("deviceName", "A0001");10 capabilities.setCapability("platformName", "Android");11 capabilities.setCapability("platformVersion", "5.0.2");12 capabilities.setCapability("appPackage", "com.android.calculator2");13 capabilities.setCapability("appActivity", "com.android.calculator2.Calculator");

Full Screen

Full Screen

execute

Using AI Code Generation

copy

Full Screen

1AppiumDriver driver = new AppiumDriver();2AppiumCommandExecutor executor = (AppiumCommandExecutor) driver.getCommandExecutor();3executor.execute(driver.getSessionId(), new AppiumCommand("command name").setParameter("param name", "param value"));4AppiumDriver driver = new AppiumDriver();5AppiumCommandExecutor executor = (AppiumCommandExecutor) driver.getCommandExecutor();6executor.executeAsync(driver.getSessionId(), new AppiumCommand("command name").setParameter("param name", "param value"));7AppiumDriver driver = new AppiumDriver();8AppiumCommandExecutor executor = (AppiumCommandExecutor) driver.getCommandExecutor();9executor.execute(driver.getSessionId(), new AppiumCommand("command name").setParameter("param name", "param value"));10AppiumDriver driver = new AppiumDriver();11AppiumCommandExecutor executor = (AppiumCommandExecutor) driver.getCommandExecutor();12executor.executeAsync(driver.getSessionId(), new AppiumCommand("command name").setParameter("param name", "param value"));13AppiumDriver driver = new AppiumDriver();14AppiumCommandExecutor executor = (AppiumCommandExecutor) driver.getCommandExecutor();

Full Screen

Full Screen

execute

Using AI Code Generation

copy

Full Screen

1public class AppiumCommandExecutor extends HttpCommandExecutor{2 public AppiumCommandExecutor(URL url) {3 super(url);4 }5 public Response execute(Command command) throws IOException {6 String url = this.getAddressOfRemoteServer().toString();7 url = url + command.getName();8 System.out.println(url);9 String json = new Gson().toJson(command);10 System.out.println(json);11 Response response = new HttpClient().execute(new HttpRequest(HttpMethod.POST, url), json);12 System.out.println(response.getValue());13 return response;14 }15}16public class AppiumCommandExecutor extends HttpCommandExecutor{17 public AppiumCommandExecutor(URL url) {18 super(url);19 }20 public Response execute(Command command) throws IOException {21 String url = this.getAddressOfRemoteServer().toString();22 url = url + command.getName();23 System.out.println(url);24 String json = new Gson().toJson(command);25 System.out.println(json);26 Response response = new HttpClient().execute(new HttpRequest(HttpMethod.POST, url), json);27 System.out.println(response.getValue());28 return response;29 }30}31public class AppiumCommandExecutor extends HttpCommandExecutor{32 public AppiumCommandExecutor(URL url) {33 super(url);34 }35 public Response execute(Command command) throws IOException {36 String url = this.getAddressOfRemoteServer().toString();37 url = url + command.getName();38 System.out.println(url);39 String json = new Gson().toJson(command);40 System.out.println(json);41 Response response = new HttpClient().execute(new HttpRequest(HttpMethod.POST, url), json);42 System.out.println(response.getValue());43 return response;44 }45}

Full Screen

Full Screen

execute

Using AI Code Generation

copy

Full Screen

1public class AppiumCommandExecutor extends HttpCommandExecutor {2 public AppiumCommandExecutor(URL addressOfRemoteServer) {3 super(addressOfRemoteServer);4 }5 public Response execute(Command command) throws IOException {6 Response response = super.execute(command);7 return response;8 }9}10public class AppiumCommandExecutor extends HttpCommandExecutor {11 public AppiumCommandExecutor(URL addressOfRemoteServer) {12 super(addressOfRemoteServer);13 }14 public Response execute(Command command) throws IOException {15 Response response = super.execute(command);16 return response;17 }18}19public class AppiumCommandExecutor extends HttpCommandExecutor {20 public AppiumCommandExecutor(URL addressOfRemoteServer) {21 super(addressOfRemoteServer);22 }23 public Response execute(Command command) throws IOException {24 Response response = super.execute(command);25 return response;26 }27}28public class AppiumCommandExecutor extends HttpCommandExecutor {29 public AppiumCommandExecutor(URL addressOfRemoteServer) {30 super(addressOfRemoteServer);31 }32 public Response execute(Command command) throws IOException {33 Response response = super.execute(command);34 return response;35 }36}37public class AppiumCommandExecutor extends HttpCommandExecutor {38 public AppiumCommandExecutor(URL addressOfRemoteServer) {39 super(addressOfRemoteServer);40 }41 public Response execute(Command command) throws IOException {42 Response response = super.execute(command);43 return response;44 }45}46public class AppiumCommandExecutor extends HttpCommandExecutor {47 public AppiumCommandExecutor(URL addressOfRemoteServer) {48 super(addressOfRemoteServer

Full Screen

Full Screen

execute

Using AI Code Generation

copy

Full Screen

1package appium;2import java.net.URL;3import java.util.HashMap;4import java.util.Map;5import org.openqa.selenium.remote.Response;6import io.appium.java_client.remote.AppiumCommandExecutor;7import io.appium.java_client.remote.AppiumCommandExecutionHelper;8import io.appium.java_client.remote.MobileCommand;9public class ExecuteCommand {10public static void main(String[] args) throws Exception {

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run io.appium 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