ProcessBuilder execute java.exe - java

i want to call a java class using ProcessBuilder.
using the below to execute a .bat file worked fine, but would anyone let me know how can i execute the java command adding the required classpaths?
ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "test "+code+"");
pb.directory(new File("C:\\Program Files\\Apache Software Foundation\\Tomcat 9.0\\webapps\\stock\\WEB-INF\\classes\\"));
Process process = pb.start();
so basically i want to call the following:
java -classpath "C:\j\x.jar;C:\j\y.jar;...." myjavaclass parameter

A simple way to launch any command is:
public class Launch
{
public static void exec(String[] cmd) throws InterruptedException, IOException
{
System.out.println("exec "+Arrays.toString(cmd));
Path tmpdir = Path.of(System.getProperty("java.io.tmpdir"));
ProcessBuilder pb = new ProcessBuilder(cmd);
Path out = tmpdir.resolve(cmd[0]+"-stdout.log");
Path err = tmpdir.resolve(cmd[0]+"-stderr.log");
pb.redirectError(out.toFile());
pb.redirectOutput(err.toFile());
Process p = pb.start();
int rc = p.waitFor();
System.out.println("Exit "+rc +' '+(rc == 0 ? "OK":"**** ERROR ****")
+" STDOUT \""+Files.readString(out)+'"'
+" STDERR \""+Files.readString(err)+'"');
System.out.println();
}
}
And to launch a java application:
public class LaunchJava
{
public static void main(String[] args) throws InterruptedException, IOException
{
String java = Path.of(System.getProperty("java.home"),"bin", "java").toAbsolutePath().toString();
String mainClass = "somepackage.MainClass";
List<String> classpath = List.of("C:\\jars\\xyz.jar", "C:\\somedirectory");
List<String> params = List.of("PARAM1","PARAM2","PARAM2");
ArrayList<String> cmd = new ArrayList<>();
cmd.add(java);
cmd.add("--class-path");
cmd.add(String.join(File.pathSeparator, classpath));
cmd.add(mainClass);
cmd.addAll(params);
Launch.exec(cmd.toArray(String[]::new));
}
}

Related

How to kill Task Manager in java?

