I am trying to execute a ghostscript command from my Java Program using Runtime.getRuntime().exec(command).
The command that i am using to generate PDF/A File is:
command = "/usr/local/bin/gs -q -dPDFA=2 -dBATCH -dNOPAUSE -sColorConversionStrategy=RGB -sDEVICE=pdfwrite -dPSFitPage -dFastWebView=true -dDOPDFMARKS -sOutputFile=" + mergedPDFFile + " " + pdfaDefFile + " " + inputPDFFile + " " + pdfMarksFile;
It works perfectly fine when the input PDF file size is less than 1 MB. However, when the input PDF File size is greater than 1 MB, the output does not get generated.
The code that i have written in Java is:
private void executeCommand(String command) {
Process p = null;
try {
p = Runtime.getRuntime().exec(new String[]{"bash", "-c", command});
String s1 = null;
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((s1= reader.readLine()) != null) {
slf4jLogger.info("+++++++++++++++++++++++++++++" + s1);
}
String s = null;
BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
while ((s = stdError.readLine()) != null) {
slf4jLogger.info("***********************" + s);
}
p.waitFor();
int returnValue = p.exitValue();
slf4jLogger.info("RETURN VALUE : " + returnValue);
} catch (Throwable e) {
slf4jLogger.error("ERROR: ********************" + e.toString(), e);
} finally {
slf4jLogger.info("END MY PROCESS:");
if (p != null) {
p.destroy();
}
}
Any help is greatly appreciated.
Related
package test_cmd_command;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.time.LocalDateTime;
public class CommandLine {
public static String executeCommand(String cliCommand) {
String s = null;
BufferedReader stdInput = null;
BufferedReader stdError = null;
String error = "";
String output = "";
try {
ProcessBuilder pb1 = new ProcessBuilder(
"bash",
"-c",
cliCommand);
pb1.redirectErrorStream(true);
Process p = pb1.start();
stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
while ((s = stdInput.readLine()) != null) {
output += "\n" + s;
}
//System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
//System.out.println(">> "+s.toString());
error += "\n" + s;
}
} catch (IOException e) {
System.out.println("exception happened - here's what I know: \n" + e.getMessage());
} finally {
try {
stdInput.close();
stdError.close();
} catch (IOException e) {
}
}
String returnValue = null;
if (output != null && error != null) {
returnValue = output + "\n" + ": " + error;
} else if (output != null) {
returnValue = output;
}
return returnValue;
}
}
"csc -version" is running in terminal but not from my java program on MAC.
it give Output "bash Command Not Found".
Is any way to solve this issue....
This program run other commands correctly like javac -version etc.
I am running this program on MAC not on windows.
This work for me
export PATH=/Library/Frameworks/Mono.framework/Versions/Versions/bin/:${PATH}
I run command like this "export PATH=/Library/Frameworks/Mono.framework/Versions/Versions/bin/:${PATH}; csc -version" and it works and return version of csc.
How do I call and execute python class methods from java. My current java code works, but only if I write:
if __name__ == '__main__':
print("hello")
But I want to execute a class method, regardless of if __name__ == '__main__':
Example python class method I would like to run:
class SECFileScraper:
def __init__(self):
self.counter = 5
def tester_func(self):
return "hello, this test works"
Essentially I would want to run SECFileScraper.tester_func() in java.
My Java code:
try {
ProcessBuilder pb = new ProcessBuilder(Arrays.asList(
"python", pdfFileScraper));
Process p = pb.start();
BufferedReader bfr = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
System.out.println("Running Python starts: " + line);
int exitCode = p.waitFor();
System.out.println("Exit Code : " + exitCode);
line = bfr.readLine();
System.out.println("First Line: " + line);
while ((line = bfr.readLine()) != null) {
System.out.println("Python Output: " + line);
}
} catch (Exception e) {
e.printStackTrace();
}
pdfFileScraper is the file path to my python script.
I've tried jython, but my python files use pandas and sqlite3, which can't be implemented using jython.
So if I understand your requirement, you want to invoke a class method in pdfFileScraper.py. The basics of doing this from the shell would be something akin to:
scraper=path/to/pdfFileScraper.py
dir_of_scraper=$(dirname $scraper)
export PYTHONPATH=$dir_of_scraper
python -c 'import pdfFileScraper; pdfFileScraper.ClassInScraper()'
What we do is get the directory of pdfFileScraper, and add it to the PYTHONPATH, then we run python with a command that imports the pdfFileScraper file as a module, which exposes all the methods and classes in the class in the namespace pdfFileScraper, and then construct a class ClassInScraper().
In java, something like:
import java.io.*;
import java.util.*;
public class RunFile {
public static void main(String args[]) throws Exception {
File f = new File(args[0]); // .py file (e.g. bob/script.py)
String dir = f.getParent(); // dir of .py file
String file = f.getName(); // name of .py file (script.py)
String module = file.substring(0, file.lastIndexOf('.'));
String command = "import " + module + "; " + module + "." + args[1];
List<String> items = Arrays.asList("python", "-c", command);
ProcessBuilder pb = new ProcessBuilder(items);
Map<String, String> env = pb.environment();
env.put("PYTHONPATH", dir);
pb.redirectErrorStream();
Process p = pb.start();
BufferedReader bfr = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
System.out.println("Running Python starts: " + line);
int exitCode = p.waitFor();
System.out.println("Exit Code : " + exitCode);
line = bfr.readLine();
System.out.println("First Line: " + line);
while ((line = bfr.readLine()) != null) {
System.out.println("Python Output: " + line);
}
}
}
You can also call Python lib directly via JNI. This way, you don't start new process, you can share context between script calls, etc.
Take a look here for a sample:
https://github.com/mkopsnc/keplerhacks/tree/master/python
This is my java class that worked for me.
class PythonFileReader {
private String path;
private String fileName;
private String methodName;
PythonFileReader(String path, String fileName, String methodName) throws Exception {
this.path = path;
this.fileName = fileName;
this.methodName = methodName;
reader();
}
private void reader() throws Exception {
StringBuilder input_result = new StringBuilder();
StringBuilder output_result = new StringBuilder();
StringBuilder error_result = new StringBuilder();
String line;
String module = fileName.substring(0, fileName.lastIndexOf('.'));
String command = "import " + module + "; " + module + "." + module + "." + methodName;
List<String> items = Arrays.asList("python", "-c", command);
ProcessBuilder pb = new ProcessBuilder(items);
pb.directory(new File(path));
Process p = pb.start();
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader out = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader error = new BufferedReader(new InputStreamReader(p.getErrorStream()));
while ((line = in.readLine()) != null)
input_result.append("\n").append(line);
if (input_result.length() > 0)
System.out.println(fileName + " : " + input_result);
while ((line = out.readLine()) != null)
output_result.append(" ").append(line);
if (output_result.length() > 0)
System.out.println("Output : " + output_result);
while ((line = error.readLine()) != null)
error_result.append(" ").append(line);
if (error_result.length() > 0)
System.out.println("Error : " + error_result);
}}
and this is the way that you can use this class
public static void main(String[] args) throws Exception {
String path = "python/path/file";
String pyFileName = "python_name.py";
String methodeName = "test('stringInput' , 20)";
new PythonFileReader(path, pyFileName, methodeName );
}
and this is my python class
class test:
def test(name, count):
print(name + " - " + str([x for x in range(count)]))
Here is a part of code written in eclipse.
I am making a GUI for a compiler and this is the action performed when a compile button is pressed.
File file = fileChooser.getSelectedFile();
try {
FileWriter out = new FileWriter(file);
textContent.write(out);
out.close();
} catch (IOException e1) {
e1.printStackTrace();
}
String filepath = file.getPath();
String filepath2 = filepath.substring(0, filepath.lastIndexOf(File.separator));
System.out.println(filepath);
System.out.println(filepath2);
String name = file.getName();
String name2 = file.getName().substring(0, file.getName().lastIndexOf("."));
String folder = filepath2+"\\";
String o = folder+name2+".o";
System.out.println(o);
ProcessBuilder pb=new ProcessBuilder();
try {
pb = new ProcessBuilder("cmd", "/C", "arm-none-eabi-gcc "+"-c "+"-march=armv8-a "+"-g " + "\"" + filepath2 + "\\" +name + "\"" + " -o \""+ name2+"\"");
pb = new ProcessBuilder("cmd", "/C", "arm-none-eabi-g++ "+"-c "+"-march=armv8-a "+"-g " + "\"" + filepath2 + "\\" +name + "\"" + " -o \""+ name2+"\"");
pb.directory(new File(filepath2));
Process p = pb.start();
p.waitFor();
int x = p.exitValue();
if (x == 0) {
area.setForeground(red);
area.setText(" == 0 error.. Compilation Finished");
} else {
BufferedReader r = new BufferedReader(new InputStreamReader(p.getErrorStream()));
//BufferedWriter rm=new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
String out;
area.setText("");
while ((out = r.readLine()) != null)
{
area.setForeground(RED);
area.append(out + System.getProperty("line.separator"));
}
}
} catch (Exception ex) {
ex.printStackTrace();
Output:
When I compile the program (test.cpp), it is simply creating a test file, and I want the output to be test.
Console:
In fact, it shows in the console that it has created a test.o file
ping and date returned output, but it's not returning anything from "ls" or "pwd". What I want to do ultimately is run an SSH command. Any idea what I am missing below?
//Works and shows the output
executeCommand("ping -c 3 " + "google.com");
//Works and shows the output
executeCommand("date");
//Does not work. No output
executeCommand("sudo ls");
//Does not work. No output
executeCommand("ls");
private void executeCommand(String command) {
StringBuffer output = new StringBuffer();
Process p;
try {
p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader reader =
new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
Log.d("Output", "Output: " + output.toString());
}
I have two solutions
first solution (you need Java 7):
...
ProcessBuilder pb = new ProcessBuilder("ls");
pb.redirectOutput(Redirect.INHERIT);
Process p = pb.start();
second solution:
Process p=Runtime.getRuntime().exec("ls");
InputStream is = p.getInputStream();
int c;
StringBuilder commandResponse = new StringBuilder();
while( (c = is.read()) != -1) {
commandResponse.append((char)c);
}
System.out.println(commandResponse);
is.close();
I am working on an Editor application where I can compile and run c,cpp and Java file.I am developing this application using java programming language.I am developing it in Eclipse.
I am able to create new files(c,cpp and java) on specific locations and also I am able to save file to different-2 locations.
And for execution I am using following methods.
String compileFileCommand = "javac "+fileName;
Process compile_process = new ProcessBuilder(compileFileCommand).redirectErrorStream(true).start();
compile_process.waitFor();
BufferedReader reader=new BufferedReader(new InputStreamReader(compile_process.getInputStream()));
String line=reader.readLine();
while(line!=null) {
System.out.println(line);
line=reader.readLine();
}
My problem is that I am not able to compile files from their corresponding locations.
Always giving Exception
java.io.IOException: error=2, No such file or directory
Please tell me how can I compile and run all c,c++ & java files.
Please also give me any other suggestion for my application.
Edited ..
I have used these two methods for compiling and running.On Compiling it creates a class file in case of Java.But all the time I am getting null from InputStreams(both getErrorStream() and getInputStream()).
void compileJavaFile(String fileName)
{
String compileFileCommand = "javac " + fileName;
try
{
System.out.println("Executing Java File");
Process compileProcess = Runtime.getRuntime().exec(compileFileCommand);
String line = "";
BufferedReader bri = new BufferedReader(new InputStreamReader(compileProcess.getInputStream()));
BufferedReader bre = new BufferedReader(new InputStreamReader(compileProcess.getErrorStream()));
while ((line = bri.readLine()) != null)
{
System.out.println(line);
}
bri.close();
while ((line = bre.readLine()) != null)
{
System.out.println(line);
}
bre.close();
compileProcess.waitFor();
System.out.println("Done.");
} catch (Exception e)
{
// TODO: handle exception
System.out.println("Exception ");
System.out.println(e.getMessage());
}
}
void runJavaFile(String fileName)
{
String runFileCommand = "java " + fileName.split(".java")[0];
try
{
System.out.println("runFileCommand : " + runFileCommand);
System.out.println("Running Java File");
Process runProcess = Runtime.getRuntime().exec(runFileCommand);
BufferedReader reader = new BufferedReader(new InputStreamReader(runProcess.getInputStream()));
String line = reader.readLine();
System.out.println("line = " + line);
while (line != null)
{
System.out.println(line);
line = reader.readLine();
}
} catch (Exception e)
{
// TODO: handle exception
System.out.println("Exception ");
System.out.println(e.getMessage());
}
}
And for C and C++ I am using.
void compileCFile(String fileName)
{
String compileFileCommand = "gcc " + fileName;
resultString = "";
try
{
System.out.println("Compiling C File");
Process processCompile = Runtime.getRuntime().exec(compileFileCommand);
BufferedReader brCompileError = new BufferedReader(new InputStreamReader(processCompile.getErrorStream()));
String errorCompile = brCompileError.readLine();
if (errorCompile != null)
System.out.println("Error Compiler = " + errorCompile);
resultString += errorCompile +"\n";
BufferedReader brCompileRun = new BufferedReader(new InputStreamReader(processCompile.getErrorStream()));
String outputCompile = brCompileRun.readLine();
if (outputCompile != null)
System.out.println("Output Compiler = " + outputCompile);
resultString += outputCompile +"\n";
} catch (Exception e)
{
// TODO: handle exception
System.out.println("Exception ");
System.out.println(e.getMessage());
}
}
void runCFile(String fileName)
{
String runFileCommand = "./" + fileName.split(".c")[0];
try
{
System.out.println("Running C File");
Process processRun = Runtime.getRuntime().exec(runFileCommand);
BufferedReader brRun = new BufferedReader(new InputStreamReader(processRun.getErrorStream()));
String errorRun = brRun.readLine();
if (errorRun != null)
System.out.println("Error Run = " + errorRun);
BufferedReader brResult = new BufferedReader(new InputStreamReader(processRun.getInputStream()));
String outputRun = brResult.readLine();
if (outputRun != null)
System.out.println("Output Run = " + outputRun);
} catch (Exception e)
{
// TODO: handle exception
System.out.println("Exception ");
System.out.println(e.getMessage());
}
}
void compileCPPFile(String fileName)
{
String compileFileCommand = "g++ " + fileName;
try
{
System.out.println("Compiling CPP File");
Process processCompile = Runtime.getRuntime().exec(compileFileCommand);
BufferedReader brCompileError = new BufferedReader(new InputStreamReader(processCompile.getErrorStream()));
String errorCompile = brCompileError.readLine();
if (errorCompile != null)
System.out.println("Error Compiler = " + errorCompile);
resultString += errorCompile +"\n";
BufferedReader brCompileRun = new BufferedReader(new InputStreamReader(processCompile.getErrorStream()));
String outputCompile = brCompileRun.readLine();
if (outputCompile != null)
System.out.println("Output Compiler = " + outputCompile);
resultString += outputCompile +"\n";
} catch (Exception e)
{
// TODO: handle exception
System.out.println("Exception ");
System.out.println(e.getMessage());
}
}
void runCPPFile(String fileName)
{
String runFileCommand = "./" + fileName.split(".cpp")[0];
try
{
System.out.println("Running CPP File");
Process processRun = Runtime.getRuntime().exec(runFileCommand);
BufferedReader brRun = new BufferedReader(new InputStreamReader(processRun.getErrorStream()));
String errorRun = brRun.readLine();
if (errorRun != null)
System.out.println("Error Run = " + errorRun);
BufferedReader brResult = new BufferedReader(new InputStreamReader(processRun.getInputStream()));
String outputRun = brResult.readLine();
if (outputRun != null)
System.out.println("Output Run = " + outputRun);
} catch (Exception e)
{
// TODO: handle exception
System.out.println("Exception ");
System.out.println(e.getMessage());
}
}
In case of C and C++ it show error like
g++: /media/disk/eclipse/\/UniversalIDE/CPP/firstCPP: No such file or directory
Please give me solution for my problems ..
Please try following,
Process p = Runtime.getRuntime().exec(command);
command is a string you pass. in command you can pass "javac Test.java" to compile your java file & just like that you can use other commands.
replace the line
String runFileCommand = "./" + fileName.split(".c")[0];
with
String runFileCommand = "./a.out";