Switching to specific window using PID (Process ID) - java

I'm working on a Java Selenium program which uses Runtime class.
There are multiple instances of Internet Explorer windows that are open.
I need to "Bring Front" only one specific window for the selenium suite to run without errors.I have retrieved the specific iexplore instance using tasklist command.
Now I have the PID of the process.
Process p = Runtime.getRuntime().exec("tasklist /FI \"WindowTitle eq Google\"");
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
int count=1;
while ((line = in.readLine()) != null) {
System.out.println(count + " " + line);
count++;
}
How to bring a process to the front (make it the active window) through Runtime command line using its PID?
EDIT:
Is there a way to switch to an application window from command prompt using the PID of the application?

To switch to an application window from command prompt you can use Windows Script Host's AppActivate function. It accepts either ProcessID or window's title as its argument. Here is a simple script:
set WshShell = CreateObject("WScript.Shell")
WshShell.AppActivate Wscript.Arguments(0)
Then call the script by using cscript AppActivate.vbs 1234

I tried to apply the advice above into a complete solution
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.apache.commons.io.FileUtils.writeStringToFile;
import static org.apache.commons.lang3.math.NumberUtils.toInt;
public class WindowSwither {
private static final Pattern TASKLIST_CSV_PATTERN = Pattern.compile("\".*?\",\"(\\d+)\".*");
private int pidActive = 0;
private final List<Integer> pidList = new ArrayList<>();
public WindowSwither(String exeName) throws IOException {
Process p = Runtime.getRuntime().exec("tasklist /FI \"ImageName eq " + exeName + ".exe\" /FO CSV");
for (String line : showProcessOut(p)) {
Matcher m = TASKLIST_CSV_PATTERN.matcher(line);
if (m.find()) {
pidList.add(toInt(m.group(1)));
}
}
}
public void next() throws IOException {
if (pidList.size() == 0) {
System.out.println("List empty! Ignored.");
return;
}
if (pidActive == 0) {
pidActive = pidList.get(0);
System.out.println("[0] " + pidActive);
} else {
Iterator<Integer> it = pidList.iterator();
while (it.hasNext()) {
Integer pid = it.next();
if (pid == pidActive) {
break;
}
}
if (it.hasNext()) {
pidActive = it.next();
System.out.println("[+] " + pidActive);
} else {
pidActive = pidList.get(0);
System.out.println("[0] " + pidActive);
}
}
activate(pidActive);
}
private static void activate(int pid) throws IOException {
String pathname = System.getProperty("java.io.tmpdir") + "WindowSwintcherAppActivate.vbs";
File file = new File(pathname);
if (!file.exists()) {
String content = "set WshShell = CreateObject(\"WScript.Shell\")\n" +
"WshShell.AppActivate Wscript.Arguments(0)";
writeStringToFile(file, content, StandardCharsets.UTF_8);
}
Runtime.getRuntime().exec("cscript " + pathname + " " + pid);
}
private List<String> showProcessOut(Process p) throws IOException {
List<String> list = new ArrayList<>();
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream(), "cp866"));
String line;
while ((line = in.readLine()) != null) {
list.add(line);
}
return list;
}
}
Main class
public class EnumerateWindows {
public static void main(String[] args) throws IOException, InterruptedException {
WindowSwither swither = new WindowSwither("notepad");
swither.next();
Thread.sleep(1000);
swither.next();
Thread.sleep(1000);
swither.next();
Thread.sleep(1000);
swither.next();
Thread.sleep(1000);
}
}

Related

which is the equivalent command for execute a curl command in windows java?

