I am trying to interact with a simple .exe I created from some Python code. I have tested the .exe through Windows cmd and it works just fine. When I try to send the same input to the .exe through my java program to produce the graphs I need, OutputStream just writes "error" to the console. I have tried sending a string and an integer through OutputStream but the same results are obtained no matter what. I have already interacted with X-Foil.exe, a console application use to produce airfoil data files, with great success through this same java app. As I have to preform curve fitting to the data, I used Python with the matplotlib plugin then used py2exe to create the .exe. I am trying to create a web application with the end goal of designing an aircraft wing, hence the use of java. Here is the method being use which I am having the problem with:
public void PyGrapher(String NACA_4d) {
try {
ProcessBuilder builder = new ProcessBuilder("PyAirfoilGraphing\\dist\\GraphPolars.exe");
builder.redirectErrorStream(true);
Process pr = builder.start();
OutputStream out = pr.getOutputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream()));
double CL_alpha;
out.write((NACA_4d + "\n").getBytes());
System.out.println(in.readLine());
System.out.println(in.readLine());
System.out.println(in.readLine());
System.out.println(in.readLine());
//CL_alpha = Double.parseDouble(in.readLine());
pr.waitFor();
pr.destroy();
out.close();
in.close();
} catch (IOException | InterruptedException ex) {
}
}
Here is what I have read in from the console:
Input NACA 4-digit code: error
Traceback (most recent call last):
File "GraphPolars.py", line 16, in <module>
IOError: [Errno 2] No such file or directory: '..\\..\\AirfoilPolars\\NACA_0024.dat'
I am stumped, and have been for quite some time. There is not a problem with the python file, and it runs fine by itself in the current directory. Can anyone help, please?
-Nick K
Could it be something with relative paths? Python default path may not be picking up the local directory/file.
Did you try passing it the full windows path, 'C:\Foo\bar\AirFoil\... ' with properly escaped '\' characters?
Related
This question already has answers here:
Bitlocker script to unlock drive
(8 answers)
Closed 6 years ago.
I am trying to unlock a drive secured by bitlocker from Java. As far as I know there are no libs which can help me to handle that, so I was trying it through cmd. Here's the code:
public static boolean unlockDisk(String pwd) throws IOException
{
String[] script =
{
"manage-bde.exe", "-unlock", "D:", "-password",
};
Process process = new ProcessBuilder(script).start();
InputStream inputStream = process.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
final OutputStream outputStream = process.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream));
writer.write(pwd);
writer.newLine();
writer.close();
System.out.println("--------------------------------------");
System.out.println("Bitlocker log:");
String line;
while ((line = bufferedReader.readLine()) != null)
{
System.out.println(line);
}
bufferedReader.close();
BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));
System.out.println("Here is the standard error of the command (if any):\n");
String tmp;
while ((tmp = stdError.readLine()) != null)
{
System.out.println(tmp);
}
System.out.println("--------------------------------------");
return true;
}
My Problem
If I execute this java code I get The handle is invalid with Code 0x80070006.
What I already tried
Different JDK Version 32 and 64 Bit Java 8 and Java 7 (JDK 32 complains somehow that it can't find the command manage-bde)
Different combinations of output streams, with and without newline...
Another script command for the processbuilder like "cmd.exe", "/k", "manage-bde.exe", "-unlock", "D:", "-password", or with /c instead of /k
With and without admin rights
Simple *.bat with the command manage-bde.exe -unlock D: -password (which works perfectly)
Locking the drive through a java command (which works perfectly)
The command without -password (which let's bitlocker claim that I have to define how I want to unlock the drive)
I googled around for some time and found others having this problems but in a different way with other applications. So it seems like a very common error message.
My guess
I think it has something to do with how I handle my Java output as Bitlocker input. Maybe I am using the wrong streams to write to.
I can't provide the value of the password within the script variable, because Bitlocker want doesn't accept that way of entering the password. Usually you enter manage-bde -unlock D: -password within the command line and after a few lines of output Bitlocker asks you for the password.
Well I described it as good as I can and hope that someone knows what the problem is.
Any suggestion, even if it just leads to a more precise error message, would be appreciated. If you have any questions, just let me know!
Thanks in advance!
I encountered same problem recently. I did a lot search. It seems that mange-bde.exe doesn't read user input from stdin. Someone said ssh client and telent clent running on Linux doesn't read password from stdin. Another example Linux command passwd. It has a flag called -stdin which enable the shell to read password from stdin. Therefore, I guessed manage-bde.exe may works in a similar way.
My solution is simulating keyboard input. The awt package can do the job.
We are busy converting PDF files to TIFF files using GhostScript 9.06 using the following command:
gswin32c -dNOPAUSE -sDEVICE=tiff24nc -r300 -sCompression=lzw -sOutputFile="C:/destination.tif" "C:/source.pdf" -c quit
This is executed via Java on a Windows server that runs most of our batch tools.
This works great for a large part of our files, but for some files, the process just hangs and the task manager shows that the gswin32c.exe process is using 0% of the CPU. We have already resorted to killing the process after a minute and convert the PDF using PDFBox instead if GhostScript fails to respond.
When using the same command, but with the gswin32 tool, the conversion works perfectly, minus the fact that it opens and closes a GUI window each time the command is executed. Because of this, using gswin32 is not an option because people are working on the server constantly.
Instead of '-c quit' add -dBATCH to the command line. Unless your PDF files are all single pages, you probably want to add a '%d' to the output filename too.
This problem has nothing to do with Ghostscript. You will get the problem with every programm that you run with ProcessBuilder which sends output to Standard out. As Windows buffer only limited amount of text, when you do not read the output in your java programm the called process will hang. So you can run gswin32c successfully when your conversion to pdf will only produce a small amount of status messages. But when you convert a file with many pages the process will hang. The solution is to read the output of the called process in your Java program.
ProcessBuilder processBuilder = new ProcessBuilder(
"C:\\Program Files (x86)\\gs\\gs9.10\\bin\\gswin32c.exe", "-sDEVICE=\"pdfwrite\"",
"-dNOPAUSE", "-dBATCH", "-dSAFER", "-dQUIET", "-sOUTPUTFILE=\"" + fileName + ".pdf\"", "\""
+ fileName + ".ps\"");
processBuilder.redirectErrorStream(true); //Redirect Error Stream to Standard Inputstream so that we have to read only Standard in
Process process = processBuilder.start();
InputStream is = process.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
rd.close();
process.waitFor();
I'm trying to convert files from png's to pdf using imagemagick and Java. I've got everything working to a place when I'm executing imagemagick command to actually merge multiple png's into one pdf. The command itself looks properly, and it works fine when executed in the terminal but my application gives me error showing that imgck can't open the file (even though it exists and I've set permissions to the folder to 777 :
line: convert: unable to open image `"/Users/mk/Documents/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/sch-java/print-1357784001005.png"': No such file or directory # error/blob.c/OpenBlob/2642.
This is my command :
/opt/local/bin/convert "/Users/mk/Documents/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/sch-java/print-1357784001005.png" "/Users/mk/Documents/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/sch-java/print-1357784001219.png" "/Users/mk/Documents/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/sch-java/complete-exportedPanel2013-01-1003:13:17.212.pdf"
And my Java code :
String filesString = "";
for (String s : pdfs){
filesString += "\""+ s + "\" ";
}
Process imgkProcess = null;
BufferedReader br = null;
File f1 = new File(pdfs[0]);
//returns true
System.out.println("OE: "+f1.exists());
String cmd = imgkPath+"convert "+ filesString+ " \""+outputPath+outName+"\"";
try {
imgkProcess = Runtime.getRuntime().exec(cmd);
InputStream stderr = imgkProcess.getErrorStream();
InputStreamReader isr = new InputStreamReader(stderr);
br = new BufferedReader(isr);
} catch (IOException e1) {
msg = e1.getMessage();
}
imgkProcess.waitFor();
while( (line=br.readLine() ) != null){
System.out.println("line: "+line);
}
The whole code is executed from a java servlet controller after getting request from a form. Any ideas what can cause this ? I'm using latest imgck, jdk, and osx 10.7 .
A few things:
When spawning anything but really trivial processes, it's usually better to use ProcessBuilder than Runtime.exec() - it gives you much better control
Even with ProcessBuilder, it often works better to write a shell script that does what you need. Then spawn a process to run the script. You get a lot more control in shell script than you do in ProcessBuilder
Remember that a spawned process is not a shell. It can't, for instance, evaluate expressions, or expand shell variables. If you need that, then you must execute a shell (like sh or bash). Better yet, write a shell script as described above
If all you need to do is to execute some ImageMagick commands, it would probably be easier to jmagick, a Java interface to ImageMagick - see http://www.jmagick.org/
Actually, since the you're assembling images into a PDF, the iText library - http://itextpdf.com is probably the best tool for the job, as it is native Java code, does not require spawning a native process, and will therefore be much more portable.
Solved it by adding all arguments to an arrayList and then casting it to String array.
ArrayList<String> cmd = new ArrayList<String>();
cmd.add(imgkPath+"convert");
for (int i=0, l=pdfs.length; i<l; i++){
cmd.add(pdfs[i]);
}
cmd.add(outputPath+outName);
imgkProcess = Runtime.getRuntime().exec(cmd.toArray(new String[cmd.size()]));
I am trying to execute an executable file and a perl script from within a java program. I have found many topics similar to this but most of them refer to windows. I know java is platform independent and it should work anyways but it doesn't. The solution I have tried already is the one based on the java Runtime and it's exec method. It works just fine on windows but since I'm porting my program on linux I need to adapt it. As I said I need to execute an executable file that I have compiled and was written in c++ which it looks like it's working but it finishes executing with an exit value of 1. I have no idea what it means but on windows it exits with 0 and that's how it should be on linux as well (?!?!). The pearl script on the other hand does not start at all. I use the command "perl script.pl" and it exits with a value of 255. Needless to say, it doesn't do what it's supposed to.
Does anybody know another way to execute these files? Or maybe where I am wrong with my implementation?
here's the code if you want to take a look at it:
This is the one for the perl script
public static void main(String[] args){
System.out.println("Starting");
try{
String[] cmd = {"perl", "cloc-1.53.pl"};
Process pr = Runtime.getRuntime().exec(cmd);
BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line=null;
while((line=input.readLine()) != null) {
System.out.println(line);
}
int exitVal = pr.waitFor();
System.out.println("Exit code: " + exitVal);
} catch (Throwable t){
t.printStackTrace();
}
}
For the compiled file I change this:
String[] cmd = {"perl", "cloc-1.53.pl"};
with:
String cmd = "./UCC";
There should be no differece in starting processes on windows and linux.
Good article http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
Its for the old way but gives good insight.
Article converting to the new way:
From Runtime.exec() to ProcessBuilder
From my java project I want to run an external .bat file in another thread. For this purpose I use the following method:
private void posAppRunner(final String path[], final Class targetClass) {
new Thread(new Runnable() {
public void run() {
try {
String line;
Process p = Runtime.getRuntime().exec(path);
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
System.out.println(line);
}
input.close();
} catch (IOException e) {
LogFactory.getLog(targetClass).warn("Error when starting a PosApplication: " + e.getMessage());
}
}
}).start();
I run the following .bat file:
call chdir %~dp0
start java <_some_arguments>
So when I do it locally from IntelliJ IDEA it works correct - a cmd process appears, after that a java process appears and after that the cmd process disappears.
But when I run my java project with this method through ANT under TeamCity windows service, only cmd process appears and nothing happens after. Java process that must be started from the bat file doesn't appear. It looks like I don't read the process output but I do!
Could you expain me, how to overcome this situation?
I believe that the problem is in current working directory. I am not so familiar with bat files and do not remember by heart what does %~dp0 mean. Anyway as the first attempt try to modify your batch file to contain the hard coded path. I believe that this will work.
In this case decide what is better for you: discover the path in java code and then pass it to batch file, generate batch file on the fly, so that it contains all parameters hard coded or debug the script. for example you can remove the start java <_some_arguments> and put
echo %~dp0 > c:\temp\batlog.log
this will print the parameter to log file. Now run it as service and see what does the log file contain. Probably you will see the problem immediately.