Launching and stopping appium server programmtically

There are two fixes which are coming out with new java_client version

The main problem was the way how Eclipse for UNIX-like OS’s works with environment variables. Else there was a problem with the starting of non-default Node.JS (e.g. NSolid)

1 Like

The same capability is supposed to be provided by .Net appium client

Hello Karthik,

Please use the code that I posted in my post http://aksahu.blogspot.in/2015/10/start-and-stop-appium-server.html

Hope it will help you!

Thanks,
Aswini Kumar

1 Like

Hi,

I am trying to launch appium on linux machine with below code but not able to launch. Please help not even getting any console output.

Process p = Runtime.getRuntime().exec(new String[]{“bash”,"-c","/home/dhiren/.linuxbrew/bin/node","~/.linuxbrew/lib/node_modules/appium/lib/appium.js"});
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));

			BufferedReader stdError = new BufferedReader(new 
			     InputStreamReader(p.getErrorStream()));

			// read the output from the command
			System.out.println("Here is the standard output of the command:\n");
			String s = null;
			while ((s = stdInput.readLine()) != null) {
			    System.out.println(s);
			}

			// read any errors from the attempted command
			System.out.println("Here is the standard error of the command (if any):\n");
			while ((s = stdError.readLine()) != null) {
			    System.out.println(s);
			}
		
		System.out.println("ANDROID_HOME : ");
		System.getenv("ANDROID_HOME");

The space problem can be solved as this:
command.addArgument(“C:/Progra~2/nodejs/node.exe”); command.addArgument(“C:/Progra~2/Appium/node_modules/appium/bin/appium.js”);

use Progra~2 for going to Program Files (x86)
use Progra~1 for going to Programme Files…

Hope this helps.

Hi,

I have posted detailed explanation on starting and stopping Appium server with java code which works in windows as well as in Linux.

Regards,
Anuja

private static Process process;
public static AndroidDriver driver;
public static Properties config = null;


// Calling the node.exe and appium.js
// private static String STARTSERVER =
// "C:\\Program Files (x86)\\Appium\\node.exe C:\\Program Files (x86)\\Appium\\node_modules\\appium\\bin\\appium.js";
private static String STARTSERVER = "\"C:/Program Files (x86)/Appium/node.exe\" \"C:/Program Files (x86)/Appium/node_modules/appium/bin/appium.js\" --no-reset --local-timezone";

// Starting the Appium Server

public static void startAppiumServer() throws IOException,
InterruptedException {

	Runtime runtime = Runtime.getRuntime();

	process = runtime.exec(STARTSERVER);

	Thread.sleep(7000);

	if (process != null) {

		System.out.println("Appium server started");

	}

}

// Stopping the Appium Server

public static void stopAppiumServer() throws IOException,
InterruptedException {

	String STOPSERVER = "cmd /c echo off & FOR /F \"usebackq tokens=5\" %a in (`netstat -nao ^| findstr /R /C:\"4723\"`) do (FOR /F \"usebackq\" %b in (`TASKLIST /FI \"PID eq %a\" ^| findstr /I node.exe`) do taskkill /F /PID %a)";
	Runtime runtime = Runtime.getRuntime();

	process = runtime.exec(STOPSERVER);

	Thread.sleep(7000);

	if (process != null) {

		System.out.println("Appium server stopped");


	}

}
1 Like

