How to get amount of running exe files from Windows Task Manager - java

I'm accessing to running exe using below method. But I want to get the count of running exe files. Basically I want to get the count of exe process currently runs. Other than assigning all the process name to a list is there a simple way to obtain the count.
public boolean isProcessRunning(String serviceName) {
try {
Process pro = Runtime.getRuntime().exec(TASKLIST);
BufferedReader reader = new BufferedReader(new InputStreamReader(pro.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
// System.out.println(line);
if (line.startsWith(serviceName)) {
return true;
}
}
} catch (IOException e) {
e.printStackTrace();
}
return false;
}

Related

Running batch files through java program: The CATALINA_HOME environment variable is not defined correctly

I have code that runs batch files in windows perfectly fine. (hey.bat just prints something simple)
public static void main(String[] args) {
static String dir1 = "C:\\Users\\Name\\Desktop\\hey.bat";
ProcessBuilder processBuilder = new ProcessBuilder(dir1);
try {
Process process = processBuilder.start();
StringBuilder output = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
}
int exitVal = process.waitFor();
if (exitVal == 0) {
System.out.println(output);
System.exit(0);
} else {
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
However, when I call a different batch file named shutdown.bat, one that is supposed to shutdown Tomcat, it gives the error
The CATALINA_HOME environment variable is not defined correctly. This
environment variable is needed to run this program
When I double click shutdown.bat it works perfectly fine, so why would it give an error when being run through java? Shouldn't all the dependencies be bundled into that batch file? Thanks

wkhtmltopdf called from java getting hanged

We are the using the following code to generate PDFs using wkhtmltopdf
public class SystemUtils{
public String executeCommand(String... command) {
Process process = null;
try {
// Using redirectErrorStream as true. Otherwise we have to read both process.getInputStream() and
// process.getErrorStream() in order to not exhaust the stream buffer.
process = new ProcessBuilder(command).redirectErrorStream(true).start();
process.waitFor();
StringBuilder outputBuilder = new StringBuilder();
try(BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
String line;
while ((line = stdError.readLine()) != null) {
outputBuilder.append(line).append(StringConstants.CARRIAGE_RETURN);
}
}
return outputBuilder.toString();
} catch (IOException | InterruptedException e) {
String exceptionMsg = "Error while executing command '"+command+"' : ";
LOGGER.error(exceptionMsg, e);
throw new AppException(exceptionMsg, e);
} finally {
if(process != null){
process.destroy();
}
}
}
public static void main(String[] args){
SystemUtils systemUtils = new SystemUtils();
String[] array = {"wkhtmltopdf", "/home/pgullapalli/Desktop/testsimilar1.html", "/home/pgullapalli/Desktop/test.pdf"};
systemUtils.executeCommand(array);
}
}
This works absolutely fine for smaller size files. But when we try to process a larger file, it is indefinitely waiting without any response. I am not sure what is going wrong? Can someone please suggest?
I moved process.waitFor() before the return statement and it started working. This probably could be happening as the output buffer has filled and we are not reading from it. After moving the process.waitFor after the stream reading, things are working fine.

Joining a thread / process in Java after some time - Java

I have the following method, which executes a command as a process and returns the ouput:
public String execute(String command) {
StringBuffer output = new StringBuffer();
Process p;
try {
p = Runtime.getRuntime().exec(command);
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
}
} catch (Exception e) {
logger.error(e.getMessage());
}
return output.toString();
}
This code is great whenever the command returns, however for continuing running processes such as top this may never return. The code does not need to keep running continuously. It only needs to capture a snapshot, or it could time out after some time, such as 3 seconds. How can I accomplish that?
Process has a method waitFor. It can be used to force a timeout. For example:
if ((p = Runtime.getRuntime().exec(execPath)) != null) && !p.waitFor(TIMEOUT_CONSTANT, TimeUnit.SECONDS)) {
p.destroyForcibly();
}

Not able to take screenshot in Android L programmatically

I'm using Nexus 5. Version 5.1.1
I want to take screenshot programmatically of phone at any given time. I'm okay if the solution is specific to Nexus 5.
After reading many answers, I've tried below solution using screencap.
Issue is it creates image file, but it is blank.
private void takeSS() {
try {
if (isExternalStorageWritable()) {
Process su = Runtime.getRuntime().exec("/system/bin/screencap -p /storage/emulated/0/img.png\n");
DataOutputStream outputStream = new DataOutputStream(su.getOutputStream());
outputStream.flush();
su.waitFor();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(su.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null) {
String output = line + System.getProperty("line.separator");
System.out.println(line);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/* Checks if external storage is available for read and write */
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
The same command if I run from command prompt, it executes successfully.
Please suggest what might be the issue.
P.S. - My phone is rooted.
Thank You
Have you tried executing the command as su?
"/system/bin/su -c \"/system/bin/screencap -p /storage/emulated/0/img.png\""

how to avoid getRuntime.exec() to block when reading inputStream?

I call a class which is located somewhere in a jar file (using java -classpath path/file.jar classname) within my java code.
My problem is when the command genKOSCommand is invalid the call to input.readLine() will block the program. So I added input.ready() to hope avoiding blocking. When I debug the program it's ok. Seem to work. But when don't run it in debug the buffer is never ready.
// Execute a command with an argument that contains a space
String[] genKOSCommand = new String[] {
"java",
"-classpath",
Config.XDSI_TEST_KIT_HOME + "/xdsitest/lib/xdsitest.jar;"
+ Config.XDSI_TEST_KIT_HOME + "/xdsitest/classes",
"ca.etsmtl.ihe.xdsitest.docsource.SimplePublisher", "-k",
"C:/Softmedical/Viewer_Test/xdsi-testkit-2.0.4/xdsihome/usr/data/image14.dcm" };
Process child = Runtime.getRuntime().exec(genKOSCommand);
BufferedReader input = new BufferedReader(new InputStreamReader(
child.getInputStream()), 13107200);
String line = null;
if (input.ready()) {
while ((line = input.readLine()) != null) {
System.out.println(line);
}
try {
child.waitFor();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Any advice on how to detect problems with the executed command?
Thank you.
You need to wait in a loop for the BufferedReader to be ready.
while (input.ready() == false) { /* intentional empty space here */ }
while ((line = input.readLine()) != null) {
System.out.println(line);
}
/* rest of code follows */

Categories