Run process through java program - java

I am working in java for Ubuntu environment. I want to execute a script file but through java program. I have tried followings
try{
Runtime.getRuntime().exec("/usr/lib/flume-ng/bin/flume-ng agent -f /home/c4/Flume/New/ClientAgent.config -n clientAgent");
}
catch(Exception e){
e.printStackTrace();
}
And
ProcessBuilder pb = new ProcessBuilder("/usr/lib/flume-ng/bin/flume-ng", "agent",
"-f", "/home/c4/Flume/New/ClientAgent.config","-n","clientAgent");
try{
pb.start();
}
catch(Exception e){
e.printStackTrace();
}
But both of these don't start my process named: flume-ng, other are parameters passed to it. Java program compiles successfully but neither gives exception etc nor run process. Please guide me if i am doing something wrong.

Consider Apache Commons Exec
It provides reliable and cross-platform mechanism to launch external processes.
Here is the latest javadoc: http://commons.apache.org/proper/commons-exec/apidocs/index.html
And here is the simple tutorial: http://commons.apache.org/proper/commons-exec/tutorial.html

Related

Launch Jar file located on network through Java Code

I'd like to launch a jar file through an existing running Java application. I've looked into ProcessBuilder, Runtime and jproc and none of them work because they all say the same error:
CreateProcess error=193, %1 is not a valid Win32 application
The way I can get it to work is by adding the command: java -jar <path of network located jar> in any of the libraries above.
I don't want to do it this way because it messes up with location of paths and such that would run in the context of the network location if you "double clicked" the jar files directly.
Is there a way to run the jar on the network using the "default" JRE on Windows/Mac?
here is example code:
String networkLocation = "//appserver/testApp/test.jar";
// new ProcBuilder(networkLocation).withNoTimeout().run();
ProcessBuilder pb = new ProcessBuilder(networkLocation);
try
{
pb.start();
}
catch (IOException ex)
{
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
Found out how to make the working directory using jproc:
new ProcBuilder("java", "-jar", networkLocation).withNoTimeout().withWorkingDirectory(new File ("//appserver/testApp/")).run();
And also with Runtime
Runtime.getRuntime().exec(new String[]{"java","-jar", networkLocation}, null, new File("//appserver/testApp/"));

Login and Reload JBoss server using Java

I am trying to login to my JBoss server using Java and reload it.
I have tried following code:
ProcessBuilder processBuilder = new ProcessBuilder("C:\\jboss\\jboss-eap-6.4\\bin\\jboss-cli.bat -c --controller=10.10.10.10 --user=user --password=pass --command=:reload");
processBuilder.inheritIO();
Process p = processBuilder.start();
try {
p.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
but I get this error:
CreateProcess error=2, The system cannot find the file specified
I have following settings for my environment variables-
1. JAVA_HOME- C:\Program Files\Java\jdk1.8.0_121
2. JBOSS_HOME-C:\jboss\jboss-eap-6.4
3. The bat file is present in the directory
4. I can login and reload it manually
I am out of ideas here.
I ended up using
Runtime.getRuntime().exec()
instead of
processBuilder()

Restart Tomcat with Java

I need to restart the tomcat from Java code.
For eg, if a query is not executed for a certain time Period then it will restart the tomcat automatically.
I have tried the following shutdown and startup code, but when we shutdown the tomcat then the java code will not run and tomcat not started.
Note :- I am running this code from a application and restarting the same tomact which the same application is using.
Following the code
try {
PreparedStatement.setQueryTimeout(10);
rs = PreparedStatement.executeQuery();
} catch (SQLException ex) {
System.out.println("IN CATCH BLOCK FOR THE REFRESH INVOICE");
String shutcommand = "killall java";
Process shutchild = Runtime.getRuntime().exec(shutcommand);
System.out.println("JAVA PROCESS KILLED");
String locationCommand = "cd /root/cluster/tomcat6/bin";
Process locationChild = Runtime.getRuntime().exec(locationCommand);
String strtcommand = "./startup.sh";
Process strtchild = Runtime.getRuntime().exec(strtcommand);
}
Killing tomcat after SQLException this is not good idea to handle this exception. Probably the problem is on database site.
But if you are sure, that it is what you need you can kill this java proces in this section, but to run tomcat you should use for example bash and cron. Why? Beacues after killing your executing code will stop, so you don't achieve the line to start tomcat.
How to check tomcat: Is Tomcat running?
TL;DR
File binaryDir = new File(System.getProperty("catalina.home") + File.separator + "bin");
String restartCommand = "\"shutdown.bat & ping 0.0.0.0 -n 4 & C:\\WINDOWS\\system32\\net start Tomcat8\"";
new ProcessBuilder("cmd", "/c", restartCommand).directory(binaryDir).start();
Survive
Creating new process will survive JVM shutdown. If you combine commands in one line
it should work fine according to my tests and this.
shutdown.bat
You need to use shutdown.bat instead stopping windows service because it often fails on Windows with message Cannot stop service Apache Tomcat...
ping 0.0.0.0 -n 4
You need to wait some time after shutdown otherwise you will get Service is already starting. Try again later error message. Also note I use ping instead timeout because it causes problems on some systems.
C:\WINDOWS\system32\net start Tomcat8
I'm starting windows service because invoking startup.bat won't work for me. Also remember to replace Tomcat8 if you using different tomcat or custom service name for example Tomcat7
Redirect I/O
Don't redirect input or output of process instance or command will shutdown with JVM, and Tomcat won't start.
You can execute this native command using java
String command = "c:\program files\tomcat\bin\startup.bat";//for linux use .sh
Process child = Runtime.getRuntime().exec(command);
You should consider using ProcessBuilder instead of Runtime exec. Also, you should split all the arguments when you want to execute a command.
I suggest this :
ProcessBuilder shutcommand = new ProcessBuilder("killall", "java");
Process shutchild = shutcommand.start();
System.out.println("JAVA PROCESS KILLED");
ProcessBuilder strtcommand = new ProcessBuilder("/root/cluster/tomcat6/bin/startup.sh", "java");
Process strtchild = strtcommand.start();

`Rserve` is not recognised as internal or external command.

The basic set-up is to have a Java based UI and R running in the background. Rserve utility helps to address this kind of a situation.
It's known that Rserve, although not a package, but can be installed and run like a normal R package. A simple library(Rserve) will invoke it and in the Windows Task Manager, you see the process up and running.
However, there is another way around, without having to go to R console frequently, by writting a script in Java itself.
/**
* initiate R serve
*/
try {
Process p=Runtime.getRuntime().exec("R CMD Rserve --vanilla"); //I'm stuck here
p.waitFor();
} catch (IOException e1) {
e1.printStackTrace();
} catch (InterruptedException e2) {
e2.printStackTrace();
}
The problem is, R CMD Rserve --vanilla is not working. It says,
`Rserve` is not recognised as internal or external command.
My R CMD is perfect, R is working good, so is Rscript but not Rserve. I wish to know how do I set the appropriate directory/path for Rserve within the R installation, so that I resolve this error?
I realise this question is from way back, but I feel an answer is still warranted for those that are interested.
Following the suggestion:
Binary installations have no way to write in $R_HOME/bin and thus Rserve() function described above is the only reliable way to start Rserve in that case.
Instead of using
R CMD Rserve
use
Rscript -e "library(Rserve); Rserve()"
Also, for those that were mystified by the comment in the Rserve documentation (?Rserve) about the line:
Java developers may want to see the StartRserve class in java/Rserve/test examples for easy way to start Rserve from Java.
You can find the class in https://rforge.net/Rserve/snapshot/Rserve_1.8-8.tar.gz by extracting the contents and navigating to ./clients/java/Rserve/test/StartRserve.java.

running build.xml from java program

i am trying to run ant script from java program.what is the procedure to execute the program
How to run build.xml from java program?
here is how iam trying to implement
Process proc = rt.exec("ant -buildfile D:ant\\trail");
regards,
techie
Check here Execute Ant From Your Application
and look at this example:
Project project = new Project();
project.init();
DefaultLogger logger = new DefaultLogger();
logger.setMessageOutputLevel(Project.MSG_INFO);
logger.setErrorPrintStream(System.err);
logger.setOutputPrintStream(System.out);
project.addBuildListener(logger);
File buildFile = new File("buildhtml.xml");
ProjectHelper.configureProject(project, buildFile);
project.setProperty("ant.file", buildFile.getAbsolutePath());
project.setProperty("item", "ant");
project.setProperty("inputdir", "src/items/ant");
project.setProperty("outputdir", "build/items/ant");
project.setProperty("graphics.prefix", "../../");
try {
project.executeTarget("checkifuptodate");
} catch(Exception e) {System.err.println(e.getMessage());}
// rest of program goes here
It is a better solution than calling Runtime.exec
Rather than trying to start a windows executable separately, it'd be a more robust and flexible solution to use the Ant API. Docs are included with ant itself, they are not online...
Try Runtime.getRuntime().exec("cmd /c start ant.bat");
taken from How do I run a batch file from my Java Application?

Categories