Could not run another java programs from ProcessBuilder? - java

TestClass.java
package test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class TestClass {
public static void main(String[] args) throws IOException {
System.out.println("inside");
ProcessBuilder pb = new ProcessBuilder("java", "-cp", "", "test.OtherClass");
Process p = pb.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
StringBuilder builder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
builder.append(line);
builder.append(System.getProperty("line.separator"));
}
String result = builder.toString();
System.out.println(result);
}
}
OtherClass.java
package test;
public class OtherClass {
public static void main(String ar[]) {
System.out.println("Hello Amit!");
}
}
I am trying to run OtherClass from TestClass, but I am not able to do it. Running TestClass just prints "inside". I am not getting any exception and I am clueless right now.
I am implementing ProcessBuilder for the first time.
NOTE: I was able to run simple program using ProcessBuilder.
Also Can you tell what is meaning of -cp; I googled a lot but could not find its meaning.
EDIT:
I have updated code and now I am getting
inside
Error: Could not find or load main class test.OtherClass
Thanks!

Its likely to be the classpath.
Assuming you have a directory called test, Have you tried something like:
ProcessBuilder pb = new ProcessBuilder("java", "-cp", ".", "test.OtherClass");

Related

How to print java compiler error log using tools.jar compile method?

In my idea IDE, I can see the compile error with red font in the console.But when I deploy the jar in the linux server.I can not see the compile log.How to print the compile error log?
public static void main(String[] args) throws Exception {
String compliePath="D:\\testFole";
String filename="D:\\test.java";
String[] arg = new String[] { "-d", compliePath, filename };
System.out.println(com.sun.tools.javac.Main.compile(arg));
}
Well if I got your question right, here is an approach to the outcome.
I think this will be platform-independent.
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
private static Process process;
public static void main(String[] args) {
runCommand();
getErrorMessage();
}
/**
* This method executes/runs the commands
*/
private static void runCommand()
{
File file = new File("D:\\\\test.java");
String changeDirectory = "cmd start cmd.exe /c cd D:\\";
String compile = " && javac D:\\test.java";
String run = " && java "+file.getName().replace(".java","");
String command = changeDirectory + compile + run;
try {
process = Runtime.getRuntime().exec(command);
}catch (IOException e){}
}
/**
* This method will get the errorStream from process
* and output it on the console.
*/
private static void getErrorMessage()
{
try (BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream())))
{
String line;
if(errorReader.readLine() != null)
while ((line = errorReader.readLine()) != null)
System.out.println(line); //display error message
}catch (IOException e){}
}
}

How to connect eclipse with docker

