Running xjc from java code - java

I am using xjc to generate classes from xsd. The generation has to happen inside the java code. Right now I have done it like this:
Process child = Runtime.getRuntime().exec(command);
try {
System.out.println("waiting...");
child.waitFor();
System.out.println("waiting ended..");
} catch (InterruptedException e) {
e.printStackTrace();
return false;
}
The output for the above program is:
waiting...
I have to use the classes after they are generated. The problem here is that the subprocess never exits and the control is never back to the java program!
Is there a way to do this without getRuntime().exec() ?

You can actually use the driver class (com.sun.tools.xjc.Driver) behind the command line tool. This worked for me:
import com.sun.tools.xjc.BadCommandLineException;
import com.sun.tools.xjc.Driver;
import com.sun.tools.xjc.XJCListener;
import org.xml.sax.SAXParseException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Generator {
public static void main(String[] args) throws BadCommandLineException, IOException {
final String targetDir = "jaxb-files";
Path path = Paths.get(targetDir);
if(!Files.exists(path)) {
Files.createDirectories(path);
}
Driver.run(new String[]{"-d", targetDir,
"D:\\dev\\onepoint\\tui\\java\\xsdjsonschema\\src\\main\\xsd\\test.xsd"}, new XJCListener() {
#Override
public void error(SAXParseException e) {
printError(e, "ERROR");
}
#Override
public void fatalError(SAXParseException e) {
printError(e, "FATAL");
}
#Override
public void warning(SAXParseException e) {
printError(e, "WARN");
}
#Override
public void info(SAXParseException e) {
printError(e, "INFO");
}
private void printError(SAXParseException e, String level) {
System.err.printf("%s: SAX Parse exception", level);
e.printStackTrace();
}
});
}
}

