1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47 package groovy.ui;
48 import groovy.lang.*;
49 import java.io.*;
50 import java.net.*;
51
52 /***
53 * Simple server that executes supplied script against a socket
54 * @author Jeremy Rayner
55 */
56
57 public class GroovySocketServer implements Runnable {
58 private URL url;
59 private GroovyShell groovy;
60 private boolean isScriptFile;
61 private String scriptFilenameOrText;
62 private boolean autoOutput;
63
64 public GroovySocketServer(GroovyShell groovy, boolean isScriptFile, String scriptFilenameOrText, boolean autoOutput, int port) {
65 this.groovy = groovy;
66 this.isScriptFile = isScriptFile;
67 this.scriptFilenameOrText = scriptFilenameOrText;
68 this.autoOutput = autoOutput;
69 try {
70 url = new URL("http", InetAddress.getLocalHost().getHostAddress(), port, "/");
71 System.out.println("groovy is listening on port " + port);
72 } catch (IOException e) {
73 e.printStackTrace();
74 }
75 new Thread(this).start();
76 }
77
78 public void run() {
79 try {
80 ServerSocket serverSocket = new ServerSocket(url.getPort());
81 while (true) {
82
83
84
85
86 Script script;
87 if (isScriptFile) {
88 script = groovy.parse(new FileInputStream(scriptFilenameOrText));
89 } else {
90 script = groovy.parse(scriptFilenameOrText);
91 }
92 new GroovyClientConnection(script, autoOutput, serverSocket.accept());
93 }
94 } catch (Exception e) {
95 e.printStackTrace();
96 }
97 }
98
99 class GroovyClientConnection implements Runnable {
100 private Script script;
101 private Socket socket;
102 private BufferedReader reader;
103 private PrintWriter writer;
104 private boolean autoOutput;
105
106 GroovyClientConnection(Script script, boolean autoOutput,Socket socket) throws IOException {
107 this.script = script;
108 this.autoOutput = autoOutput;
109 this.socket = socket;
110 reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
111 writer = new PrintWriter(socket.getOutputStream());
112 new Thread(this, "Groovy client connection - " + socket.getInetAddress().getHostAddress()).start();
113 }
114 public void run() {
115 try {
116 String line = null;
117 script.setProperty("out", writer);
118 script.setProperty("socket", socket);
119 script.setProperty("init", Boolean.TRUE);
120 while ((line = reader.readLine()) != null) {
121
122 script.setProperty("line", line);
123 Object o = script.run();
124 script.setProperty("init", Boolean.FALSE);
125 if (o != null) {
126 if ("success".equals(o)) {
127 break;
128 } else {
129 if (autoOutput) {
130 writer.println(o);
131 }
132 }
133 }
134 writer.flush();
135 }
136 } catch (IOException e) {
137 e.printStackTrace();
138 } finally {
139 try {
140 writer.flush();
141 writer.close();
142 } finally {
143 try {
144 socket.close();
145 } catch (IOException e3) {
146 e3.printStackTrace();
147 }
148 }
149 }
150 }
151 }
152 }