Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   +Copyright 2014-2015 Appium contributors
   +Copyright 2014-2015 Software Freedom Conservancy
   +
   +Licensed under the Apache License, Version 2.0 (the "License");
   +you may not use this file except in compliance with the License.
   +You may obtain a copy of the License at
   +
   +     http://www.apache.org/licenses/LICENSE-2.0
  +
  +Unless required by applicable law or agreed to in writing, software
  +distributed under the License is distributed on an "AS IS" BASIS,
  +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  +See the License for the specific language governing permissions and
  +limitations under the License.
  + */
 
 package io.appium.java_client;
 
 import static io.appium.java_client.MobileCommand.CLOSE_APP;
 import static io.appium.java_client.MobileCommand.COMPLEX_FIND;
 import static io.appium.java_client.MobileCommand.CURRENT_ACTIVITY;
 import static io.appium.java_client.MobileCommand.END_TEST_COVERAGE;
 import static io.appium.java_client.MobileCommand.GET_NETWORK_CONNECTION;
 import static io.appium.java_client.MobileCommand.GET_SETTINGS;
 import static io.appium.java_client.MobileCommand.GET_STRINGS;
 import static io.appium.java_client.MobileCommand.HIDE_KEYBOARD;
 import static io.appium.java_client.MobileCommand.INSTALL_APP;
 import static io.appium.java_client.MobileCommand.IS_APP_INSTALLED;
 import static io.appium.java_client.MobileCommand.IS_LOCKED;
 import static io.appium.java_client.MobileCommand.KEY_EVENT;
 import static io.appium.java_client.MobileCommand.LAUNCH_APP;
 import static io.appium.java_client.MobileCommand.LOCK;
 import static io.appium.java_client.MobileCommand.OPEN_NOTIFICATIONS;
 import static io.appium.java_client.MobileCommand.PERFORM_MULTI_TOUCH;
 import static io.appium.java_client.MobileCommand.PERFORM_TOUCH_ACTION;
 import static io.appium.java_client.MobileCommand.PULL_FILE;
 import static io.appium.java_client.MobileCommand.PULL_FOLDER;
 import static io.appium.java_client.MobileCommand.PUSH_FILE;
 import static io.appium.java_client.MobileCommand.REMOVE_APP;
 import static io.appium.java_client.MobileCommand.RESET;
 import static io.appium.java_client.MobileCommand.RUN_APP_IN_BACKGROUND;
 import static io.appium.java_client.MobileCommand.SET_NETWORK_CONNECTION;
 import static io.appium.java_client.MobileCommand.SET_SETTINGS;
 import static io.appium.java_client.MobileCommand.SET_VALUE;
 import static io.appium.java_client.MobileCommand.SHAKE;
 import static io.appium.java_client.MobileCommand.START_ACTIVITY;
 import static io.appium.java_client.MobileCommand.TOGGLE_LOCATION_SERVICES;
 
 import java.net.URL;
 import java.util.List;
 import java.util.Set;
 
 
 import  org.openqa.selenium.By;
 import  org.openqa.selenium.Capabilities;
 import  org.openqa.selenium.Dimension;
 import  org.openqa.selenium.Point;
 import  org.openqa.selenium.ScreenOrientation;
 import  org.openqa.selenium.WebDriver;
 import  org.openqa.selenium.WebDriverException;
 import  org.openqa.selenium.WebElement;
 import  org.openqa.selenium.html5.Location;
 import  org.openqa.selenium.remote.CommandInfo;
 import  org.openqa.selenium.remote.DesiredCapabilities;
 import  org.openqa.selenium.remote.DriverCommand;
 import  org.openqa.selenium.remote.ErrorHandler;
 import  org.openqa.selenium.remote.ExecuteMethod;
 import  org.openqa.selenium.remote.HttpCommandExecutor;
 import  org.openqa.selenium.remote.RemoteWebElement;
 import  org.openqa.selenium.remote.Response;
 import  org.openqa.selenium.remote.html5.RemoteLocationContext;
 import  org.openqa.selenium.remote.http.HttpMethod;
 

