How can i execute multiple commands with JAVA code? - java

I need to restart my Tomcat server from Java code. I'm a beginner in Java. I try to do that by cmd. I need to stop tomcat then restart it. I try this code. It works with just two commands (one &&) and it doesn't work if I add a third command (two && in the line exec("cmd /c start cmd.exe ...)).
PS: If another way exists to restart Tomcat with Java code please tell me
public class restart_tomcat {
public static void main(String[] args) throws SDKException, IOException {
Runtime rt = Runtime.getRuntime();
try {
// Process process1 = Runtime.getRuntime().exec("cmd /c start cmd.exe /K " + cmd1);
rt.exec("cmd /c start cmd.exe /K \"cd C:\\\\Program Files (x86)\\\\SAP BusinessObjects\\\\tomcat\\\\bin&&startup.bat\"");
System.out.println("succesful");
} catch (IOException e) {
e.printStackTrace();
}
}
}

It would be good to know why do you need to start/stop Tomcat from java code, is that a homework or something else? In the real-world, we have initialization scripts that can start/stop it by simply running them from the terminal. You can automate that with a very simple shell script (yourscript.sh) and add the following content:
#!/bin/bash
<path_to_tomcat>/bin/shutdown.sh
<path_to_tomcat>/bin/startup.sh
If you really need to do it from Java code, you may find your answer in one of these resources:
Start and Stop Tomcat from java code
Restart Tomcat with Java
Start and Stop Tomcat from java code
How to start Tomcat Server programmatically in Java
how to restart tomcat from a running webapp?

Related

Running a shell script which runs a Java program

I have a java application and from that application I want to be able to run new applications. While the concept is the same, I'm using this in a Minecraft environment where I want to have one application be able to run other Minecraft servers whenever I specify so in the first application.
I'm trying to run the startup shell script but whenever I do I simply get the error Error: Unable to access jarfile server.jar.
Note that I am perfectly able to run the script on my computer by "double clicking it", the shell script works, Java application starts up, and I can join the game server and play without any problems.
I've also tried running the jar application directly from the code, but then I get either CreatProcess error=5 or CreatProcess error=193 (using ProcessBuilder), even though I've set all the computer to have all permissions regarding reading and writing the file.
This is my code for running the shell script:
// Starts the server by running the script
File startScript = new File("C:\\Users\\{MYUSER}\\Desktop\\{PROJECTNAME_FOLDER}\\Network\\prison-spawn-2\\start.bat");
// Run the process
try {
Process process = Runtime.getRuntime().exec("cmd /c start " + startScript.getCanonicalPath());
int exitVal = process.waitFor();
if (exitVal == 0) {
System.out.println("Success!");
}
} catch (Exception exception) {
exception.printStackTrace();
}
Batch Script Content
echo "Starting server..."
java -jar C:\Users\{MYUSER}\Desktop\{PROJECTNAME_FOLDER}\Network\prison-spawn-2\server.jar nogui

Is it possible to automate ffmpeg-normalize in java?

I need to use ffmpeg-normalize (https://github.com/slhck/ffmpeg-normalize) to properly normalize audio files in my java program but ffmpeg-normalize requires manual installation and command usage.
I thought I could automate it in java using ProcessBuilder but it's been proving somewhat impossible.
ffmpeg-normalize is written in python, so I tried every stackoverflow question that relates to running python commands in java. None of them worked, it seems windows just refuses to allow java to run commands in general.
I added python to my environment variables as well. No dice. Windows keeps telling me it doesn't recognize python nor py nor pip as valid internal or external commands.
This is my final code, I tried all other solutions before this including Runtime.exe, using "cmd /c start", and all other derivatives of that.
My last attempt was running a .bat file from the java cmd processor and have the .bat do the rest, but not only is that windows only, but also fails.
Running pip in a cmd from cmd.exe directly (outside the java program I mean), it runs properly and shows me the help menu for pip. When the cmd opens from the java app, windows refuses to acknowledge the existence of python all together like in the image below.
Process process = Runtime.getRuntime().exec("cmd /c start " + installerBat.getAbsolutePath(), null, ffNormExtractDir);
StreamGobbler errorGobbler = new StreamGobbler(process.getErrorStream());
StreamGobbler outputGobbler = new StreamGobbler(process.getInputStream());
errorGobbler.start();
outputGobbler.start();
try {
process.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
I expected the java-born cmd to run the commands instantly and perfectly, but it simply refuses to run them.
So what is my best approach to make installing ffmpeg-normalize a breeze to the user?

How to run a .ps1 file in PowerShell_ISE.exe through Java

So I am creating a GUI in java that launches a variety of different scripts through powershell. I have been able to write a command that opens the .ps1 file in powershellISE, but the script doesn't actually run. My code is as follows:
String [] str = {"cmd", "/c" "start", "powershell_ise.exe", "-file", "myPath"};
try{
Runtime.getRuntime().exec(str);
} catch (IOException e) {
e.printStackTrace();
}
I found this question to be helpful:
Powershell open window (from Java.Runtime.exec)
But it did not solve my issue of actually running the script
Thanks so much!
Windows PowerShell Integrated Scripting Environment (ISE) is a graphical host application that enables you to read, write, run, debug, and test scripts.
If you want to run scripts you know work, you might try replacing powershell_ise.exe with powershell.exe. How to run powershell in cmd should help.

Check if jar is running or not

I would like to check whether a jar of mine is running on the users system, to then relaunch if it is closed.
I am aware of the command jps -l which makes it possible to check the current running jars. Only problem is that for that line to work, it requires the user to have a JDK installed. So I was then wondering whether or not there is an equivalent to the jps -l line, which doesn't need a JDK or anything, but just checks whether a specific jar is running.
In the past I have also used the line cmd /c tasklist for Windows and the line top -F -R -o cpu for Mac. To check whether an app or exe was running, but that doesn't really seem to be working. When running the tasklist line on Windows and I then check for an exe called "myApp", it doesn't find it. Even though it might be running. Otherwise this would have been a perfect method, to check for a running app, exe or jar.
Here is an example code of how I tried to use the tasklist command to check for a specific executable.
try {
String procss;
Process pRun = Runtime.getRuntime().exec("cmd /c tasklist");
BufferedReader input = new BufferedReader(new InputStreamReader(pRun.getInputStream()));
while ((procss = input.readLine()) != null) {
if(!procss.contains("myApp"))
{
//Runtime command to launch exe or app.
}
}
input.close();
} catch (Exception err) {
err.printStackTrace();
}
Basically I would like to just edit the code above, to have a command line, of which is able to actually check whether the exe, app or jar is running. Maybe there is an alternative to cmd /c tasklist and top -F -R -o cpu, which is able to get all processes running on a pc and not just .exe or .app
On windows, you could use the wmic command to get the command line parameters a program was launched with.
For example, using wmic process where "name like '%java%'" get commandline,processid (basically just means "get the PID and command line arguments of process with a name like java") gives me this output for a test program:
616
"C:\Program Files\Java\jre1.8.0_111\bin\javaw.exe" -jar "A:\Programmering\Java\Pong\out\artifacts\Pong_jar\Pong.jar"
As you can see, you can get the location of the jar file which is running (which you could then use to check if it's your program). In this case, I just launched it by double clicking the jar file, you may get different outputs if you launch it in a different way, but there should always be something you can use to identify the java process (like a main class or jar file).

exit the batch file after running using java

I know how to start the batch file using java code.
When i run the batch file command prompt is opened.
To close the command prompt i am using the taskill /im cmd.exe.
but the problem is that the command prompt that is used to start the jboss is also closed.
i want to kill the cmd with a particular process id.
How do i get the process id of a particular cmd promt and kill that using java
Run the batch file with cmd.exe /c job.bat. The /c switch carries out the command and then terminates the command interpreter.
can't you add exit to your batch file to exit it's own command prompt. Uisng taskill seems overkill for just closing one command prompt, don't you think?
PS: I've never worked on batch files just the command prompt so I'm assuming it accepts the same commands.
Here is the solution that works: to close command window after executing the commands from the batch (.bat) file you need to add "exit" (without the quotes) in a new line of your batch file. If you want to delay the execution this is the way and it works:
public class TestSleep
{
public static void main ( String [ ] args )
{
System.out.println("Do this stuff");
try
{
Thread.currentThread().sleep(3000);
}
catch ( Exception e ) { }
System.out.println("Now do everything after this");
}
}
Cheers
If you start the batch file with Runtime.exec(), it returns you a Process object. Calling the destroy() method will kill that process.
Although this seems to be an old question and probably resolved.. I struggled with the same thing for a long time.. Finally this works
String command = "cmd.exe /c build.bat";
Runtime rt = Runtime().getRuntime();
Process pr = rt.exec(command);
I too had the same problem. I first used as
Runtime.getRuntime().exec("cmd.exe start /c test.bat");
Then I tried as below. It works fine.
Runtime.getRuntime().exec("cmd.exe /c start test.bat");
Try this.

Categories

Resources