KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > tools > ant > taskdefs > optional > net > TelnetTask


1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one or more
3  * contributor license agreements. See the NOTICE file distributed with
4  * this work for additional information regarding copyright ownership.
5  * The ASF licenses this file to You under the Apache License, Version 2.0
6  * (the "License"); you may not use this file except in compliance with
7  * the License. You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  */

18
19 package org.apache.tools.ant.taskdefs.optional.net;
20
21 import org.apache.commons.net.telnet.TelnetClient;
22 import java.io.IOException JavaDoc;
23 import java.io.InputStream JavaDoc;
24 import java.io.OutputStream JavaDoc;
25 import java.util.Calendar JavaDoc;
26 import java.util.Enumeration JavaDoc;
27 import java.util.Vector JavaDoc;
28 import org.apache.tools.ant.BuildException;
29 import org.apache.tools.ant.Project;
30 import org.apache.tools.ant.Task;
31
32 /**
33  * Automates the telnet protocol.
34  *
35  */

36
37 public class TelnetTask extends Task {
38     /**
39      * The userid to login with, if automated login is used
40      */

41     private String JavaDoc userid = null;
42
43     /**
44      * The password to login with, if automated login is used
45      */

46     private String JavaDoc password = null;
47
48     /**
49      * The server to connect to.
50      */

51     private String JavaDoc server = null;
52
53     /**
54      * The tcp port to connect to.
55      */

56     private int port = 23;
57
58     /**
59      * The list of read/write commands for this session
60      */

61     private Vector JavaDoc telnetTasks = new Vector JavaDoc();
62
63     /**
64      * If true, adds a CR to beginning of login script
65      */

66     private boolean addCarriageReturn = false;
67
68     /**
69      * Default time allowed for waiting for a valid response
70      * for all child reads. A value of 0 means no limit.
71      */

72     private Integer JavaDoc defaultTimeout = null;
73
74     /**
75      * Verify that all parameters are included.
76      * Connect and possibly login
77      * Iterate through the list of Reads and writes
78      * @throws BuildException on error
79      */

80     public void execute() throws BuildException {
81        /** A server name is required to continue */
82        if (server == null) {
83            throw new BuildException("No Server Specified");
84        }
85        /** A userid and password must appear together
86         * if they appear. They are not required.
87         */

88        if (userid == null && password != null) {
89            throw new BuildException("No Userid Specified");
90        }
91        if (password == null && userid != null) {
92            throw new BuildException("No Password Specified");
93        }
94
95        /** Create the telnet client object */
96        AntTelnetClient telnet = null;
97        try {
98            telnet = new AntTelnetClient();
99            try {
100                telnet.connect(server, port);
101            } catch (IOException JavaDoc e) {
102                throw new BuildException("Can't connect to " + server);
103            }
104            /** Login if userid and password were specified */
105            if (userid != null && password != null) {
106                login(telnet);
107            }
108            /** Process each sub command */
109            Enumeration JavaDoc tasksToRun = telnetTasks.elements();
110            while (tasksToRun != null && tasksToRun.hasMoreElements()) {
111                TelnetSubTask task = (TelnetSubTask) tasksToRun.nextElement();
112                if (task instanceof TelnetRead && defaultTimeout != null) {
113                    ((TelnetRead) task).setDefaultTimeout(defaultTimeout);
114                }
115                task.execute(telnet);
116            }
117        } finally {
118            if (telnet != null && telnet.isConnected()) {
119                try {
120                    telnet.disconnect();
121                } catch (IOException JavaDoc e) {
122                    throw new BuildException("Error disconnecting from "
123                                             + server);
124                }
125            }
126        }
127     }
128
129     /**
130      * Process a 'typical' login. If it differs, use the read
131      * and write tasks explicitely
132      */

133     private void login(AntTelnetClient telnet) {
134        if (addCarriageReturn) {
135           telnet.sendString("\n", true);
136        }
137        telnet.waitForString("ogin:");
138        telnet.sendString(userid, true);
139        telnet.waitForString("assword:");
140        telnet.sendString(password, false);
141     }
142
143     /**
144      * Set the the login id to use on the server;
145      * required if <tt>password</tt> is set.
146      * @param u a <code>String</code> value
147      */

148     public void setUserid(String JavaDoc u) {
149         this.userid = u;
150     }
151
152     /**
153      * Set the the login password to use
154      * required if <tt>userid</tt> is set.
155      * @param p a <code>String</code> value
156      */

157     public void setPassword(String JavaDoc p) {
158         this.password = p;
159     }
160
161     /**
162      * Set the hostname or address of the remote server.
163      * @param m a <code>String</code> value
164      */

165     public void setServer(String JavaDoc m) {
166         this.server = m;
167     }
168
169     /**
170      * Set the tcp port to connect to; default is 23.
171      * @param p an <code>int</code> value
172      */

173     public void setPort(int p) {
174         this.port = p;
175     }
176
177     /**
178      * send a carriage return after connecting; optional, defaults to false.
179      * @param b a <code>boolean</code> value
180      */

181     public void setInitialCR(boolean b) {
182        this.addCarriageReturn = b;
183     }
184
185     /**
186      * set a default timeout in seconds to wait for a response,
187      * zero means forever (the default)
188      * @param i an <code>Integer</code> value
189      */

190     public void setTimeout(Integer JavaDoc i) {
191        this.defaultTimeout = i;
192     }
193
194     /**
195      * A string to wait for from the server.
196      * A subTask &lt;read&gt; tag was found. Create the object,
197      * Save it in our list, and return it.
198      * @return a read telnet sub task
199      */

200
201     public TelnetSubTask createRead() {
202         TelnetSubTask task = (TelnetSubTask) new TelnetRead();
203         telnetTasks.addElement(task);
204         return task;
205     }
206
207     /**
208      * Add text to send to the server
209      * A subTask &lt;write&gt; tag was found. Create the object,
210      * Save it in our list, and return it.
211      * @return a write telnet sub task
212      */

213     public TelnetSubTask createWrite() {
214         TelnetSubTask task = (TelnetSubTask) new TelnetWrite();
215         telnetTasks.addElement(task);
216         return task;
217     }
218
219     /**
220      * This class is the parent of the Read and Write tasks.
221      * It handles the common attributes for both.
222      */

223     public class TelnetSubTask {
224         // CheckStyle:VisibilityModifier OFF - bc
225
protected String JavaDoc taskString = "";
226         // CheckStyle:VisibilityModifier ON
227
/**
228          * Execute the subtask.
229          * @param telnet the client
230          * @throws BuildException always as it is not allowed to instantiate this object
231          */

232         public void execute(AntTelnetClient telnet)
233                 throws BuildException {
234             throw new BuildException("Shouldn't be able instantiate a SubTask directly");
235         }
236
237         /**
238          * the message as nested text
239          * @param s the nested text
240          */

241         public void addText(String JavaDoc s) {
242             setString(getProject().replaceProperties(s));
243         }
244
245         /**
246          * the message as an attribute
247          * @param s a <code>String</code> value
248          */

249         public void setString(String JavaDoc s) {
250            taskString += s;
251         }
252     }
253
254     /**
255      * Sends text to the connected server
256      */

257     public class TelnetWrite extends TelnetSubTask {
258         private boolean echoString = true;
259         /**
260          * Execute the write task.
261          * @param telnet the task to use
262          * @throws BuildException on error
263          */

264         public void execute(AntTelnetClient telnet)
265                throws BuildException {
266            telnet.sendString(taskString, echoString);
267         }
268
269         /**
270          * Whether or not the message should be echoed to the log.
271          * Defaults to <code>true</code>.
272          * @param b a <code>boolean</code> value
273          */

274         public void setEcho(boolean b) {
275            echoString = b;
276         }
277     }
278
279     /**
280      * Reads the output from the connected server
281      * until the required string is found or we time out.
282      */

283     public class TelnetRead extends TelnetSubTask {
284         private Integer JavaDoc timeout = null;
285         /**
286          * Execute the read task.
287          * @param telnet the task to use
288          * @throws BuildException on error
289          */

290         public void execute(AntTelnetClient telnet)
291                throws BuildException {
292             telnet.waitForString(taskString, timeout);
293         }
294         /**
295          * a timeout value that overrides any task wide timeout.
296          * @param i an <code>Integer</code> value
297          */

298         public void setTimeout(Integer JavaDoc i) {
299            this.timeout = i;
300         }
301
302         /**
303          * Sets the default timeout if none has been set already
304          * @param defaultTimeout an <code>Integer</code> value
305          * @ant.attribute ignore="true"
306          */

307         public void setDefaultTimeout(Integer JavaDoc defaultTimeout) {
308            if (timeout == null) {
309               timeout = defaultTimeout;
310            }
311         }
312     }
313
314     /**
315      * This class handles the abstraction of the telnet protocol.
316      * Currently it is a wrapper around <a
317      * HREF="http://jakarta.apache.org/commons/net/index.html">Jakarta
318      * Commons Net</a>.
319      */

320     public class AntTelnetClient extends TelnetClient {
321         /**
322          * Read from the telnet session until the string we are
323          * waiting for is found
324          * @param s The string to wait on
325          */

326         public void waitForString(String JavaDoc s) {
327             waitForString(s, null);
328         }
329
330         /**
331          * Read from the telnet session until the string we are
332          * waiting for is found or the timeout has been reached
333          * @param s The string to wait on
334          * @param timeout The maximum number of seconds to wait
335          */

336         public void waitForString(String JavaDoc s, Integer JavaDoc timeout) {
337             InputStream JavaDoc is = this.getInputStream();
338             try {
339                 StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
340                 if (timeout == null || timeout.intValue() == 0) {
341                     while (sb.toString().indexOf(s) == -1) {
342                         sb.append((char) is.read());
343                     }
344                 } else {
345                     Calendar JavaDoc endTime = Calendar.getInstance();
346                     endTime.add(Calendar.SECOND, timeout.intValue());
347                     while (sb.toString().indexOf(s) == -1) {
348                         while (Calendar.getInstance().before(endTime)
349                                && is.available() == 0) {
350                             Thread.sleep(250);
351                         }
352                         if (is.available() == 0) {
353                             log("Read before running into timeout: "
354                                 + sb.toString(), Project.MSG_DEBUG);
355                             throw new BuildException(
356                                 "Response timed-out waiting for \"" + s + '\"',
357                                 getLocation());
358                         }
359                         sb.append((char) is.read());
360                     }
361                 }
362                 log(sb.toString(), Project.MSG_INFO);
363             } catch (BuildException be) {
364                 throw be;
365             } catch (Exception JavaDoc e) {
366                 throw new BuildException(e, getLocation());
367             }
368         }
369
370         /**
371          * Write this string to the telnet session.
372          * @param s the string to write
373          * @param echoString if true log the string sent
374          */

375         public void sendString(String JavaDoc s, boolean echoString) {
376             OutputStream JavaDoc os = this.getOutputStream();
377             try {
378                 os.write((s + "\n").getBytes());
379                 if (echoString) {
380                     log(s, Project.MSG_INFO);
381                 }
382                 os.flush();
383             } catch (Exception JavaDoc e) {
384                 throw new BuildException(e, getLocation());
385             }
386         }
387     }
388 }
389
Popular Tags