Parameters:
<RequiredElementType> means the required type from the list of allowed types below that implement WebElement Instances of the defined type will be returned via findElement* and findElements*. Warning (!!!). Allowed types:
WebElement
TouchableElement
RemoteWebElement
MobileElement and its subclasses that designed specifically for each target mobile OS (still Android and iOS)
 
 @SuppressWarnings("unchecked")
 public abstract class AppiumDriver<RequiredElementType extends WebElement> extends DefaultGenericMobileDriver<RequiredElementType> {
 
 	private final static ErrorHandler errorHandler = new ErrorHandler(
 			new ErrorCodesMobile(), true);
 	private URL remoteAddress;
 	private RemoteLocationContext locationContext;
	private ExecuteMethod executeMethod;
	// frequently used command parameters
	protected final String KEY_CODE = "keycode";
	protected final String PATH = "path";
	private final String SETTINGS = "settings";
	private final String LANGUAGE_PARAM = "language";

Parameters:
originalCapabilities the given Capabilities
newPlatform a MobileCapabilityType.PLATFORM_NAME value which has to be set up
Returns:
Capabilities with changed mobile platform value
	protected static Capabilities substituteMobilePlatform(
			Capabilities originalCapabilitiesString newPlatform) {
		DesiredCapabilities dc = new DesiredCapabilities(originalCapabilities);
		dc.setCapability(.newPlatform);
		return dc;
	}
    @Override
    public List<RequiredElementType> findElements(By by){
        return super.findElements(by);
    }
    @Override
    public List<RequiredElementType> findElementsById(String id){
        return super.findElementsById(id);
    }
	public List<RequiredElementType> findElementsByLinkText(String using) {
        return super.findElementsByLinkText(using);
    }
    public List<RequiredElementType> findElementsByPartialLinkText(String using) {
        return super.findElementsByPartialLinkText(using);
    }
    public List<RequiredElementType> findElementsByTagName(String using) {
        return super.findElementsByTagName(using);
    }
    public List<RequiredElementType> findElementsByName(String using) {
        return super.findElementsByName(using);
    }
    public List<RequiredElementType> findElementsByClassName(String using) {
        return super.findElementsByClassName(using);
    }
    public List<RequiredElementType> findElementsByCssSelector(String using) {
        return super.findElementsByCssSelector(using);
    }
    public List<RequiredElementType> findElementsByXPath(String using) {
        return super.findElementsByXPath(using);
    }
    @Override
    public List<RequiredElementType> findElementsByAccessibilityId(String using) {
        return (List<RequiredElementType>) findElements("accessibility id"using);
    }

    

Parameters:
param is a parameter name
value is the parameter value
Returns:
built ImmutableMap
			String paramObject value) {
		ImmutableMap.Builder<StringObjectbuilder = ImmutableMap.builder();
		builder.put(paramvalue);
		return builder.build();
	}

Parameters:
params is the array with parameter names
values is the array with parameter values
Returns:
built ImmutableMap
			String[] paramsObject[] values) {
		ImmutableMap.Builder<StringObjectbuilder = ImmutableMap.builder();
		for (int i = 0; i < params.lengthi++) {
			if (_isNotNullOrEmpty(params[i]) && _isNotNullOrEmpty(values[i])) {
				builder.put(params[i], values[i]);
			}
		}
		return builder.build();
	}
	public AppiumDriver(URL remoteAddress, Capabilities desiredCapabilities) {
		super(remoteAddressdesiredCapabilities);
		this. = remoteAddress;
		 = new RemoteLocationContext();
		ImmutableMap.Builder<String, CommandInfo> builder = ImmutableMap
		builder.put(postC("/session/:sessionId/appium/app/reset"))
						postC("/session/:sessionId/appium/app/strings"))
						postC("/session/:sessionId/appium/device/keyevent"))
						getC("/session/:sessionId/appium/device/current_activity"))
						postC("/session/:sessionId/appium/element/:id/value"))
						postC("/session/:sessionId/appium/device/pull_file"))
						postC("/session/:sessionId/appium/device/pull_folder"))
						postC("/session/:sessionId/appium/device/hide_keyboard"))
						postC("/session/:sessionId/appium/device/push_file"))
						postC("/session/:sessionId/appium/app/background"))
						postC("/session/:sessionId/touch/perform"))
						postC("/session/:sessionId/touch/multi/perform"))
						postC("/session/:sessionId/appium/device/app_installed"))
						postC("/session/:sessionId/appium/device/install_app"))
						postC("/session/:sessionId/appium/device/remove_app"))
				.put(postC("/session/:sessionId/appium/app/launch"))
				.put(postC("/session/:sessionId/appium/app/close"))
						postC("/session/:sessionId/appium/app/end_test_coverage"))
				.put(postC("/session/:sessionId/appium/device/lock"))
						postC("/session/:sessionId/appium/device/is_locked"))
				.put(postC("/session/:sessionId/appium/device/shake"))
						postC("/session/:sessionId/appium/app/complex_find"))
						postC("/session/:sessionId/appium/device/open_notifications"))
						getC("/session/:sessionId/network_connection"))
						postC("/session/:sessionId/network_connection"))
				.put(getC("/session/:sessionId/appium/settings"))
				.put(postC("/session/:sessionId/appium/settings"))
						postC("/session/:sessionId/appium/device/start_activity"))
				.put(postC("/session/:sessionId/appium/device/toggle_location_services"));
		ImmutableMap<String, CommandInfo> mobileCommands = builder.build();
		HttpCommandExecutor mobileExecutor = new HttpCommandExecutor(
				mobileCommandsremoteAddress);
		super.setCommandExecutor(mobileExecutor);
		super.setErrorHandler();
	}
	protected Response execute(String command) {
		return super.execute(command, ImmutableMap.<StringObject>of());
	}
	public ExecuteMethod getExecuteMethod() {
	}

