Redirecting command to another program thro' objects.
Prashanth Sivarajan
Greenhorn
Joined: May 15, 2007
Posts: 7
posted
0
I am need of something like this.
I create an object that points to another program like MYSQL(something like mysql not exactly mysql). Let the objects name be sqlobj.
now when I say, sqlobj.send("show databases"); the command should be sent to mysql.
I should also be able to get the response to the command also so that I can send the second command based on the response.
sqlobj.send("use somedatabse");
please help
Ulf Dittmer
Marshal
Joined: Mar 22, 2005
Posts: 35241
7
posted
0
I'm not quite clear on what you mean by "an object that points to a program", but in Java databases are generally accessed through the JDBC API. An introduction to JDBC can be found here.
Process proc = Runtime.getRuntime().exec("/opt/bin/someprogram");
// Output to console BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream())); BufferedOutputStream out = new BufferedOutputStream(proc.getOutputStream()); try { while ((str = in.readLine()) != null) { System.out.println(str); if(str.contains("Ready for commands")) //No response after this. { out.write("command".getBytes()); out.flush(); } str = in.readLine();
I see. You might want to have a look at this article, which talks about the various ways Runtime.exec can cause trouble.
Prashanth Sivarajan
Greenhorn
Joined: May 15, 2007
Posts: 7
posted
0
I did read about the limitations somewhere else. Is there any alternative to exec?(can a socket be used?)
Ulf Dittmer
Marshal
Joined: Mar 22, 2005
Posts: 35241
7
posted
0
Runtime.exec has its limitations, but as long as the target program communicates via tandard input/output it should work.
Other means of communication may be possible if the target program supports them (ports in particular won't generally be available).
Stan James
(instanceof Sidekick)
Ranch Hand
Joined: Jan 29, 2003
Posts: 8791
posted
0
Yes, this kind of thing can work. I once used a language called EASEL (now ESL) whose "database integration" was done via shelled programs and the input / output streams. This is not really EASEL, but conversations looked something like
This is a bit harder in Java. I'm reading stdout from the shell program here. If it writes a zillion lines to errout it will block waiting for somebody to read them. Multiple threads are involved for sure. If you have a conversational request-response model like this you might use Futures to get the response from stdout and errout.
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi