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