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