KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > bsh > Remote


1 /*****************************************************************************
2  * *
3  * This file is part of the BeanShell Java Scripting distribution. *
4  * Documentation and updates may be found at http://www.beanshell.org/ *
5  * *
6  * Sun Public License Notice: *
7  * *
8  * The contents of this file are subject to the Sun Public License Version *
9  * 1.0 (the "License"); you may not use this file except in compliance with *
10  * the License. A copy of the License is available at http://www.sun.com *
11  * *
12  * The Original Code is BeanShell. The Initial Developer of the Original *
13  * Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
14  * (C) 2000. All Rights Reserved. *
15  * *
16  * GNU Public License Notice: *
17  * *
18  * Alternatively, the contents of this file may be used under the terms of *
19  * the GNU Lesser General Public License (the "LGPL"), in which case the *
20  * provisions of LGPL are applicable instead of those above. If you wish to *
21  * allow use of your version of this file only under the terms of the LGPL *
22  * and not to allow others to use your version of this file under the SPL, *
23  * indicate your decision by deleting the provisions above and replace *
24  * them with the notice and other provisions required by the LGPL. If you *
25  * do not delete the provisions above, a recipient may use your version of *
26  * this file under either the SPL or the LGPL. *
27  * *
28  * Patrick Niemeyer (pat@pat.net) *
29  * Author of Learning Java, O'Reilly & Associates *
30  * http://www.pat.net/~pat/ *
31  * *
32  *****************************************************************************/

33
34 package bsh;
35
36 import java.io.*;
37 import java.net.*;
38 import java.text.*;
39 /**
40     Remote executor class. Posts a script from the command line to a BshServlet
41     or embedded interpreter using (respectively) HTTP or the bsh telnet
42     service. Output is printed to stdout and a numeric return value is scraped
43     from the result.
44 */

45 public class Remote
46 {
47     public static void main( String JavaDoc args[] )
48         throws Exception JavaDoc
49     {
50         if ( args.length < 2 ) {
51             System.out.println(
52                 "usage: Remote URL(http|bsh) file [ file ] ... ");
53             System.exit(1);
54         }
55         String JavaDoc url = args[0];
56         String JavaDoc text = getFile(args[1]);
57         int ret = eval( url, text );
58         System.exit( ret );
59         }
60
61     /**
62         Evaluate text in the interpreter at url, returning a possible integer
63         return value.
64     */

65     public static int eval( String JavaDoc url, String JavaDoc text )
66         throws IOException
67     {
68         String JavaDoc returnValue = null;
69         if ( url.startsWith( "http:" ) ) {
70             returnValue = doHttp( url, text );
71         } else if ( url.startsWith( "bsh:" ) ) {
72             returnValue = doBsh( url, text );
73         } else
74             throw new IOException( "Unrecognized URL type."
75                 +"Scheme must be http:// or bsh://");
76
77         try {
78             return Integer.parseInt( returnValue );
79         } catch ( Exception JavaDoc e ) {
80             // this convention may change...
81
return 0;
82         }
83     }
84
85     static String JavaDoc doBsh( String JavaDoc url, String JavaDoc text )
86     {
87         OutputStream out;
88         InputStream in;
89         String JavaDoc host = "";
90         String JavaDoc port = "";
91         String JavaDoc returnValue = "-1";
92         String JavaDoc orgURL = url;
93         
94         // Need some format checking here
95
try {
96             url = url.substring(6); // remove the bsh://
97
// get the index of the : between the host and the port is located
98
int index = url.indexOf(":");
99             host = url.substring(0,index);
100             port = url.substring(index+1,url.length());
101         } catch ( Exception JavaDoc ex ) {
102             System.err.println("Bad URL: "+orgURL+": "+ex );
103             return returnValue;
104         }
105
106         try {
107             System.out.println("Connecting to host : "
108                 + host + " at port : " + port);
109             Socket s = new Socket(host, Integer.parseInt(port) + 1);
110             
111             out = s.getOutputStream();
112             in = s.getInputStream();
113             
114             sendLine( text, out );
115
116             BufferedReader bin = new BufferedReader(
117                 new InputStreamReader(in));
118               String JavaDoc line;
119               while ( (line=bin.readLine()) != null )
120                 System.out.println( line );
121
122             // Need to scrape a value from the last line?
123
returnValue="1";
124             return returnValue;
125         } catch(Exception JavaDoc ex) {
126             System.err.println("Error communicating with server: "+ex);
127             return returnValue;
128         }
129     }
130
131     private static void sendLine( String JavaDoc line, OutputStream outPipe )
132         throws IOException
133     {
134         outPipe.write( line.getBytes() );
135         outPipe.flush();
136     }
137
138
139     /*
140         TODO: this is not unicode friendly, nor is getFile()
141         The output is urlencoded 8859_1 text.
142         should probably be urlencoded UTF-8... how does the servlet determine
143         the encoded charset? I guess we're supposed to add a ";charset" clause
144         to the content type?
145     */

146     static String JavaDoc doHttp( String JavaDoc postURL, String JavaDoc text )
147     {
148         String JavaDoc returnValue = null;
149         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
150         sb.append( "bsh.client=Remote" );
151         sb.append( "&bsh.script=" );
152         sb.append( URLEncoder.encode( text ) );
153         /*
154         // This requires Java 1.3
155         try {
156             sb.append( URLEncoder.encode( text, "8859_1" ) );
157         } catch ( UnsupportedEncodingException e ) {
158             e.printStackTrace();
159         }
160         */

161         String JavaDoc formData = sb.toString( );
162
163         try {
164           URL url = new URL( postURL );
165           HttpURLConnection urlcon =
166               (HttpURLConnection) url.openConnection( );
167           urlcon.setRequestMethod("POST");
168           urlcon.setRequestProperty("Content-type",
169               "application/x-www-form-urlencoded");
170           urlcon.setDoOutput(true);
171           urlcon.setDoInput(true);
172           PrintWriter pout = new PrintWriter( new OutputStreamWriter(
173               urlcon.getOutputStream(), "8859_1"), true );
174           pout.print( formData );
175           pout.flush();
176
177           // read results...
178
int rc = urlcon.getResponseCode();
179           if ( rc != HttpURLConnection.HTTP_OK )
180             System.out.println("Error, HTTP response: "+rc );
181
182           returnValue = urlcon.getHeaderField("Bsh-Return");
183
184           BufferedReader bin = new BufferedReader(
185             new InputStreamReader( urlcon.getInputStream() ) );
186           String JavaDoc line;
187           while ( (line=bin.readLine()) != null )
188             System.out.println( line );
189
190           System.out.println( "Return Value: "+returnValue );
191
192         } catch (MalformedURLException e) {
193           System.out.println(e); // bad postURL
194
} catch (IOException e2) {
195           System.out.println(e2); // I/O error
196
}
197
198         return returnValue;
199     }
200
201     /*
202         Note: assumes default character encoding
203     */

204     static String JavaDoc getFile( String JavaDoc name )
205         throws FileNotFoundException, IOException
206     {
207         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
208         BufferedReader bin = new BufferedReader( new FileReader( name ) );
209         String JavaDoc line;
210         while ( (line=bin.readLine()) != null )
211             sb.append( line ).append( "\n" );
212         return sb.toString();
213     }
214
215 }
216
Popular Tags