01: /*
02: * Copyright 2003-2004 The Apache Software Foundation
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
15: */
16: package org.apache.commons.net.telnet;
17:
18: import java.io.InputStream;
19: import java.io.OutputStream;
20:
21: /***
22: * Simple stream responder.
23: * Waits for strings on an input stream and answers
24: * sending corresponfing strings on an output stream.
25: * The reader runs in a separate thread.
26: * <p>
27: * @author Bruno D'Avanzo
28: ***/
29: public class TelnetTestResponder implements Runnable {
30: InputStream _is;
31: OutputStream _os;
32: String _inputs[], _outputs[];
33: long _timeout;
34:
35: /***
36: * Constructor.
37: * Starts a new thread for the reader.
38: * <p>
39: * @param is - InputStream on which to read.
40: * @param os - OutputStream on which to answer.
41: * @param inputs - Array of waited for Strings.
42: * @param inputs - Array of answers.
43: ***/
44: public TelnetTestResponder(InputStream is, OutputStream os,
45: String inputs[], String outputs[], long timeout) {
46: _is = is;
47: _os = os;
48: _timeout = timeout;
49: _inputs = inputs;
50: _outputs = outputs;
51: Thread reader = new Thread(this );
52:
53: reader.start();
54: }
55:
56: /***
57: * Runs the responder
58: ***/
59: public void run() {
60: boolean result = false;
61: byte buffer[] = new byte[32];
62: long starttime = System.currentTimeMillis();
63:
64: try {
65: String readbytes = new String();
66: while (!result
67: && ((System.currentTimeMillis() - starttime) < _timeout)) {
68: if (_is.available() > 0) {
69: int ret_read = _is.read(buffer);
70: readbytes = readbytes
71: + new String(buffer, 0, ret_read);
72:
73: for (int ii = 0; ii < _inputs.length; ii++) {
74: if (readbytes.indexOf(_inputs[ii]) >= 0) {
75: Thread.sleep(1000 * ii);
76: _os.write(_outputs[ii].getBytes());
77: result = true;
78: }
79: }
80: } else {
81: Thread.sleep(500);
82: }
83: }
84:
85: } catch (Exception e) {
86: System.err.println("Error while waiting endstring. "
87: + e.getMessage());
88: }
89: }
90: }
|