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