My Eclipse version is Photon and docker version is 18.06.0-ce-mac70.
I want to execute the Docker command when I issue shell script commands on Eclipse.
But when I use a shell script, the ls command works well, but not docker + command
Error Stack trace :
`Exception in thread "main" java.io.IOException: Cannot run program
"docker": error=2, No such file or directory
at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1128)
at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1071)
at java.base/java.lang.Runtime.exec(Runtime.java:635)
at java.base/java.lang.Runtime.exec(Runtime.java:459)
at java.base/java.lang.Runtime.exec(Runtime.java:356)
at dbUpdate.ShellCommander.shellCmd1(ShellCommander.java:36)
at dbUpdate.ShellCommander.main(ShellCommander.java:29)
Caused by: java.io.IOException: error=2, No such file or directory
at java.base/java.lang.ProcessImpl.forkAndExec(Native Method)
at java.base/java.lang.ProcessImpl.<init>(ProcessImpl.java:339)
at java.base/java.lang.ProcessImpl.start(ProcessImpl.java:270)
at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1107)
... 6 more
And the code:
`package dbUpdate;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Scanner;`
public class ShellCommander {
static Scanner sc = new Scanner(System.in);
static String carSSID;
static String target;
static String IPAddress;
public static void main(String[] args) throws Exception {
String command = "docker ps";
shellCmd1(command);
}
public static void shellCmd1(String command) throws Exception {
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(command);
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while((line = br.readLine()) != null) {
System.out.println(line);
}
}
}
Java doesn't search your PATH for commands. On my mac docker is in /usr/local/bin; I also would prefer a ProcessBuilder over Runtime.exec. Like
public static void main(String[] args) throws Exception {
String command = "/usr/local/bin/docker ps";
shellCmd1(command);
}
public static void shellCmd1(String command) throws Exception {
ProcessBuilder pb = new ProcessBuilder(command.split("\\s+"));
pb.inheritIO();
Process p = pb.start();
p.waitFor();
}

Java program just stops when I try to execute a terminal command

I'm trying to write my first program in java. It's purpose is to root and unroot my Nexus 6P which I can do all in terminal with adb and fastboot, but I want to make a program that I can run and have menus of sorts. I found a way to execute commands weather it be batch, or bash (I use both Windows and Linux). My main class is
class main{
public static void main(String[] args){
String version = "0.0.1";
String commandIn = "adb";
int OSType = OSValidator.sys();
ExecuteShellCommand.main(commandIn);
System.out.println("Welcome to Nexus Tools: " + version);
System.out.println("This program will help you Root and UnRoot your Google Nexus 6P");
It does not make it past the ExecuteShellCommand it just stops.
Here is the ExecuteShellCommand class I found online and slightly changed
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class ExecuteShellCommand {
public static void main(String inputCommand) {
ExecuteShellCommand obj = new ExecuteShellCommand();
String command = inputCommand;
String output = obj.executeCommand(command);
System.out.println(output);
}
private String 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();
}
return output.toString();
}
}
the program just stops and I dont know whats going wrong.

Running an external python script from maven

I have to run a run a python script from a maven project. I created a temporary class with main method to check if it works as expected, used the process builder and it works if I specify the absolute path of the python script and then run the java class from eclipse using RUN as Java application.
If I change it getClass().getResourceAsStream("/scripts/script.py"), it throws an exception as it cannot locate the python script.
What would be the best place to place the python script and how can I access it in the Java class without specifying the complete path. Since I am new to maven, it could be due to the method used to execute the Java program.
package discourse.apps.features;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class Test {
protected String scriptPath = "/Users/user1/project1/scripts/script.py";
protected String python3Path = "/Users/user1/.virtualenvs/python3/bin/python3";
public static void main(String[] args) throws IOException {
new Test().score();
}
public JSONObject score() {
String text1="a";
String text2="b";
JSONObject rmap =null;
try
{
String line= null;
String writedir=System.getProperty("user.dir")+ "/Tmp";
String pbCommand[] = { python3Path, scriptPath,"--stringa", text1, "--stringb",text2,"--writedir", writedir };
ProcessBuilder pb = new ProcessBuilder(pbCommand);
Process p = pb.start();
InputStream is = p.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
while ((line = br.readLine()) != null) {
JSONParser parser = new JSONParser();
rmap= (JSONObject) parser.parse(line);
}
} catch (IOException | ParseException ioe) {
System.err.println("Error running script");
ioe.printStackTrace();
System.exit(0);
}
return rmap;
}
}
Here is the output from pb command
pbCommand[0]:/Users/user1/.virtualenvs/python3/bin/python3
pbCommand[1]:displays the complete python script
import os,sys
from pyrouge import Rouge155
import json
from optparse import OptionParser
def get_opts():
parser = OptionParser()
parser.add_option("--stringa", dest="str_a",help="First string")
parser.add_option("--stringb", dest= "str_b",help="second string")
parser.add_option("--writedir", dest="write_dir", help="Tmp write directory for rouge")
(options, args) = parser.parse_args()
if options.str_a is None:
print("Error: requires string")
parser.print_help()
sys.exit(-1)
if options.str_b is None:
print("Error:requires string")
parser.print_help()
sys.exit(-1)
if options.write_dir is None:
print("Error:requires write directory for rouge")
parser.print_help()
sys.exit(-1)
return (options, args)
def readTextFile(Filename):
f = open(Filename, "r", encoding='utf-8')
TextLines=f.readlines()
f.close()
return TextLines
def writeTextFile(Filename,Lines):
f = open(Filename, "w",encoding='utf-8')
f.writelines(Lines)
f.close()
def rougue(stringa, stringb, writedirRouge):
newrow={}
r = Rouge155()
count=0
dirname_sys= writedirRouge +"rougue/System/"
dirname_mod=writedirRouge +"rougue/Model/"
if not os.path.exists(dirname_sys):
os.makedirs(dirname_sys)
if not os.path.exists(dirname_mod):
os.makedirs(dirname_mod)
Filename=dirname_sys +"string_."+str(count)+".txt"
LinesA=list()
LinesA.append(stringa)
writeTextFile(Filename, LinesA)
LinesB=list()
LinesB.append(stringb)
Filename=dirname_mod+"string_.A."+str(count)+ ".txt"
writeTextFile(Filename, LinesB)
r.system_dir = dirname_sys
r.model_dir = dirname_mod
r.system_filename_pattern = 'string_.(\d+).txt'
r.model_filename_pattern = 'string_.[A-Z].#ID#.txt'
output = r.convert_and_evaluate()
output_dict = r.output_to_dict(output)
newrow["rouge_1_f_score"]=output_dict["rouge_1_f_score"]
newrow["rouge_2_f_score"]=output_dict["rouge_2_f_score"]
newrow["rouge_3_f_score"]=output_dict["rouge_3_f_score"]
newrow["rouge_4_f_score"]=output_dict["rouge_4_f_score"]
newrow["rouge_l_f_score"]=output_dict["rouge_l_f_score"]
newrow["rouge_s*_f_score"]=output_dict["rouge_s*_f_score"]
newrow["rouge_su*_f_score"]=output_dict["rouge_su*_f_score"]
newrow["rouge_w_1.2_f_score"]=output_dict["rouge_w_1.2_f_score"]
rouge_dict=json.dumps(newrow)
print (rouge_dict)
def run():
(options, args) = get_opts()
stringa=options.str_a
stringb=options.str_b
writedir=options.write_dir
rougue(stringa, stringb, writedir)
if __name__ == '__main__':
run()
pbCommand[2]:--stringa
pbCommand[3]:a
pbCommand[4]:--stringb
pbCommand[5]:b
pbCommand[6]:--writedir
pbCommand[7]:/users/user1/project1/Tmp
Put the script in the main/resources folder it will then be copied to the target folder.
Then make sure you use something like the com.google.common.io.Resources class, which you can add with
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava-io</artifactId>
<version>r03</version>
</dependency>
I then have a class like this which helps to convert resource files to Strings:
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import com.google.common.base.Charsets;
import com.google.common.io.Resources;
public class FileUtil
{
public static String convertResourceToString(URL url)
{
try
{
return Resources.toString(url, Charsets.UTF_8);
}
catch (Exception e)
{
return null;
}
}
public static String convertResourceToString(String path)
{
return convertResourceToString(Resources.getResource(path));
}
public static String convertResourceToString(URI url)
{
try
{
return convertResourceToString(url.toURL());
}
catch (MalformedURLException e)
{
return null;
}
}
}
Some advice if you are learning maven try using it instead of the IDE to run and package your application, that is what it is suppose to do. Then once you are confident that the application will function as a packaged jar then just use the IDE to run it.

use ffmpeg in java ubuntu

i try to convert video using ffmpeg in ubuntu.
ffmpeg -i inputfile.flv -sameq outputfile.mpeg
this works if change directory to inputfile directory.
is that posible to use this command ?
ffmpeg -i "home/Documents/inputfile.flv" -sameq "home/Documents/outputfile.mpeg"
i don't want to change directory when i use that command, because that command is using for my java code.
so my input file and output file is variable in my code .
here's my full code
package Converter;
import Controller.ConvertedButtonListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Arrays;
/**
*
* #author roylisto
*/
public class VideoConverter {
private String defaultFile;
private String convertedFile;
private ConverterThread myThread;
private ConvertedButtonListener butListener;
public VideoConverter(String fileDir,String convertOutput,ConvertedButtonListener buttonListener){
this.defaultFile=fileDir;
this.convertedFile=convertOutput;
this.butListener=buttonListener;
}
public void convertToMjpeg(){
String[] listCommands={"ffmpeg","-i","\""+defaultFile+"\"","-qscale","0","\""+convertedFile+"\""};
myThread=new ConverterThread(listCommands,this);
myThread.start();
}
public void setCommandStream(String stream){
butListener.setCommandOutput(stream);
}
class ConverterThread extends Thread{
VideoConverter vc;
String[] command;
ConverterThread(String[] command,VideoConverter vc){
this.command=command;
this.vc=vc;
}
public void run(){
synchronized(vc){
try{
String s = null;
Process process = new ProcessBuilder(command).start();
BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));
StringBuffer start= new StringBuffer();
// read the output from the command
while ((s = stdInput.readLine()) != null)
{
start.append(s);
vc.setCommandStream(s);
}
stdInput.close();
// read any errors from the attempted command
while ((s = stdError.readLine()) != null)
{
start.append(s);
vc.setCommandStream(s);
}
}catch(Exception ex){
System.out.println(ex.toString());
}
}
}
}
}
until now my code works well in windows with some modification like change ffmpeg to ffmpeg.exe because ffmpeg isn't native in my windows. but when i use my code in ubuntu
it show this error
"/home/roylisto/Documents/Tugas Akhir/Video Master/3a.avi": No such file or directory
UPDATE
solve problem, here's my code :)
package Converter;
import Controller.ConvertedButtonListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Arrays;
/**
*
* #author roylisto
*/
public class VideoConverter {
private String defaultFile;
private String convertedFile;
private ConverterThread myThread;
private ConvertedButtonListener butListener;
public VideoConverter(String fileDir,String convertOutput,ConvertedButtonListener buttonListener){
this.defaultFile=fileDir;
this.convertedFile=convertOutput;
this.butListener=buttonListener;
}
public void convertToMjpeg(){
String[] listCommands={"ffmpeg","-i",defaultFile,"-qscale","0",convertedFile};
myThread=new ConverterThread(listCommands,this);
myThread.start();
}
public void setCommandStream(String stream){
butListener.setCommandOutput(stream);
}
class ConverterThread extends Thread{
VideoConverter vc;
String[] command;
ConverterThread(String[] command,VideoConverter vc){
this.command=command;
this.vc=vc;
}
public void run(){
synchronized(vc){
try{
String s = null;
Process process = new ProcessBuilder(command).start();
BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));
StringBuffer start= new StringBuffer();
// read the output from the command
while ((s = stdInput.readLine()) != null)
{
start.append(s);
vc.setCommandStream(s);
}
stdInput.close();
// read any errors from the attempted command
while ((s = stdError.readLine()) != null)
{
start.append(s);
vc.setCommandStream(s);
}
}catch(Exception ex){
System.out.println(ex.toString());
}
}
}
}
}
is that posible to use this command ?
Yes, it is possible, as long as you specify a valid absolute or a relative path:
"home/Documents/inputfile.flv"
Should be:
"/home/Documents/inputfile.flv"
Otherwise it'd look for a home directory inside the current working directory. Notice the / at the beginning.
And as for this:
"/home/roylisto/Documents/Tugas Akhir/Video Master/3a.avi": No such file or directory
Are you really shure the file is there and you have r/w access to that directory?

Categories

Resources