See also:
InteractsWithApps.resetApp()
	public void resetApp() {
	}

See also:
InteractsWithApps.isAppInstalled(String)
	public boolean isAppInstalled(String bundleId) {
		Response response = execute(,
				ImmutableMap.of("bundleId"bundleId));
		return Boolean.parseBoolean(response.getValue().toString());
	}

See also:
InteractsWithApps.installApp(String)
	public void installApp(String appPath) {
		execute(, ImmutableMap.of("appPath"appPath));
	}

See also:
InteractsWithApps.removeApp(String)
	public void removeApp(String bundleId) {
		execute(, ImmutableMap.of("bundleId"bundleId));
	}

See also:
InteractsWithApps.launchApp()
	public void launchApp() {
	}

See also:
InteractsWithApps.closeApp()
	public void closeApp() {
	}

See also:
InteractsWithApps.runAppInBackground(int)
	public void runAppInBackground(int seconds) {
		execute(, ImmutableMap.of("seconds"seconds));
	}

See also:
DeviceActionShortcuts.hideKeyboard()
	public void hideKeyboard() {
	}

See also:
InteractsWithFiles.pullFile(String)
	public byte[] pullFile(String remotePath) {
		Response response = execute(,
				ImmutableMap.of(remotePath));
		String base64String = response.getValue().toString();
		return DatatypeConverter.parseBase64Binary(base64String);
	}

See also:
InteractsWithFiles.pullFolder(String)
	public byte[] pullFolder(String remotePath) {
		Response response = execute(,
				ImmutableMap.of(remotePath));
		String base64String = response.getValue().toString();
		return DatatypeConverter.parseBase64Binary(base64String);
	}

See also:
PerformsTouchActions.performTouchAction(TouchAction)
	@SuppressWarnings("rawtypes")
	public TouchAction performTouchAction(TouchAction touchAction) {
		ImmutableMap<StringImmutableListparameters = touchAction
		touchAction.clearParameters();
		return touchAction;
	}

See also:
PerformsTouchActions.performMultiTouchAction(MultiTouchAction)
	@SuppressWarnings({ "rawtypes"})
	public void performMultiTouchAction(MultiTouchAction multiAction) {
		ImmutableMap<StringImmutableListparameters = multiAction
	}

See also:
TouchShortcuts.tap(int, WebElement, int)
	public void tap(int fingers, WebElement elementint duration) {
		MultiTouchAction multiTouch = new MultiTouchAction(this);
		for (int i = 0; i < fingersi++) {
			multiTouch.add(createTap(elementduration));
		}
		multiTouch.perform();
	}

See also:
TouchShortcuts.tap(int, int, int, int)
	public void tap(int fingersint xint yint duration) {
		MultiTouchAction multiTouch = new MultiTouchAction(this);
		for (int i = 0; i < fingersi++) {
			multiTouch.add(createTap(xyduration));
		}
		multiTouch.perform();
	}

See also:
TouchShortcuts.swipe(int, int, int, int, int)
	public void swipe(int startxint startyint endxint endyint duration) {
		TouchAction touchAction = new TouchAction(this);
		// appium converts press-wait-moveto-release to a swipe action
		touchAction.press(startxstarty).waitAction(duration)
				.moveTo(endxendy).release();
		touchAction.perform();
	}

  
