How to stop appium server programmatically (stop AppiumDriverLocalService)


#1

I am trying to run and stop appium server programmatically using AppiumDriverLocalService. Starting the server is working fine but while stopping it after the test suite i am getting an error…

org.openqa.selenium.os.ProcessUtils killWinProcess
WARNING: Process refused to die after 10 seconds, and couldn’t taskkill it…

My code for starting and stopping the server-

import java.io.File;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.URL;

import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;

import io.appium.java_client.service.local.AppiumDriverLocalService;
import io.appium.java_client.service.local.AppiumServiceBuilder;
import io.appium.java_client.service.local.flags.GeneralServerFlag;

public class appiumService {

private AppiumDriverLocalService service;
private AppiumServiceBuilder builder;
private DesiredCapabilities cap;
private int port = 4723;
protected URL appiumServerURL;


@BeforeSuite	
public void startServer() {
	//Set Capabilities
	cap = new DesiredCapabilities();
	cap.setCapability("noReset", "false");
	
	//Build the Appium service
	builder = new AppiumServiceBuilder();
	builder.usingDriverExecutable(new File("C:\\Program Files\\nodejs\\node.exe"));
	builder.withAppiumJS(new File(System.getProperty("user.home")+"\\AppData\\Roaming\\npm\\node_modules\\appium\\build\\lib\\main.js"));
	builder.withLogFile(new File (System.getProperty("user.home")+"\\AppiumServerLogs.txt"));
	System.out.println(System.getProperty("user.home"));
	builder.withIPAddress("127.0.0.1");
	builder.usingPort(port);
	
	
	//builder.withCapabilities(cap);
	builder.withArgument(GeneralServerFlag.SESSION_OVERRIDE);
//	builder.withArgument(GeneralServerFlag.LOG_LEVEL,"debug");
	
	if (!this.checkIfServerIsRunning(port)) {
	//Start the server with the builder
	service = AppiumDriverLocalService.buildService(builder);
	service.start();
	appiumServerURL = service.getUrl();
	
}
	else {
		System.out.println("Appium Server already running on Port - " + port);
	}
}

@AfterSuite
public void stopServer() {
	service.stop();
}

public boolean checkIfServerIsRunning(int port) {
	
	boolean isServerRunning = false;
	ServerSocket serverSocket;
	try {
		serverSocket = new ServerSocket(port);
		serverSocket.close();
		
	} catch (IOException e) {
		//If control comes here, then it means that the port is in use
		isServerRunning = true;
		
	} finally {
		serverSocket = null;
	}
	return isServerRunning;
}

}