Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 5 of 5

Thread: Reading ant output when exec the command

  1. #1
    Junior Member
    Join Date
    Oct 2010
    Posts
    4
    Thanks
    0
    Thanked 1 Time in 1 Post

    Default Reading ant output when exec the command

    Hi all,

    I hope that is not a stupid question and you'll forgive me if it is and excuse me for my english

    I want to exec an ant build from java code. The response of the ant should be put in the future in a JScrollPane and if script has inputs this should be capture somehow and resend them to the script, like it is working in console.

    I managed to do it, but I have a problem if ant script needs inputs. When I run the code, I must to input somehow back to the Process the value expected but I don't know how



    Below is my code any hints or advices are welcome
    Thank you!

    * TestAnt.class where call is made
    * test.xml - the ant script
    * the output of the script when is called from java

    public class TestAnt {
        public static void main(String[] args) {
            try {
                InputStream stdout = null;
                String jarLocation=new File(TestAnt.class.getProtectionDomain().getCodeSource().getLocation().getPath()).getParentFile().getAbsolutePath();
                String antFileLocation = "c:/ant_1.8/bin/ant.bat";
                String cmd = antFileLocation+" -f "+jarLocation+"/test.xml";
                Process process = Runtime.getRuntime().exec(cmd);
                stdout = process.getInputStream();
                BufferedReader input = new BufferedReader(new InputStreamReader(stdout));
                String line;
                while ((line = input.readLine()) != null) {
                    if (line.indexOf("[input]") == -1) {
                        System.out.println(line);
                    } else {
                        System.out.println(line);
                        //in this place an input should be sent back to the process
                        //the code will freeze
                        //my intention is to put all this code in JScrollPane to avoid opening a console
                    }
                }
                process.waitFor();
                input.close();
            } catch (InterruptedException ex) {
                Logger.getLogger(TestAnt.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(TestAnt.class.getName()).log(Level.SEVERE, null, ex);
            }
         }
    }

    <?xml version="1.0"?>
    <project name="set_package" basedir="." default="test">
        <target name="test">
            <echo message="Do you want to continue?"/>
            <input message="obs. responde with y/n" validargs="y,n" addproperty="skip"/>
            <echo message="${skip}"/>
        </target>
    </project>

    Buildfile: V:\...\SetPackageSwing\dist\test.xml
     
    test:
         [echo] Do you want to continue?
        [input] obs. responde with y/n (y, n)


  2. #2
    Super Moderator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,102
    Thanks
    169
    Thanked 779 Times in 725 Posts
    Blog Entries
    5

    Default Re: Reading ant output when exec the command

    You will need to get the OutputStream of the Process as well to send data to the process. Place both the reader and writer in their own threads...see When Runtime.exec() won't - JavaWorld for how to do this with the input. A similar thing can be done with the output stream

  3. #3
    Junior Member
    Join Date
    Oct 2010
    Posts
    4
    Thanks
    0
    Thanked 1 Time in 1 Post

    Default Re: Reading ant output when exec the command

    @copeg
    Thank you for your response!
    In the meantime I managed to "send" the input to the ant script like below

    I still got an error "java.io.IOException: Result too large" if I insert an unexpected string several times (ex. b instead if y/n) but I suppose that if I use separate threads, will work. I always avoid using threads because I didn't understand it

    Anyway I'll read the link that you sent hopping to find the proper way.
    Have a nice day!

    public class TestAnt {
     
        public static void main(String[] args) {
            InputStream stdout = null;
            OutputStream stdi = null;
            Process process = null;
            try {
                String jarLocation = new File(TestAnt.class.getProtectionDomain().getCodeSource().getLocation().getPath()).getParentFile().getAbsolutePath();
                String antFileLocation = "c:/ant_1.8/bin/ant.bat";
                String cmd = antFileLocation + " -f " + jarLocation + "/test.xml";
     
    //            Process process = Runtime.getRuntime().exec("cmd.exe /c start "+cmd);
                process = Runtime.getRuntime().exec(cmd);
                stdout = process.getInputStream();
     
                BufferedReader input = new BufferedReader(new InputStreamReader(stdout));
                String line;
                while ((line = input.readLine()) != null) {
                    if (line.indexOf("[input]") == -1) {
                        System.out.println(line);
                    } else {
                        System.out.println(line);
                        boolean go = false;
                        String jInput = null;
                            jInput = JOptionPane.showInputDialog("Enter String: ");
     
                        stdi = process.getOutputStream();
                        stdi.write(jInput.getBytes());
                        stdi.flush();
                        stdi.close();
                    }
                }
                input.close();
            } catch (IOException ex) {
                Logger.getLogger(TestAnt.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

  4. #4
    Junior Member
    Join Date
    Oct 2010
    Posts
    4
    Thanks
    0
    Thanked 1 Time in 1 Post

    Default Re: Reading ant output when exec the command

    copeg helped me and also the link that he gave to me.
    Below is the full functionally code maybe others newbies like me will find useful

    package com.resources;
     
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.swing.JOptionPane;
     
    /**
     *
     * @author ciprian.muntean
     */
    class ReadAntOutput1 extends Thread {
     
        InputStream is;
        String type;
     
        ReadAntOutput1(InputStream is, String type) {
            this.is = is;
            this.type = type;
        }
     
        public void run() {
            try {
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);
                String line = null;
                while ((line = br.readLine()) != null) {
                    line.replaceAll("\\[echo\\]", "");
                    System.out.println(type + ">" + line);
                }
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }
     
    class WriteAntInputs1 extends Thread {
     
        OutputStream stdi;
        String type;
     
        WriteAntInputs1(OutputStream stdi, String type) {
            this.stdi = stdi;
            this.type = type;
        }
     
        public void run() {
            try {
                String jInput = null;
                do {
                    jInput = JOptionPane.showInputDialog("Enter String[y/n]: ");
                } while (!jInput.equals("y") || jInput.equals("n"));
                stdi.write(jInput.getBytes());
                stdi.flush();
                stdi.close();
            } catch (Exception e) {
                try {
                    stdi.flush();
                } catch (IOException ex) {
                    Logger.getLogger(WriteAntInputs1.class.getName()).log(Level.SEVERE, null, ex);
                }
                try {
                    stdi.close();
                } catch (IOException ex) {
                    Logger.getLogger(WriteAntInputs1.class.getName()).log(Level.SEVERE, null, ex);
                }
     
            }
        }
    }
     
    public class TestAnt1 {
     
        Thread errorThrower; // just for testing (Throws an Exception at this Console
        public boolean quit;
     
     
        public static void main(String[] args) {
            InputStream stdout = null;
            OutputStream stdin = null;
            Process process = null;
            try {
                String jarLocation = new File(TestAnt1.class.getProtectionDomain().getCodeSource().getLocation().getPath()).getParentFile().getAbsolutePath();
                String antFileLocation = "c:/ant_1.8/bin/ant.bat";
                String cmd = antFileLocation + " -f " + jarLocation + "/test.xml";
     
                process = Runtime.getRuntime().exec(cmd);
                stdout = process.getInputStream();
                stdin = process.getOutputStream();
                InputStream stderr = process.getErrorStream();
     
     
                // deals with errors
                ReadAntOutput1 proccessError = new ReadAntOutput1(stderr, "ERROR");
     
                // read ant output
                ReadAntOutput1 proccessResponse = new ReadAntOutput1(stdout, "OUTPUT");
     
                //send to ant inputs
                WriteAntInputs1 proccessRequest = new WriteAntInputs1(stdin, "INPUT");
     
                // kick them off
                proccessError.start();
                proccessResponse.start();
                proccessRequest.start();
     
                // any error???
                int exitVal = process.waitFor();
                System.out.println("ExitValue: " + exitVal);
     
            } catch (InterruptedException ex) {
                Logger.getLogger(TestAnt1.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(TestAnt1.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

  5. The Following User Says Thank You to cipm66 For This Useful Post:

    copeg (October 23rd, 2010)

  6. #5
    Junior Member
    Join Date
    Oct 2010
    Posts
    4
    Thanks
    0
    Thanked 1 Time in 1 Post

    Default Re: Reading ant output when exec the command

    Back again
    It seams that the code works only for an ant script with only one input.
    The flow is wrong because if I put two or more "inputs" in ant, like in the code below, will not work.
    I don't know what I did wrong, maybe it is need some communication between the threads? After I typed the second response in the input dialog the string will not go back to the script process and in console I got again and again the last line displayed by the script
    ex:
    [input] obs1. responde with y/n (y, n)
    It is like the response don;t go back to the script. I know that it is possible (the behavior that I want to achieve can be see in Netbeans when a built is run from IDE)

    Any hints? Thx in advance.

    test.xml source
     
    <?xml version="1.0"?>
    <project name="set_package" basedir="." default="test">
        <target name="test">
            <echo message=""/>
            <echo message=""/>
            <echo message="Do you want to continue?"/>
            <input message="obs0. responde with y/n" validargs="y,n" addproperty="skip"/>
            <echo message="${skip}"/>
            <echo message="Do you want to continue1?"/>
            <input message="obs1. responde with y/n" validargs="y,n" addproperty="skip1"/>
            <echo message="${skip1}"/>
            <echo message="Do you want to continue2?"/>
            <input message="obs2. responde with y/n" validargs="y,n" addproperty="skip2"/>
            <echo message="${skip2}"/>
        </target>
    </project>

Similar Threads

  1. Runtime.getRuntime().exec(command) - I get nothing
    By andersbk in forum What's Wrong With My Code?
    Replies: 0
    Last Post: October 7th, 2010, 08:47 PM
  2. How To Make JCreator Output in a Command Window
    By Kimimaru in forum Java Theory & Questions
    Replies: 4
    Last Post: October 4th, 2010, 09:36 PM
  3. Run 2 systems command in applet, how?
    By bulgin in forum What's Wrong With My Code?
    Replies: 3
    Last Post: April 8th, 2010, 03:11 PM
  4. [SOLVED] Command Line Argument Help
    By EmSaint in forum Loops & Control Statements
    Replies: 2
    Last Post: January 28th, 2010, 09:55 AM
  5. How to Navigate to a URL with Runtime.getRuntime().exec()
    By Flash in forum Java SE API Tutorials
    Replies: 4
    Last Post: October 5th, 2009, 07:18 PM