An equivalent command for something like this I don't know which is the correct form to call a batch command
def proc =["/bin/sh", "-c","curl https://stackoverflow.com"]
proc.waitFor()
StringBuffer outputStream = new StringBuffer()
proc.waitForProcessOutput(outputStream, System.err)
String output = outputStream.toString()
Why don't you consider using java.net.URL instead?
Sample code is here
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Hello{
public static void main(String []args){
try
{
URL url = new URL("http://stackoverflow.com");
try (BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"))) {
for (String line; (line = reader.readLine()) != null;) {
System.out.println(line);
}
}
}
catch (Exception e)
{
System.out.println("error occured");
}
}
}
instead if you want to invoke the curl command from java use the below
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class ShellFromJava {
public static ArrayList<String> command(final String cmdline,
final String directory) {
try {
Process process =
new ProcessBuilder(new String[] {"bash", "-c", cmdline})
.redirectErrorStream(true)
.directory(new File(directory))
.start();
ArrayList<String> output = new ArrayList<String>();
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
while ( (line = br.readLine()) != null )
output.add(line);
if (0 != process.waitFor())
return null;
return output;
} catch (Exception e) {
//Warning: doing this is no good in high-quality applications.
//Instead, present appropriate error messages to the user.
//But it's perfectly fine for prototyping.
return null;
}
}
public static void main(String[] args) {
testHandler("curl http://stackoverflow.com");
}
static void testHandler(String cmdline) {
ArrayList<String> output = command(cmdline, ".");
if (null == output)
System.out.println("\n\n\t\tCOMMAND FAILED: " + cmdline);
else
for (String line : output)
System.out.println(line);
}
}
You can spawn a process from Java:
public class useProcess {
public static void main(String[] args) throws Exception {
String params[] = {"/bin/sh", "-c", "curl", "https://stackoverflow.com"};
Process myProcess = Runtime.getRuntime().exec(params);
myProcess.waitFor();
}
}

Need help searching through three files and printing out the same common lines