have you see “[36m”,what’s meaning?

[36m is an escape code for the command line shell you’re using. These codes are used to instruct your shell to colorize the output text. If the shell doesn’t understand these codes, then they’re printed out in the given format you see. You can also see these if Appium’s output is redirected to a file.

Hi Ashok ,

I am new to appium . I am facing the same issue while trying to start the appium using the java code .

I tried to escape the spaces with different ways . But unable to start the appium server sucessfully. Kindly let me how to resolve this issue.

please reply . Thanks in advance .

Hi All,

Mention below the code to run Appium with java
public boolean launchAppiumServer() throws IOException {
boolean isRunning = false;
String appiumHome = safeInit.appiumLocation;
String serverIP = safeInit.appiumNodeIP;
String serverPort = safeInit.appiumNodePort;
String appiumJsHome = safeInit.appiumJsLocation;
String udid = safeInit.deviceUDID;

    GlobalParameters.getGlobalParams();
    if (((GlobalParameters.globalParamsMap.get("APPIUM_RUNNING")).toLowerCase()).equals("false")){
        logIOSDriverAPI.info("Appium server is not running so starting to run soon");
    }else{
        logIOSDriverAPI.info("Appium server is already started and running");
        GlobalParameters.getGlobalParams();
        GlobalParameters.globalParamsMap.put("APPIUM_RUNNING","true");
        return true;
    }

    logIOSDriverAPI.info("Creating appium server batch file");
    logIOSDriverAPI.info("Appium location " + appiumHome);
    logIOSDriverAPI.info("Appium server IP " + serverIP);
    logIOSDriverAPI.info("Appium server port " + serverPort);
    logIOSDriverAPI.info("Appium server java script path " + appiumJsHome);

    CommandLine command = new CommandLine(appiumHome);
    command.addArgument(appiumJsHome, false);
    command.addArgument("--address", false);
    command.addArgument(serverIP);
    command.addArgument("--port", false);
    command.addArgument(serverPort);
    command.addArgument("--log-level");
    command.addArgument("warn");
    command.addArgument("--session-override", true);
    command.addArgument("--local-timezone", true);
    // command.addArgument("--log-no-colors", true);
    command.addArgument("--backend-retries");
    command.addArgument("6");
    //command.addArgument("--autoAcceptAlerts",true);
    /*
     * command.addArgument("--force-quit-instruments",true);
     * command.addArgument("--log-g /Users/slinger/Desktop/appium.log");
     * command.addArgument("--native-instruments-lib",true);
     * command.addArgument("--automation-name");
     * command.addArgument("Jitu_iPad_Automation");
     * command.addArgument("--ignoreUnimportantViews",true);
     * command.addArgument("--autoAcceptAlerts",false);
    command.addArgument("--show-ios-log");         */
    // command.addArgument("--full-reset", false);
    try{
        DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
        DefaultExecutor executor = new DefaultExecutor();
        executor.setExitValue(0);
        executor.execute(command, resultHandler);
        isRunning = true;
        logIOSDriverAPI.info("Executed the appium server command successfully");
        GlobalParameters.getGlobalParams();
        GlobalParameters.globalParamsMap.put("APPIUM_RUNNING","true");
    } catch (Exception e) {
        logIOSDriverAPI
        .error("Exception occoured while starting the appium server");
        //logAndroidDriverAPI.error(e.getMessage());
        logIOSDriverAPI.error(genCodes.getExceptionMessage(e));
        GlobalParameters.getGlobalParams();
        GlobalParameters.globalParamsMap.put("APPIUM_RUNNING","false");
    }    

    try {
        waitForAction(20, "Waiting appium server to come up");
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return isRunning;
}

Then run the capabilities
public IOSDriver initializeIOSDriver() {
IOSDriver driver = null;
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(“udid”, safeInit.deviceUDID);
capabilities.setCapability(“platformVersion”, safeInit.deviceOSVersion);
capabilities.setCapability(“deviceName”, safeInit.deviceName);
capabilities.setCapability(“newCommandTimeout”, 480000);
capabilities.setCapability(“bundleId”, safeInit.applicationPackageName);
capabilities.setCapability(“autoDismissAlerts”, true);
capabilities.setCapability(“autoWebviewTimeout”, 60000);
capabilities.setCapability(“ignoreUnimportantViews”, true);
capabilities.setCapability(“resetKeyboard”, true);
capabilities.setCapability(“unicodeKeyboard”, true);

    logIOSDriverAPI.info("Loading the following IOS capabilities");
    logIOSDriverAPI.info("deviceName " + safeInit.deviceName);
    logIOSDriverAPI.info("device " + safeInit.deviceOSName);
    logIOSDriverAPI.info("device version " + safeInit.deviceOSVersion);
    logIOSDriverAPI
    .info("Package name is " + safeInit.applicationPackageName);

    try {
        driver = new IOSDriver(new URL("http://" + safeInit.appiumNodeIP
                + ":" + safeInit.appiumNodePort + "/wd/hub"), capabilities);
        iosDriver = driver;
        GlobalParameters.getGlobalParams();
        GlobalParameters.globalParamsMap.put("APPIUM_RUNNING","true");
    } catch (Exception e) {
        logIOSDriverAPI
        .error("Exception occured while loading capabilities");
        logIOSDriverAPI.error(e.getMessage());
        logIOSDriverAPI.error(genCodes.getExceptionMessage(e));
        driver = null;
        GlobalParameters.getGlobalParams();
        GlobalParameters.globalParamsMap.put("APPIUM_RUNNING","false");
    }
    logIOSDriverAPI.info("After loading capabilities");
    return driver;
}

Bro,

You need to invoke main.js so re-route your path and try

Hi,
I used below code to start appium automatically:

CommandLine command = new CommandLine("/Applications/Appium.app/Contents/Resources/node/bin/node");
command.addArgument("/Applications/Appium.app/Contents/Resources/node_modules/appium/build/lib/appium.js", false);
command.addArgument("–address", false);
command.addArgument(“0.0.0.0”);
command.addArgument("–port", false);
command.addArgument(“4723”);
command.addArgument("–no-reset", false);
DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
DefaultExecutor executor = new DefaultExecutor();
executor.setExitValue(1);
executor.execute(command, resultHandler);

For me its throwing unreachable browser exception… please help!

Hi All,

I am new to Appium and just had a skim of this thread. Is such command line approach still required to start appium now that we have the AppiumServiceBuilder and AppiumDriverLocalService packages? Is there any difference in end results between using the approach in this thread and simply service.start()?

Cheers

Hi,

Can u tell me how did u launch appium using those in MAC OS?

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.