001 /* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017 package org.apache.commons.net.telnet; 018 019 import java.io.InputStream; 020 import java.io.OutputStream; 021 022 023 /*** 024 * Simple stream responder. 025 * Waits for strings on an input stream and answers 026 * sending corresponfing strings on an output stream. 027 * The reader runs in a separate thread. 028 * <p> 029 * @author Bruno D'Avanzo 030 ***/ 031 public class TelnetTestResponder implements Runnable 032 { 033 InputStream _is; 034 OutputStream _os; 035 String _inputs[], _outputs[]; 036 long _timeout; 037 038 /*** 039 * Constructor. 040 * Starts a new thread for the reader. 041 * <p> 042 * @param is - InputStream on which to read. 043 * @param os - OutputStream on which to answer. 044 * @param inputs - Array of waited for Strings. 045 * @param inputs - Array of answers. 046 ***/ 047 public TelnetTestResponder(InputStream is, OutputStream os, String inputs[], String outputs[], long timeout) 048 { 049 _is = is; 050 _os = os; 051 _timeout = timeout; 052 _inputs = inputs; 053 _outputs = outputs; 054 Thread reader = new Thread (this); 055 056 reader.start(); 057 } 058 059 /*** 060 * Runs the responder 061 ***/ 062 public void run() 063 { 064 boolean result = false; 065 byte buffer[] = new byte[32]; 066 long starttime = System.currentTimeMillis(); 067 068 try 069 { 070 String readbytes = ""; 071 while(!result && 072 ((System.currentTimeMillis() - starttime) < _timeout)) 073 { 074 if(_is.available() > 0) 075 { 076 int ret_read = _is.read(buffer); 077 readbytes = readbytes + new String(buffer, 0, ret_read); 078 079 for(int ii=0; ii<_inputs.length; ii++) 080 { 081 if(readbytes.indexOf(_inputs[ii]) >= 0) 082 { 083 Thread.sleep(1000 * ii); 084 _os.write(_outputs[ii].getBytes()); 085 result = true; 086 } 087 } 088 } 089 else 090 { 091 Thread.sleep(500); 092 } 093 } 094 095 } 096 catch (Exception e) 097 { 098 System.err.println("Error while waiting endstring. " + e.getMessage()); 099 } 100 } 101 }