In my program I want kill Task Manager if it's running. I've tried this:
private static final String TASKLIST = "tasklist";
private static final String KILL = "taskkill /F /IM ";
if(isProcessRunning("Taskmgr.exe")){
// TODO code application logic here
killProcess("Taskmgr.exe");
}
Here is my isProcessRunning() method:
public static boolean isProcessRunning(String servicename) throws Exception {
Process p = Runtime.getRuntime().exec(TASKLIST);
BufferedReader reader = new BufferedReader(new InputStreamReader(
p.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
if (line.contains(servicename)) {
System.err.println(line);
return true;
}
}
return false;
}
And the killprocess() method:
public static void killProcess(String serviceName) throws Exception {
Runtime.getRuntime().exec(KILL + serviceName);
}
But Task Manager is still running. What can i do?
okay as to kill taskmanager you need administrator privilage. for this download this.
now copy any one file Elevate.exe or Elevate64.exe in your java project source path.
then
Runtime.getRuntime().exec("src//Elevate64.exe TASKKILL /F /IM Taskmgr.exe");
now it will prompt for yes or no. click on yes.... and BOOM
try{
Process p = Runtime.getRuntime()
p.exec("taskkill /F /IM taskmgr.exe /T")
catch(*Enter applicable exception type here* e){
System.err.println("Caught Exception: " + e.getMessage());
}
It isn't necessary to explicitly check if the task is running. If it isn't found then the command won't be executed. Try to kill it and if you get an exception, then account for it in the catch block(s).
Have you tried to change the case of the process?
For example:
if(isProcessRunning("taskmgr.exe")){
killProcess("taskmgr.exe");
}

Run Windows service with Java

I need to run Windows service with my parameter (token). I know how to start service:
String[] command = {"cmd.exe", "/c", "net", "start", "service name"};
new ProcessBuilder(command).start();
But don't know how to start it with my parameters?
A simple Java based utility to either start or stop a service could be something like this.
public static boolean stopService(final String serviceName) {
return execCommand("cmd.exe", "/c", "net", "stop", "\"" + serviceName + "\"");
}
public static boolean startService(final String serviceName) {
return execCommand("cmd.exe", "/c", "net", "start", "\"" + serviceName + "\"");
}
private static boolean execCommand(final String... args) {
try {
Process process = new ProcessBuilder(args)
.redirectErrorStream(true)
.start();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
String output = reader.lines().collect(Collectors.joining("\n"));
System.out.println("Command output:: " + output);
}
process.waitFor();
return process.exitValue() == 0;
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
return false;
}
Note that the execCommand method can be used to run basically any command. Also, if not really necessary I would recommend using sc to manage services instead of net.
Also the reason that this was not working for you, was that you where passing in the service name wrong.

Passing command prompt functions from java

I want to get the result of windows command prompt function from Java.
Java code:
Process process2 = Runtime.getRuntime().exec("cmd /c getmac");
Are there any alternative libraries available other than Runtime?
Use Apache Commons Exec. It can be used to get a console output of the running process.
A part of code from a real project
private final Executor executor = new DefaultExecutor();
private final ExecuteWatchdog watchDog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
private final ProcessDestroyer shutdownHookProcessDestroyer = new ShutdownHookProcessDestroyer();
private final DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler() {
#Override
public void onProcessFailed(ExecuteException ex) {
super.onProcessFailed(ex);
LOG.error("Error executing xxx.exe", ex);
}
};
public void startInSaveRecordMode(Long callId, File pathToResult) throws IOException {
CommandLine commandLine = createModeUserPasswordCommandLine(SAVE_RECORD_MODE_COMMAND)
.addArgument(ValidationUtil.toString(callId)).addArgument(
ValidationUtil.toString(pathToResult));
execute(commandLine);
}
private void execute(CommandLine commandLine) throws IOException {
Assert.notNull(pathToProcess);
executor.setWatchdog(watchDog);
executor.setProcessDestroyer(shutdownHookProcessDestroyer);
executor.setStreamHandler(createStreamHandler());
if (LOG.isDebugEnabled()) {
LOG.debug("Executing " + commandLine);
}
executor.execute(commandLine, resultHandler);
}
private CommandLine createModeUserPasswordCommandLine(String mode) {
Assert.hasLength(sensormUser);
Assert.notNull(sensormPassword);
return createCommandLine().addArgument(mode).addArgument(sensormUser);
}
private CommandLine createCommandLine() {
return new CommandLine(pathToProcess);
}
private ExecuteStreamHandler createStreamHandler() {
OutputEventsHandler eventsHandler = new OutputEventsHandler(eventsQueue);
SensormLogHandler errorLogHandler = new SensormLogHandler(LOG, Level.ERROR);
return new PumpStreamHandler(eventsHandler, errorLogHandler);
}
public int waitFor() throws InterruptedException {
resultHandler.waitFor();
return resultHandler.getExitValue();
}

ProcessBuilder command argument

(Sorry for my english I'm french) I'm creating a tiny Java IDE for my school project, but I'm facing a problem with running classes under Linux (I'm using Debian 7.3), no problem with Win 8.1
I'm using ProcessBuilder class to execute the java bin with some arguments, wich are args and projectOut
args = the class we want to run
projectOut = the absolute project path+"/out"
package com.esgi.honeycode;
import java.io.*;
import java.util.Scanner;
public class CustomRun {
public static void run(String args, final String projectOut) throws IOException {
System.out.flush();
if (args != null && projectOut != null) {
//SEPARATOR is a const for the file separator
ProcessBuilder builder = new ProcessBuilder("java", "-classpath", "\"" + System.getProperty("java.class.path") + System.getProperty("path.separator") + projectOut + PropertiesShared.SEPARATOR + "out\"", args);
System.out.println(builder.command());
builder.redirectErrorStream(true);
final Process process = builder.start();
Thread outThread = new Thread()
{
#Override
public void run() {
try {
String line;
try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
};
Thread inThread = new Thread() {
#Override
public void run() {
Scanner s = new Scanner(System.in);
//Need to control in before !!
while (true) {
String input = s.nextLine();
try (PrintWriter pw = new PrintWriter(new OutputStreamWriter(process.getOutputStream()))) {
pw.write(input);
pw.flush();
}
}
}
};
outThread.start();
inThread.start();
}
}
}
Testing with a simple class :
public class MyClass{
public static void main(String[] args)
{
System.out.println("TESTESTE");
}
}
the class is stored in : /home/m3te0r/HoneyCodeProjects/untitledaaa/out
And if I try to run the class, I get this output, with the command print :
[java, -classpath, "/home/m3te0r/Bureau/HoneyCode.jar:/home/m3te0r/HoneyCodeProjects/untitledaaa/out", MyClass]
Error: Could not find or load main class MyClass
Like I said, there is no problem under Win 8.1 and it also works when I run the same command in a terminal.
EDIT FOR THE ANSWER ():
Ok, so I figured out what was wrong.
I just removed the escaped double quotes fot the classpath and it worked.
I was thinking there would be a problem with spaced dir names or files, but there is not.
ProcessBuilder builder = new ProcessBuilder("java", "-classpath", System.getProperty("java.class.path") + System.getProperty("path.separator") + projectOut + PropertiesShared.SEPARATOR + "out", args);

How to find and kill running Win-Processes from within Java?

I need a Java way to find a running Win process from which I know to name of the executable. I want to look whether it is running right now and I need a way to kill the process if I found it.
private static final String TASKLIST = "tasklist";
private static final String KILL = "taskkill /F /IM ";
public static boolean isProcessRunning(String serviceName) throws Exception {
Process p = Runtime.getRuntime().exec(TASKLIST);
BufferedReader reader = new BufferedReader(new InputStreamReader(
p.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
if (line.contains(serviceName)) {
return true;
}
}
return false;
}
public static void killProcess(String serviceName) throws Exception {
Runtime.getRuntime().exec(KILL + serviceName);
}
EXAMPLE:
public static void main(String args[]) throws Exception {
String processName = "WINWORD.EXE";
//System.out.print(isProcessRunning(processName));
if (isProcessRunning(processName)) {
killProcess(processName);
}
}
You can use command line windows tools tasklist and taskkill and call them from Java using Runtime.exec().
Here's a groovy way of doing it:
final Process jpsProcess = "cmd /c jps".execute()
final BufferedReader reader = new BufferedReader(new InputStreamReader(jpsProcess.getInputStream()));
def jarFileName = "FileName.jar"
def processId = null
reader.eachLine {
if (it.contains(jarFileName)) {
def args = it.split(" ")
if (processId != null) {
throw new IllegalStateException("Multiple processes found executing ${jarFileName} ids: ${processId} and ${args[0]}")
} else {
processId = args[0]
}
}
}
if (processId != null) {
def killCommand = "cmd /c TASKKILL /F /PID ${processId}"
def killProcess = killCommand.execute()
def stdout = new StringBuilder()
def stderr = new StringBuilder()
killProcess.consumeProcessOutput(stdout, stderr)
println(killCommand)
def errorOutput = stderr.toString()
if (!errorOutput.empty) {
println(errorOutput)
}
def stdOutput = stdout.toString()
if (!stdOutput.empty) {
println(stdOutput)
}
killProcess.waitFor()
} else {
System.err.println("Could not find process for jar ${jarFileName}")
}
There is a little API providing the desired functionality:
https://github.com/kohsuke/winp
Windows Process Library
You could use a command line tool for killing processes like SysInternals PsKill and SysInternals PsList.
You could also use the build-in tasklist.exe and taskkill.exe, but those are only available on Windows XP Professional and later (not in the Home Edition).
Use java.lang.Runtime.exec to execute the program.
Use the following class to kill a Windows process (if it is running). I'm using the force command line argument /F to make sure that the process specified by the /IM argument will be terminated.
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class WindowsProcess
{
private String processName;
public WindowsProcess(String processName)
{
this.processName = processName;
}
public void kill() throws Exception
{
if (isRunning())
{
getRuntime().exec("taskkill /F /IM " + processName);
}
}
private boolean isRunning() throws Exception
{
Process listTasksProcess = getRuntime().exec("tasklist");
BufferedReader tasksListReader = new BufferedReader(
new InputStreamReader(listTasksProcess.getInputStream()));
String tasksLine;
while ((tasksLine = tasksListReader.readLine()) != null)
{
if (tasksLine.contains(processName))
{
return true;
}
}
return false;
}
private Runtime getRuntime()
{
return Runtime.getRuntime();
}
}
You will have to call some native code, since IMHO there is no library that does it. Since JNI is cumbersome and hard you might try to use JNA (Java Native Access). https://jna.dev.java.net/
small change in answer written by Super kakes
private static final String KILL = "taskkill /IMF ";
Changed to ..
private static final String KILL = "taskkill /IM ";
/IMF option doesnot work .it does not kill notepad..while /IM option actually works

Categories