I am using Runtime.getRuntime().exec() method for running 'optimathsat.exe' file. My code is like
public boolean runOptimathSat() throws InterruptedException {
boolean runSucceed = false;
smtInputFileDirectory = getInputDirectory();
txtOutputFileDirectory = getOutputDirectory();
optimathsatDirectory = getOptimathSatDirectory();
if ((smtInputFileDirectory != null) && (txtOutputFileDirectory != null)
&& (optimathsatDirectory != null)) {
if (isWindows()) {
String winCommand;
winCommand = "cmd /c cd " + optimathsatDirectory + " && optimathsat.exe -opt.print_objectives=True -opt.output_format=old -optimization.card_constr_encoding=2 -optimization.dpll.search_strategy=1 -preprocessor.toplevel_propagation=False -preprocessor.simplification=0 < " + smtInputFileDirectory + " > " + txtOutputFileDirectory + " 2>& 1";
System.err.println("COMMAND: "+winCommand);
try {
Process p = Runtime.getRuntime().exec(winCommand);
p.waitFor();
runSucceed = true;
} catch (IOException e) {
e.printStackTrace();
}
return runSucceed;}
After running this code, it shows the below line in console
COMMAND: cmd /c cd "C:\Users\Karencom\OptiMathSAT\optimathsat-1.5.1-windows-64-bit-mingw\bin" && optimathsat.exe -opt.print_objectives=True -opt.output_format=old -optimization.card_constr_encoding=2 -optimization.dpll.search_strategy=1 -preprocessor.toplevel_propagation=False -preprocessor.simplification=0 < "C:/Users/Karencom/runtime-New_configuration/tetest/Optimathsat/bibi.smt2" > "C:/Users/Karencom/runtime-New_configuration/tetest/Optimathsat/bibi.txt" 2>& 1
and shows below error in bibi.txt file
'optimathsat.exe' is not recognized as an internal or external command, operable program or batch file.
However, when I copy some lines of the above code in a separate project(which has just one class), and replace the generated command in winCommand variable, it works perfectly.
import java.io.IOException;
public class Test {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
try {
String winCommand="cmd /c cd"+ " \"C:\\Users\\Karencom\\OptiMathSAT\\optimathsat-1.5.1-windows-64-bit-mingw\\bin\" && optimathsat.exe -opt.print_objectives=True -opt.output_format=old -optimization.card_constr_encoding=2 -optimization.dpll.search_strategy=1 -preprocessor.toplevel_propagation=False -preprocessor.simplification=0 < \"C:/Users/Karencom/runtime-New_configuration/tetest/Optimathsat/sensen.smt2\" > \"C:/Users/Karencom/runtime-New_configuration/tetest/Optimathsat/sensen.txt\" 2>& 1";
Process p = Runtime.getRuntime().exec(winCommand);
p.waitFor();
System.err.println("COMMAND: "+winCommand);
} catch (IOException e) {
e.printStackTrace();
}
}
}
I guess that first project's configuration is not right but I do not know how can I resolve it.
You are using cmd for 2 things:
Setting the current directory
Redirecting input and output
Rather than using cmd for that, you should use Java's ProcessBuilder.
String[] winCommand = {
"optimathsat.exe",
"-opt.print_objectives=True",
"-opt.output_format=old",
"-optimization.card_constr_encoding=2",
"-optimization.dpll.search_strategy=1",
"-preprocessor.toplevel_propagation=False",
"-preprocessor.simplification=0"
};
Process p = new ProcessBuilder(winCommand)
.directory(new File(optimathsatDirectory)) // "cd " + optimathsatDirectory
.redirectInput(new File(smtInputFileDirectory)) // "< " + smtInputFileDirectory
.redirectOutput(new File(txtOutputFileDirectory)) // "> " + txtOutputFileDirectory
.redirectErrorStream(true) // 2>& 1
.start();
p.waitFor();
Related
I have a tif image where I am trying to draw a box and compress the image with LZW compression simultaneously.
this is the command I am running, and it works fine from windows command line.
C:\ImageMagick-7.1.0\convert.exe "C:\Users\admin\Orig.tif" -draw "rectangle 576,1069,943,1114" -compress LZW "C:\Users\admin\DrawLZW.tif"
when I try to execute the same command with my java program, I get an image file created, but the file size is 1kb
String[] cmd = {"C:\\ImageMagick-7.1.0\\convert.exe", "\"C:\\Users\\chris.macwilliams\\Orig.tif\"", "-draw", "\"rectangle 576,1069,943,1114\"", "–compress","LZW", "\"C:\\Users\\chris.macwilliams\\DrawLZWwithJava.tif\""};
LOGGER.info(cmd);
Process pt = Runtime.getRuntime().exec(cmd);
pt.waitFor();
if (pt.exitValue() != 0) {
LOGGER.error("ERROR with Image Magic Command exit value:" + pt.exitValue()+ " "+ commandTIF);
Any Ideas here?
Using IM Version: ImageMagick-7.1.0
I have included the test images that I am getting the errors on.
zip file download
If you are using an array, it's easier to declare the size of the array and add each argument before executing the cmd.
private void redactCMDArray() {
String[] cmd = new String[7];
cmd[0] = "C:\\ImageMagick-7.1.0\\convert.exe";
cmd[1] = "\"C:\\Users\\Administrator\\Desktop\\images\\Orig.tif\"";
cmd[2] = "-draw";
cmd[3] = "rectangle 576,1069,943,1114";
cmd[4] = "-compress";
cmd[5] = "LZW";
cmd[6] = "\"C:\\Users\\Administrator\\Desktop\\images\\DrawLZW_CMD_Option1.tif\"";
System.out.println(Arrays.toString(cmd));
Process pt;
try {
pt = Runtime.getRuntime().exec(cmd);
pt.waitFor();
if (pt.exitValue() != 0) System.out.println("ERROR with Image Magic Command exit value:" + pt.exitValue()+ " " + Arrays.toString(cmd));
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
Another option, as stated by Esther, is to add a whitespace between parameters within the command and not pass an array.
private void redactCMDLine(){
String imPath = "C:\\ImageMagick-7.1.0\\convert.exe";
String imEXE = "/convert.exe";
String cmd = imPath + imEXE + " " + "C:\\Users\\Administrator\\Desktop\\images\\Orig.tif" + " " + "-draw \"rectangle 576,1069,943,1114\"" + " " + "-compress LZW" + " " + "C:\\Users\\Administrator\\Desktop\\images\\DrawLZW_CMD_Option2.tif";
try {
Process p = Runtime.getRuntime().exec(cmd);
p.waitFor();
System.out.println("Exit code: " + p.exitValue());
} catch (InterruptedException | IOException e) {
e.printStackTrace();
}
}
If the IM4Java jar is available, a more straightforward solution would be the following.
private void redactIM4Java() {
ConvertCmd convertCmd = new ConvertCmd();
IMOperation op = new IMOperation();
op.addImage("C:\\Users\\Administrator\\Desktop\\images\\Orig.tif");
op.fill("Black");
op.draw("rectangle 576,1069,943,1114");
op.compress("LZW");
op.format("TIF");
op.addImage("C:\\Users\\Administrator\\Desktop\\images\\DrawLZW_MB_JavaIM4Java.tif");
try {
convertCmd.run(op);
} catch (IOException | InterruptedException | IM4JavaException e) {
e.printStackTrace();
}
}
I am working on a java UNO project, OS : Ubuntu 14. I am calling exec via passing command to run via a jar file with some set of sub commands of that jar file.
String finalOutputMSG = "";
String[] cmd = {JAVA_LOCATION, " -jar ", JAR_LOCATION, " " + inputFile, " -dir ", ".isc", " -out xml"};//java location provides java location, jar location provides jar location, inputfile contains input file's location -dir provides output directory with name .isc, -out is output file with file format for output is xml
Similar command ran properly without showing any errors but in a case where I am trying to import a file and convert it into another format eg .xlsx to .xml, is giving error. In commands it worked, I have already generated outputs from an input file.
finalOutputMSG = exec(cmd);
/**
* exec() is executed and outputs are displayed
*
* #param String[] command passed to jar
* #return output message containing outputs or output message
*/
private static String exec(String[] cmd) {
String outputMSG = "";
Process proc = null;
try {
ProcessBuilder pb = new ProcessBuilder(cmd);
pb.redirectErrorStream(true);//any error output generated by subprocesses merged with the standard output,
//read using the Process.getInputStream()
///* Start the process */
proc = pb.start();
if (debug) {
System.out.println("Process started !");
}
outputMSG = getOutput(proc);
if (debug) {
System.out.println("outputMSG " + outputMSG);
}
} catch (IOException e) {
if (debug) {
System.out.println("Exception in exec " + e.getMessage());
JOptionPane.showMessageDialog(null, "Exception in exec ");
}
// StringBuilder append = appendToFile.append("Exception in exec ").append(e.getMessage());
} catch (Exception e) {
if (debug) {
System.out.println("Exception in exec " + e.getMessage());
JOptionPane.showMessageDialog(null, "Exception in exec ");
}
} finally {
///* Clean-up */
proc.destroy();
if (debug) {
System.out.println("Process ended !");
}
}
return outputMSG;
}
/**
* Reads output from current process
*
* #param current process
* #return output read in current process
*/
private static String getOutput(Process p) {
StringBuilder outStream = new StringBuilder();
if (debug) {
System.out.println("StringBuilder initialized in getOutput");
}
try {
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
if (debug) {
System.out.println("BufferedReader initialized in getOutput");
}
String line = null;
if (debug) {
System.out.println("in.readLine() in getOutput abt to be read");
}
while ((line = in.readLine()) != null) {
outStream.append(line);
if (debug) {
System.out.println("line in getOutput " + line);
System.out.println("outStream in getOutput " + outStream);
}
outStream.append("\n");
}
} catch (IOException e) {
if (debug1) {
System.out.println("IOException in getOutputs " + e.getMessage());
}
} catch (Exception ex) {
if (debug1) {
System.out.println("Exception in getOutputs" + ex.getMessage());
}
}
return outStream.toString();
}
Error Message depicted by Netbeans
Error: Could not find or load main class -jar
I have searched on the issue, but could not find any help that is useful, I could not understand, what is missing.
Solution:
String[] cmd = {JAVA_LOCATION, " -jar ", JAR_LOCATION, " " + inputFile, " -dir ", ".isc", " -out xml"};
I replaced the values that printed in console, and ran the command so got on terminal, it worked fine.
Solution: the command to be used must be without any spaces in the ends. Because terminal in linux interprets the commands like for "ls", but in java/ any programming language, it doesn't interprets for ls, so in case of the following parameter cmdarray
public Process exec(String[] cmdarray)
throws IOException
takes the command as it is.
String[] cmd = {JAVA_LOCATION, "-jar", JAR_LOCATION, inputFile, "-dir", ".isc", "-out", "xml"};
I want to test to run mysqldump command in my function but I could not create aaadumpdb.sql file. My code is below:
#Test
public void dumpDB() {
Process p = null;
try {
Runtime runtime = Runtime.getRuntime();
p = runtime
.exec("mysqldump -u root -padmin --add-drop-database aaa_db "
+ "D:\\backupdenemeaaa " + "aaadumpdb.sql");
// change the dbpass and dbname with your dbpass and dbname
int processComplete = p.waitFor();
if (processComplete == 0) {
System.out.println("Backup created successfully!");
} else {
JOptionPane.showMessageDialog(new JDialog(),
"Could not create the backup");
}
} catch (Exception e) {
e.printStackTrace();
}
File f = new File("aaadumpdb.sql");
assertTrue(f.exists());
}
Can anybody give me some advice about it? Thank you.
I did some edit in my code but when I run, my code enter into else structure. What can be the problem?
My editted code is below:
#Test
public void dumpDB() {
Process p = null;
try {
Runtime runtime = Runtime.getRuntime();
String mysqldumpExecutable = "C:\\Program Files\\MySQL\\MySQL Server 5.6\\bin\\mysqldump.exe";
p = runtime.exec(mysqldumpExecutable + " -uroot -padmin --add-drop-database -B aaa_db -r" + "D:\\backupdenemeaaa " + "\\aaadumpdb.sql");
// change the dbpass and dbname with your dbpass and dbname
int processComplete = p.waitFor();
if (processComplete == 0) {
System.out.println("Backup created successfully!");
} else {
JOptionPane.showMessageDialog(new JDialog(),
"Could not create the backup");
}
} catch (Exception e) {
e.printStackTrace();
}
File f = new File("aaadumpdb.sql");
assertTrue(f.exists());
How can I solve this problem? Thank you.
The stacktrace would really help to debug it, but I believe you can check if "mysqldump" is in your PATH or the application will simple not find the executable. If you don't want to mess around with your PATH you can hardcode the path to the executable like below:
String mysqldumpExecutable = "C:\\apps\\mysql\\mysqldump.exe";
runtime.exec(mysqldumpExecutable + "-u root -padmin --add-drop-database aaa_db (.....));
When you say you can't create the file what exactly does that mean? Are you getting an error? Nothing happens? Help us help you.
Add the below snippet to find what exactly is happening
try
{
InputStreamReader isr = new InputStreamReader(process.getErrorStream());
BufferedReader br = new BufferedReader(isr,4094);
String line=null;
while ( (line = br.readLine()) != null)
System.out.println(type + "> " + line);
} catch (IOException ioe)
{
ioe.printStackTrace();
}
}
You will be aware of the the exceptions and errors that might occur in that Process execution
I want to automatically change the ip address of an Ubuntu 12.04 PC by a program fires at startup. For some certain reasons, I want to code it in Java.
Exactly the solution is written here:
Java - Execute a .SH file
But it does not work in my case. I could not manage to find why,essentially my case is a special case of so called thread, I try to run a sudo-command in linux with
public static void executeCommandLine(String strCommand){
Runtime rt = Runtime.getRuntime();
try {
Process p = rt.exec(strCommand);
if(p==null){
System.out.println("Error in process");
}
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
try {
while ((line = reader.readLine()) != null)
{
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
I call this executeCommandLine() function from another function as follows:
public static void changeIpAddress(String strIpAddress, String strRootPassword, String strEthDevice){
String strCommandLine = "";
if(PLATFORM == PLATFORM_LINUX){
strCommandLine = "/bin/echo " + strRootPassword + "| sudo -S /sbin/ifconfig " + strEthDevice + " " + strIpAddress;
}else if(PLATFORM == PLATFORM_WINDOWS){
// TODO: Write for Windows
}else{
System.out.println("OS not supported");
}
System.out.println("Executed command:");
System.out.println(strCommandLine);
executeCommandLine(strCommandLine);
}
I am executing powershell commands in java and I have written two programs, however the strange part is one works fine and the other throws the error. The code that throws the error is as shown
I have tried the following
1) Spcifying the fully specified path of powershell
2) My path variable has the following - "C:\WINDOWS\system32\WindowsPowerShell\v1.0"
I know I might be doing something trivial but its been a day and I am unable to figure out what the issue might be
import java.io.IOException;
public class FileCount {
public static void main(String[] args) {
Process flCntProcess = null;
try {
String test = "C:\\WINDOWS\\system32\\windowspowershell\\v1.0\\powershell.exe -Command \"& { Get-ChildItem C:\\test -Recurse -force | Measure-Object }\"";
System.out.println("Powershell command : " + test);
ProcessBuilder builder = new ProcessBuilder(test);
builder.redirectErrorStream(true);
flCntProcess = builder.start();
// FILE COUNT OUTPUT STREAM PROCESSING
NotifyThreadComplete outputThread = new ProcessHandler(flCntProcess.getInputStream(),"OUTPUT");
outputThread.addListener(new ThreadCompleteListener() {
#Override
public void notifyCompletion(Thread t, long startTm, boolean didErrorOut, String noOfLines) {
System.out.println("Completed Output Stream Processing");
System.out.println("Printing values");
System.out.println("No of Lines : " + noOfLines);
System.out.println("Did Error out : " + didErrorOut);
if(didErrorOut) {
System.out.println("Do not continue with processing");
} else {
System.out.println("Continue with processing");
}
}
});
System.out.println("Starting output thread ");
outputThread.start();
} catch (Exception e) {
System.err.println("Exception while counting files using Powershell Command" + e.getMessage());
} finally {
if(flCntProcess != null && flCntProcess.getOutputStream() != null) {
try {
flCntProcess.getOutputStream().close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Error code indicates the file to execute can't be found. Try splitting up the program from its arguments:
String ps = "C:\\WINDOWS\\system32\\windowspowershell\\v1.0\\powershell.exe";
String args = "-Command \"& { Get-ChildItem C:\\test -Recurse -force | Measure-Object}\"";
ProcessBuilder builder = new ProcessBuilder(ps, args);
The constructor of ProcessBuilder does not accept a single String containing a cli invocation, but an array of Strings containing in order :
the program to be executed
its arguments
See the javadoc
So it interprets your whole String test as the program name, splitting it up should work :
final String psh = "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe";
final String args = "-Command & { Get-ChildItem C:\\temp -Recurse -force | Measure-Object }";
final ProcessBuilder builder = new ProcessBuilder(psh, args);