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