For now, I'm searching through the first one then sending it to the second one but the second one only prints and compares the first line.
I don't know how to make the second method start from the next line and so on. The objective is to do this with three text files but i cant even get through the first one. It has to be using bufferedreader and a while loop.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.FileReader;
public class scanner {
public static String line;
public static String line2;
public static String line3;
public static boolean match = false;
public static void main (String [] args) throws IOException
{
BufferedReader in = new BufferedReader(new FileReader("creditCards1.txt"));
line = in.readLine();
while (match==false && line != null)
{
System.out.println(line);
line = in.readLine();
scan2(line);
}
in.close();
}
public static boolean scan2(String line) throws IOException
{
BufferedReader in2 = new BufferedReader(new FileReader("creditCards2.txt"));
if (line2 == null || line2 == "7120-0824-9323-2825")
{
line2 = in2.readLine();
}
while(match==false && line!=null)
{
System.out.println(line2);
if(line2 == line)
{
match = true;
System.out.println("sdsds" + line);
in2.close();
break;
}
line2= in2.readLine();
break;
}
return match;
}
}
package so;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class Test {
public static void main(String[] args) {
File f1 = new File("/home/guest/Desktop/file1.txt");
File f2 = new File("/home/guest/Desktop/file2.txt");
File f3 = new File("/home/guest/Desktop/file3.txt");
try {
compareTwo(f1, f2);
compareTwo(f1, f3);
compareTwo(f2, f3);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void compareTwo(File f1, File f2) throws IOException {
String l1,l2;
try (BufferedReader r1 = new BufferedReader(new FileReader(f1))) {
while ((l1 = r1.readLine()) != null) {
try (BufferedReader r2 = new BufferedReader(new FileReader(f2))) {
while ((l2 = r2.readLine()) != null) {
if(l1.equals(l2))
System.out.println("line: " + l1 + " in file " + f1 + " exists in file " + f2);
}
}
}
}
}
}

How can I put the first three words on each line into an arraylist?

public class scripttest {
public static void main(String[] args) {
File file = new File("text.txt");
script(file);
}
public static void script(File filename) {
String line = null;
try {
FileReader fileReader = new FileReader(filename);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null)
{
System.out.println(line);
}
bufferedReader.close();
} catch(IOException ex) {
System.out.println("Error reading file named '" + filename + "'");
}
}
}
Im trying to make a script function for my program, the script requires a file, which each command written out on each line to be carried out consecutively. How do I add the first three words on each line to an arraylist, which will then be used to interpret the commands for each line?
// considering you have line variable. myArrayList is ur list.
String[] words = line.split(" ");
if(words.length() >= 3) {
myArrayList.add(words[0] + " " + words[1] + " " + words[2])
}
If you can use Java 8:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class TestScript {
public static void main(String[] args) {
script("text.txt");
}
private static void script(String filename) {
try (Stream<String> stream = Files.lines(Paths.get(filename))) {
stream.forEach(TestScript::executeLine);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static void executeLine(String line) {
System.out.println(line);
String[] args = line.split(" ");
executeCommand(Arrays.stream(args).limit(3).collect(Collectors.toList()),
Arrays.stream(args).skip(3).collect(Collectors.toList()));
}
private static void executeCommand(List<String> command, List<String> args) {
System.out.println(command + ": " + args);
}
}

Start and stop postgreSQL service through java code

I have one requirement where I need to start and stop postgreSQL service through java code. I have written below code but I am getting below error:
System error 5 has occurred.
Access is denied.
System error 5 has occurred.
Access is denied.
Below is my code:
package frontend.guifx.pginstallation;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import common.core.Logger;
import frontend.guifx.util.ConstPG;
public class StartAndStopPostgres {
public static String version = "9.5";
public static void main(String[] args){
try {
System.out.println("Execution starts");
copyPostgreSqlConfFileAndRestartPg();
System.out.println("Execution finished");
} catch (IOException | InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static void copyPostgreSqlConfFileAndRestartPg() throws IOException, InterruptedException {
// TODO Auto-generated method stub
Path path = Paths.get("data/PGLogs");
//if directory exists?
if (!Files.exists(path)) {
try {
Files.createDirectories(path);
} catch (IOException e) {
//fail to create directory
e.printStackTrace();
}
}
Logger.print(StartAndStopPostgres.class, new String[] { "Copying postgresql.conf file ........" });
Path source = Paths.get("data/postgresql.windows.conf");
String copyConfFileTo = getInstallationPath(version);
copyConfFileTo = copyConfFileTo.substring(0, copyConfFileTo.lastIndexOf("\\"));
Path outputDirectoryPath = Paths.get(copyConfFileTo+File.separator+"data");
Files.copy(source, outputDirectoryPath.resolve(outputDirectoryPath.getFileSystem().getPath("postgresql.conf")), StandardCopyOption.REPLACE_EXISTING);
Logger.print(StartAndStopPostgres.class, new String[] { "Tunning datbase starts........" });
Runtime rt = Runtime.getRuntime();
final File file = new File(System.getProperty("java.io.tmpdir") + File.separator + ConstPG.CREATE_RESTART_PG_BAT_FILE);
PrintWriter writer = new PrintWriter(file, "UTF-8");
writer.println("net stop postgresql-x64-"+version);
writer.println("net start postgresql-x64-"+version);
writer.close();
String executeSqlCommand = file.getAbsolutePath();
Process process = rt.exec(executeSqlCommand);
/*final List<String> commands = new ArrayList<String>();
commands.add("cmd.exe");
commands.add("/C");
commands.add("net stop postgresql-x64-9.5");
commands.add("net start postgresql-x64-9.5");
ProcessBuilder b = new ProcessBuilder(commands);
Process process = b.start();*/
//public static final String PG_RESTART_PG_LOG_FILE = PG_LOGS+"/pgRestartProcess.log";
File createPgRestartProcessFile = new File(ConstPG.PG_RESTART_PG_LOG_FILE);
redirectProcessExecutionOutput(process, createPgRestartProcessFile);
int exitVal = process.waitFor();
Logger.print(StartAndStopPostgres.class, new String[] { "EXIT VALUE after tunning the PostgreSql database :::::::::::::::::::::" + exitVal + " Logs written to file at: " + createPgRestartProcessFile.getAbsolutePath() });
}
public static String getInstallationPath( String version) {
//public static final String PROGRAMME_FILES = "C:\\Program Files\\";
// public static final String PROGRAMME_FILES_X86 = "C:\\Program Files (x86)\\";
// public static final String POSTGRESQL = "PostgreSQL";
// public static final String PSQL_PATH = "\\bin\\psql.exe";
//Const values used below are as above
String psql = findFile(ConstPG.PROGRAMME_FILES, ConstPG.POSTGRESQL + "\\" + version + ConstPG.PSQL_PATH);
if (psql == null) {
psql = findFile(ConstPG.PROGRAMME_FILES_X86, ConstPG.POSTGRESQL + "\\" + version + ConstPG.PSQL_PATH);
}
if(psql != null){
psql = psql.substring(0, psql.lastIndexOf("\\"));
}
return psql;
}
public static String findFile(String directoryName, String fileName) {
File directory = new File(directoryName);
// get all the files from a directory
File[] fList = directory.listFiles();
String absolutePath;
if (fList != null) {
for (File file : fList) {
if (file.isFile()) {
absolutePath = file.getAbsolutePath();
if (absolutePath.contains(fileName))
return (absolutePath);
} else if (file.isDirectory()) {
absolutePath = findFile(file.getAbsolutePath(), fileName);
if (absolutePath != null)
return (absolutePath);
}
}
}
return (null);
}
private static void redirectProcessExecutionOutput(Process process, File processFile) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
String line = null;
FileWriter fw = new FileWriter(processFile.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
while ((line = reader.readLine()) != null) {
Logger.print(StartAndStopPostgres.class, new String[] { line });
bw.write(line);
bw.newLine();
}
bw.close();
}
}
If I start my eclipse as an Administrator then this works fine. Also if I run start and stop commands on command prompt (which is opened as an Administrator i.e. right click on command prompt icon and click 'run as Administrator') then they execute successfully. But if I run the commands on normal command prompt (which is not opened as a administrator) then I get the same error there as well.
Please advise if there is any solution or any approach to solve this problem.
In java there is a option to run windows cmd as administrator
replace your code "commands.add("cmd.exe");" with below code and try
commands.add("runas /profile /user:ADMINUSERNAME \"cmd.exe");

How can I write large output to Process getOutputStream?

I am trying to execute a command (eg. ps -ef | grep apache) using ProcessBuilder and Process. The code works as long as the output of 'ps -ef' is small. But if the output is too big, the program hangs. Is there a way to fix this? Here is my code based on [http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html]
#### Program.java ####
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
public class Program {
private List<String> command;
public Program(String commandString) throws IOException {
this(commandString, null);
}
public List<String> getCommand() {
return this.command;
}
private void setCommand(String filename, String location, String commandString, List<String> parameters) throws IOException {
if(filename != null) {
commandString = new File(location, filename).getCanonicalPath();
}
this.command =
Collections.synchronizedList(new ArrayList<String>());
this.command.add(commandString);
if (parameters != null) {
for (String arg: parameters) {
command.add(arg);
}
}
}
public String[] run() throws IOException, InterruptedException {
return this.run(null);
}
public String[] run(String input) throws IOException, InterruptedException {
ProcessBuilder processBuilder = new ProcessBuilder(this.command);
List<String> commandList = processBuilder.command();
Process process = processBuilder.start();
if(input != null) {
PrintWriter writer = new PrintWriter(new OutputStreamWriter(new BufferedOutputStream(process.getOutputStream())), true);
writer.println(input);
writer.flush();
writer.close();
}
process.getOutputStream().close();
Gobbler outGobbler = new Gobbler(process.getInputStream());
Gobbler errGobbler = new Gobbler(process.getErrorStream());
Thread outThread = new Thread(outGobbler);
Thread errThread = new Thread(errGobbler);
outThread.start();
errThread.start();
outThread.join();
errThread.join();
int exitVal = process.waitFor();
System.out.println("PROCESS WAIT FOR: " + exitVal);
List<String> output = outGobbler.getOuput();
return output.toArray(new String[output.size()]);
}
}
#### CommandExecutor.java ####
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
public class CommandExecutor {
public List<List<Object>> programs;
public static void main(String[] args) {
try {
CommandExecutor ce = new CommandExecutor(args[0]);
String output = ce.run();
System.out.println("Command: " + args[0]);
System.out.println("Output: " + output);
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println(e.getLocalizedMessage());
e.printStackTrace();
} catch (InterruptedException ie) {
// TODO Auto-generated catch block
System.out.println(ie.getLocalizedMessage());
ie.printStackTrace();
}
}
public CommandExecutor(String command) throws IOException {
this.setPrograms(command);
}
private void setPrograms(String command) throws IOException {
this.programs = new ArrayList<List<Object>>();
//String cmdstring = "";
String[] commands = command.split("\\s*;\\s*");
for(String c: commands) {
//String subcmdstr = "";
String file = null;
String[] chainedCommands = c.split("\\s*\\|\\s*");
String lastCmd = chainedCommands[chainedCommands.length-1];
String[] fileCmd = lastCmd.split("\\s*>\\s*");
if(fileCmd.length > 1) {
chainedCommands[chainedCommands.length-1] = fileCmd[0];
file = fileCmd[1];
}
List<Object> l = new ArrayList<Object>();
for(String p: chainedCommands) {
/*if(subcmdstr.equals("")) {
subcmdstr = p;
}
else {
subcmdstr += " redirects to " + p;
}*/
String[] cmdparams = p.split(" ");
String cmd = cmdparams[0];
List<String> params = new ArrayList<String>();
for(int j = 1; j < cmdparams.length; j++) {
params.add(cmdparams[j]);
}
Program prog = new Program(cmd, params);
l.add(prog);
}
if(file != null) {
//subcmdstr += " redirects to file: " + file;
l.add(file);
}
this.programs.add(l);
//cmdstring += "new command: " + subcmdstr + "\n";
}
//System.out.println("Actual Command: " + command);
//System.out.println("Command String:\n" + cmdstring);
}
public String run() throws IOException, InterruptedException {
String output = "";
for(List<Object> l: this.programs) {
String[] out = new String[0];
int count = 0;
boolean filenotfound = true;
for(Object o: l) {
if(o instanceof Program) {
Program p = (Program) o;
if(count == 0) {
out = p.run();
}
else {
out = p.run(CommandExecutor.arrayToString(out));
}
}
else if(o instanceof String) {
PrintWriter f = new PrintWriter(new File((String)o));
f.print(CommandExecutor.arrayToString(out));
f.close();
filenotfound = false;
}
count++;
}
if(filenotfound) {
output += CommandExecutor.arrayToString(out);
}
}
return output;
}
public static String arrayToString(String[] strArray) {
String str = "";
for(String s: strArray) {
str += s;
}
return str;
}
}
Thanks,
Quadir
Ok, I got it working. Below is the code, given a list of commands, it pipes the output of one command to the next.
/*
####### PipeRedirection.java
*/
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
public class PipeRedirection {
public static void main(String[] args) throws FileNotFoundException {
if(args.length < 2) {
System.err.println("Need at least two arguments");
System.exit(1);
}
try {
String input = null;
for(int i = 0; i < args.length; i++) {
String[] commandList = args[i].split(" ");
ProcessBuilder pb = new ProcessBuilder(commandList);
//pb.redirectErrorStream(true);
Process p = pb.start();
if(input != null) {
PrintWriter writer = new PrintWriter(new OutputStreamWriter(new BufferedOutputStream(p.getOutputStream())), true);
writer.println(input);
writer.flush();
writer.close();
}
InputProcess.Gobbler outGobbler = new InputProcess.Gobbler(p.getInputStream());
InputProcess.Gobbler errGobbler = new InputProcess.Gobbler(p.getErrorStream());
Thread outThread = new Thread(outGobbler);
Thread errThread = new Thread(errGobbler);
outThread.start();
errThread.start();
outThread.join();
errThread.join();
int exitVal = p.waitFor();
System.out.println("\n****************************");
System.out.println("Command: " + args[i]);
System.out.println("Exit Value = " + exitVal);
List<String> output = outGobbler.getOuput();
input = "";
for(String o: output) {
input += o;
}
}
System.out.println("Final Output:");
System.out.println(input);
} catch (IOException ioe) {
// TODO Auto-generated catch block
System.err.println(ioe.getLocalizedMessage());
ioe.printStackTrace();
} catch (InterruptedException ie) {
// TODO Auto-generated catch block
System.err.println(ie.getLocalizedMessage());
ie.printStackTrace();
}
}
public static class Gobbler implements Runnable {
private BufferedReader reader;
private List<String> output;
public Gobbler(InputStream inputStream) {
this.reader = new BufferedReader(new InputStreamReader(inputStream));
}
public void run() {
String line;
this.output = new ArrayList<String>();
try {
while((line = this.reader.readLine()) != null) {
this.output.add(line + "\n");
}
this.reader.close();
}
catch (IOException e) {
// TODO
System.err.println("ERROR: " + e.getMessage());
}
}
public List<String> getOuput() {
return this.output;
}
}
}
Don't print it as a String but give the CommandExecuter an optional OutputStream (in your Case you pass System.out as the argument) and write it to that stream.
In your current program the Main Method will execute the program and won't print anything (hang) until your run method returns something.

Categories