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