Convenience method for pinching an element on the screen. "pinching" refers to the action of two appendages pressing the screen and sliding towards each other. NOTE: This convenience method places the initial touches around the element, if this would happen to place one of them off the screen, appium with return an outOfBounds error. In this case, revert to using the MultiTouchAction api instead of this method.

Parameters:
el The element to pinch
  public void pinch(WebElement el) {
    MultiTouchAction multiTouch = new MultiTouchAction(this);
    Dimension dimensions = el.getSize();
    Point upperLeft = el.getLocation();
    Point center = new Point(upperLeft.getX() + dimensions.getWidth() / 2, upperLeft.getY() + dimensions.getHeight() / 2);
    int yOffset = center.getY() - upperLeft.getY();
    TouchAction action0 = new TouchAction(this).press(elcenter.getX(), center.getY() - yOffset).moveTo(el).release();
    TouchAction action1 = new TouchAction(this).press(elcenter.getX(), center.getY() + yOffset).moveTo(el).release();
    multiTouch.add(action0).add(action1);
    multiTouch.perform();
  }

  
Convenience method for pinching an element on the screen. "pinching" refers to the action of two appendages pressing the screen and sliding towards each other. NOTE: This convenience method places the initial touches around the element at a distance, if this would happen to place one of them off the screen, appium will return an outOfBounds error. In this case, revert to using the MultiTouchAction api instead of this method.

Parameters:
x x coordinate to terminate the pinch on
y y coordinate to terminate the pinch on
  public void pinch(int xint y) {
    MultiTouchAction multiTouch = new MultiTouchAction(this);
    int scrHeight = manage().window().getSize().getHeight();
    int yOffset = 100;
    if (y - 100 < 0) {
      yOffset = y;
    } else if (y + 100 > scrHeight) {
      yOffset = scrHeight - y;
    }
    TouchAction action0 = new TouchAction(this).press(xy - yOffset).moveTo(xy).release();
    TouchAction action1 = new TouchAction(this).press(xy + yOffset).moveTo(xy).release();
    multiTouch.add(action0).add(action1);
    multiTouch.perform();
  }

  
Convenience method for "zooming in" on an element on the screen. "zooming in" refers to the action of two appendages pressing the screen and sliding away from each other. NOTE: This convenience method slides touches away from the element, if this would happen to place one of them off the screen, appium will return an outOfBounds error. In this case, revert to using the MultiTouchAction api instead of this method.

Parameters:
el The element to pinch
  public void zoom(WebElement el) {
    MultiTouchAction multiTouch = new MultiTouchAction(this);
    Dimension dimensions = el.getSize();
    Point upperLeft = el.getLocation();
    Point center = new Point(upperLeft.getX() + dimensions.getWidth() / 2, upperLeft.getY() + dimensions.getHeight() / 2);
    int yOffset = center.getY() - upperLeft.getY();
    TouchAction action0 = new TouchAction(this).press(el).moveTo(elcenter.getX(), center.getY() - yOffset).release();
    TouchAction action1 = new TouchAction(this).press(el).moveTo(elcenter.getX(), center.getY() + yOffset).release();
    multiTouch.add(action0).add(action1);
    multiTouch.perform();
  }

  
Convenience method for "zooming in" on an element on the screen. "zooming in" refers to the action of two appendages pressing the screen and sliding away from each other. NOTE: This convenience method slides touches away from the element, if this would happen to place one of them off the screen, appium will return an outOfBounds error. In this case, revert to using the MultiTouchAction api instead of this method.

Parameters:
x x coordinate to start zoom on
y y coordinate to start zoom on
  public void zoom(int xint y) {
    MultiTouchAction multiTouch = new MultiTouchAction(this);
    int scrHeight = manage().window().getSize().getHeight();
    int yOffset = 100;
    if (y - 100 < 0) {
      yOffset = y;
    } else if (y + 100 > scrHeight) {
      yOffset = scrHeight - y;
    }
    TouchAction action0 = new TouchAction(this).press(xy).moveTo(xy - yOffset).release();
    TouchAction action1 = new TouchAction(this).press(xy).moveTo(xy + yOffset).release();
    multiTouch.add(action0).add(action1);
    multiTouch.perform();
  }

