001    /*
002     $Id: GroovySocketServer.java 2273 2005-06-10 14:05:02Z cstein $
003    
004     Copyright 2003 (C) James Strachan and Bob Mcwhirter. All Rights Reserved.
005    
006     Redistribution and use of this software and associated documentation
007     ("Software"), with or without modification, are permitted provided
008     that the following conditions are met:
009    
010     1. Redistributions of source code must retain copyright
011        statements and notices.  Redistributions must also contain a
012        copy of this document.
013    
014     2. Redistributions in binary form must reproduce the
015        above copyright notice, this list of conditions and the
016        following disclaimer in the documentation and/or other
017        materials provided with the distribution.
018    
019     3. The name "groovy" must not be used to endorse or promote
020        products derived from this Software without prior written
021        permission of The Codehaus.  For written permission,
022        please contact info@codehaus.org.
023    
024     4. Products derived from this Software may not be called "groovy"
025        nor may "groovy" appear in their names without prior written
026        permission of The Codehaus. "groovy" is a registered
027        trademark of The Codehaus.
028    
029     5. Due credit should be given to The Codehaus -
030        http://groovy.codehaus.org/
031    
032     THIS SOFTWARE IS PROVIDED BY THE CODEHAUS AND CONTRIBUTORS
033     ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
034     NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
035     FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL
036     THE CODEHAUS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
037     INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
038     (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
039     SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
040     HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
041     STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
042     ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
043     OF THE POSSIBILITY OF SUCH DAMAGE.
044    
045     */
046    package groovy.ui;
047    
048    import groovy.lang.GroovyShell;
049    import groovy.lang.Script;
050    
051    import java.io.BufferedReader;
052    import java.io.FileInputStream;
053    import java.io.IOException;
054    import java.io.InputStreamReader;
055    import java.io.PrintWriter;
056    import java.net.InetAddress;
057    import java.net.ServerSocket;
058    import java.net.Socket;
059    import java.net.URL;
060    
061    /**
062     * Simple server that executes supplied script against a socket
063     * @author Jeremy Rayner
064     */
065    
066    public class GroovySocketServer implements Runnable {
067        private URL url;
068        private GroovyShell groovy;
069        private boolean isScriptFile;
070        private String scriptFilenameOrText;
071        private boolean autoOutput;
072        
073        public GroovySocketServer(GroovyShell groovy, boolean isScriptFile, String scriptFilenameOrText, boolean autoOutput, int port) {
074            this.groovy = groovy;
075            this.isScriptFile = isScriptFile;
076            this.scriptFilenameOrText = scriptFilenameOrText;
077            this.autoOutput = autoOutput;
078            try {
079                url = new URL("http", InetAddress.getLocalHost().getHostAddress(), port, "/");
080                System.out.println("groovy is listening on port " + port);
081            } catch (IOException e) { 
082                e.printStackTrace();
083            }
084            new Thread(this).start();
085        }
086    
087        public void run() {
088            try {
089                ServerSocket serverSocket = new ServerSocket(url.getPort());
090                while (true) {
091                    // Create one script per socket connection.
092                    // This is purposefully not caching the Script
093                    // so that the script source file can be changed on the fly,
094                    // as each connection is made to the server.
095                    Script script;
096                    if (isScriptFile) {
097                        GroovyMain gm = new GroovyMain();
098                        script = groovy.parse(new FileInputStream(gm.huntForTheScriptFile(scriptFilenameOrText)));
099                    } else {
100                        script = groovy.parse(scriptFilenameOrText);
101                    }
102                    new GroovyClientConnection(script, autoOutput, serverSocket.accept());
103                }
104            } catch (Exception e) {
105                e.printStackTrace();
106            }
107        }
108        
109        class GroovyClientConnection implements Runnable {
110            private Script script;
111            private Socket socket;
112            private BufferedReader reader;
113            private PrintWriter writer;
114            private boolean autoOutputFlag;
115        
116            GroovyClientConnection(Script script, boolean autoOutput,Socket socket) throws IOException {
117                this.script = script;
118                this.autoOutputFlag = autoOutput;
119                this.socket = socket;
120                reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
121                writer = new PrintWriter(socket.getOutputStream());
122                new Thread(this, "Groovy client connection - " + socket.getInetAddress().getHostAddress()).start();
123            }
124            public void run() {
125                try {
126                    String line = null;
127                    script.setProperty("out", writer);
128                    script.setProperty("socket", socket);
129                    script.setProperty("init", Boolean.TRUE);
130                    while ((line = reader.readLine()) != null) {
131                        // System.out.println(line);
132                        script.setProperty("line", line);
133                        Object o = script.run();
134                        script.setProperty("init", Boolean.FALSE);
135                        if (o != null) {
136                            if ("success".equals(o)) {
137                                break; // to close sockets gracefully etc...
138                            } else {
139                                if (autoOutputFlag) {
140                                    writer.println(o);
141                                }
142                            }
143                        }
144                        writer.flush();
145                    }
146                } catch (IOException e) {
147                    e.printStackTrace();
148                } finally {
149                    try {
150                        writer.flush();
151                        writer.close();
152                    } finally {
153                        try {
154                            socket.close();
155                        } catch (IOException e3) {
156                            e3.printStackTrace();
157                        }
158                    }
159                }
160            }
161        }
162    }