Im trying to start Appium server programmatically from Java
(OS: Windows7 x64)
using first method from source: http://www.automationtestinghub.com/3-ways-to-start-appium-server-from-java/
The code that I use for starting Appium sever is:
public void startServer() {
//Set Capabilities
cap = new DesiredCapabilities();
cap.setCapability("noReset", "false");
//Build the Appium service
builder = new AppiumServiceBuilder();
builder.withIPAddress("127.0.0.1");
builder.usingPort(4723);
builder.withCapabilities(cap);
builder.withArgument(GeneralServerFlag.SESSION_OVERRIDE);
builder.withArgument(GeneralServerFlag.LOG_LEVEL, "error");
//added by myself:
builder.usingDriverExecutable(new File("C:/node/node.exe"));
builder.withAppiumJS(new File("C:/Users/[user]/AppData/Roaming/npm/node_modules/appium/lib/appium.js"));
//Start the server with the builder
service = AppiumDriverLocalService.buildService(builder);
service.start();
}
I'm getting an exception:
Exception in thread "main" io.appium.java_client.service.local.AppiumServerHasNotBeenStartedLocallyException: The local appium server has not been started. The given Node.js executable: C:\node\node.exe Arguments: [C:\Users\Dima\AppData\Roaming\npm\node_modules\appium\lib\appium.js, --port, 4723, --address, 127.0.0.1, --log-level, error, --session-override, --default-capabilities, {\"noReset\": \"false\"}]
Process output: C:\Users[user]\AppData\Roaming\npm\node_modules\appium\lib\appium.js:1
(function (exports, require, module, __filename, __dirname) { import _ from 'lodash'; ^^^^^^
SyntaxError: Unexpected token import
at createScript (vm.js:80:10)
at Object.runInThisContext (vm.js:139:10)
at Module._compile (module.js:616:28)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Function.Module.runMain (module.js:693:10)
at startup (bootstrap_node.js:188:16)
at bootstrap_node.js:609:3
I tried every way to start Appium server from the source, but second one causes to the same, but third causes to error
Any ideas? Thanks to all in advance!
Take a look at official documentation:
https://github.com/appium/java-client/blob/master/docs/The-starting-of-an-app-using-Appium-node-server-started-programmatically.md
Make sure your env setup for Appium is correct and that appium service/client versions are compatible.
It did mistake in code. Fixed method is:
public static String runAppiumService(int appiumPort) {
//Build parameters for appium server:
AppiumServiceBuilder appiumServiceBuilder = new AppiumServiceBuilder();
appiumServiceBuilder.usingPort(appiumPort)
.withIPAddress(APPIUM_IP)
.withAppiumJS(new File(getAppiumJsPath()))
.withArgument(GeneralServerFlag.SESSION_OVERRIDE)
.withLogFile(new File(System.getProperty("user.dir") + "/target/resources/appium_server_logs" + Thread.currentThread().getId()));
AppiumDriverLocalService service = AppiumDriverLocalService.buildService(appiumServiceBuilder);
service.start();
}
public class ServerManager {
AppiumDriverLocalService service;
public static void main(String args[]) {
ServerManager sm = new ServerManager();
sm.startServer();
}
public void startServer() {
final DesiredCapabilities cap = new DesiredCapabilities();
//Set Capabilities
cap.setCapability("noReset", "false");
//Build the Appium service
AppiumServiceBuilder builder = new AppiumServiceBuilder();
builder = new AppiumServiceBuilder();
builder.withIPAddress("127.0.0.1");
builder.usingPort(4723);
builder.withCapabilities(cap);
builder.withArgument(GeneralServerFlag.SESSION_OVERRIDE);
builder.withArgument(GeneralServerFlag.LOG_LEVEL,"error");
//Start the server with the builder
service = AppiumDriverLocalService.buildService(builder);
service = AppiumDriverLocalService.buildService(builder);
service.start();
}
public void stopServer() {
service.stop();
}
}
Mac OS here, but looking for a solution that is platform agnostic. Also please note, even though Consul is mentioned here, it is just arbitrary and the solution should have nothing to do with, nor require knowledge of, Consul.
When I open a shell and run consul -v (to determine if Consul is installed locally), I get the following STDOUT:
Consul v0.5.2
Consul Protocol: 2 (Understands back to: 1)
When I run the following code:
public class VerifyConsul {
public static void main(String[] args) {
PrintStream oldPS = System.out;
try {
Runtime runtime = Runtime.getRuntime();
Process proc;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream newPS = new PrintStream(baos);
System.setOut(newPS);
proc = runtime.exec(“consul -v”);
proc.waitFor();
String capturedOut = baos.toString();
if(capturedOut.isEmpty()) {
throw new IllegalArgumentException(“Consul not found.”);
}
} catch(Throwable t) {
System.out.println(t.getMessage());
System.setOut(oldPS);
}
}
}
I get the IllegalArgumentException stating that Consul [is] not found.
What is wrong with my code? Why isn’t it “hooking”/capturing STDOUT?
Use Process#getInputStream() to read STDOUT or Process#getErrorStream() to read STDERR
Here's an example (using java process and reading STDERR):
package so32589604;
import org.apache.commons.io.IOUtils;
public class App {
public static void main(String[] args) throws Exception {
final Runtime runtime = Runtime.getRuntime();
final Process proc = runtime.exec("java -version");
proc.waitFor();
// IOUtils from apache commons-io
final String capturedOut = IOUtils.toString(proc.getErrorStream());
System.out.println("output = " + capturedOut);
if(capturedOut.isEmpty()) {
throw new IllegalArgumentException("Java not found.");
}
}
}
I have a self-contained Java application packaged with the javapackager tool (version 8.0, Windows). How do I pass it system property values at application runtime (not at package time) on the command line?
The doc does not seem to address this.
I tried the standard Java way as in:
mypackagedapp.exe -Dmyprop=myvalue
but that does not appear to have an effect.
Here is a code that validates if an argument exists in the command line.
See if the next code can help you.
public static void main(final String[] args) throws Exception {
CommandLine line = validateArgs(args);
if (null == line) {
return;
}
}
private static CommandLine validateArgs(String[] args) {
Options flags = getArgs();
CommandLineParser parser = new BasicParser();
CommandLine line = null;
try {
// parse the command line arguments
line = parser.parse(flags, args);
if (line == null) {
return null;
}
} catch (ParseException exp) {
System.out.println(exp.getMessage());
}
return line;
}
static Options getArgs() {
Options flags = new Options();
Option dmyprop = OptionBuilder.withArgName("dmyprop")
.hasArg()
.withDescription("add description")
.create("Dmyprop");
flags.addOption(dmyprop);
return flags;
}
In order to get environment variable you need to use:
String env = System.getenv(option);
where option is your desired environment variable.
Hope it helped.
Does anyone know how to clear the cache on a new start of a test while running SafariDriver? I've tried to use java robot to keypress command + option + e, but that does not seem to work. It does not focus on the browser.
Robot r = new Robot();
try {
Robot robot = new Robot();
r.keyPress(KeyEvent.META_MASK);
r.keyPress(KeyEvent.VK_META);
r.keyPress(KeyEvent.VK_E);
r.keyRelease(KeyEvent.VK_E);
r.keyRelease(KeyEvent.VK_META);
r.keyRelease(KeyEvent.META_MASK);
} catch (AWTException e) {
e.printStackTrace();
}
Ive also tried to do an actions.builder method but that does not seem to work
String clearCache = Keys.chord(Keys.CONTROL, Keys.COMMAND, "E");
Actions builder = new Actions(browser);
builder.sendKeys(clearCache);
Action clearCacheAction = builder.build();
clearCacheAction.perform();
I've also looked into using SafariDriver options but my java is not that good to fully understand how to implement it. Below is the code that Ive been trying to use. I created a SafariOptions Class and tried to instantiate it in my #before class.
package test
import org.openqa.selenium.safari.SafariDriver;
public class SafariOptions extends SafariDriver {
private static SafariOptions ourInstance = new SafariOptions();
public static SafariOptions getInstance() {
return ourInstance;
}
public void setUseCleanSession(boolean useCleanSession){
}
public SafariOptions() {
boolean useCleanSession = true;
}
}
#Before
public void createDriver() {
assumeTrue(isSupportedPlatform());
browser = new SafariDriver();
SafariDriver options = new SafariOptions();
}
Nothing seems to clear the Safari cache on each test run.
Quick and easy solution for all who might want to know.
Add the following code to a .sh file to root.
killall cookied
rm -rf ~/Library/Caches/com.apple.Safari/*
rm -rf ~/Library/Safari/LocalStorage/*
rm -rf ~/Library/Cookies/*
Call on the file in #Before
Runtime runtime = Runtime.getRuntime();
runtime.exec("file.sh");
System.out.println("Cookies Removed");
Can someone point me in the right direction on how to open the default web browser and set the page to "www.example.com" thanks
java.awt.Desktop is the class you're looking for.
import java.awt.Desktop;
import java.net.URI;
// ...
if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
Desktop.getDesktop().browse(new URI("http://www.example.com"));
}
For me solution with Desktop.isDesktopSupported() doesn't work (windows 7 and ubuntu). Please try this to open browser from java code:
Windows:
Runtime rt = Runtime.getRuntime();
String url = "http://stackoverflow.com";
rt.exec("rundll32 url.dll,FileProtocolHandler " + url);
Mac
Runtime rt = Runtime.getRuntime();
String url = "http://stackoverflow.com";
rt.exec("open " + url);
Linux:
Runtime rt = Runtime.getRuntime();
String url = "http://stackoverflow.com";
String[] browsers = { "google-chrome", "firefox", "mozilla", "epiphany", "konqueror",
"netscape", "opera", "links", "lynx" };
StringBuffer cmd = new StringBuffer();
for (int i = 0; i < browsers.length; i++)
if(i == 0)
cmd.append(String.format( "%s \"%s\"", browsers[i], url));
else
cmd.append(String.format(" || %s \"%s\"", browsers[i], url));
// If the first didn't work, try the next browser and so on
rt.exec(new String[] { "sh", "-c", cmd.toString() });
If you want to have multiplatform application, you need to add operation system checking(for example):
String os = System.getProperty("os.name").toLowerCase();
Windows:
os.indexOf("win") >= 0
Mac:
os.indexOf("mac") >= 0
Linux:
os.indexOf("nix") >=0 || os.indexOf("nux") >=0
Here is my code. It'll open given url in default browser (cross platform solution).
import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
public class Browser {
public static void main(String[] args) {
String url = "http://www.google.com";
if(Desktop.isDesktopSupported()){
Desktop desktop = Desktop.getDesktop();
try {
desktop.browse(new URI(url));
} catch (IOException | URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
Runtime runtime = Runtime.getRuntime();
try {
runtime.exec("xdg-open " + url);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
As noted in the answer provided by Tim Cooper, java.awt.Desktop has provided this capability since Java version 6 (1.6), but with the following caveat:
Use the isDesktopSupported() method to determine whether the Desktop API is available. On the Solaris Operating System and the Linux platform, this API is dependent on Gnome libraries. If those libraries are unavailable, this method will return false.
For platforms which do not support or provide java.awt.Desktop, look into the BrowserLauncher2 project. It is derived and somewhat updated from the BrowserLauncher class originally written and released by Eric Albert. I used the original BrowserLauncher class successfully in a multi-platform Java application which ran locally with a web browser interface in the early 2000s.
Note that BrowserLauncher2 is licensed under the GNU Lesser General Public License. If that license is unacceptable, look for a copy of the original BrowserLauncher which has a very liberal license:
This code is Copyright 1999-2001 by Eric Albert (ejalbert#cs.stanford.edu) and may be redistributed or modified in any form without restrictions as long as the portion of this comment from this paragraph through the end of the comment is not removed. The author requests that he be notified of any application, applet, or other binary that makes use of this code, but that's more out of curiosity than anything and is not required. This software includes no warranty. The author is not repsonsible for any loss of data or functionality or any adverse or unexpected effects of using this software.
Credits:
Steven Spencer, JavaWorld magazine (Java Tip 66)
Thanks also to Ron B. Yeh, Eric Shapiro, Ben Engber, Paul Teitlebaum, Andrea Cantatore, Larry Barowski, Trevor Bedzek, Frank Miedrich, and Ron Rabakukk
Projects other than BrowserLauncher2 may have also updated the original BrowserLauncher to account for changes in browser and default system security settings since 2001.
You can also use the Runtime to create a cross platform solution:
import java.awt.Desktop;
import java.net.URI;
public class App {
public static void main(String[] args) throws Exception {
String url = "http://stackoverflow.com";
if (Desktop.isDesktopSupported()) {
// Windows
Desktop.getDesktop().browse(new URI(url));
} else {
// Ubuntu
Runtime runtime = Runtime.getRuntime();
runtime.exec("/usr/bin/firefox -new-window " + url);
}
}
}
Hope you don't mind but I cobbled together all the helpful stuff, from above, and came up with a complete class ready for testing...
import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
public class MultiBrowPop {
public static void main(String[] args) {
OUT("\nWelcome to Multi Brow Pop.\nThis aims to popup a browsers in multiple operating systems.\nGood luck!\n");
String url = "http://www.birdfolk.co.uk/cricmob";
OUT("We're going to this page: "+ url);
String myOS = System.getProperty("os.name").toLowerCase();
OUT("(Your operating system is: "+ myOS +")\n");
try {
if(Desktop.isDesktopSupported()) { // Probably Windows
OUT(" -- Going with Desktop.browse ...");
Desktop desktop = Desktop.getDesktop();
desktop.browse(new URI(url));
} else { // Definitely Non-windows
Runtime runtime = Runtime.getRuntime();
if(myOS.contains("mac")) { // Apples
OUT(" -- Going on Apple with 'open'...");
runtime.exec("open " + url);
}
else if(myOS.contains("nix") || myOS.contains("nux")) { // Linux flavours
OUT(" -- Going on Linux with 'xdg-open'...");
runtime.exec("xdg-open " + url);
}
else
OUT("I was unable/unwilling to launch a browser in your OS :( #SadFace");
}
OUT("\nThings have finished.\nI hope you're OK.");
}
catch(IOException | URISyntaxException eek) {
OUT("**Stuff wrongly: "+ eek.getMessage());
}
}
private static void OUT(String str) {
System.out.println(str);
}
}
Its very simple just write below code:
String s = "http://www.google.com";
Desktop desktop = Desktop.getDesktop();
desktop.browse(URI.create(s));
or if you don't want to load URL then just write your browser name into string values like,
String s = "chrome";
Desktop desktop = Desktop.getDesktop();
desktop.browse(URI.create(s));
it will open browser automatically with empty URL after executing a program
I recast Brajesh Kumar's answer above into Clojure as follows:
(defn open-browser
"Open a new browser (window or tab) viewing the document at this `uri`."
[uri]
(if (java.awt.Desktop/isDesktopSupported)
(let [desktop (java.awt.Desktop/getDesktop)]
(.browse desktop (java.net.URI. uri)))
(let [rt (java.lang.Runtime/getRuntime)]
(.exec rt (str "xdg-open " uri)))))
in case it's useful to anyone.
on windows invoke "cmd /k start http://www.example.com"
Infact you can always invoke "default" programs using the start command.
For ex start abc.mp3 will invoke the default mp3 player and load the requested mp3 file.
JavaFX bundles a cross-platform solution inside its StandaloneHostService that is independent of AWT, which is somehow similar to krzysiek.ste's answer.
I rewrote it to include some xdg-open alternatives (which are actually used by xdg-open by the way).
private static final String[][] commands = new String[][]{
{"xdg-open", "$1"},
{"gio", "open", "$1"},
{"gvfs-open", "$1"},
{"gnome-open", "$1"}, // Gnome
{"mate-open", "$1"}, // Mate
{"exo-open", "$1"}, // Xfce
{"enlightenment_open", "$1"}, // Enlightenment
{"gdbus", "call", "--session", "--dest", "org.freedesktop.portal.Desktop",
"--object-path", "/org/freedesktop/portal/desktop",
"--method", "org.freedesktop.portal.OpenURI.OpenURI",
"", "$1", "{}"}, // Flatpak
{"open", "$1"}, // Mac OS fallback
{"rundll32", "url.dll,FileProtocolHandler", "$1"}, // Windows fallback
};
Here is the final Java snippet, avoiding string concatenation and escape character issues.
public static void showDocument(final String uri) {
String osName = System.getProperty("os.name");
try {
if (osName.startsWith("Mac OS")) {
Runtime.getRuntime().exec(new String[]{"open", uri});
} else if (osName.startsWith("Windows")) {
Runtime.getRuntime().exec(new String[]{"rundll32", "url.dll,FileProtocolHandler", uri});
} else { //assume Unix or Linux
new Thread(() -> {
try {
for (String[] browser : commands) {
try {
String[] command = new String[browser.length];
for (int i = 0; i < browser.length; i++)
if (browser[i].equals("$1"))
command[i] = uri;
else
command[i] = browser[i];
if (Runtime.getRuntime().exec(command).waitFor() == 0)
return;
} catch (IOException ignored) {
}
}
String browsers = System.getenv("BROWSER") == null ? "x-www-browser:firefox:iceweasel:seamonkey:mozilla:" +
"epiphany:konqueror:chromium:chromium-browser:google-chrome:" +
"www-browser:links2:elinks:links:lynx:w3m" : System.getenv("BROWSER");
for (String browser : browsers.split(":")) {
try {
Runtime.getRuntime().exec(new String[]{browser, uri});
return;
} catch (IOException ignored) {
}
}
} catch (Exception ignored) {
}
}).start();
}
} catch (Exception e) {
// should not happen
// dump stack for debug purpose
e.printStackTrace();
}
}
There is also
BrowserUtil.browse(uri);
(source code) that seems to be a more compatible with some more exotic setups. I recently had a client where Desktop.getDesktop().browse(uri) was failing in Fedora Linux, but BrowserUtil.browse(uri) worked.
I also believe this is now the preferred way by JetBrains to open a browser (for example, see this thread)
As I had this same problem and found no decent solution for our case so I ported the https://www.npmjs.com/package/open npm package to Java https://github.com/vaadin/open and released it into Maven central. Can be used as
<dependency>
<groupId>com.vaadin</groupId>
<artifactId>open</artifactId>
<version>8.4.0.2</version>
</dependency>
Open.open("https://stackoverflow.com/")
or for a specific browser
Open.open("https://stackoverflow.com/", App.FIREFOX);