Get settings stored for this test session It's probably better to use a convenience function, rather than use this function directly. Try finding the method for the specific setting you want to read

Returns:
JsonObject, a straight-up hash of settings
	public JsonObject getSettings() {
		Response response = execute();
		JsonParser parser = new JsonParser();
		JsonObject settings = (JsonObjectparser.parse(response.getValue()
				.toString());
		return settings;
	}

Set settings for this test session It's probably better to use a convenience function, rather than use this function directly. Try finding the method for the specific setting you want to change

Parameters:
settings Map of setting keys and values
	private void setSettings(ImmutableMap<?, ?> settings) {
	}

Set a setting for this test session It's probably better to use a convenience function, rather than use this function directly. Try finding the method for the specific setting you want to change

Parameters:
setting AppiumSetting you wish to set
value value of the setting
	protected void setSetting(AppiumSetting settingObject value) {
	}

Lock the device (bring it to the lock screen) for a given number of seconds

Parameters:
seconds number of seconds to lock the screen for
	public void lockScreen(int seconds) {
		execute(, ImmutableMap.of("seconds"seconds));
	}
	public WebDriver context(String name) {
		if (!_isNotNullOrEmpty(name)) {
			throw new IllegalArgumentException("Must supply a context name");
		}
		execute(DriverCommand.SWITCH_TO_CONTEXT, ImmutableMap.of("name"name));
		return AppiumDriver.this;
	}
		Response response = execute(DriverCommand.GET_CONTEXT_HANDLES);
		Object value = response.getValue();
		try {
			List<StringreturnedValues = (List<String>) value;
			return new LinkedHashSet<String>(returnedValues);
catch (ClassCastException ex) {
			throw new WebDriverException(
					"Returned value cannot be converted to List<String>: "
valueex);
		}
	}
	public String getContext() {
		String contextName = String.valueOf(execute(
				DriverCommand.GET_CURRENT_CONTEXT_HANDLE).getValue());
		if (contextName.equals("null")) {
			return null;
		}
		return contextName;
	}
	public void rotate(ScreenOrientation orientation) {
		execute(DriverCommand.SET_SCREEN_ORIENTATION, ImmutableMap.of(
				"orientation"orientation.value().toUpperCase()));
	}
	public ScreenOrientation getOrientation() {
		Response response = execute(DriverCommand.GET_SCREEN_ORIENTATION);
		String orientation = response.getValue().toString().toLowerCase();
		if (orientation.equals(ScreenOrientation.LANDSCAPE.value())) {
			return ScreenOrientation.LANDSCAPE;
else if (orientation.equals(ScreenOrientation.PORTRAIT.value())) {
			return ScreenOrientation.PORTRAIT;
else {
			throw new WebDriverException("Unexpected orientation returned: "
orientation);
		}
	}
	public Location location() {
		return .location();
	}
	public void setLocation(Location location) {
		.setLocation(location);
	}

See also:
HasAppStrings.getAppStrings()
	public String getAppStrings() {
		Response response = execute();
		return response.getValue().toString();
	}

Parameters:
language strings language code
Returns:
a string of all the localized strings defined in the app
See also:
HasAppStrings.getAppStrings(String)
	public String getAppStrings(String language) {
		Response response = execute(,
		return response.getValue().toString();
	}
	private TouchAction createTap(WebElement elementint duration) {
		TouchAction tap = new TouchAction(this);
		return tap.press(element).waitAction(duration).release();
	}
	private TouchAction createTap(int xint yint duration) {
		TouchAction tap = new TouchAction(this);
		return tap.press(xy).waitAction(duration).release();
	}
	private static CommandInfo getC(String url) {
		return new CommandInfo(url, HttpMethod.GET);
	}
	private static CommandInfo postC(String url) {
		return new CommandInfo(url, HttpMethod.POST);
	}
	private static CommandInfo deleteC(String url) {
		return new CommandInfo(url, HttpMethod.DELETE);
	}
	public URL getRemoteAddress() {
	}

Checks if a string is null, empty, or whitespace.

Parameters:
str String to check.
Returns:
True if str is not null or empty.
	protected static boolean _isNotNullOrEmpty(String str) {
		return str != null && !str.isEmpty() && str.trim().length() > 0;
	}
	protected static boolean _isNotNullOrEmpty(Object ob) {
		return ob != null;
	}
New to GrepCode? Check out our FAQ X