try this
Process child = Runtime.getRuntime().exec(command);
BufferedReader in = new BufferedReader(
new InputStreamReader(child.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
}

Related

ModuleNotFindError No module named 'sumolib' when I try to excecute python3 in java

When i execute the following command on the terminal
python3 main.py "J1" "Red2Way.net.xml" "i"
I receive the response that i was waiting for without problems. But when i execute the same command from java using the following code
ProcToString pts=new ProcToString("python3","main.py","J1","Red2Way.net.xml","i");
try {
System.out.println(pts.runProcess());
System.out.println(pts.hasResult());
if (pts.hasResult()){
String resultado = pts.getResult();
System.out.println(resultado);
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
I get the following error
Traceback (most recent call last): File "main.py", line 2, in <module> import sumolibModuleNotFoundError: No module named 'sumolib'
I have installed sumolib in my pc for that in terminal it works perfect, i dont know why in java not.
I am using python3 and executing from NetBeans, and my os is MacOS Big Sur.
The class ProcToString have the following code
package main;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ProcToString {
private ProcessBuilder pb;
private String out="";
private Process proc=null;
public ProcToString(String... cmd){
pb = new ProcessBuilder(cmd);
pb.redirectErrorStream(true);
}
public int runProcess() throws IOException, InterruptedException{
proc = pb.start();
new Stream().start();
return proc.waitFor();
}
public boolean hasResult(){
return out!="";
}
public String getResult(){
return out;
}
final class Stream extends Thread{
#Override
public void run() {
StringBuilder sb=new StringBuilder();
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(proc.getInputStream()));
try {
while((line = br.readLine())!=null){
out+=line;
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
out=sb.toString();
}
}
}
}
I try to find python and add it to the execution but i do not know where i can put the path

How to send a String via Telnet?

I want to send a String to a Telnet Connection using TelnetConnection from Apache
import java.io.IOException;
import org.apache.commons.net.telnet.TelnetClient;
public class TestClass {
public static void main(String[] args) throws IOException, InterruptedException {
String telnetServer = "123.456.789.123";
int telnetPort = 32106;
TelnetClient telnet = new TelnetClient();
try {
telnet.connect(telnetServer, telnetPort);
String start = "start";
telnet.getOutputStream().write(start.getBytes());
telnet.getOutputStream().flush();
System.out.println(telnet.getInputStream());
} catch (Exception e) {
System.out.println(e);
}finally {
telnet.disconnect();
}
}
}
However, I don't get a result. How do I use Input and Output Stream in this case?
The command ("start") should start the recording of METUS INGEST 5.6.
Thanks to Some programmer dude(https://stackoverflow.com/users/440558/some-programmer-dude). This totally did the job.
Here is the complete code:
import java.io.IOException;
import org.apache.commons.net.telnet.TelnetClient;
public class TestClass {
public static void main(String[] args) throws IOException, InterruptedException {
String telnetServer = "123.456.789.123";
int telnetPort = 32106;
TelnetClient telnet = new TelnetClient();
try {
telnet.connect(telnetServer, telnetPort);
String start = "start\r\n";
telnet.getOutputStream().write(start.getBytes());
telnet.getOutputStream().flush();
System.out.println(telnet.getInputStream());
} catch (Exception e) {
System.out.println(e);
}finally {
telnet.disconnect();
}
}
}
You can stop the recording of all sources with:
String stop = "stop\r\n";
telnet.getOutputStream().write(stop.getBytes());
telnet.getOutputStream().flush();

RED5 AXIS camera capturing & streaming

I want to capture an AXIS camera & stream it. I am quite new to RED5. I get the following error:
Exception in thread "main" java.lang.NullPointerException at
org.vikulin.rtmp.publisher.Publisher2.packetReceived(Publisher2.java:23)
at
org.red5.server.presentation.output.flv.FLVStream.dispatchEvent(FLVStream.java:243)
at
org.red5.server.presentation.output.flv.FLVStream.sendAVCDecoderConfig(FLVStream.java:162)
at
org.red5.server.presentation.output.flv.FLVStream.addEvent(FLVStream.java:76) at
org.red5.server.presentation.MediaPresentation.onMediaEvent(MediaPresentation.java:43)
at
org.red5.server.presentation.input.avp.codecs.H264.addPacket(H264.java:206)
at
org.red5.server.presentation.RTSPStream.onRTSPEvent(RTSPStream.java:100)
at
org.red5.server.net.rtsp.proxy.RtspTcp.setupAndPlay(RtspTcp.java:287)
at org.red5.server.presentation.RTSPStream.onSDP(RTSPStream.java:138)
at
org.red5.server.net.rtsp.proxy.RtspTcp.parseDescription(RtspTcp.java:128)
at org.red5.server.net.rtsp.proxy.RtspTcp.describe(RtspTcp.java:64)
at
org.red5.server.presentation.RTSPStream.startInput(RTSPStream.java:77)
at org.red5.server.presentation.RTSPStream.start(RTSPStream.java:82)
at org.vikulin.rtmp.publisher.Publisher2.main(Publisher2.java:49)
Here is the code:
import java.io.IOException;
import org.red5.server.api.stream.IBroadcastStream;
import org.red5.server.api.stream.IStreamListener;
import org.red5.server.api.stream.IStreamPacket;
import org.red5.server.net.rtmp.event.VideoData;
import org.red5.server.presentation.RTSPStream;
import org.red5.server.stream.message.RTMPMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Publisher2 implements IStreamListener {
PublishClient client;
#Override
public void packetReceived(IBroadcastStream arg0, IStreamPacket arg1) {
System.out.println("" + arg1);
VideoData data = new VideoData(arg1.getData());
RTMPMessage message = RTMPMessage.build(data);
try {
client.pushMessage(message);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException, InterruptedException {
Logger log = LoggerFactory.getLogger(Publisher2.class);
String publishName = "testb";
String host = "127.0.0.1";
int port = 1935;
String app = "live";
PublishClient client = new PublishClient();
client.setHost(host);
client.setPort(port);
client.setApp(app);
client.start(publishName, "live", null);
while (client.getState() != PublishClient.PUBLISHED) {
Thread.sleep(500);
}
Publisher2 test = new Publisher2();
final RTSPStream camera = new RTSPStream("192.168.254.115", 554,
"rtsp://192.168.254.115/axis-media/media.amp?videocodec=h264&videokeyframeinterval=30&fps=30");
camera.addStreamListener(test);
new Thread(new Runnable() {
#Override
public void run() {
camera.start();
}
}).start();
try {
Thread.sleep(30000);
} catch (InterruptedException e) {
e.printStackTrace();
}
camera.stop();
try {//wait for write out.
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
client.stop();
}
}
If you have any idea please help me!
You declared a client variable in your main method, but in your packetReceived method, you reference the class variable. The class variable is still null at that point. So, possibly change this line:
PublishClient client = new PublishClient();
to this:
client = new PublishClient();
or pass the client in to your method, and remove variable declaration from your class.

about classpath in run configuration in eclipse

Test1_Exec.java
import java.io.IOException;
public class Test1_Exec {
public static void main(String[] args) throws IOException {
Runtime run = Runtime.getRuntime();
try {
Process p = run.exec("java -cp bin Test1");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Test1.java:
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class Test1 {
public static void main(String[] args)
{
FileOutputStream fOut = null;
try {
fOut = new FileOutputStream("d:\\ppp\\Test1.txt");
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Test1_Exec.class and Test1.class are both in the bin folder under JavaTest(project name), and the codes do work. But I want to replace the code "Process p = run.exec("java -cp bin Test1")" with "Process p = run.exec("java Test1")" by adding bin folder( right clikcing JavaTest(project name)->Run As->Run Configuration | Tab Classpath --- User Entries --- Advanced --- Add Folders ), then Test1.txt is not created by new codes. So where is the problem ?
To me program seemed unnecessarily complex. Why not below(if you dont have specific requirement)
import java.io.IOException;
public class Test1_Exec {
public static void main(String[] args) throws IOException {
try {
Test1.createFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class Test1 {
public static void createFile()
{
FileOutputStream fOut = null;
try {
fOut = new FileOutputStream("d:\\ppp\\Test1.txt");
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Running grep From Java Program

I've spent the past 3 days without much luck on google on how to run a grep process from within Java.
I have the following code to run a grep process, however, I am only getting the first line of the response.
package com.example.parser;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) {
try {
Process process = new ProcessBuilder("grep", "-rni", "\"public static void main(\"", "/home/user/dev/java/").start();
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = "";
while((line = br.readLine()) != null) {
System.out.println(line);
}
System.out.println("Exit Code: " + process.exitValue());
} catch (IOException e) {
e.printStackTrace();
}
}
}
I am only getting the following response:
Binary file /home/user/dev/java/Parser/parser/bin/com/example/parser/Main.class matches
Exit Code: 0
When I should be getting the following response:
Binary file /home/user/dev/java/Parser/parser/com/example/parser/Main.class matches
/home/user/dev/java/Parser/parser/src/com/example/parser/Main.java:10: public static void main(String[] args) {
/home/user/dev/java/Parser/parser/src/com/example/parser/Main.java:12: Process process = new ProcessBuilder("grep", "-rni", "\"public static void main(\"", "/home/user/dev/java/Parser/parser").start();
Exit Code: 0
I am wondering why I only get output for the first finding? Is grep forking several processes to run the search and I'm only getting a handle on the first one?
I have also tried running the process from a Thread:
package com.example.parser;
public class Main {
public static void main(String[] args) {
try {
Analyzer analyzer = new Analyzer();
analyzer.start();
analyzer.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
package com.example.parser;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Analyzer extends Thread {
public Analyzer() {
}
#Override
public void run() {
try {
Process process = new ProcessBuilder("grep", "-rni", "\"public static void main(\"", "/home/user/dev/java/Parser/parser").start();
process.waitFor();
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = "";
while((line = br.readLine()) != null) {
System.out.println(line);
}
System.out.println("Exit Code: " + process.exitValue());
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
As well as the following:
package com.example.parser;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
Process process = new ProcessBuilder("grep", "-rni", "\"public static void main(\"", "/home/user/dev/java/Parser/parser").start();
process.waitFor();
Analyzer analyzer_is = new Analyzer(process.getInputStream());
Analyzer analyzer_es = new Analyzer(process.getErrorStream());
analyzer_is.start();
analyzer_es.start();
analyzer_is.join();
analyzer_es.join();
System.out.println("Exit Code: " + process.exitValue());
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
package com.example.parser;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class Analyzer extends Thread {
InputStream is = null;
public Analyzer(InputStream is) {
this.is = is;
}
#Override
public void run() {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(this.is));
String line = "";
while((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
As suggested by the following article: http://www.javaworld.com/jw-12-2000/jw-1229-traps.html
I was able to solve the issue by launching a shell with the -c flag. The following code does what I had originally intended:
package com.example.parser;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
try {
List<String> commands = new ArrayList<String>();
commands.add("/bin/sh");
commands.add("-c");
commands.add("grep -rni --include \"*.java\" \"public static void main(\" /home/user/dev/java/Parser/parser");
Process process = new ProcessBuilder(commands).start();
Analyzer analyzer_is = new Analyzer(process.getInputStream());
Analyzer analyzer_es = new Analyzer(process.getErrorStream());
analyzer_is.start();
analyzer_es.start();
process.waitFor();
analyzer_is.join();
analyzer_es.join();
System.out.println("Exit Code: " + process.exitValue());
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
package com.example.parser;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class Analyzer extends Thread {
InputStream is = null;
public Analyzer(InputStream is) {
this.is = is;
}
#Override
public void run() {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(this.is));
String line = "";
while((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
This is probably because you don't wait for the grep to finish.
Use the waitFor method :
Process process = new ProcessBuilder("grep", "-rni", "\"public static void main(\"", "/home/user/dev/java/").start();
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
process.waitFor();
String line = "";
while((line = br.readLine()) != null) {
System.out.println(line);
}
Note that you may also read the output (mainly to get what happens) while it is being processed using
Process process = new ProcessBuilder("grep", "-rni", "\"public static void main(\"", String line;
while (true) {
line = reader.readLine(); // add IO exception catching
if (line != null) {
System.out.println(line);
} else {
Thread.sleep(DELAY); // DELAY could be 100 (ms) for example
}
}
I suppose you're sure a grep launched by the owner of the java program is more than one line long ?
The other reason could be your process is still running but your Java program just exited.
Use the process.waitFor(); and Read your input stream in a thread.
Start the process.
Lunch a thread with the process input stream as the input.
Now wait for the process to exit by using process.waitFor();
This might help!
Have a look at this project for grep in java https://code.google.com/p/grep4j

Categories

Resources