Launching and stopping appium server programmtically

1- Install npm
npm install npm -g
2- Install appium
npm install -g appium
3- Just type appium in the CL

I think it was just that

No. actually I wanted to start the server programmatically. I have installed the appium using node command

you can use the above command to run appium

Has anyone had success starting appium on a remote machine using SSH client in C#.NET? I’m using a remote Mac machine running OSX 10.12.1 and appium v1.6.3. I am sending commands from my Windows machine via a remote driver.

I have the following code:

public static void StartRemoteAppiumServer(string host, string username, string password, string command)
{
    client = new SshClient(host, username, password);
    try
    {
        // Connect to remote IP
        client.Connect();
        // Run the command
        client.RunCommand(command);
    }
    catch (Exception e)
    {
        Debug.WriteLine("Unable to establish SSH connection to host" + host + "\nException:" + e.Message);
    }
    finally
    {
        client.Disconnect();
    }
}

The command I’m running is as follows:

/bin/sh /Users/[User]/Documents/iOSAutomation/start_appium.sh

and the script file contains a simple command:

appium --port 4723

It seems to run this successfully; however, when it gets to the point where it tries to start the driver, I receive the following error:

Result1 Name:	01- SetCCLOptions (iossmoketest)
Result1 Outcome:	Failed
Result1 Duration:	0:00:00
Result1 StackTrace:	
at System.Net.HttpWebRequest.GetResponse()
   at OpenQA.Selenium.Remote.HttpCommandExecutor.CreateResponse(WebRequest request)
 --- End of inner exception stack trace ---
    at OpenQA.Selenium.Appium.Service.AppiumCommandExecutor.Execute(Command commandToExecute)
   at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters)
   at OpenQA.Selenium.Remote.RemoteWebDriver.StartSession(ICapabilities desiredCapabilities)
   at OpenQA.Selenium.Remote.RemoteWebDriver..ctor(ICommandExecutor commandExecutor, ICapabilities desiredCapabilities)
   at OpenQA.Selenium.Appium.iOS.IOSDriver`1..ctor(Uri remoteAddress, DesiredCapabilities desiredCapabilities, TimeSpan commandTimeout)
   at iOSAutomation.Base.Setup() in [File]:line 100
   at iOSAutomation.iOSSmokeTest.BeforeClass(TestContext tc) in [file]:line 25
Result1 Message:	Class Initialization method iOSAutomation.iOSSmokeTest.BeforeClass threw exception. OpenQA.Selenium.WebDriverException: OpenQA.Selenium.WebDriverException: A exception with a null response was thrown sending an HTTP request to the remote WebDriver server for URL http://172.xx.xxx.xx:4723/wd/hub/session. The status of the exception was ConnectionClosed, and the message was: The underlying connection was closed: The connection was closed unexpectedly. ---> System.Net.WebException: The underlying connection was closed: The connection was closed unexpectedly..

Any help would be much appreciated.

Appium 1.6.3
OS Sierra 10.12.2

  1. Open Terminal
  2. Which Node
  3. Copy that path into the NodePath below
  4. Which Appium
  5. Copy that path into the Appium Path below
  6. Remove the []

//Start Appium Server
CommandLine command = new CommandLine("[NodePath]");
command.addArgument("[AppiumPath]",false);
command.addArgument("–address", false);
command.addArgument(“127.0.0.1”);
command.addArgument("–port", false);
command.addArgument(strAppiumPort);
command.addArgument("-bp", false);
command.addArgument(strBootstrapPort);
command.addArgument("–full-reset", true);
command.addArgument("–session-override", true);
//command.addArgument("–no-reset", true);
DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
DefaultExecutor executor = new DefaultExecutor();
executor.setExitValue(1);
try {executor.execute(command, resultHandler);
Thread.sleep(5000);System.out.println(“Appium server started.”);}
catch (IOException e)
{e.printStackTrace();}
catch (InterruptedException e)
{e.printStackTrace();}

//Stop Appium Server
String[] command1 = {“sh”, “-c”, “lsof -P | grep '=”+strAppiumPort+"’ | awk ‘{print $2}’ | xargs kill -9"};
try {Runtime.getRuntime().exec(command1);
System.out.println(“Appium server stopped. Port(”+strAppiumPort+")");}catch (IOException e) {e.printStackTrace();}

hello dduphorn, my friend :slight_smile:
Thanks for your solution! I have Appium 1.6.3 and OS Sierra 10.12.2

Unfortunately I have a problem with your code :frowning:

  1. I run appium server from Java by using your code
  2. I run iOS driver from Java by using: driver = new IOSDriver(url, capabilities);
  3. Program crashes with following errors:

[XCUITest] Error: Command ‘idevice_id -l’ errored out: Error: spawn idevice_id ENOENT
…
Error: Command ‘idevice_id -l’ errored out: Error: spawn idevice_id ENOENT
…
[debug] [XCUITest] Reset not set, not ending sim
[MJSONWP] Encountered internal error running command: Error: Command ‘idevice_id -l’ errored out: Error: spawn idevice_id ENOENT
…
[HTTP] ← POST /wd/hub/session 500 246 ms - 521
Jan 08, 2017 10:45:25 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Falling back to original OSS JSON Wire Protocol.
…
[BaseDriver] Session created with session id: 6d3bfa8b-fb6b-4330-a824-90d13a00b1b1
[debug] [XCUITest] Xcode version set to ‘8.2.1’
[debug] [XCUITest] iOS SDK Version set to ‘10.2’
[XCUITest] Error: Command ‘idevice_id -l’ errored out: Error: spawn idevice_id ENOENT
…
Error: Command ‘idevice_id -l’ errored out: Error: spawn idevice_id ENOENT
…
[debug] [XCUITest] Reset not set, not ending sim
[MJSONWP] Encountered internal error running command: Error: Command ‘idevice_id -l’ errored out: Error: spawn idevice_id ENOENT
…
[HTTP] ← POST /wd/hub/session 500 109 ms - 521
Jan 08, 2017 10:50:06 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Falling back to straight W3C remote end connection
…
Exception in thread “main” org.openqa.selenium.SessionNotCreatedException: Unable to create new remote session.
…
Driver info: driver.version: IOSDriver
at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:91)
at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:141)
at io.appium.java_client.remote.AppiumCommandExecutor.execute(AppiumCommandExecutor.java:69)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:601)
at io.appium.java_client.DefaultGenericMobileDriver.execute(DefaultGenericMobileDriver.java:42)
at io.appium.java_client.AppiumDriver.execute(AppiumDriver.java:1)
at io.appium.java_client.ios.IOSDriver.execute(IOSDriver.java:1)
at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:241)
at org.openqa.selenium.remote.RemoteWebDriver.(RemoteWebDriver.java:128)
at org.openqa.selenium.remote.RemoteWebDriver.(RemoteWebDriver.java:141)
at io.appium.java_client.DefaultGenericMobileDriver.(DefaultGenericMobileDriver.java:38)
at io.appium.java_client.AppiumDriver.(AppiumDriver.java:83)
at io.appium.java_client.AppiumDriver.(AppiumDriver.java:93)
at io.appium.java_client.ios.IOSDriver.(IOSDriver.java:75)
at io.appium.iOSTestingSystem.App.driver_start(App.java:179)
at io.appium.iOSTestingSystem.App.main(App.java:86)

Second scenario:

  1. I run appium server from mac os terminal by using “appium” command
  2. I run iOS driver by using the same my Java code : driver = new IOSDriver(url, capabilities);
  3. Program DOESN’T crash
    Do you know where is the bug?

What is your node and appium path?

My node is: /Users/dduphorn/.nvm/versions/node/v6.0.0/bin/node
My Path is: /Users/"dduphorn/.nvm/versions/node/v6.0.0/bin/appium

My guess is that the issue is because these are incorrect.

DD

/usr/local/bin/Appium
/usr/local/bin/node
get from “which” command

I have new information, the issue is visible only if I run program in Eclipse.
There is no issue if I run the same code from mac command line by using “java -jar file.jar”.
It’s strange for me. Have you ever seen this issue?

It appears that you are pointing to the wrong appium and node.

  1. Open Terminal
  2. Enter: brew install node
  3. Enter: nvm install 6.0.0
  4. Enter: which node
  5. If the node path changes continue with 6 and 7
  6. npm install -g appium
  7. npm install -g appium-doctor

Do you have idevice_id installed on your computer? If you aren’t sure, open a terminal and type ‘which idevice_id’. If you get a path to the executable, then it’s installed, but if you get nothing returned, you’ll need to install libimobiledevice:

@ dduphorn,

Maybe these informations will be help for you:

  1. my installation before your 7 steps, was:
    brew install node
    sudo npm -g install ios-deploy --unsafe-perm=true
    brew install ruby
    gem install xcpretty
    npm install appium
    sudo npm install -g appium-doctor

my OLD patches after installation by brew:
/usr/local/bin/appium
/usr/local/bin/node

  1. now I did your seven steps:
    I didn’t have NVM, so I installed it
    nvm list
    node -> stable (-> N/A) (default)
    iojs -> N/A (default)
    nvm install 6.0.0

and I have new patches:
/Users/me/.nvm/versions/node/v6.0.0/bin/appium
/Users/me/.nvm/versions/node/v6.0.0/bin/node

I paste this patches to eclipse, but still the same error:
[XCUITest] Error: Command ‘idevice_id -l’ errored out: Error: spawn idevice_id ENOENT

  1. now, after new installation of Node and Appium
    /Users/me/.nvm/versions/node/v6.0.0/bin/appium
    /Users/me/.nvm/versions/node/v6.0.0/bin/node
    I can’t run IOSDriver on Eclipse, if appium is run on command line

with this patches in eclipse:
/usr/local/bin/appium
/usr/local/bin/node
I could do it.

  1. maybe problem is in driver java code:
    capabilities.setCapability and url, could you please show your code to start IOSDriver?

@wreed
Yes I have:
/usr/local/bin/idevice_id

Below is How I started the appium server

CommandLine command = new CommandLine("/Users/"+strAutomationUser+"/.nvm/versions/node/v6.0.0/bin/node");
command.addArgument("/Users/"+strAutomationUser+"/.nvm/versions/node/v6.0.0/bin/appium",false);
command.addArgument("–address", false);
command.addArgument(“127.0.0.1”);
command.addArgument("–port", false);
command.addArgument(strAppiumPort);
command.addArgument("-bp", false);
command.addArgument(strBootstrapPort);
command.addArgument("–full-reset", true);
command.addArgument("–session-override", true);
//command.addArgument("–no-reset", true);
DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
DefaultExecutor executor = new DefaultExecutor();
executor.setExitValue(1);
try {executor.execute(command, resultHandler);
Thread.sleep(5000);System.out.println(“Appium server started.”);}
catch (IOException e)
{e.printStackTrace();}
catch (InterruptedException e)
{e.printStackTrace();}

//Capabilities
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(“newCommandTimeout”, 60 * 5);
capabilities.setCapability(“platformName”,“iOS”);
capabilities.setCapability(“deviceName”,strIOSDeviceName);
capabilities.setCapability(“automationName”,“XCUITest”);
capabilities.setCapability(“udid”,strIOSUdid);
capabilities.setCapability(“deviceName”,strIOSDeviceName+"("+strIOSUdid+")");
File f = new File(strIOSPath);
if(f.exists()) {capabilities.setCapability(“app”,strIOSPath);}
else{String strErrorMsg = “The IOS application path didn’t exists (”+strIOSPath+")";Reporter.log(""+strErrorMsg+"");Assert.fail(strErrorMsg);return null;}
capabilities.setCapability(“launchTimeout”, 60000);
capabilities.setCapability(“sendKeyStrategy”,“setValue”);
IOSDriver iosdriver = new IOSDriver(new URL(“http://127.0.0.1:”+strAppiumPort+"/wd/hub"), capabilities);

Hope that helps

DD

still the same :frowning:
[XCUITest] Error: Command ‘idevice_id -l’ errored out: Error: spawn idevice_id ENOENT

1 Like

these type of approaches always result in lots of issues as we need to think a lot and write lots of code hence better use AppiumDriverLocalService which is small and crispy…it uses very less and excellent output besides helps to plug-in with other programs

HI Team,
@Hassan_Radi

I am trying to start appium server through java code but getting UnreachableBrowserException. I have posted my question on StackOverflow with all the code and logs. Please have a look and help.

http://stackoverflow.com/questions/41741420/unreachablebrowserexception-in-appium-while-trying-to-initiate-androiddriver

Node.exe is started but i get exception during AndroidDriver initialization and node.exe is closed during the same.
NPM method is not working for me as I cannot install appium via npm due to network proxy settings in my office network.

check IP - > String url = “http://127.0.0.1:4723/wd/hub”;

when your appium started what it is writing?

for example:
[Appium] Appium REST http interface listener started on 0.0.0.0:4723

U are starting the server by splitting the normal command into different strings I mean ip—>1 string, port—> another string ,etc…which is always a big headache because of starting of the server requires certain parameters in the relevant sequence hence it’s always better to use AppiumDriverLocalService in your program which is the best and efficient…there are lots of tutorials available and U can go through this http://aksahu.blogspot.in/2015/10/start-and-stop-appium-server.html which is one of the best for this purpose

Appium server launches every time whenever new scenario starts while using Cucumber-Selenium.
Please do help in resolving this issue.It will be very helpful!!!Thanks in Advance :slight_smile:

I am trying your suggestions on a Mac setup. I was able to start up the appium server programmatically but a driver session could not be made. When I dug into the logs it is complaining that the capabilities are not proper as deviceName can’t be null. But I am setting deviceName in the desired capabilities. Any inputs on these.

EDIT : There was a silly error in my code and I was able to fix that but now I am getting a different error. Attaching logs.

[Appium] Welcome to Appium v1.6.3 (REV f58265b0c3d15444b3ed8b046a020724be683f63)
[Appium] Appium REST http interface listener started on 0.0.0.0:4723
[HTTP] --> POST /wd/hub/session {“desiredCapabilities”:{“app”:"/Users/vikumar/Desktop/ShareConnect.zip",“platformVersion”:“9.3”,“automationName”:“XCUITest”,“platformName”:“iOS”,“udid”:“dd5287b0c2c5c9a86b3144e5f6dbaa646744b835”,“deviceName”:“iPad”,“fullReset”:true}}
[debug] [MJSONWP] Calling AppiumDriver.createSession() with args: [{“app”:"/Users/vikumar/Desktop/ShareConnect.zip",“platformVersion”:“9.3”,“automationName”:“XCUITest”,“platformName”:“iOS”,“udid”:“dd5287b0c2c5c9a86b3144e5f6dbaa646744b835”,“deviceName”:“iPad”,“fullReset”:true},null,null,null,null]
[Appium] Creating new XCUITestDriver session
[Appium] Capabilities:
[Appium] app: ‘/Users/vikumar/Desktop/ShareConnect.zip’
[Appium] platformVersion: ‘9.3’
[Appium] automationName: ‘XCUITest’
[Appium] platformName: ‘iOS’
[Appium] udid: ‘dd5287b0c2c5c9a86b3144e5f6dbaa646744b835’
[Appium] deviceName: ‘iPad’
[Appium] fullReset: true
[debug] [XCUITest] XCUITestDriver version: 2.4.2
[BaseDriver] Session created with session id: 10f7e916-1665-48e0-a7f7-23b280ca2436
[debug] [XCUITest] Error: Could not get Xcode version. /Library/Developer/Info.plist does not exist on disk.
at getVersionWithoutRetry$ (lib/xcode.js:116:11)
at tryCatch (/usr/local/lib/node_modules/appium/node_modules/babel-runtime/regenerator/runtime.js:67:40)
at GeneratorFunctionPrototype.invoke [as _invoke] (/usr/local/lib/node_modules/appium/node_modules/babel-runtime/regenerator/runtime.js:315:22)
at GeneratorFunctionPrototype.prototype.(anonymous function) [as next] (/usr/local/lib/node_modules/appium/node_modules/babel-runtime/regenerator/runtime.js:100:21)
at GeneratorFunctionPrototype.invoke (/usr/local/lib/node_modules/appium/node_modules/babel-runtime/regenerator/runtime.js:136:37)
Error: Could not get Xcode version. /Library/Developer/Info.plist does not exist on disk.
at getVersionWithoutRetry$ (lib/xcode.js:116:11)
at tryCatch (/usr/local/lib/node_modules/appium/node_modules/babel-runtime/regenerator/runtime.js:67:40)
at GeneratorFunctionPrototype.invoke [as _invoke] (/usr/local/lib/node_modules/appium/node_modules/babel-runtime/regenerator/runtime.js:315:22)
at GeneratorFunctionPrototype.prototype.(anonymous function) [as next] (/usr/local/lib/node_modules/appium/node_modules/babel-runtime/regenerator/runtime.js:100:21)
at GeneratorFunctionPrototype.invoke (/usr/local/lib/node_modules/appium/node_modules/babel-runtime/regenerator/runtime.js:136:37)

Don’t see this error when I run appium from command prompt. My env is as follows :
Mac book pro (sierra), appium : 1.6.3, java 1.8