Second part of onap rename
[appc.git] / appc-config / appc-config-adaptor / provider / src / main / java / org / onap / appc / ccadaptor / SshJcraftWrapper.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : APPC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Copyright (C) 2017 Amdocs
8  * =============================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  *
21  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22  * ============LICENSE_END=========================================================
23  */
24
25 package org.onap.appc.ccadaptor;
26
27 import java.io.BufferedReader;
28 import java.io.IOException;
29 import java.io.InputStream;
30 import java.io.InputStreamReader;
31 import java.io.*;
32 import java.util.*;
33 import java.text.DateFormat;
34 import java.text.SimpleDateFormat;
35 import java.util.Calendar;
36 import com.jcraft.jsch.*;
37
38 public class SshJcraftWrapper
39 {
40
41     private String debugLogFileName = "/tmp/sshJcraftWrapperDebug";
42     InputStream inputStream = null;
43     OutputStream outputStream = null;
44     private TelnetListener listener = null;
45     private String routerLogFileName = null;
46     DebugLog debugLog = new DebugLog();
47     private String host = null;
48     private String RouterName = null;
49     private int BUFFER_SIZE = 512000;
50     // private int BUFFER_SIZE = 4000000;
51     private DataInputStream dis = null;
52     private BufferedReader reader = null;
53     char[] charBuffer = new char[BUFFER_SIZE];
54     private BufferedWriter out = null;
55     private File _tmpFile = null;
56     private JSch jsch = null;
57     private Session session = null;
58     private Channel channel = null;
59     private String tId = "";
60     private String aggregatedReceivedString = "";
61     private File extraDebugFile = new File("/tmp/sshJcraftWrapperDEBUG");
62     private String routerCmdType = "XML";
63     private String routerFileName = null;
64     private File  jcraftReadSwConfigFileFromDisk = new File("/tmp/jcraftReadSwConfigFileFromDisk");
65   private String equipNameCode = null;
66   private String hostName = null;
67   private String userName = null;
68   private String passWord = null;
69     private StringBuffer charactersFromBufferFlush = new StringBuffer();
70   private Runtime runtime = Runtime.getRuntime();
71   private DebugLog dbLog = new DebugLog();
72
73     public void SshJcraftWrapper()
74     {
75         String fn = "SshJcraftWrapper.SshJcraftWrapper";
76         debugLog.printRTAriDebug (fn, "SshJcraftWrapper has been instantated");
77         routerLogFileName = "/tmp/" +host;
78         this.host = host;
79     }
80
81     public void connect (String hostname, String username, String password, String prompt, int timeOut) throws IOException
82     {
83         String fn = "SshJcraftWrapper.connect";
84         jsch = new JSch();
85         debugLog.printRTAriDebug (fn, "Attempting to connect to "+hostname +" username="+username +" password="+password + " prompt='"+prompt +"' timeOut="+timeOut);
86         debugLog.printRTAriDebug (fn, "Trace A");
87         RouterName = hostname;
88     hostName = hostname;
89     userName = username;
90     passWord = password;
91         try
92         {
93             session = jsch.getSession(username, hostname, 22);
94             UserInfo ui = new MyUserInfo();
95             session.setPassword(password);
96             session.setUserInfo(ui);
97             session.connect(timeOut);
98             channel = session.openChannel("shell");
99             session.setServerAliveCountMax(0); // If this is not set to '0', then socket timeout on all reads will not work!!!!
100             ((ChannelShell)channel).setPtyType("vt102");
101             inputStream = channel.getInputStream();
102             dis = new DataInputStream(inputStream);
103             reader = new BufferedReader(new InputStreamReader(dis), BUFFER_SIZE);
104             channel.connect();
105             debugLog.printRTAriDebug (fn, "Successfully connected.");
106             debugLog.printRTAriDebug (fn, "Flushing input buffer");
107       try
108       {
109         receiveUntil(prompt, 3000, "No cmd was sent, just waiting");
110       }
111           catch (Exception e)
112           {
113               debugLog.printRTAriDebug (fn, "Caught an Exception: Nothing to flush out.");
114       }
115         }
116         catch (Exception e)
117         {
118             debugLog.printRTAriDebug (fn, "Caught an Exception. e="+e);
119       // dbLog.storeData("ErrorMsg= Exception trying to connect to "+hostname +" "+e);
120             throw new IOException(e.toString());
121         }
122     }
123
124     // User specifies the port number.
125     public void connect (String hostname, String username, String password, String prompt, int timeOut, int portNum) throws IOException
126     {
127         String fn = "SshJcraftWrapper.connect";
128         debugLog.printRTAriDebug (fn, ":Attempting to connect to "+hostname +" username="+username +" password="+password + " prompt='"+prompt +"' timeOut="+timeOut +" portNum="+portNum);
129         RouterName = hostname;
130     hostName = hostname;
131     userName = username;
132     passWord = password;
133         RouterName = hostname;
134         jsch = new JSch();
135         try
136         {
137             session = jsch.getSession(username, hostname, portNum);
138             UserInfo ui = new MyUserInfo();
139             session.setPassword(password);
140             session.setUserInfo(ui);
141       session.setConfig("StrictHostKeyChecking", "no");
142             debugLog.printRTAriDebug (fn, ":StrictHostKeyChecking set to 'no'");
143
144             session.connect(timeOut);
145             session.setServerAliveCountMax(0); // If this is not set to '0', then socket timeout on all reads will not work!!!!
146             channel = session.openChannel("shell");
147             ((ChannelShell)channel).setPtyType("vt102");
148             inputStream = channel.getInputStream();
149             dis = new DataInputStream(inputStream);
150             reader = new BufferedReader(new InputStreamReader(dis), BUFFER_SIZE);
151             channel.connect();
152             debugLog.printRTAriDebug (fn, ":Successfully connected.");
153             debugLog.printRTAriDebug (fn, ":Flushing input buffer");
154       try
155       {
156         if (prompt.equals("]]>]]>"))
157           receiveUntil("]]>]]>", 10000, "No cmd was sent, just waiting");
158         else
159           receiveUntil(":~#", 5000, "No cmd was sent, just waiting");
160       }
161           catch (Exception e)
162           {
163               debugLog.printRTAriDebug (fn, "Caught an Exception::: Nothing to flush out.");
164       }
165         }
166         catch (Exception e)
167         {
168             debugLog.printRTAriDebug (fn, ":Caught an Exception. e="+e);
169       dbLog.outputStackTrace(e);
170
171       // dbLog.storeData("ErrorMsg= Exception trying to connect to "+hostname +" "+e);
172             throw new IOException(e.toString());
173         }
174     }
175
176
177     public String receiveUntil (String delimeters, int timeout, String cmdThatWasSent) throws TimedOutException, IOException
178     {
179         String fn = "SshJcraftWrapper.receiveUntil";
180         boolean match = false;
181         boolean cliPromptCmd = false;
182         StringBuffer sb2 = new StringBuffer();
183         StringBuffer sbReceive = new StringBuffer();
184         debugLog.printRTAriDebug (fn, "delimeters='"+delimeters +"' timeout="+timeout +" cmdThatWasSent='"+cmdThatWasSent +"'");
185     appendToFile(debugLogFileName, fn +" delimeters='"+delimeters +"' timeout="+timeout +" cmdThatWasSent='"+cmdThatWasSent +"'\n");
186         String CmdThatWasSent = removeWhiteSpaceAndNewLineCharactersAroundString(cmdThatWasSent);
187         int readCounts = 0;
188         aggregatedReceivedString = "";
189
190         long  deadline = new Date().getTime() + timeout;
191         try
192         {
193             session.setTimeout(timeout);  // This is the socket timeout value.
194             while (!match)
195             {
196                 if(new Date().getTime() > deadline)
197                 {
198                     debugLog.printRTAriDebug (fn, "Throwing a TimedOutException: time in routine has exceed our deadline: RouterName:"+RouterName +" CmdThatWasSent="+ CmdThatWasSent);
199                     throw new TimedOutException("Timeout: time in routine has exceed our deadline");
200                 }
201         try
202                 {
203                     Thread.sleep(500);
204                 }
205                 catch (java.lang.InterruptedException ee)
206                 {
207                     boolean ignore = true;
208                 }
209                 int len =  reader.read(charBuffer, 0, BUFFER_SIZE);
210                 appendToFile(debugLogFileName, fn +" After reader.read cmd: len="+len +"\n");
211                 if (len <= 0)
212                 {
213                     debugLog.printRTAriDebug (fn, "Reader read "+len  +" bytes. Looks like we timed out, router="+RouterName);
214                     throw new TimedOutException ("Received a SocketTimeoutException router="+RouterName);
215                 }
216                 if (!cliPromptCmd)
217                 {
218                     if (cmdThatWasSent.indexOf("IOS_XR_uploadedSwConfigCmd") != -1)
219                     {
220                         if (out == null)
221                         {
222                             // This is a IOS XR sw config file. We will write it to the disk.
223                             timeout = timeout * 2;
224                             deadline = new Date().getTime() + timeout;
225                             debugLog.printRTAriDebug (fn, "IOS XR upload for software config: timeout="+timeout);
226                             StringTokenizer st = new StringTokenizer(cmdThatWasSent);
227                             st.nextToken();
228                             routerFileName = st.nextToken();
229                             out = new BufferedWriter(new FileWriter(routerFileName));
230                             routerLogFileName = "/tmp/"+RouterName;
231                             _tmpFile = new File(routerLogFileName);
232                             debugLog.printRTAriDebug (fn, "Will write the swConfigFile to disk, routerFileName="+routerFileName);
233                         }
234                         int c;
235                         out.write(charBuffer, 0, len);
236                         out.flush();
237                         appendToFile(debugLogFileName, fn +" Wrote "+len +" bytes to the disk\n");
238                         if (_tmpFile.exists())
239                             appendToRouterFile(routerLogFileName, len);
240                         match = checkIfReceivedStringMatchesDelimeter(len, "\nXML>");
241                         if (match == true)
242                         {
243                             out.flush();
244                             out.close();
245               out = null;
246                             return null;
247                         }
248                     }
249                     else
250                     {
251                         readCounts ++;
252                         appendToFile(debugLogFileName, fn +" readCounts="+readCounts +"  Reader read "+len +" of data\n");
253                         int c;
254                         sb2.setLength(0);
255                         for(int i=0; i<len; i++ )
256                         {
257                             c = charBuffer[i];
258                             if ((c != 7) && (c != 13) && (c != 0) && (c != 27))
259                             {
260                                 sbReceive.append((char)charBuffer[i]);
261                                 sb2.append((char)charBuffer[i]);
262                             }
263                         }
264                         appendToRouterFile("/tmp/"+RouterName, len);
265                         if (listener != null)
266                             listener.receivedString(sb2.toString());
267
268                         appendToFile(debugLogFileName, fn +" Trace 1\n");
269                         match = checkIfReceivedStringMatchesDelimeter(delimeters, sb2.toString(), cmdThatWasSent);
270                         appendToFile(debugLogFileName, fn +" Trace 2\n");
271                         if (match == true)
272                         {
273                             appendToFile(debugLogFileName, fn +" Match was true, breaking...\n");
274                             break;
275                         }
276                     }
277                 }
278                 else
279                 {
280                     debugLog.printRTAriDebug (fn, "cliPromptCmd, Trace 2");
281                     sb2.setLength(0);
282                     for(int i=0; i<len; i++ )
283                     {
284                         sbReceive.append( (char)charBuffer[i] );
285                         sb2.append( (char)charBuffer[i] );
286                     }
287                     appendToRouterFile("/tmp/"+RouterName, sb2);
288                     if (listener != null)
289                         listener.receivedString(sb2.toString());
290                     debugLog.printRTAriDebug (fn, "sb2='"+sb2.toString() +"'  delimeters='" +delimeters +"'");
291                     if (sb2.toString().indexOf("\nariPrompt>") != -1)
292                     {
293                         debugLog.printRTAriDebug (fn, "Found our prompt");
294                         match = true;
295                         break;
296                     }
297                 }
298             }
299         }
300         catch (JSchException e)
301         {
302             debugLog.printRTAriDebug (fn, "Caught an JSchException e="+e.toString());
303       dbLog.outputStackTrace(e);
304             throw new TimedOutException (e.toString());
305         }
306         catch (IOException ee)
307         {
308             debugLog.printRTAriDebug (fn, "Caught an IOException: ee="+ee.toString());
309       dbLog.outputStackTrace(ee);
310             throw new TimedOutException (ee.toString());
311         }
312         String result = stripOffCmdFromRouterResponse(sbReceive.toString());
313         debugLog.printRTAriDebug (fn, "Leaving method successfully");
314         return (result);
315     }
316
317     public boolean checkIfReceivedStringMatchesDelimeter(String delimeters, String receivedString, String cmdThatWasSent)
318     {
319         // The delimeters are in a '|' seperated string. Return true on the first match.
320         String fn = "SshJcraftWrapper.checkIfReceivedStringMatchesDelimeter";
321         appendToFile(debugLogFileName, fn +" Entered:  delimeters='"+delimeters +" cmdThatWasSent='"+cmdThatWasSent +"' receivedString='"+receivedString +"'\n");
322         StringTokenizer st = new StringTokenizer(delimeters, "|");
323
324         if ((delimeters.indexOf("#$") != -1) || (routerCmdType.equals("CLI")))  // This would be an IOS XR, CLI command.
325         {
326             int x = receivedString.lastIndexOf("#");
327             int y = receivedString.length() - 1;
328             appendToFile(debugLogFileName, fn +" IOS XR, CLI command\n");
329             if (extraDebugFile.exists())
330                 appendToFile(debugLogFileName, fn +" :::cmdThatWasSent='"+cmdThatWasSent +"'  x="+x +" y="+y +"\n");
331             if ((x != -1) && (y == x))
332                 return(true);
333             else
334                 return(false);
335         }
336         if (cmdThatWasSent.indexOf("show config") != -1)
337         {
338             appendToFile(debugLogFileName, fn +"In the block for 'show config'\n");
339             while (st.hasMoreTokens())
340             {
341                 String delimeter = st.nextToken();
342                 // Make sure we don't get faked out by a response of " #".
343                 // Proc #0
344                 //   # signaling-local-address ipv6 FD00:F4D5:EA06:1::110:136:254
345                 // LAAR2#
346                 int x = receivedString.lastIndexOf(delimeter);
347                 if ((receivedString.lastIndexOf(delimeter) != -1) && (receivedString.lastIndexOf(" #") != x-1))
348                 {
349                 appendToFile(debugLogFileName, fn +"receivedString=\n'" +receivedString +"'\n");
350                 appendToFile(debugLogFileName, fn +"Returning true for the 'show config' command. We found our real delmeter. \n\n");
351                     return (true);
352                 }
353             }
354         }
355         else
356         {
357             aggregatedReceivedString = aggregatedReceivedString + receivedString;
358       _appendToFile ("/tmp/aggregatedReceivedString.debug", aggregatedReceivedString);
359
360             while (st.hasMoreTokens())
361             {
362                 String delimeter = st.nextToken();
363                 appendToFile(debugLogFileName, fn +" Looking for an delimeter of:'"+delimeter+"'\n");
364                 appendToFile(debugLogFileName, fn +" receivedString='"+receivedString);
365                 if (aggregatedReceivedString.indexOf(delimeter) != -1)
366                 {
367                     debugLog.printRTAriDebug (fn, "Found our delimeter, which was: '"+delimeter +"'");
368                     aggregatedReceivedString = "";
369                     return (true);
370                 }
371             }
372         }
373         return (false);
374     }
375
376     public boolean checkIfReceivedStringMatchesDelimeter(int len, String delimeter)
377     {
378         String fnName = "SshJcraftWrapper.checkIfReceivedStringMatchesDelimeter:::";
379         int x;
380         int c;
381         String str = null;
382
383         if (jcraftReadSwConfigFileFromDisk())
384         {
385             DebugLog.printAriDebug(fnName, "jcraftReadSwConfigFileFromDisk block");
386             File fileName = new File(routerFileName);
387             appendToFile(debugLogFileName, fnName +" jcraftReadSwConfigFileFromDisk::: Will read the tail end of the file from the disk");
388             try
389             {
390                 str = getLastFewLinesOfFile(fileName, 3);
391             }
392             catch (IOException e)
393             {
394                 DebugLog.printAriDebug(fnName, "Caught an Exception, e="+e);
395         dbLog.outputStackTrace(e);
396                 e.printStackTrace();
397             }
398         }
399         else
400         {
401             // DebugLog.printAriDebug(fnName, "TRACE 1: ******************************");
402             // When looking at the end of the charBuffer, don't include any linefeeds or spaces. We only want to make the smallest string possible.
403             for(x=len-1; x>=0; x--)
404             {
405                 c = charBuffer[x];
406                 if (extraDebugFile.exists())
407                     appendToFile(debugLogFileName, fnName +" x="+x +" c="+c +"\n");
408                 if ((c != 10) && (c != 32)) // Not a line feed nor a space.
409                     break;
410             }
411             if ((x+1 - 13) >= 0)
412             {
413                 str = new String (charBuffer, (x+1-13), 13);
414                 appendToFile(debugLogFileName, fnName +" str:'"+str +"'\n");
415             }
416             else
417             {
418                 File fileName = new File(routerFileName);
419                 appendToFile(debugLogFileName, fnName +" Will read the tail end of the file from the disk, x="+x +" len="+len +" str::'"+str +"' routerFileName='" +routerFileName +"'\n");
420                 DebugLog.printAriDebug(fnName, "Will read the tail end of the file from the disk, x="+x +" len="+len +" str::'"+str +"' routerFileName='" +routerFileName +"'");
421                 try
422                 {
423                     str = getLastFewLinesOfFile(fileName, 3);
424                 }
425                 catch (IOException e)
426                 {
427                     DebugLog.printAriDebug(fnName, "Caught an Exception, e="+e);
428           dbLog.outputStackTrace(e);
429                     e.printStackTrace();
430                 }
431             }
432         }
433
434         if (str.indexOf(delimeter) != -1)
435         {
436             DebugLog.printAriDebug(fnName, "str in break is:'"+str +"'" +" delimeter='" +delimeter +"'");
437             appendToFile(debugLogFileName, fnName +" str in break is:'"+str +" delimeter='" +delimeter +"'" +"'\n");
438             return(true);
439         }
440         else
441         {
442             appendToFile(debugLogFileName, fnName +" Returning false");
443             return(false);
444         }
445
446     }
447
448     public void closeConnection()
449     {
450         String fn = "SshJcraftWrapper.closeConnection";
451         debugLog.printRTAriDebug (fn, "Executing the closeConnection....");
452         inputStream = null;
453         outputStream = null;
454         dis = null;
455         charBuffer = null;
456         session.disconnect();
457     session = null;
458     }
459
460     public void send (String cmd) throws IOException
461     {
462         String fn = "SshJcraftWrapper.send";
463         OutputStream out = channel.getOutputStream();
464         DataOutputStream dos = new DataOutputStream(out);
465
466         if ((cmd.charAt(cmd.length() - 1) != '\n') && (cmd.charAt(cmd.length() - 1) != '\r'))
467             cmd += "\n";
468     int length = cmd.length();
469     int i = -1;
470     int nchars = 300000;
471     int ncharsTotalSent = 0;
472     int ncharsSent = 0;
473
474         appendToFile(debugLogFileName, fn+": Sending: '"+cmd );
475         // debugLog.printRTAriDebug (fn, "cmd = "+cmd);
476         debugLog.printRTAriDebug (fn, "Length of cmd is:" +length); // 2,937,706
477         try
478         {
479       if (length > 600000)
480       {
481         int timeout = 9000;
482         for (i=0; i<length; i+=nchars)
483         {
484           String Cmd = cmd.substring(i, Math.min(length, i + nchars));
485           ncharsSent = Cmd.length();
486           ncharsTotalSent = ncharsTotalSent + Cmd.length();
487                 debugLog.printRTAriDebug (fn, "i="+i +" Sending Cmd: ncharsSent="+ncharsSent);
488                 dos.writeBytes(Cmd);
489               dos.flush();
490           try
491           {
492                   debugLog.printRTAriDebug (fn, ":::i="+i +" length="+length);
493             if (ncharsSent < length)
494                  receiveUntilBufferFlush (ncharsSent, timeout, "buffer flush  i="+i);
495             else
496             {
497                     debugLog.printRTAriDebug (fn, "i="+i +" No Waiting this time....");
498                     dos.flush();
499             }
500           }
501               catch (Exception e)
502               {
503                   debugLog.printRTAriDebug (fn, "Caught an Exception: Nothing to flush out.");
504           }
505         }
506       }
507       else
508       {
509             debugLog.printRTAriDebug (fn, "Before executing the dos.writeBytes");
510               dos.writeBytes(cmd);
511       }
512           dos.flush();
513             debugLog.printRTAriDebug (fn, "Leaving method");
514           appendToFile(debugLogFileName, fn+": Leaving method\n");
515         }
516         catch (IOException e)
517         {
518             debugLog.printRTAriDebug (fn, "Caught an IOException. e="+e);
519       dbLog.outputStackTrace(e);
520             throw new IOException(e.toString());
521         }
522     }
523
524
525     public void sendChar (int v) throws IOException
526     {
527         String fn = "SshJcraftWrapper.sendChar";
528         OutputStream out = channel.getOutputStream();
529         DataOutputStream dos = new DataOutputStream(out);
530         try
531         {
532             debugLog.printRTAriDebug (fn, "Sending: '" +v +"'");
533             dos.writeChar (v);
534             dos.flush();
535         }
536         catch (IOException e)
537         {
538             debugLog.printRTAriDebug (fn, "Caught an IOException. e="+e);
539             throw new IOException(e.toString());
540         }
541     }
542
543     public void send (byte[] b, int off, int len) throws IOException
544     {
545         String fn = "SshJcraftWrapper.send:byte[]";
546         OutputStream out = channel.getOutputStream();
547         DataOutputStream dos = new DataOutputStream(out);
548         try
549         {
550             dos.write (b, off, len);
551             dos.flush();
552         }
553         catch (IOException e)
554         {
555             debugLog.printRTAriDebug (fn, "Caught an IOException. e="+e);
556             throw new IOException(e.toString());
557         }
558     }
559
560     public static class MyUserInfo implements UserInfo, UIKeyboardInteractive
561     {
562         public String getPassword()
563         {
564             return null;
565         }
566         public boolean promptYesNo(String str)
567         {
568             return false;
569         }
570         public String getPassphrase()
571         {
572             return null;
573         }
574         public boolean promptPassphrase(String message)
575         {
576             return false;
577         }
578         public boolean promptPassword(String message)
579         {
580             return false;
581         }
582         public void showMessage(String message)
583         { }
584         public String[] promptKeyboardInteractive(String destination,
585                 String name,
586                 String instruction,
587                 String[] prompt,
588                 boolean[] echo)
589         {
590             return null;
591         }
592     }
593
594     public void addListener(TelnetListener listener)
595     {
596         this.listener = listener;
597     }
598
599     public void appendToFile (String fileName, String dataToWrite)
600     {
601         String fn = "SshJcraftWrapper.appendToFile";
602
603         try
604         {
605             // First check to see if a file 'fileName' exist, if it does
606             // write to it. If it does not exist, don't write to it.
607             File tmpFile = new File(fileName);
608             if (tmpFile.exists())
609             {
610                 BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true));
611                 // out.write(dataToWrite);
612                 // out.write(getTheDate() +": " +Thread.currentThread().getName() +": "+dataToWrite);
613                 out.write(getTheDate() +": " +tId +": "+dataToWrite);
614                 out.close();
615             }
616         }
617         catch (IOException e)
618         {
619             debugLog.printRTAriDebug (fn, "Caught an IOException: e="+e);
620         }
621         catch (Exception e)
622         {
623             debugLog.printRTAriDebug (fn, "Caught an Exception: e="+e);
624         }
625     }
626
627   public void _appendToFile (String fileName, String dataToWrite)
628     {
629         String fn = "SshJcraftWrapper.appendToFile";
630
631         try
632         {
633             // First check to see if a file 'fileName' exist, if it does
634             // write to it. If it does not exist, don't write to it.
635             File tmpFile = new File(fileName);
636             if (tmpFile.exists())
637             {
638                 BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true));
639                 out.write(dataToWrite);
640                 out.close();
641             }
642         }
643         catch (IOException e)
644         {
645             debugLog.printRTAriDebug (fn, "Caught an IOException: e="+e);
646         }
647         catch (Exception e)
648         {
649             debugLog.printRTAriDebug (fn, "Caught an Exception: e="+e);
650         }
651     }
652
653
654     public String getTheDate()
655     {
656         Calendar cal = Calendar.getInstance();
657         java.util.Date today = cal.getTime();
658         DateFormat df1 = DateFormat.getDateInstance();
659         DateFormat df3 = new SimpleDateFormat("MM/dd/yyyy H:mm:ss  ");
660         return (df3.format(today));
661     }
662
663
664     public void appendToRouterFile (String fileName, StringBuffer dataToWrite)
665     {
666         String fnName = "SshJcraftWrapper.appendToRouterFile";
667         debugLog.printRTAriDebug (fnName, "Entered.... ");
668         try
669         {
670             // First check to see if a file 'fileName' exist, if it does
671             // write to it. If it does not exist, don't write to it.
672             File tmpFile = new File(fileName);
673             {
674                 // if ((tmpFile.exists()) && (tmpFile.setWritable(true, true)))
675                 if (tmpFile.exists())
676                 {
677                     BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true));
678           // out.write("<!--  "+getTheDate() +": " +tId +"  -->\n");
679                     out.write(dataToWrite.toString());
680                     out.close();
681                 }
682             }
683         }
684         catch (IOException e)
685         {
686             System.err.println("writeToFile() exception: " + e);
687             e.printStackTrace();
688         }
689     }
690
691     public void appendToRouterFile (String fileName, int len)
692     {
693         String fnName = "SshJcraftWrapper.appendToFile";
694         // debugLog.printRTAriDebug (fnName, "Entered.... len="+len);
695         try
696         {
697             // First check to see if a file 'fileName' exist, if it does
698             // write to it. If it does not exist, don't write to it.
699             File tmpFile = new File(fileName);
700                 // if ((tmpFile.exists()) && (tmpFile.setWritable(true, true)))
701                 if (tmpFile.exists())
702                 {
703                     BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true));
704           // out.write("<!--  "+getTheDate() +": " +tId +"  -->\n");
705                     out.write(charBuffer, 0, len);
706                     out.close();
707                 }
708         }
709         catch (IOException e)
710         {
711             System.err.println("writeToFile() exception: " + e);
712             e.printStackTrace();
713         }
714     }
715
716     public String removeWhiteSpaceAndNewLineCharactersAroundString(String str)
717     {
718         if (str != null)
719         {
720             StringTokenizer strTok = new StringTokenizer(str, "\n");
721             StringBuffer sb = new StringBuffer();
722
723             while (strTok.hasMoreTokens())
724             {
725                 String line = strTok.nextToken();
726                 sb.append(line);
727             }
728             return (sb.toString().trim());
729         }
730         else
731             return(str);
732     }
733
734     public String stripOffCmdFromRouterResponse(String routerResponse)
735     {
736         String fn = "SshJcraftWrapper.stripOffCmdFromRouterResponse";
737         // appendToFile(debugLogFileName, fn+": routerResponse='"+routerResponse +"'\n");
738
739         // The session of SSH will echo the command sent to the router, in the router's response.
740         // Since all our commands are terminated by a '\n', strip off the first line
741         // of the response from the router. This first line contains the orginal command.
742
743         StringTokenizer rr = new StringTokenizer(routerResponse, "\n");
744         StringBuffer sb = new StringBuffer();
745
746         int numTokens = rr.countTokens();
747         // debugLog.printRTAriDebug (fn, "Number of lines in the response from the router is:" +numTokens);
748         if (numTokens > 1)
749         {
750             rr.nextToken(); //Skip the first line.
751             while (rr.hasMoreTokens())
752             {
753                 sb.append(rr.nextToken()+'\n');
754             }
755         }
756         return (sb.toString());
757     }
758
759     public void setRouterCommandType(String type)
760     {
761         String fn = "SshJcraftWrapper.setRouterCommandType";
762         this.routerCmdType = type;
763         debugLog.printRTAriDebug (fn, "Setting routerCmdType to a value of '"+type +"'");
764     }
765
766     public String getLastFewLinesOfFile(File file, int linesToRead) throws FileNotFoundException, IOException
767     {
768         String fn = "SshJcraftWrapper.getLastFewLinesOfFile";
769         RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
770         int lines = 0;
771         StringBuilder builder = new StringBuilder();
772         String tail = "";
773         long length = file.length();
774         length--;
775         randomAccessFile.seek(length);
776         for(long seek = length; seek >= 0; --seek)
777         {
778             randomAccessFile.seek(seek);
779             char c = (char)randomAccessFile.read();
780             builder.append(c);
781             if(c == '\n')
782             {
783                 builder = builder.reverse();
784                 // System.out.println(builder.toString());
785                 tail = builder.toString() + tail;
786                 lines++;
787                 builder.setLength(0);
788                 if (lines == linesToRead)
789                 {
790                     break;
791                 }
792             }
793         }
794         randomAccessFile.close();
795         if(!jcraftReadSwConfigFileFromDisk())
796             debugLog.printRTAriDebug (fn, "tail='"+tail +"'");
797         appendToFile(debugLogFileName, "tail='"+tail +"'\n");
798         return tail;
799     }
800
801     public boolean jcraftReadSwConfigFileFromDisk()
802     {
803         if (jcraftReadSwConfigFileFromDisk.exists())
804             return(true);
805         else
806             return(false);
807     }
808
809   public String getEquipNameCode()
810   {
811     return (equipNameCode);
812
813   }
814
815   public void setEquipNameCode(String equipNameCode)
816   {
817     this.equipNameCode = equipNameCode;
818   }
819
820   public String getRouterName()
821   {
822     return(RouterName);
823   }
824
825   // Routine does reads until it has read 'nchars' or times out.
826      public void receiveUntilBufferFlush (int ncharsSent, int timeout, String message) throws TimedOutException, IOException
827     {
828         String fn = "SshJcraftWrapper.receiveUntilBufferFlush";
829         StringBuffer sb2 = new StringBuffer();
830         StringBuffer sbReceive = new StringBuffer();
831         debugLog.printRTAriDebug (fn, "ncharsSent="+ncharsSent+" timeout="+timeout +" "+message);
832     int ncharsTotalReceived = 0;
833     int ncharsRead = 0;
834     boolean flag = false;
835     charactersFromBufferFlush.setLength(0);
836
837         long  deadline = new Date().getTime() + timeout;
838     logMemoryUsage();
839         try
840         {
841             session.setTimeout(timeout);  // This is the socket timeout value.
842             while (true)
843             {
844                 if(new Date().getTime() > deadline)
845                 {
846                     debugLog.printRTAriDebug (fn, "Throwing a TimedOutException: time in routine has exceed our deadline: ncharsSent="+ncharsSent+" ncharsTotalReceived="+ncharsTotalReceived);
847           flag = true;
848                     throw new TimedOutException("Timeout: time in routine has exceed our deadline");
849                 }
850                 ncharsRead =  reader.read(charBuffer, 0, BUFFER_SIZE);
851                 if (listener != null)
852                     listener.receivedString(String.copyValueOf(charBuffer,0,ncharsRead));
853                 appendToRouterFile("/tmp/"+RouterName, ncharsRead);
854         ncharsTotalReceived = ncharsTotalReceived + ncharsRead;
855             // debugLog.printRTAriDebug (fn, "::ncharsSent="+ncharsSent+" ncharsTotalReceived="+ncharsTotalReceived +" ncharsRead="+ncharsRead);
856         if (ncharsTotalReceived >= ncharsSent)
857         {
858               debugLog.printRTAriDebug (fn, "Received the correct number of characters, ncharsSent="+ncharsSent +" ncharsTotalReceived="+ncharsTotalReceived);
859           logMemoryUsage();
860           return;
861         }
862             }
863         }
864         catch (JSchException e)
865         {
866             debugLog.printRTAriDebug (fn, "Caught an JSchException e="+e.toString());
867           debugLog.printRTAriDebug (fn, "ncharsSent="+ncharsSent+" ncharsTotalReceived="+ncharsTotalReceived +" ncharsRead="+ncharsRead);
868             throw new TimedOutException (e.toString());
869         }
870     }
871
872   public String getHostName()
873   {
874     return(hostName);
875   }
876   
877   public String getUserName()
878   {
879     return(userName);
880   }
881
882   public String getPassWord()
883   {
884     return(passWord);
885   }
886
887   public void sftpPut(String sourcePath, String destDirectory) throws IOException
888   {
889     String fn = "SshJcraftWrapper.sftp";
890     try
891     {
892       Session sftpSession = jsch.getSession(userName, hostName, 22);
893             UserInfo ui = new MyUserInfo();
894             sftpSession.setPassword(passWord);
895             sftpSession.setUserInfo(ui);
896             sftpSession.connect(30*1000);
897           debugLog.printRTAriDebug (fn, "Opening up an sftp channel....");
898       ChannelSftp sftp=(ChannelSftp)sftpSession.openChannel("sftp");
899           debugLog.printRTAriDebug (fn, "Connecting....");
900       sftp.connect();
901           debugLog.printRTAriDebug (fn, "Sending "+sourcePath +" --> "+destDirectory);
902       sftp.put(sourcePath, destDirectory, ChannelSftp.OVERWRITE);
903           debugLog.printRTAriDebug (fn, "Sent successfully");
904       sftpSession.disconnect();
905     }
906     catch (Exception e)
907     {
908           debugLog.printRTAriDebug (fn, "Caught an Exception, e="+e);
909       // dbLog.storeData("ErrorMsg= sftp threw an Exception. error is:"+e);
910             throw new IOException(e.toString());
911     }
912   }
913
914
915
916   public void SftpPut(String stringOfData, String fullPathDest) throws IOException
917   {
918     String fn = "SshJcraftWrapper.Sftp";
919     try
920     {
921       Session sftpSession = jsch.getSession(userName, hostName, 22);
922             UserInfo ui = new MyUserInfo();
923             sftpSession.setPassword(passWord);
924             sftpSession.setUserInfo(ui);
925             sftpSession.connect(30*1000);
926           debugLog.printRTAriDebug (fn, "Opening up an sftp channel....");
927       ChannelSftp sftp=(ChannelSftp)sftpSession.openChannel("sftp");
928           debugLog.printRTAriDebug (fn, "Connecting....");
929       sftp.connect();
930       InputStream is = new ByteArrayInputStream(stringOfData.getBytes());
931           debugLog.printRTAriDebug (fn, "Sending stringOfData --> "+fullPathDest);
932       sftp.put(is, fullPathDest, ChannelSftp.OVERWRITE);
933           debugLog.printRTAriDebug (fn, "Sent successfully");
934       sftpSession.disconnect();
935     }
936     catch (Exception e)
937     {
938           debugLog.printRTAriDebug (fn, "Caught an Exception, e="+e);
939       // dbLog.storeData("ErrorMsg= sftp threw an Exception. error is:"+e);
940             throw new IOException(e.toString());
941     }
942   }
943
944   public String sftpGet(String fullFilePathName) throws IOException
945   {
946     String fn = "SshJcraftWrapper.Sftp";
947     try
948     {
949       Session sftpSession = jsch.getSession(userName, hostName, 22);
950             UserInfo ui = new MyUserInfo();
951             sftpSession.setPassword(passWord);
952             sftpSession.setUserInfo(ui);
953             sftpSession.connect(30*1000);
954           debugLog.printRTAriDebug (fn, "Opening up an sftp channel....");
955       ChannelSftp sftp=(ChannelSftp)sftpSession.openChannel("sftp");
956           debugLog.printRTAriDebug (fn, "Connecting....");
957       sftp.connect();
958       InputStream in = null;
959       in = sftp.get(fullFilePathName);
960       String sftpFileString = readInputStreamAsString(in);
961           debugLog.printRTAriDebug (fn, "Retreived successfully");
962           // debugLog.printRTAriDebug (fn, "sftpFileString="+sftpFileString);
963       sftpSession.disconnect();
964       return(sftpFileString);
965     }
966     catch (Exception e)
967     {
968           debugLog.printRTAriDebug (fn, "Caught an Exception, e="+e);
969       // dbLog.storeData("ErrorMsg= sftp threw an Exception. error is:"+e);
970             throw new IOException(e.toString());
971     }
972   }
973
974   public static String readInputStreamAsString(InputStream in) throws IOException
975   {
976     BufferedInputStream bis = new BufferedInputStream(in);
977     ByteArrayOutputStream buf = new ByteArrayOutputStream();
978     int result = bis.read();
979     while(result != -1)
980     {
981       byte b = (byte)result;
982       buf.write(b);
983       result = bis.read();
984     }
985     return buf.toString();
986   }
987
988
989   public void logMemoryUsage()
990   {
991     String fn = "SshJcraftWrapper.logMemoryUsage";
992     int mb = 1024*1024;
993         long usedMemory;
994         long maxMemoryAdvailable;
995         long  memoryLetfOnHeap;
996         maxMemoryAdvailable = (runtime.maxMemory() / mb);
997     usedMemory = ((runtime.totalMemory()/mb) - (runtime.freeMemory()/mb));
998     memoryLetfOnHeap = maxMemoryAdvailable - usedMemory;
999     DebugLog.printAriDebug(fn, "maxMemoryAdvailable="+maxMemoryAdvailable +" usedMemory="+usedMemory +" memoryLetfOnHeap="+memoryLetfOnHeap);
1000   }
1001
1002   // ----------------------------------------------------------------------------
1003   // ----------------------------------------------------------------------------
1004   // ----------------------------------------------------------------------------
1005   // ----------------------------------------------------------------------------
1006
1007
1008        // User specifies the port number, and the subsystem
1009     public void connect (String hostname, String username, String password, String prompt, int timeOut, int portNum, String subsystem) throws IOException
1010     {
1011         String fn = "SshJcraftWrapper.connect";
1012
1013         debugLog.printRTAriDebug (fn, ":::Attempting to connect to "+hostname +" username="+username +" password="+password + " prompt='"+prompt +"' timeOut="+timeOut +" portNum="+portNum +" subsystem="+subsystem);
1014         RouterName = hostname;
1015         jsch = new JSch();
1016         try
1017         {
1018             session = jsch.getSession(username, hostname, portNum);
1019             UserInfo ui = new MyUserInfo();
1020             session.setPassword(password);
1021             session.setUserInfo(ui);
1022       session.setConfig("StrictHostKeyChecking", "no");
1023             session.connect(timeOut);
1024             session.setServerAliveCountMax(0); // If this is not set to '0', then socket timeout on all reads will not work!!!!
1025             channel = session.openChannel("subsystem");
1026       ((ChannelSubsystem)channel).setSubsystem(subsystem);
1027       // ((ChannelSubsystem)channel).setPtyType("vt102");
1028       ((ChannelSubsystem)channel).setPty(true);
1029
1030             inputStream = channel.getInputStream();
1031             dis = new DataInputStream(inputStream);
1032             reader = new BufferedReader(new InputStreamReader(dis), BUFFER_SIZE);
1033             channel.connect();
1034             debugLog.printRTAriDebug (fn, "Successfully connected.");
1035             debugLog.printRTAriDebug (fn, "Five second sleep....");
1036       try { Thread.sleep(5000); } catch (java.lang.InterruptedException ee) { boolean ignore = true; }
1037         }
1038         catch (Exception e)
1039         {
1040             debugLog.printRTAriDebug (fn, "Caught an Exception. e="+e);
1041             throw new IOException(e.toString());
1042         }
1043     }
1044
1045      public void connect (String hostName, String username, String password, int portNumber) throws IOException
1046     {
1047         String fn = "SshJcraftWrapper.connect";
1048         jsch = new JSch();
1049         debugLog.printRTAriDebug (fn, "::Attempting to connect to "+hostName +" username="+username +" password="+password +" portNumber="+portNumber);
1050         debugLog.printRTAriDebug (fn, "Trace C");
1051         RouterName = hostName;
1052     this.hostName = hostName;
1053     userName = username;
1054     passWord = password;
1055         try
1056         {
1057       java.util.Properties config = new java.util.Properties();
1058       config.put("StrictHostKeyChecking", "no");
1059             session = jsch.getSession(username, hostName, 22);
1060             // session = jsch.getSession(username, hostName, portNumber);
1061             UserInfo ui = new MyUserInfo();
1062       session.setConfig(config);
1063             session.setPassword(password);
1064             session.setUserInfo(ui);
1065             session.connect(30000);
1066             channel = session.openChannel("shell");
1067             session.setServerAliveCountMax(0); // If this is not set to '0', then socket timeout on all reads will not work!!!!
1068             ((ChannelShell)channel).setPtyType("vt102");
1069             inputStream = channel.getInputStream();
1070             dis = new DataInputStream(inputStream);
1071             reader = new BufferedReader(new InputStreamReader(dis), BUFFER_SIZE);
1072             channel.connect();
1073             debugLog.printRTAriDebug (fn, "::Successfully connected.");
1074       debugLog.printRTAriDebug (fn, "::Flushing input buffer");
1075       try
1076       {
1077         receiveUntil(":~#", 9000, "No cmd was sent, just waiting, but we can stop on a '~#'");
1078       }
1079       catch (Exception e)
1080       {
1081         debugLog.printRTAriDebug (fn, "Caught an Exception::: Nothing to flush out.");
1082       }
1083
1084         }
1085         catch (Exception e)
1086         {
1087             debugLog.printRTAriDebug (fn, "Caught an Exception. e="+e);
1088       // dbLog.storeData("ErrorMsg= Exception trying to connect to "+hostName +" "+e);
1089             throw new IOException(e.toString());
1090         }
1091     }
1092
1093
1094   public void put(String sourcePath, String destDirectory) throws IOException
1095   {
1096     String fn = "SshJcraftWrapper.sftp";
1097     try
1098     {
1099       Session sftpSession = jsch.getSession(userName, hostName, 22);
1100             UserInfo ui = new MyUserInfo();
1101             sftpSession.setPassword(passWord);
1102             sftpSession.setUserInfo(ui);
1103             sftpSession.connect(30*1000);
1104           debugLog.printRTAriDebug (fn, "Opening up an sftp channel....");
1105       ChannelSftp sftp=(ChannelSftp)sftpSession.openChannel("sftp");
1106           debugLog.printRTAriDebug (fn, "Connecting....");
1107       sftp.connect();
1108           debugLog.printRTAriDebug (fn, "Sending "+sourcePath +" --> "+destDirectory);
1109       sftp.put(sourcePath, destDirectory, ChannelSftp.OVERWRITE);
1110           debugLog.printRTAriDebug (fn, "Sent successfully");
1111       sftpSession.disconnect();
1112     }
1113     catch (Exception e)
1114     {
1115           debugLog.printRTAriDebug (fn, "Caught an Exception, e="+e);
1116       // dbLog.storeData("ErrorMsg= sftp threw an Exception. error is:"+e);
1117             throw new IOException(e.toString());
1118     }
1119   }
1120
1121   public void put(InputStream is, String fullPathDest, String hostName, String userName, String passWord) throws IOException
1122   {
1123     String fn = "SshJcraftWrapper.put";
1124     Session sftpSession = null;
1125     try
1126     {
1127           debugLog.printRTAriDebug (fn, "userName="+userName +" hostName="+hostName +" passWord="+passWord);
1128           jsch = new JSch();
1129       java.util.Properties config = new java.util.Properties();
1130       config.put("StrictHostKeyChecking", "no");
1131       sftpSession = jsch.getSession(userName, hostName, 22);
1132             UserInfo ui = new MyUserInfo();
1133             sftpSession.setPassword(passWord);
1134             sftpSession.setUserInfo(ui);
1135       sftpSession.setConfig(config);
1136             sftpSession.connect(30*1000);
1137           debugLog.printRTAriDebug (fn, "Opening up an sftp channel....");
1138       ChannelSftp sftp=(ChannelSftp)sftpSession.openChannel("sftp");
1139           debugLog.printRTAriDebug (fn, "Connecting....");
1140       sftp.connect();
1141       String oldFiles = fullPathDest +"*";
1142           debugLog.printRTAriDebug (fn, "Deleting old files --> "+oldFiles);
1143           try{
1144               sftp.rm(oldFiles);
1145               debugLog.printRTAriDebug (fn, "Sending stringOfData --> "+fullPathDest);
1146          }
1147          catch(SftpException sft){
1148              String exp = "No such file";
1149              if(sft.getMessage()!=null && sft.getMessage().contains(exp))
1150                  debugLog.printRTAriDebug (fn, "No files found -- Continue");
1151              else{
1152                  debugLog.printRTAriDebug (fn, "Exception while sftp.rm " + sft.getMessage());
1153                  sft.printStackTrace();
1154                   throw sft;
1155              }
1156          }
1157       sftp.put(is, fullPathDest, ChannelSftp.OVERWRITE);
1158           debugLog.printRTAriDebug (fn, "Sent successfully");
1159       sftpSession.disconnect();
1160       sftpSession = null;
1161     }
1162     catch (Exception e)
1163     {
1164           debugLog.printRTAriDebug (fn, "Caught an Exception, e="+e);
1165       sftpSession.disconnect();
1166       sftpSession = null;
1167       // dbLog.storeData("ErrorMsg= sftp threw an Exception. error is:"+e);
1168             throw new IOException(e.toString());
1169     }
1170   }
1171
1172
1173   public String get(String fullFilePathName, String hostName, String userName, String passWord) throws IOException
1174   {
1175     String fn = "SshJcraftWrapper.get";
1176     Session sftpSession = null;
1177     try
1178     {
1179           debugLog.printRTAriDebug (fn, "userName="+userName +" hostName="+hostName +" passWord="+passWord);
1180           jsch = new JSch();
1181       sftpSession = jsch.getSession(userName, hostName, 22);
1182       java.util.Properties config = new java.util.Properties();
1183       config.put("StrictHostKeyChecking", "no");
1184             UserInfo ui = new MyUserInfo();
1185             sftpSession.setPassword(passWord);
1186             sftpSession.setUserInfo(ui);
1187       sftpSession.setConfig(config);
1188             sftpSession.connect(30*1000);
1189           debugLog.printRTAriDebug (fn, "Opening up an sftp channel....");
1190       ChannelSftp sftp=(ChannelSftp)sftpSession.openChannel("sftp");
1191           debugLog.printRTAriDebug (fn, "Connecting....");
1192       sftp.connect();
1193       InputStream in = null;
1194       in = sftp.get(fullFilePathName);
1195       String sftpFileString = readInputStreamAsString(in);
1196           debugLog.printRTAriDebug (fn, "Retreived successfully");
1197           // debugLog.printRTAriDebug (fn, "sftpFileString="+sftpFileString);
1198       sftpSession.disconnect();
1199       sftpSession = null;
1200       return(sftpFileString);
1201     }
1202     catch (Exception e)
1203     {
1204           debugLog.printRTAriDebug (fn, "Caught an Exception, e="+e);
1205       sftpSession.disconnect();
1206       sftpSession = null;
1207       // dbLog.storeData("ErrorMsg= sftp threw an Exception. error is:"+e);
1208             throw new IOException(e.toString());
1209     }
1210   }
1211
1212   public String send(String cmd, String delimiter) throws IOException
1213     {
1214         String fn = "SshJcraftWrapper.send";
1215         OutputStream out = channel.getOutputStream();
1216         DataOutputStream dos = new DataOutputStream(out);
1217
1218         if ((cmd.charAt(cmd.length() - 1) != '\n') && (cmd.charAt(cmd.length() - 1) != '\r'))
1219             cmd += "\n";
1220     int length = cmd.length();
1221     int i = -1;
1222     int nchars = 300000;
1223     int ncharsTotalSent = 0;
1224     int ncharsSent = 0;
1225
1226         debugLog.printRTAriDebug (fn, "Length of cmd is:" +length); // 2,937,706
1227         debugLog.printRTAriDebug (fn, "Length of cmd is:" +length); // 2,937,706
1228         try
1229         {
1230       if (length > 600000)
1231       {
1232         int timeout = 9000;
1233         for (i=0; i<length; i+=nchars)
1234         {
1235           String Cmd = cmd.substring(i, Math.min(length, i + nchars));
1236           ncharsSent = Cmd.length();
1237           ncharsTotalSent = ncharsTotalSent + Cmd.length();
1238                 debugLog.printRTAriDebug (fn, "i="+i +" Sending Cmd: ncharsSent="+ncharsSent);
1239                 dos.writeBytes(Cmd);
1240               dos.flush();
1241           try
1242           {
1243                   debugLog.printRTAriDebug (fn, ":::i="+i +" length="+length);
1244             if (ncharsSent < length)
1245                  receiveUntilBufferFlush (ncharsSent, timeout, "buffer flush  i="+i);
1246             else
1247             {
1248                     debugLog.printRTAriDebug (fn, "i="+i +" No Waiting this time....");
1249                     dos.flush();
1250             }
1251           }
1252               catch (Exception e)
1253               {
1254                   debugLog.printRTAriDebug (fn, "Caught an Exception: Nothing to flush out.");
1255           }
1256         }
1257       }
1258       else
1259       {
1260             debugLog.printRTAriDebug (fn, "Before executing the dos.writeBytes");
1261               dos.writeBytes(cmd);
1262       }
1263           dos.flush();
1264       // Now lets get the response.
1265       String response = receiveUntil (delimiter, 300000, cmd);
1266             debugLog.printRTAriDebug (fn, "Leaving method");
1267       return(response);
1268         }
1269         catch (IOException e)
1270         {
1271             debugLog.printRTAriDebug (fn, "Caught an IOException. e="+e);
1272             throw new IOException(e.toString());
1273         }
1274     }
1275
1276
1277 }