Stack Exchange
How to start appium sever from the Java code in Eclipse
I'm trying to start the appium server programmatically from my test case code, but nothing helps. Console always give me "org.openqa.selenium.remote.UnreachableBrowserException: Could not start a new session. Possible causes are invalid address of the remote server or browser start-up failure" error message. What have I tried so far:
CommandLine command = new CommandLine("cmd");
command.addArgument("/c");
command.addArgument("C:/Program Files (x86)/Appium/node.exe");
command.addArgument("C:/Program Files (x86)/Appium/node_modules/appium/bin/appium.js");
        command.addArgument("--address");
        command.addArgument("127.0.0.1");
        command.addArgument("--bootstrap-port");
        command.addArgument("5001");
        command.addArgument("--no-reset");
        command.addArgument("--log");

Doesn't work. Next:
DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
        DefaultExecutor executor = new DefaultExecutor();
        executor.setExitValue(1);
        executor.execute(new CommandLine("C:/Program Files (x86)/Appium/node.exe"), resultHandler);
        executor.execute(new CommandLine("C:/Program Files (x86)/Appium/node_modules/appium/bin/Appium.js --address 127.0.0.1 --chromedriver-port 9516 --bootstrap-port 4725 --selendroid-port 8082 --no-reset --local-timezone"), resultHandler);

Doesn't work. Next:
ProcessBuilder pb = new ProcessBuilder("C:/Program Files(x86)/Appium/node.exe/");
        ProcessBuilder pb1 = new ProcessBuilder("C:/Program Files(x86)/Appium/node_modules/appium/bin/Appium.js --address 127.0.0.1 --chromedriver-port 9516 --bootstrap-port 5002 --no-reset --local-timezone");
        pb.start();
        pb1.start();

Doesn't work. Next:
String path = "cmd /c start C:/Users/jamesrobinson/Desktop/Run automation servers.bat";
        Runtime rn = Runtime.getRuntime();
        Process process = rn.exec(path);

The only way I can start it is manually from UI. Any ideas how to resolve that will be greatly appreciated. 

could you share the screenshot for UI General settings that runs successfully. I can see a lot of port changes in your attempts.

                Explanation: 
                1. Create a command string and then write this command in some .bat file and then execute this .bat file.
                2. (Code not posted here for this ==> )After executing this, you need to put a wait until appium server is started, you can do this by sending request to http://localhost:4723, wait until you get response from this url and then you can initiate the driver.

                    //Getting temp dir
                    String tempDir = System.getProperty("java.io.tmpdir").toString();
                    logFile = new File(tempDir+"\\applog.txt");

                    String commandFile = "C:\\appium_commands.bat";

                    String nodeExe = "C:\\node.exe";
                    String appiumJs = "C:\\node_modules\\appium\\bin\\Appium.js");

                    String strText = "start /B " + nodeExe + "  " + appiumJs + " -g " + logFile.toString() + " --full-reset --command-timeout 90 ";

                    logger.info("****** STARTING APPIUM SERVER USING COMMAND: "+strText);

                    WriteTextInFile(commandFile, strText);
                    Runtime.getRuntime().exec(commandFile);

            *********************  Code to Write Text in File  ***********
            WriteTextInFile(String commandFile, String strText)
           {
            FileWriter writer = new FileWriter(file);
            writer.write(strText);
            writer.close();
          }

          ************ Code to Send GET Request and Check Response *******
    //In this code, you can keep on checking until you get NON-Empty //result.tostring(); Also download and add apache httpclient-4.XXX.jar and //httpcore-4.XXX.jar to your project.

    import java.io.BufferedReader;
    import java.io.InputStreamReader;

    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.conn.HttpHostConnectException;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClients;

    public class Test {

        public static void main(String[] args) {

            String ServerURL = "http://localhost:4723";
            StringBuffer result = new StringBuffer();
            CloseableHttpClient httpclient = null;
            CloseableHttpResponse response = null;

            try 
            {
                httpclient = HttpClients.createDefault();

                ServerURL = ServerURL.replace("%%", "").trim();
                HttpGet GetRequest = new HttpGet(ServerURL);
                try{
                    response = httpclient.execute(GetRequest);
                }catch(HttpHostConnectException h){
                    System.out.println("Couldn't connect to host: "+ServerURL);
                }

                BufferedReader rd = null;
                try{
                    rd = new BufferedReader( new InputStreamReader(response.getEntity().getContent()));
                }catch(NullPointerException e){
                    System.out.println("no response received.. ");
                }

                if(rd != null)
                {
                    String line = "";
                    while ((line = rd.readLine()) != null)
                    {
                        result.append(line);
                    }
                }
            } 
            catch(Exception e)
            {
            }
            finally 
            {
                try{
                    response.close();
                    httpclient.close();
                }
                catch(Exception e){
                }

            System.out.println("Final Response: "+result.toString());
            }
        }

    }

