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 package org.apache.commons.net.telnet;
18
19 import java.io.InputStream;
20 import java.io.OutputStream;
21
22
23 /***
24 * Simple stream responder.
25 * Waits for strings on an input stream and answers
26 * sending corresponfing strings on an output stream.
27 * The reader runs in a separate thread.
28 * <p>
29 * @author Bruno D'Avanzo
30 ***/
31 public class TelnetTestResponder implements Runnable
32 {
33 InputStream _is;
34 OutputStream _os;
35 String _inputs[], _outputs[];
36 long _timeout;
37
38 /***
39 * Constructor.
40 * Starts a new thread for the reader.
41 * <p>
42 * @param is - InputStream on which to read.
43 * @param os - OutputStream on which to answer.
44 * @param inputs - Array of waited for Strings.
45 * @param inputs - Array of answers.
46 ***/
47 public TelnetTestResponder(InputStream is, OutputStream os, String inputs[], String outputs[], long timeout)
48 {
49 _is = is;
50 _os = os;
51 _timeout = timeout;
52 _inputs = inputs;
53 _outputs = outputs;
54 Thread reader = new Thread (this);
55
56 reader.start();
57 }
58
59 /***
60 * Runs the responder
61 ***/
62 public void run()
63 {
64 boolean result = false;
65 byte buffer[] = new byte[32];
66 long starttime = System.currentTimeMillis();
67
68 try
69 {
70 String readbytes = "";
71 while(!result &&
72 ((System.currentTimeMillis() - starttime) < _timeout))
73 {
74 if(_is.available() > 0)
75 {
76 int ret_read = _is.read(buffer);
77 readbytes = readbytes + new String(buffer, 0, ret_read);
78
79 for(int ii=0; ii<_inputs.length; ii++)
80 {
81 if(readbytes.indexOf(_inputs[ii]) >= 0)
82 {
83 Thread.sleep(1000 * ii);
84 _os.write(_outputs[ii].getBytes());
85 result = true;
86 }
87 }
88 }
89 else
90 {
91 Thread.sleep(500);
92 }
93 }
94
95 }
96 catch (Exception e)
97 {
98 System.err.println("Error while waiting endstring. " + e.getMessage());
99 }
100 }
101 }