View Javadoc

1   /**
2    * 
3    */
4   package org.mortbay.jetty.plugin.util;
5   
6   import java.io.IOException;
7   
8   import org.mortbay.jetty.plugin.AbstractJettyMojo;
9   
10  public class ConsoleScanner extends Thread {
11      
12      private final AbstractJettyMojo mojo;
13      
14      public ConsoleScanner(AbstractJettyMojo mojo) {
15          this.mojo = mojo;
16          setName("Console scanner");
17          setDaemon(true);
18      }
19      
20      public void run() {
21          
22          try 
23          {
24              while (true) 
25              {
26                  checkSystemInput();
27                  getSomeSleep();
28              }
29          } 
30          catch (IOException e) 
31          {
32              mojo.getLog().warn(e);
33          }
34      }
35      
36      private void getSomeSleep() {
37          try 
38          {
39              Thread.sleep(500);
40          } 
41          catch (InterruptedException e) 
42          {
43              mojo.getLog().debug(e);
44          }
45      }
46      
47      private void checkSystemInput() throws IOException {
48          
49          while (System.in.available() > 0) {
50              int inputByte = System.in.read();
51              if (inputByte >= 0) 
52              {
53                  char c = (char)inputByte;
54                  if (c == '\n') {
55                      restartWebApp();
56                  }
57              }
58          }
59      }
60      
61      
62      /**
63       * Skip buffered bytes of system console.
64       */
65      private void clearInputBuffer() {
66  
67          try {
68              while (System.in.available() > 0) 
69              {
70                  // System.in.skip doesn't work properly. I don't know why
71                  long available = System.in.available();
72                  for (int i = 0; i < available; i++) {
73                      if (System.in.read() == -1) 
74                      {
75                          break;
76                      }
77                  }
78              }
79          } catch (IOException e) 
80          {
81              mojo.getLog().warn("Error discarding console input buffer", e);
82          }
83          
84      }
85      
86      private void restartWebApp() {
87          try 
88          {
89              mojo.restartWebApp(false);
90              // Clear input buffer to discard anything entered on the console
91              // while the application was being restarted.
92              clearInputBuffer();
93          } 
94          catch (Exception e) 
95          {
96              mojo.getLog().error("Error reconfiguring/restarting webapp after a new line on the console", e);
97          }
98      }
99  }