6 Replies Latest reply: Dec 17, 2013 8:43 PM by EJP RSS

    Last line is not read

    meandmycode

      Hi,

       

      We run a native command on linux like:

       

      Process p = Runtime.getRuntime().exec("/bin/tcsh");

       

      Then for the process we use outputstream to send the following:

       

      getOutputStream().write((command + getNewline()).getBytes());

      getOutputStream().flush();

       

       

      Command is a shell application' /home/myid/test/myshell/bin/run' that starts a ascii gui that looks like ( see below). It waits for input from user.

       

      *******************************************
      *   My shell Application                   *

      *******************************************

       

      HELP: h

      COMMAND: c

      QUIT:q

      135.19.45.18>

       

      We then use the inputstream to read the above and match on the ip address ( see code below).

      Each time I run this I cannot see that we get the last line ( ip and prompt). So the below code will

      timeout each time.

      Any ideas why I don't get the last line. I tested to send a 'q' after the command and then I see the prompt...

       

      br,

       

      //mike

       

      protected StringBuilder readUntilIpMatch(final InputStream in) {

         final long timeForTimeout = System.currentTimeMillis()

         + sessionData.getSendTimeoutMillis();

         //reset buffer 

       

        buffer.setLength(0);

       

         while (true) {

         try {

         if (in.available() > 0 ) {

        buffer.append((char) in.read());

         //extra check to avoid prompt matching starvation.

         if (matchIp()) {

         return buffer;

        }

        }

        } catch (final IOException e) {

         throw new ReadException(

         "Failed to read buffer in while looking for prompt!",

         this, e);

        }

         // If timeout is reached.

         if ((sessionData.getSendTimeoutMillis() > 0)

         && (System.currentTimeMillis() > timeForTimeout)) {

         throw new ReadTimeoutException(

         "Did not find prompt within the time limit(SendTimeout): "

         + this.getSendTimeoutMillis() + "ms", this,

         null);

        }

        }

        }

        • 1. Re: Last line is not read
          gimbal2

          In the advanced editor you can find the forum's syntax highlighting under the >> button. Please repost the code using it. What you have now is really hard to read.

           

          Regardless: I see you're reading from a low level inputstream. Consider using a Reader, preferrably a BufferedReader, since you're working on text and not bytes. If using a BufferedReader you can use its convenient readLine() method to make your life a lot easier.

          • 2. Re: Last line is not read
            TPD-Opitz

            I guess your implementation of matchIp() is wrong:

             

            public class ReaderTest {
            
                public static void main(String[] args) {
                    new ReaderTest().testReaderMethod();
                }
            
                private void testReaderMethod() {
                    ByteArrayInputStream dummyStrem = new ByteArrayInputStream(
                            ("*******************************************\n"
                                    + "*   My shell Application                   *\n"
                                    + "\n"
                                    + "*******************************************\n"
                                    + "\n" + " \n" + "\n" + "HELP: h\n" + "\n"
                                    + "COMMAND: c\n" + "\n" + "QUIT:q\n" + "\n"
                                    + "135.19.45.18> ").getBytes());
                    System.out.println(readUntilIpMatch(dummyStrem));
            
                }
            
                private StringBuilder buffer = new StringBuilder();
            
                protected String readUntilIpMatch(final InputStream in) {
                    while (true) {
                        try {
                            if (in.available() > 0) {
                                buffer.append((char) in.read());
                                Pattern pattern = Pattern
                                        .compile("\\d{1,3}(\\.\\d{1,3}){3}(?=\\D)");
                                Matcher matcher = pattern.matcher(buffer);
                                if (matcher.find()) {
                                    return matcher.group();
                                }
                            }
                        } catch (final IOException e) {
                            throw new RuntimeException(
                                    "Failed to read buffer in while looking for prompt!", e);
                        }
                    }
                } // runs forever if not matching!!!!
            }
            

            bye

            TPD

            • 3. Re: Last line is not read
              meandmycode

              Hi again,

               

              I am really confused since I still cannot read the last line. I have added code for checking number of characters. When I debug the bufferedinputstream is 765.

              When I do bis.available() it is 760 and then when I count the number of character that I have added I get 762. Last thing it hangs on is the print of the characters.

              I am really confused and in bad need of clarification from someone with a deeper understanding....

               

              //mike

               

              
              
               
              private void cmd() {
               InputStream is = process.getInputStream();
               BufferedInputStream bis = new BufferedInputStream(is);
               
               int nbrChr = 0;
               while (bis.available() > 0) {
               System.out.println("Total char in bis: "+bis.available());
               byte[] buffer = new byte[1];// 1 ascii character
               char c;
               
               StringBuilder sb = new StringBuilder();
              
               try {
               // new input stream created
              
               System.out.println("Characters printed:");
              
               // read stream data into buffer
               while (bis.read(buffer) != -1) {
              
               // for each byte in the buffer
               for (byte b : buffer) {
               // convert byte to character
               c = (char) b;
               nbrChr++;
               if (c == 113) {
               System.out.println("q found");
               System.out.println("ascii :"+c);
               }
               System.out.println("Tot. number of char." + nbrChr);
               sb.append(c);
               // prints character
              
               }
               }
               System.out.println(sb.toString());
              
               } catch (Exception e) {
              
               System.out.println("Got an exception!");
               e.printStackTrace();
               } finally {
              
               // releases system resources associated with this stream
               if (is != null)
               is.close();
               }
              
               processInputStream.close();
               process.destroy();
               System.out.println("exit value: " + process.exitValue());
               processWriter.close();
              
               }
              
              
              • 4. Re: Last line is not read
                TPD-Opitz

                Could you try to change the shell script so that it does a line break after the IP address?

                 

                bye

                TPD

                • 5. Re: Last line is not read
                  meandmycode

                  I have contacted the person who wrote the script ( it is huge) and he will add a new line. However I still think it is odd that it will not be possible to read the characters ( in perl it is possible to read the line .....). There must be more people who has run into this problem using java orrr .,...

                   

                  Anyway thanks for hint.

                   

                  //mike

                  • 6. Re: Last line is not read
                    EJP

                    Get rid if the available() test. available() is not a valid test for end of stream. See the Javadoc. You should stop the loop when read() returns -1, and *block* while the sender isn't sending, instead of smoking the CPU.