下面列出了怎么用org.openqa.selenium.os.CommandLine的API类实例代码及写法,或者点击链接到github查看源代码。
public void executeCommand() throws Throwable {
JavaProfile profile = new JavaProfile(LaunchMode.JAVA_COMMAND_LINE).setMainClass("-version");
final CommandLine commandLine = profile.getCommandLine();
AssertJUnit.assertNotNull(commandLine);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
commandLine.copyOutputTo(baos);
commandLine.executeAsync();
new Wait("Waiting till the command is complete") {
@Override
public boolean until() {
return !commandLine.isRunning();
}
};
BufferedReader reader = new BufferedReader(new StringReader(new String(baos.toByteArray())));
String line = reader.readLine();
while (line != null && !line.contains("java version")) {
line = reader.readLine();
}
AssertJUnit.assertTrue(line.contains("java version"));
}
public void executeWSCommand() throws Throwable {
if (OS.isFamilyWindows()) {
throw new SkipException("Test not valid for Windows");
}
JavaProfile profile = new JavaProfile(LaunchMode.JAVA_WEBSTART).addWSArgument("-verbose").addVMArgument("-Dx.y.z=hello");
final CommandLine commandLine = profile.getCommandLine();
AssertJUnit.assertNotNull(commandLine);
AssertJUnit.assertTrue(commandLine.toString().contains("-javaagent:"));
AssertJUnit.assertTrue(commandLine.toString().contains("-verbose"));
AssertJUnit.assertTrue(commandLine.toString().contains("-Dx.y.z=hello"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
commandLine.copyOutputTo(baos);
commandLine.executeAsync();
new Wait("Waiting till the command is complete") {
@Override
public boolean until() {
return !commandLine.isRunning();
}
};
BufferedReader reader = new BufferedReader(new StringReader(new String(baos.toByteArray())));
String line = reader.readLine();
while (line != null && !line.contains("Web Start")) {
line = reader.readLine();
}
AssertJUnit.assertTrue(line.contains("Web Start"));
}
public static void launchAllure(boolean showDialog, String... args) {
if (showDialog)
WaitMessageDialog.setVisible(true, "Generating reports");
List<String> vmArgs = getVMArgs();
Iterator<String> iterator = vmArgs.iterator();
while (iterator.hasNext()) {
String next = iterator.next();
if (next.contains("-javaagent") || next.contains("-D")) {
if (!next.contains("-Dallure")) {
iterator.remove();
}
}
}
vmArgs.add("-classpath");
vmArgs.add(System.getProperty("java.class.path"));
String property = System.getProperty(Constants.PROP_TMS_PATTERN);
if (property != null && !"".equals(property)) {
vmArgs.add("-D" + Constants.PROP_TMS_PATTERN + "=" + property);
}
property = System.getProperty(Constants.PROP_ISSUE_PATTERN);
if (property != null && !"".equals(property)) {
vmArgs.add("-D" + Constants.PROP_ISSUE_PATTERN + "=" + property);
}
ArrayList<String> newArgs = new ArrayList<String>();
newArgs.add(getJavaCommand());
newArgs.addAll(vmArgs);
newArgs.add(AllureMain.class.getName());
newArgs.addAll(new ArrayList<String>(Arrays.asList(args)));
CommandLine command = new CommandLine(newArgs.toArray(new String[newArgs.size()]));
command.copyOutputTo(System.out);
Logger.getLogger(TestRunner.class.getName()).info("Launching: " + command);
command.execute();
if (showDialog)
WaitMessageDialog.setVisible(false);
}
private void setToolOptions(CommandLine commandLine) {
StringBuilder java_tool_options = new StringBuilder();
java_tool_options.append("-DkeepLog=" + Boolean.toString(keepLog)).append(" ");
java_tool_options.append("-Dmarathon.launch.mode=" + launchMode.getName()).append(" ");
java_tool_options.append("-Dmarathon.mode=" + (recordingPort != -1 ? "recording" : "playing")).append(" ");
if (startWindowTitle != null) {
java_tool_options.append("-Dstart.window.title=\"" + startWindowTitle).append("\" ");
}
if (LaunchMode.JAVA_WEBSTART == launchMode || LaunchMode.JAVA_APPLET == launchMode)
java_tool_options.append("-D" + MARATHON_AGENT + "=" + getAgentJarURL()).append(" ");
java_tool_options.append("-javaagent:\"" + getAgentJar() + "\"=" + port).append(" ");
if (recordingPort != -1) {
if (LaunchMode.JAVA_WEBSTART == launchMode || LaunchMode.JAVA_APPLET == launchMode)
java_tool_options.append("-D" + MARATHON_RECORDER + "=" + getRecorderJarURL()).append(" ");
java_tool_options.append(" -javaagent:\"" + getRecorderJar() + "\"=" + recordingPort).append(" ");
}
addExtensions(java_tool_options);
for (String vmArg : vmArguments) {
java_tool_options.append("\"" + vmArg + "\"").append(" ");
}
if (System.getProperty("java.util.logging.config.file") != null) {
java_tool_options
.append("-Djava.util.logging.config.file=\"" + System.getProperty("java.util.logging.config.file") + "\" ");
}
if (System.getProperty("marathon.project.dir") != null) {
java_tool_options.append("-Dmarathon.project.dir=\"" + System.getProperty("marathon.project.dir") + "\" ");
}
java_tool_options.setLength(java_tool_options.length() - 1);
if (java_tool_options.length() > 1023) {
throw new RuntimeException("JAVA_TOOL_OPTIONS is more than 1023 bytes. Move marathon installation to a shorter path");
}
String currentOptions = System.getenv("JAVA_TOOL_OPTIONS");
if (currentOptions != null) {
commandLine.setEnvironmentVariable("USER_JTO", currentOptions);
}
commandLine.setEnvironmentVariable("JAVA_TOOL_OPTIONS", java_tool_options.toString());
}
public void getJavaCommandLineWithClasspath() throws Throwable {
File f = new File(".").getCanonicalFile();
JavaProfile profile = new JavaProfile(LaunchMode.JAVA_COMMAND_LINE).addClassPath(f);
CommandLine commandLine = profile.getCommandLine();
AssertJUnit.assertTrue(commandLine.toString().contains("-cp"));
AssertJUnit.assertTrue(commandLine.toString().contains(f.getAbsolutePath()));
}
public void getWsCommandWithJNLP() throws Throwable {
JavaProfile profile = new JavaProfile(LaunchMode.JAVA_WEBSTART).addWSArgument("-verbose").addVMArgument("-Dx.y.z=hello");
profile.setJNLPPath(new File("SwingSet3.jnlp").getAbsolutePath());
final CommandLine commandLine = profile.getCommandLine();
AssertJUnit.assertNotNull(commandLine);
AssertJUnit.assertTrue(commandLine.toString().contains("-javaagent:"));
AssertJUnit.assertTrue(commandLine.toString().contains("-verbose"));
AssertJUnit.assertTrue(commandLine.toString().contains("-Dx.y.z=hello"));
AssertJUnit.assertTrue(commandLine.toString().contains("SwingSet3.jnlp"));
}
public void checkForArguments() throws Throwable {
JavaProfile profile = new JavaProfile(LaunchMode.JAVA_WEBSTART);
File f = findFile();
profile.setJNLPPath(f.getAbsolutePath());
profile.setStartWindowTitle("SwingSet3");
profile.addVMArgument("-Dhello=world");
CommandLine commandLine = profile.getCommandLine();
System.out.println(commandLine);
AssertJUnit.assertTrue(commandLine.toString().matches(".*JAVA_TOOL_OPTIONS=.*-Dhello=world.*"));
}
public void checkGivenExecutableIsUsed() throws Throwable {
JavaProfile profile = new JavaProfile(LaunchMode.JAVA_WEBSTART);
profile.setJavaCommand("java");
File f = findFile();
profile.setJNLPPath(f.getAbsolutePath());
profile.setStartWindowTitle("SwingSet3");
profile.addVMArgument("-Dhello=world");
CommandLine commandLine = profile.getCommandLine();
String exec = findExecutableOnPath("java");
AssertJUnit.assertTrue(commandLine.toString(), commandLine.toString().contains(exec));
}
public static void main(String[] args) throws InterruptedException {
JavaProfile profile = new JavaProfile(LaunchMode.JAVA_WEBSTART);
File f = findFile();
profile.setJNLPPath(f.getAbsolutePath());
profile.setStartWindowTitle("SwingSet3");
CommandLine commandLine = profile.getCommandLine();
commandLine.copyOutputTo(System.err);
System.out.println(commandLine);
commandLine.execute();
}
public void checkForArguments() throws Throwable {
JavaProfile profile = new JavaProfile(LaunchMode.JAVA_APPLET);
File f = findFile();
profile.setAppletURL(f.getAbsolutePath());
profile.setStartWindowTitle("Applet Viewer: SwingSet3Init.class");
profile.addVMArgument("-Dhello=world");
CommandLine commandLine = profile.getCommandLine();
AssertJUnit.assertTrue(commandLine.toString().contains("-Dhello=world"));
}
public void checkGivenExecutableIsUsed() throws Throwable {
JavaProfile profile = new JavaProfile(LaunchMode.JAVA_APPLET);
File f = findFile();
profile.setAppletURL(f.getAbsolutePath());
profile.setStartWindowTitle("Applet Viewer: SwingSet3Init.class");
String actual = "";
if (OS.isFamilyWindows()) {
String path = System.getenv("Path");
String[] split = path.split(";");
File file = new File(split[0]);
File[] listFiles = file.listFiles();
if (listFiles != null) {
for (File listFile : listFiles) {
if (listFile.getName().contains(".exe")) {
profile.setJavaCommand(listFile.getAbsolutePath());
actual = listFile.getAbsolutePath();
break;
}
}
}
} else {
actual = "ls";
profile.setJavaCommand(actual);
}
CommandLine commandLine = profile.getCommandLine();
AssertJUnit.assertTrue(commandLine.toString().contains(actual));
}
/**
* Starts the defined appium server.
*
* @throws AppiumServerHasNotBeenStartedLocallyException If an error occurs while spawning the child process.
* @see #stop()
*/
public void start() throws AppiumServerHasNotBeenStartedLocallyException {
lock.lock();
try {
if (isRunning()) {
return;
}
try {
process = new CommandLine(this.nodeJSExec.getCanonicalPath(),
nodeJSArgs.toArray(new String[]{}));
process.setEnvironmentVariables(nodeJSEnvironment);
process.copyOutputTo(stream);
process.executeAsync();
ping(startupTimeout, timeUnit);
} catch (Throwable e) {
destroyProcess();
String msgTxt = "The local appium server has not been started. "
+ "The given Node.js executable: " + this.nodeJSExec.getAbsolutePath()
+ " Arguments: " + nodeJSArgs.toString() + " " + "\n";
if (process != null) {
String processStream = process.getStdOut();
if (!StringUtils.isBlank(processStream)) {
msgTxt = msgTxt + "Process output: " + processStream + "\n";
}
}
throw new AppiumServerHasNotBeenStartedLocallyException(msgTxt, e);
}
} finally {
lock.unlock();
}
}
private static Path sign(Path toSign) throws IOException {
LOG.info("Signing " + toSign);
// Ideally, we'd use BouncyCastle for this, but for now brute force by assuming
// the gpg binary is on the path
String path = new ExecutableFinder().find("gpg");
if (path == null) {
throw new IllegalStateException("Unable to find gpg for signing artifacts");
}
Path dir = Files.createTempDirectory("maven-sign");
Path file = dir.resolve(toSign.getFileName() + ".asc");
CommandLine gpg = new CommandLine(
"gpg", "--use-agent", "--armor", "--detach-sign", "--no-tty",
"-o", file.toAbsolutePath().toString(), toSign.toAbsolutePath().toString());
gpg.execute();
if (!gpg.isSuccessful()) {
throw new IllegalStateException("Unable to sign: " + toSign + "\n" + gpg.getStdOut());
}
// Verify the signature
CommandLine verify = new CommandLine(
"gpg", "--verify", "--verbose", "--verbose",
file.toAbsolutePath().toString(), toSign.toAbsolutePath().toString());
verify.execute();
if (!verify.isSuccessful()) {
throw new IllegalStateException("Unable to verify signature of " + toSign + "\n" + gpg.getStdOut());
}
return file;
}
public void build(String target) {
if (!isInDevMode()) {
// we should only need to do this when we're in dev mode
// when running in a test suite, our dependencies should already
// be listed.
log.info("Not in dev mode. Ignoring attempt to build: " + target);
return;
}
Path projectRoot = InProject.findProjectRoot();
if (!Files.exists(projectRoot.resolve("Rakefile"))) {
// we're not in dev mode
return;
}
if (target == null || "".equals(target)) {
throw new IllegalStateException("No targets specified");
}
log.info("\nBuilding " + target + " ...");
CommandLine commandLine = new CommandLine("bazel", "build", target);
commandLine.setWorkingDirectory(projectRoot.toAbsolutePath().toString());
commandLine.copyOutputTo(System.err);
commandLine.execute();
if (!commandLine.isSuccessful()) {
throw new WebDriverException("Build failed! " + target + "\n" + commandLine.getStdOut());
}
}
public void getJavaCommandLine() {
JavaProfile profile = new JavaProfile(LaunchMode.JAVA_COMMAND_LINE).addVMArgument("-version");
CommandLine commandLine = profile.getCommandLine();
AssertJUnit.assertNotNull(commandLine);
}
@Override
public void start() throws IOException {
lock.lock();
try {
profile.setPreference(PORT_PREFERENCE, port);
addWebDriverExtension(profile);
profile.checkForChangesInFrozenPreferences();
profileDir = profile.layoutOnDisk();
ImmutableMap.Builder<String, String> envBuilder = new ImmutableMap.Builder<String, String>()
.putAll(getEnvironment())
.put("XRE_PROFILE_PATH", profileDir.getAbsolutePath())
.put("MOZ_NO_REMOTE", "1")
.put("MOZ_CRASHREPORTER_DISABLE", "1") // Disable Breakpad
.put("NO_EM_RESTART", "1"); // Prevent the binary from detaching from the console
if (Platform.getCurrent().is(Platform.LINUX) && profile.shouldLoadNoFocusLib()) {
modifyLinkLibraryPath(envBuilder, profileDir);
}
Map<String, String> env = envBuilder.build();
List<String> cmdArray = new ArrayList<>(getArgs());
cmdArray.addAll(binary.getExtraOptions());
cmdArray.add("-foreground");
process = new CommandLine(binary.getPath(), Iterables.toArray(cmdArray, String.class));
process.setEnvironmentVariables(env);
process.updateDynamicLibraryPath(env.get(CommandLine.getLibraryPathPropertyName()));
// On Snow Leopard, beware of problems the sqlite library
if (! (Platform.getCurrent().is(Platform.MAC) && Platform.getCurrent().getMinorVersion() > 5)) {
String firefoxLibraryPath = System.getProperty(
FirefoxDriver.SystemProperty.BROWSER_LIBRARY_PATH,
binary.getFile().getAbsoluteFile().getParentFile().getAbsolutePath());
process.updateDynamicLibraryPath(firefoxLibraryPath);
}
process.copyOutputTo(getOutputStream());
process.executeAsync();
waitUntilAvailable();
} finally {
lock.unlock();
}
}