*********** node.json to be used with appium ***********



{
 "capabilities":
  [
{
"version":"4.4.2",
"maxInstances": 3,
"platformName":"ANDROID"
}
],
"configuration":
{
"cleanUpCycle":2000,
"timeout":30000,
"proxy": "org.openqa.grid.selenium.proxy.DefaultRemoteProxy",
"url":"http://WHERE_APPIUM_RUNNING_IP:4723/wd/hub",
"host": "WHERE_APPIUM_RUNNING_IP",
"port": 4723,
"maxSession": 6,
"register": true,
"registerCycle": 5000,
"hubPort": 4444,
"hubHost": "WHERE_GRID_RUNNING_IP"
}
}


How can I create a command string and also write command in bat file. I understand how to save any text file as .bat May be you meant this. Also, can you explain how to send a request to http://localhost:4723. Any kind of response will be greatly appreciated.

I've added code in my answer, which can be used to send GET request and check response.

well I meant same as you said, save text in a file as .bat.

I'm trying to register an Appium node in Selnium Grid and always getting an error:  node.exe node_modules\appium\bin\appium.js --nodeconfig "C:\XXX\IXXX\xxx.json" -p 4723 -U d66d8f10
info: Welcome to Appium v1.4.16 (REV ae6877eff263066b26328d457bd285c0cc62430d)
info: Appium REST http interface listener started on 0.0.0.0:4723
info: [debug] Non-default server args: {"udid":"d66d8f10","nodeconfig":"C:\XXX\XXX\xxx.json"}
info: Console LogLevel: debug
error: Unable to load node configuration file to register with grid I'm successfully able to launch Selenium Grid server and access that.

I was able to register appium node to a grid, Can you check if your node.json is actually present the given location or if it is in correct json format, just paste the content of node.json to jsonlint.com and see if its okay, I am pasting the whole node.json content in my answer, It may help you. Thanks.

Sorry man, I'm new to this web site. Let me find out exactly what you're asking..

Before you share the screenshot, I am just guessing maybe changing to default port might help you create the session successfully :
command.addArgument("--bootstrap-port");
command.addArgument("4723");

A general one line command is as :
String command = "/Applications/Appium.app/Contents/Resources/node/bin/node /Applications/Appium.app/Contents/Resources/node_modules/appium/lib/server/main.js --command-timeout 120 --session-override" + nativelib + " --platform-name " + mobileOS + " --log-timestamp -a 0.0.0.0 -p "+4723; //+" --chromedriver-port "+chromePort+" -bp "+bootstrapPort;

where 
nativelib = " --native-instruments-lib"; //for iOS
nativelib = ""; //for android

and 
mobileOS = "iOS"; //for iOS
mobileOS = "Android"; //for Android


I think I understand what is the problem, I can start the appium server programmatically, but that code is failing due to UnreachableBrowserException..........driver info: driver.version: AndroidDriver. But the miracle thing is if I launch appium server manually fro the UI, no failures occur.

Yes sure I can share the screenshot.

You can attach the same in the question

Pre-condition:

Ensure nodejs is installed in your system
Ensure appium is installed in your system.

--Enter the location of both in the below given script.
public class mainClass{

AppiumDriverLocalService service;

@Test

public void  startSErver(){


    service=AppiumDriverLocalService.buildService(new AppiumServiceBuilder()
            .usingDriverExecutable(new File("C:\\Program Files\\nodejs\\node.exe"))
            .withAppiumJS(new File("C:\\Program Files (x86)\\Appium\\node_modules\\appium\\bin\\appium.js"))
            .withIPAddress("127.0.0.1").usingPort(4723));

 service.start(); // To start the appium  server

