Executing a command from java code - java

Hi I want to execute this command from java code :
cd C:/Users/Amira/junoWorkspace/TestProjectUI
mvn -Dtest=MyClassTest.java test
So I found this method but i didn't find a way to adapt it to my case :
public static void main(String[] args) throws IOException
{
try
{
// Runtime runtime = Runtime.getRuntime();
String[] cmd={"C:\\WINDOWS\\System32\\cmd.exe","/C start test.bat"};
Process p = Runtime.getRuntime().exec(cmd);
// TODO code application logic here
}
catch(IOException e)
{
System.err.println("echec de l'execution du script: "+e);
System.exit(1);
}
}
Any idea ?
Cheers

What you are looking for is ProcessBuilder which will allow you to set arguments like the working directory etc, it will also allow for multiple arguments, check here and here and ProcessBuilder Demo for some examples on how to use it

Related

Runtime exec command working when when run from terminal but not eclipse

I'm trying to use tesseract to do OCR on an image in java. I realize there are wrappers like Tess4J that provide a bunch more functionality and stuff, but I've been struggling to get it set up properly. Simply running a one-line command with Runtime is really all I need anyways since this is just a personal little project and doesn't need to work on other computers or anything.
I have this code:
import java.io.IOException;
public class Test {
public static void main(String[] args) {
System.out.println(scan("full-path-to-test-image"));
}
public static String scan(String imgPath) {
String contents = "";
String cmd = "[full-path-to-tesseract-binary] " + imgPath + " stdout";
try { contents = execCmd(cmd); }
catch (IOException e) { e.printStackTrace(); }
return contents;
}
public static String execCmd(String cmd) throws java.io.IOException {
java.util.Scanner s = new java.util.Scanner(Runtime.getRuntime().exec(cmd).getInputStream()).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
}
When it's compiled and run directly from terminal, it works perfectly. When I open the exact same file in eclipse, however, it gives an IOException:
java.io.IOException: Cannot run program "tesseract": error=2, No such file or directory
What's going on? Thank you for any help.
Check the working folder in the run configuration for the Test class in Eclipse. I bet it's different from the one when you run the same program from a terminal.

Spark submit in java(SparkLauncher)

I made spark+hadoop yarn enviroment and spark-submit command works well. So I made SparkLauncher java code to do this in my application jar, BUT somehow it doesn't work (actually computer fan is spinning at first but not as long as i did with spark-submit.)
It seems not work well (no application log in hadoop web ui, unlike spark-submit). I cannot see any error log when I do with 'SparkLauncher'. without log message, I can do nothing with it.
Here is how I made it so far.
public class Main {
public static void main(String[] args) {
Process spark = null;
try
{
spark = new SparkLauncher()
.setAppResource("/usr/local/spark/examples/jars/spark-examples*.jar")
.setMainClass("org.apache.spark.examples.SparkPi")
.setMaster("yarn")
.setDeployMode( "cluster")
.launch();
}
catch( IOException e)
{
e.printStackTrace();
}
}
}
executed it with ( java -jar example.jar)
I had the same problem at first. I think the main issue is that you forgot about the waitFor().
Also, it's really helpfull to extract your errorMessage and deal with it (e.g. log it or checking it while debuging ) within your java code. To allow this, you should create a streamReader thread as follows:
InputStreamReaderRunnable errorStreamReaderRunnable = new InputStreamReaderRunnable(spark.getErrorStream(), "error");
Thread errorThread = new Thread(errorStreamReaderRunnable, "LogStreamReader error");
errorThread.start();
int result= spark.waitFor();
if(result!=0) {
String errorMessage = extractExceptionMessage(errorStreamReaderRunnable.getMessage());
LOGGER.error(errorMessage);
}
This should be after your launch() command and inside your try block. Hope it helps

Java - Printing to cmd

So my problem here is that I'm not too sure how to print a set of commands to cmd. I have a batch file that runs a Minecraft server, and I need to be able to run commands through the command prompt that shows up when I run the batch file, which will in turn perform commands to the server.
Here is my code so far:
package com.Kaelinator;
import java.io.IOException;
public class ServerManager {
public static void main(String[] args){
try {
System.out.println("Opening");
Runtime runTime = Runtime.getRuntime();
Process process = runTime.exec("cmd /C start /min " + "C:/Users/Owner/Desktop/rekt/Run.bat");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//System.out.println("Closing");
//process.destroy();
} catch (IOException e){
e.printStackTrace();
}
}
}
Yes, I understand that all this does so far is open the batch file. :P I am expecting something like this that I need to add to my code:
process.InputStream(command1);
But I am certain that there is more to it, something along the lines of bufferedWriters or something like that...
Whenever I try to get answers from Google, the answers always have a whole load of extra code, or have something completely different about them.
Thanks!

Catch Java Exception with PHP shell_exec

Is there any way to catch a java exception from a JAR call by a php script? I have (!) to use some external JAVA libraries, which throws Exceptions. The Question is how can i extract valuable information for developers and show some explanation to the customer?
PHP Script
try{
$cmd = "java -jar myjar.jar";
$output = shell_exec(escapeshellcmd($cmd));
}
catch(Javaexception $e){
//do some error handling ....
}
Java Jar
//....
public class Main{
public static void main(String[] args){
throw new Exception("Testexception");
}
}
//...
shell_exec only returns a String or Null, so you can't catch the Java Exception like that, try to create your own Exception and "catch it" with a if
$cmd = "java -jar myjar.jar";
$output = shell_exec(escapeshellcmd($cmd));
if($output == 'expected output') throw new MyException();
Basic answer: not directly.
You can use exit statuses to communicate processing status from the Java application.
In Java:
public class Main{
public static void main(String[] args){
try {
// work
} catch (MyException e) {
// handle error
// write exception to file or STDOUT
System.exit(1);
}
}
}
In PHP you can get the exit status via return_var in exec call:
string exec ( string $command [, array &$output [, int &$return_var ]] )
You can also write Exception details to STDOUT or file and process its content in the PHP when status code is non 0.

Running a .cmd file through Java code

I am trying to run a .cmd program from Java. Doesn't run.
I'm using Runtime.exec as advised in some other posts.
public void mouseClicked(MouseEvent arg0) {
Runtime runtime = Runtime.getRuntime();
String path = "E:/Marvin/Marvin_Cleanup.CMD";
try {
runtime.exec(path);
} catch (Exception e1) {
e1.printStackTrace();
}
}
Im not familiar with windows executeables but using the process builder combined with that url should work fine.
http://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html
If you call further batches from your batch file you might need to use cmd /c prefix. https://superuser.com/questions/712279/commands-run-in-a-batch-file-only-when-writing-cmd-c-before
String path = "cmd /c E:/Marvin/Marvin_Cleanup.CMD";

Categories