2  * ============LICENSE_START=======================================================
 
   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
 
  11  *     http://www.apache.org/licenses/LICENSE-2.0
 
  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=========================================================
 
  21 package org.onap.appc.ccadaptor;
 
  23 import com.att.eelf.configuration.EELFLogger;
 
  24 import com.att.eelf.configuration.EELFManager;
 
  25 import com.sun.jersey.api.client.Client;
 
  26 import com.sun.jersey.api.client.ClientResponse;
 
  27 import com.sun.jersey.api.client.WebResource;
 
  28 import com.sun.jersey.core.util.Base64;
 
  29 import java.io.BufferedReader;
 
  30 import java.io.ByteArrayInputStream;
 
  31 import java.io.FileReader;
 
  32 import java.io.IOException;
 
  33 import java.io.InputStream;
 
  34 import java.io.InputStreamReader;
 
  35 import java.net.HttpURLConnection;
 
  36 import java.nio.file.Paths;
 
  37 import java.util.HashMap;
 
  39 import java.util.NoSuchElementException;
 
  40 import java.util.Properties;
 
  41 import java.util.StringTokenizer;
 
  42 import org.onap.ccsdk.sli.core.sli.SvcLogicAdaptor;
 
  43 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
 
  45 public class ConfigComponentAdaptor implements SvcLogicAdaptor {
 
  47     private static final EELFLogger log = EELFManager.getInstance().getLogger(ConfigComponentAdaptor.class);
 
  48     private static final DebugLog debugLog = new DebugLog(Paths.get(DebugLog.LOG_FILE));
 
  50     private String configUrl;
 
  51     private String configUser;
 
  52     private String configPassword;
 
  53     private String auditUrl;
 
  54     private String auditUser;
 
  55     private String auditPassword;
 
  56     private String configCallbackUrl;
 
  57     private String auditCallbackUrl;
 
  59     public ConfigComponentAdaptor(Properties props) {
 
  61             configUrl = props.getProperty("configComponent.url", "");
 
  62             configUser = props.getProperty("configComponent.user", "");
 
  63             configPassword = props.getProperty("configComponent.passwd", "");
 
  64             auditUrl = props.getProperty("auditComponent.url", "");
 
  65             auditUser = props.getProperty("auditComponent.user", "");
 
  66             auditPassword = props.getProperty("auditComponent.passwd", "");
 
  67             configCallbackUrl = props.getProperty("service-configuration-notification-url", "");
 
  68             auditCallbackUrl = props.getProperty("audit-configuration-notification-url", "");
 
  73     public ConfigStatus configure(String key, Map<String, String> parameters, SvcLogicContext ctx) {
 
  74         String fnName = "ConfigComponentAdaptor.configure";
 
  75         HttpResponse r = new HttpResponse();
 
  77         log.debug("ConfigComponentAdaptor.configure - key = " + key);
 
  78         debugLog.printRTAriDebug(fnName, "key = " + key);
 
  79         log.debug("Parameters:");
 
  80         debugLog.printRTAriDebug(fnName, "Parameters:");
 
  81         for (String parmName : parameters.keySet()) {
 
  82             log.debug("    " + parmName + " = " + parameters.get(parmName));
 
  83             debugLog.printRTAriDebug(fnName, "    " + parmName + " = " + parameters.get(parmName));
 
  86         String parmval = parameters.get("config-component-configUrl");
 
  87         if ((parmval != null) && (parmval.length() > 0)) {
 
  88             log.debug("Overwriting URL with " + parmval);
 
  92         parmval = parameters.get("config-component-configPassword");
 
  93         if ((parmval != null) && (parmval.length() > 0)) {
 
  94             log.debug("Overwriting configPassword with " + parmval);
 
  95             configPassword = parmval;
 
  98         parmval = parameters.get("config-component-configUser");
 
  99         if ((parmval != null) && (parmval.length() > 0)) {
 
 100             log.debug("Overwriting configUser id with " + parmval);
 
 101             configUser = parmval;
 
 104         String action = parameters.get("action");
 
 106         String chg = ctx.getAttribute(
 
 107             "service-data.vnf-config-parameters-list.vnf-config-parameters[0].update-configuration[0].block-key-name");
 
 108         if (chg != null && "prepare".equalsIgnoreCase(action)) {
 
 109             return prepare(ctx, "CHANGE", "change");
 
 111         if (chg != null && "activate".equalsIgnoreCase(action)) {
 
 112             return activate(ctx, true);
 
 115         String scale = ctx.getAttribute(
 
 116             "service-data.vnf-config-parameters-list.vnf-config-parameters[0].scale-configuration[0].network-type");
 
 117         if (scale != null && "prepare".equalsIgnoreCase(action)) {
 
 118             return prepare(ctx, "CHANGE", "scale");
 
 120         if (scale != null && "activate".equalsIgnoreCase(action)) {
 
 121             return activate(ctx, true);
 
 124         if ("prepare".equalsIgnoreCase(action)) {
 
 125             return prepare(ctx, "BASE", "create");
 
 127         if ("activate".equalsIgnoreCase(action)) {
 
 128             return activate(ctx, false);
 
 131         if ("backup".equalsIgnoreCase(action)) {
 
 132             return prepare(ctx, "BACKUP", "backup");
 
 134         if ("restorebackup".equalsIgnoreCase(action)) {
 
 135             return prepare(ctx, "RESTOREBACKUP", "restorebackup");
 
 137         if ("deletebackup".equalsIgnoreCase(action)) {
 
 138             return prepare(ctx, "DELETEBACKUP", "deletebackup");
 
 140         if ("audit".equalsIgnoreCase(action)) {
 
 141             return audit(ctx, "FULL");
 
 143         if ("getrunningconfig".equalsIgnoreCase(action)) {
 
 144             return audit(ctx, "RUNNING");
 
 147         if ((key.equals("put")) || (key.equals("get"))) {
 
 148             String loginId = parameters.get("loginId");
 
 149             String host = parameters.get("host");
 
 150             String password = parameters.get("password");
 
 151             password = EncryptionTool.getInstance().decrypt(password);
 
 152             String fullPathFileName = parameters.get("fullPathFileName");
 
 154             if (key.equals("put")) {
 
 155                 data = parameters.get("data");
 
 158             SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
 
 159             log.debug("SCP: SshJcraftWrapper has been instantiated");
 
 160             debugLog.printRTAriDebug(fnName, "SCP: SshJcraftWrapper has been instantiated");
 
 162                 if (key.equals("put")) {
 
 163                     debugLog.printRTAriDebug(fnName, "Command is for put: Length of data is: " + data.length());
 
 164                     InputStream is = new ByteArrayInputStream(data.getBytes());
 
 165                     log.debug("SCP: Doing a put: fullPathFileName=" + fullPathFileName);
 
 166                     debugLog.printRTAriDebug(fnName, "SCP: Doing a put: fullPathFileName=" + fullPathFileName);
 
 167                     sshJcraftWrapper.put(is, fullPathFileName, host, loginId, password);
 
 169                         debugLog.printRTAriDebug(fnName, "Sleeping for 180 seconds....");
 
 170                         Thread.sleep(1000 * 180);
 
 171                         debugLog.printRTAriDebug(fnName, "Woke up....");
 
 172                     } catch (java.lang.InterruptedException ee) {
 
 173                         boolean ignore = true;
 
 175                 } else   // Must be a get
 
 177                     log.debug("SCP: Doing a get: fullPathFileName=" + fullPathFileName);
 
 178                     debugLog.printRTAriDebug(fnName, "SCP: Doing a get: fullPathFileName=" + fullPathFileName);
 
 179                     String response = sshJcraftWrapper.get(fullPathFileName, host, loginId, password);
 
 180                     debugLog.printRTAriDebug(fnName, "Got the response and putting into the ctx object");
 
 181                     ctx.setAttribute("fileContents", response);
 
 182                     log.debug("SCP: Closing the SFTP connection");
 
 184                 sshJcraftWrapper = null;
 
 185                 return (setResponseStatus(ctx, r));
 
 186             } catch (IOException e) {
 
 187                 debugLog.printRTAriDebug(fnName, "Caught a IOException e=" + e);
 
 188                 log.debug(fnName + " : Caught a IOException e=" + e);
 
 189                 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
 
 190                 r.message = e.getMessage();
 
 191                 sshJcraftWrapper = null;
 
 192                 return (setResponseStatus(ctx, r));
 
 195         if (key.equals("cli")) {
 
 196             String loginId = parameters.get("loginId");
 
 197             String host = parameters.get("host");
 
 198             String password = parameters.get("password");
 
 199             password = EncryptionTool.getInstance().decrypt(password);
 
 200             String cliCommand = parameters.get("cli");
 
 201             String portNumber = parameters.get("portNumber");
 
 202             SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
 
 204                 log.debug("CLI: Attempting to login: host=" + host + " loginId=" + loginId + " password=" + password +
 
 205                     " portNumber=" + portNumber);
 
 206                 debugLog.printRTAriDebug(fnName, "CLI: Attempting to login: host=" + host + " loginId=" + loginId +
 
 207                     " password=" + password + " portNumber=" + portNumber);
 
 208                 sshJcraftWrapper.connect(host, loginId, password, Integer.parseInt(portNumber));
 
 210                 debugLog.printRTAriDebug(fnName, "Sending 'sdc'");
 
 211                 String response = sshJcraftWrapper.send("sdc", ":");
 
 212                 debugLog.printRTAriDebug(fnName, "Sending 1");
 
 213                 response = sshJcraftWrapper.send("1", ":");
 
 214                 debugLog.printRTAriDebug(fnName, "Sending 1, the second time");
 
 215                 response = sshJcraftWrapper.send("1", "#");
 
 216                 debugLog.printRTAriDebug(fnName, "Sending paging-options disable");
 
 217                 response = sshJcraftWrapper.send("paging-options disable", "#");
 
 218                 debugLog.printRTAriDebug(fnName, "Sending show config");
 
 219                 response = sshJcraftWrapper.send("show config", "#");
 
 221                 debugLog.printRTAriDebug(fnName, "response is now:'" + response + "'");
 
 222                 debugLog.printRTAriDebug(fnName, "Populating the ctx object with the response");
 
 223                 ctx.setAttribute("cliOutput", response);
 
 224                 sshJcraftWrapper.closeConnection();
 
 226                 sshJcraftWrapper = null;
 
 227                 return (setResponseStatus(ctx, r));
 
 228             } catch (IOException e) {
 
 229                 debugLog.printRTAriDebug(fnName, "Caught a IOException e=" + e);
 
 230                 log.debug(fnName + " : Caught a IOException e=" + e);
 
 231                 sshJcraftWrapper.closeConnection();
 
 232                 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
 
 233                 r.message = e.getMessage();
 
 234                 sshJcraftWrapper = null;
 
 235                 debugLog.printRTAriDebug(fnName, "Returning error message");
 
 236                 return (setResponseStatus(ctx, r));
 
 239         if (key.equals("escapeSql")) {
 
 240             String data = parameters.get("artifactContents");
 
 241             log.debug("ConfigComponentAdaptor.configure - escapeSql");
 
 242             data = escapeMySql(data);
 
 243             ctx.setAttribute("escapedData", data);
 
 244             return (setResponseStatus(ctx, r));
 
 246         if (key.equals("GetCliRunningConfig")) {
 
 247             debugLog.printRTAriDebug(fnName, "key was: GetCliRunningConfig: ");
 
 248             log.debug("key was: GetCliRunningConfig: ");
 
 249             String User_name = parameters.get("User_name");
 
 250             String Host_ip_address = parameters.get("Host_ip_address");
 
 251             String Password = parameters.get("Password");
 
 252             Password = EncryptionTool.getInstance().decrypt(Password);
 
 253             String Port_number = parameters.get("Port_number");
 
 254             String Get_config_template = parameters.get("Get_config_template");
 
 255             SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
 
 256             log.debug("GetCliRunningConfig: sshJcraftWrapper was instantiated");
 
 257             debugLog.printRTAriDebug(fnName, "GetCliRunningConfig: sshJcraftWrapper was instantiated");
 
 259                 debugLog.printRTAriDebug(fnName,
 
 260                     "GetCliRunningConfig: User_name=" + User_name + " Host_ip_address=" + Host_ip_address + " Password="
 
 261                         + Password + " Port_number=" + Port_number);
 
 262                 log.debug("GetCliRunningConfig: Attempting to login: Host_ip_address=" + Host_ip_address + " User_name="
 
 263                     + User_name + " Password=" + Password + " Port_number=" + Port_number);
 
 264                 StringBuffer sb = new StringBuffer();
 
 265                 String response = "";
 
 266                 String CliResponse = "";
 
 267                 boolean showConfigFlag = false;
 
 269                     .connect(Host_ip_address, User_name, Password, "", 30000, Integer.parseInt(Port_number));
 
 270                 debugLog.printRTAriDebug(fnName, "GetCliRunningConfig: On the VNF device");
 
 271                 StringTokenizer st = new StringTokenizer(Get_config_template, "\n");
 
 272                 String command = null;
 
 274                     while (st.hasMoreTokens()) {
 
 275                         String line = st.nextToken();
 
 276                         debugLog.printRTAriDebug(fnName, "line=" + line);
 
 277                         if (line.indexOf("Request:") != -1) {
 
 278                             debugLog.printRTAriDebug(fnName, "Found a Request line: line=" + line);
 
 279                             command = getStringBetweenQuotes(line);
 
 280                             debugLog.printRTAriDebug(fnName, "Sending command=" + command);
 
 281                             sshJcraftWrapper.send(command);
 
 282                             debugLog.printRTAriDebug(fnName, "command has been sent");
 
 283                             if (line.indexOf("show config") != -1) {
 
 284                                 showConfigFlag = true;
 
 285                                 debugLog.printRTAriDebug(fnName, "GetCliRunningConfig: setting 'showConfigFlag' to true");
 
 286                                 log.debug("GetCliRunningConfig: GetCliRunningConfig: setting 'showConfigFlag' to true");
 
 289                         if (line.indexOf("Response: Ends_With") != -1) {
 
 290                             debugLog.printRTAriDebug(fnName, "Found a Response line: line=" + line);
 
 291                             String delemeter = getStringBetweenQuotes(line);
 
 292                             debugLog.printRTAriDebug(fnName, "The delemeter=" + delemeter);
 
 293                             String tmpResponse = sshJcraftWrapper.receiveUntil(delemeter, 120 * 1000, command);
 
 294                             response += tmpResponse;
 
 295                             if (showConfigFlag) {
 
 296                                 showConfigFlag = false;
 
 297                                 StringTokenizer st2 = new StringTokenizer(tmpResponse, "\n");
 
 298                                 while (st2.hasMoreTokens()) {
 
 299                                     String line2 = st2.nextToken();
 
 300                                     if (line2.indexOf("#") == -1) {
 
 301                                         CliResponse += line2 + "\n";
 
 307                 } catch (NoSuchElementException e) {
 
 308                     debugLog.printRTAriDebug(fnName, "Caught a NoSuchElementException: e=" + e);
 
 310                 debugLog.printRTAriDebug(fnName, "CliResponse=\n" + CliResponse);
 
 311                 ctx.setAttribute("cliOutput", CliResponse);
 
 312                 sshJcraftWrapper.closeConnection();
 
 314                 sshJcraftWrapper = null;
 
 315                 return (setResponseStatus(ctx, r));
 
 316             } catch (IOException e) {
 
 317                 debugLog.printRTAriDebug(fnName, "GetCliRunningConfig: Caught a IOException e=" + e);
 
 318                 log.debug(fnName + " : GetCliRunningConfig: Caught a IOException e=" + e);
 
 319                 sshJcraftWrapper.closeConnection();
 
 320                 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
 
 321                 r.message = e.getMessage();
 
 322                 sshJcraftWrapper = null;
 
 323                 debugLog.printRTAriDebug(fnName, "GetCliRunningConfig: Returning error message");
 
 324                 return (setResponseStatus(ctx, r));
 
 327         if (key.equals("xml-download")) {
 
 328             log(fnName, "key was:  xml-download");
 
 329             String User_name = parameters.get("User_name");
 
 330             String Host_ip_address = parameters.get("Host_ip_address");
 
 331             String Password = parameters.get("Password");
 
 332             Password = EncryptionTool.getInstance().decrypt(Password);
 
 333             String Port_number = parameters.get("Port_number");
 
 334             String Contents = parameters.get("Contents");
 
 335             String netconfHelloCmd = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <hello xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n  <capabilities>\n   <capability>urn:ietf:params:netconf:base:1.0</capability>\n  <capability>urn:com:ericsson:ebase:1.1.0</capability> </capabilities>\n </hello>";
 
 336             String terminateConnectionCmd = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n  <rpc message-id=\"terminateConnection\" xmlns:netconf=\"urn:ietf:params:xml:ns:netconf:base:1.0\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n <close-session/> \n </rpc>\n ]]>]]>";
 
 337             String commitCmd = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <rpc> <commit/> </rpc>\n ]]>]]>";
 
 340                 "xml-download: User_name=" + User_name + " Host_ip_address=" + Host_ip_address + " Password=" + Password
 
 341                     + " Port_number=" + Port_number);
 
 342             SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
 
 345                     .connect(Host_ip_address, User_name, Password, "]]>]]>", 30000, Integer.parseInt(Port_number),
 
 347                 String NetconfHelloCmd = netconfHelloCmd;
 
 348                 NetconfHelloCmd = NetconfHelloCmd + "]]>]]>";
 
 349                 log(fnName, "Sending the hello command");
 
 350                 sshJcraftWrapper.send(NetconfHelloCmd);
 
 351                 String response = sshJcraftWrapper.receiveUntil("]]>]]>", 10000, "");
 
 352                 log(fnName, "Sending xmlCmd cmd");
 
 353                 String xmlCmd = Contents;
 
 354                 String messageId = "1";
 
 355                 messageId = "\"" + messageId + "\"";
 
 356                 String loadConfigurationString =
 
 357                     "<?xml version=\"1.0\" encoding=\"UTF-8\"?> <rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\" message-id="
 
 359                         + "> <edit-config> <target> <candidate /> </target> <default-operation>merge</default-operation> <config xmlns:xc=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
 
 360                         + xmlCmd + "</config> </edit-config> </rpc>";
 
 361                 loadConfigurationString = loadConfigurationString + "]]>]]>";
 
 362                 sshJcraftWrapper.send(loadConfigurationString);
 
 363                 debugLog.printRTAriDebug(fnName, ":After sending loadConfigurationString");
 
 364                 response = sshJcraftWrapper.receiveUntil("</rpc-reply>", 600000, "");
 
 365                 if (response.indexOf("rpc-error") != -1) {
 
 366                     debugLog.printRTAriDebug(fnName, "Error from device: Response from device had 'rpc-error'");
 
 367                     debugLog.printRTAriDebug(fnName, "response=\n" + response + "\n");
 
 368                     r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
 
 369                     r.message = response;
 
 371                     debugLog.printRTAriDebug(fnName, ":LoadConfiguration was a success, sending commit cmd");
 
 372                     sshJcraftWrapper.send(commitCmd);
 
 373                     debugLog.printRTAriDebug(fnName, ":After sending commitCmd");
 
 374                     response = sshJcraftWrapper.receiveUntil("</rpc-reply>", 180000, "");
 
 375                     if (response.indexOf("rpc-error") != -1) {
 
 376                         debugLog.printRTAriDebug(fnName, "Error from device: Response from device had 'rpc-error'");
 
 377                         debugLog.printRTAriDebug(fnName, "response=\n" + response + "\n");
 
 378                         r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
 
 379                         r.message = response;
 
 381                         debugLog.printRTAriDebug(fnName, ":Looks like a success");
 
 382                         debugLog.printRTAriDebug(fnName, "response=\n" + response + "\n");
 
 386                 sshJcraftWrapper.send(terminateConnectionCmd);
 
 387                 sshJcraftWrapper.closeConnection();
 
 388                 sshJcraftWrapper = null;
 
 389                 return (setResponseStatus(ctx, r));
 
 390             } catch (Exception e) {
 
 391                 log(fnName, "Caught an Exception, e=" + e);
 
 392                 debugLog.outputStackTrace(e);
 
 393                 sshJcraftWrapper.closeConnection();
 
 394                 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
 
 395                 r.message = e.getMessage();
 
 396                 sshJcraftWrapper = null;
 
 397                 log(fnName, "Returning error message");
 
 398                 return (setResponseStatus(ctx, r));
 
 401         if (key.equals("xml-getrunningconfig")) {
 
 402             log(fnName, "key was: : xml-getrunningconfig");
 
 403             String xmlGetRunningConfigCmd = "<?xml version=\"1.0\" encoding=\"UTF-8\"?> <rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\" message-id=\"1\">  <get-config> <source> <running /> </source> </get-config> </rpc>\n";
 
 404             String Host_ip_address = parameters.get("Host_ip_address");
 
 405             String User_name = parameters.get("User_name");
 
 406             String Password = parameters.get("Password");
 
 407             Password = EncryptionTool.getInstance().decrypt(Password);
 
 408             String Port_number = parameters.get("Port_number");
 
 409             String Protocol = parameters.get("Protocol");
 
 410             String netconfHelloCmd = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <hello xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n  <capabilities>\n   <capability>urn:ietf:params:netconf:base:1.0</capability>\n <capability>urn:com:ericsson:ebase:1.1.0</capability> </capabilities>\n </hello>";
 
 411             String terminateConnectionCmd = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n  <rpc message-id=\"terminateConnection\" xmlns:netconf=\"urn:ietf:params:xml:ns:netconf:base:1.0\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n <close-session/> \n </rpc>\n ]]>]]>";
 
 413                 "xml-getrunningconfig: User_name=" + User_name + " Host_ip_address=" + Host_ip_address + " Password="
 
 414                     + Password + " Port_number=" + Port_number);
 
 415             SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
 
 417                 String NetconfHelloCmd = netconfHelloCmd;
 
 419                     .connect(Host_ip_address, User_name, Password, "]]>]]>", 30000, Integer.parseInt(Port_number),
 
 421                 NetconfHelloCmd = NetconfHelloCmd + "]]>]]>";
 
 422                 log(fnName, ":Sending the hello command");
 
 423                 sshJcraftWrapper.send(NetconfHelloCmd);
 
 424                 String response = sshJcraftWrapper.receiveUntil("]]>]]>", 10000, "");
 
 425                 log(fnName, "Sending get running config command");
 
 426                 sshJcraftWrapper.send(xmlGetRunningConfigCmd + "]]>]]>\n");
 
 427                 response = sshJcraftWrapper.receiveUntil("</rpc-reply>", 180000, "");
 
 428                 debugLog.printRTAriDebug(fnName, "Response from getRunningconfigCmd=" + response);
 
 429                 response = trimResponse(response);
 
 430                 ctx.setAttribute("xmlRunningConfigOutput", response);
 
 431                 sshJcraftWrapper.send(terminateConnectionCmd);
 
 432                 sshJcraftWrapper.closeConnection();
 
 434                 sshJcraftWrapper = null;
 
 435                 return (setResponseStatus(ctx, r));
 
 436             } catch (Exception e) {
 
 437                 log(fnName, "Caught an Exception, e=" + e);
 
 438                 debugLog.outputStackTrace(e);
 
 439                 sshJcraftWrapper.closeConnection();
 
 440                 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
 
 441                 r.message = e.getMessage();
 
 442                 sshJcraftWrapper = null;
 
 443                 log(fnName, "Returning error message");
 
 444                 return (setResponseStatus(ctx, r));
 
 447         if (key.equals("DownloadCliConfig")) {
 
 448             debugLog.printRTAriDebug(fnName, "key was: DownloadCliConfig: ");
 
 449             log.debug("key was: DownloadCliConfig: ");
 
 450             String User_name = parameters.get("User_name");
 
 451             String Host_ip_address = parameters.get("Host_ip_address");
 
 452             String Password = parameters.get("Password");
 
 453             Password = EncryptionTool.getInstance().decrypt(Password);
 
 454             String Port_number = parameters.get("Port_number");
 
 455             String Download_config_template = parameters.get("Download_config_template");
 
 456             String Config_contents = parameters.get("Config_contents");
 
 457             debugLog.printRTAriDebug(fnName, "Contents of the 'Config_contents' are: " + Config_contents);
 
 458             SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper();
 
 459             log.debug("DownloadCliConfig: sshJcraftWrapper was instantiated");
 
 460             debugLog.printRTAriDebug(fnName, "DownloadCliConfig: sshJcraftWrapper was instantiated");
 
 461             int timeout = 4 * 60 * 1000;
 
 463                 debugLog.printRTAriDebug(fnName,
 
 464                     "DownloadCliConfig: User_name=" + User_name + " Host_ip_address=" + Host_ip_address + " Password="
 
 465                         + Password + " Port_number=" + Port_number);
 
 466                 log.debug("DownloadCliConfig: Attempting to login: Host_ip_address=" + Host_ip_address + " User_name="
 
 467                     + User_name + " Password=" + Password + " Port_number=" + Port_number);
 
 468                 StringBuffer sb = new StringBuffer();
 
 469                 String response = "";
 
 470                 String CliResponse = "";
 
 472                     .connect(Host_ip_address, User_name, Password, "", 30000, Integer.parseInt(Port_number));
 
 473                 debugLog.printRTAriDebug(fnName, "DownloadCliConfig: On the VNF device");
 
 474                 StringTokenizer st = new StringTokenizer(Download_config_template, "\n");
 
 475                 String command = null;
 
 476                 String executeConfigContentsDelemeter = null;
 
 478                     while (st.hasMoreTokens()) {
 
 479                         String line = st.nextToken();
 
 480                         debugLog.printRTAriDebug(fnName, "line=" + line);
 
 481                         if (line.indexOf("Request:") != -1) {
 
 482                             debugLog.printRTAriDebug(fnName, "Found a Request line: line=" + line);
 
 483                             command = getStringBetweenQuotes(line);
 
 484                             debugLog.printRTAriDebug(fnName, "Sending command=" + command);
 
 485                             sshJcraftWrapper.send(command);
 
 486                             debugLog.printRTAriDebug(fnName, "command has been sent");
 
 487                         } else if ((line.indexOf("Response: Ends_With") != -1) && (
 
 488                             line.indexOf("Execute_config_contents Response: Ends_With") == -1)) {
 
 489                             debugLog.printRTAriDebug(fnName, "Found a Response line: line=" + line);
 
 490                             String delemeter = getStringBetweenQuotes(line);
 
 491                             debugLog.printRTAriDebug(fnName, "The delemeter=" + delemeter);
 
 492                             String tmpResponse = sshJcraftWrapper.receiveUntil(delemeter, timeout, command);
 
 493                             response += tmpResponse;
 
 494                             CliResponse += tmpResponse;
 
 495                         } else if (line.indexOf("Execute_config_contents Response: Ends_With") != -1) {
 
 496                             debugLog.printRTAriDebug(fnName, "Found a 'Execute_config_contents Response:' line=" + line);
 
 497                             executeConfigContentsDelemeter = getStringBetweenQuotes(line);
 
 498                             debugLog.printRTAriDebug(fnName,
 
 499                                 "executeConfigContentsDelemeter=" + executeConfigContentsDelemeter);
 
 500                             StringTokenizer st2 = new StringTokenizer(Config_contents, "\n");
 
 501                             while (st2.hasMoreTokens()) {
 
 502                                 String cmd = st2.nextToken();
 
 503                                 debugLog.printRTAriDebug(fnName, "Config_contents: cmd=" + cmd);
 
 504                                 sshJcraftWrapper.send(cmd);
 
 505                                 String tmpResponse = sshJcraftWrapper
 
 506                                     .receiveUntil(executeConfigContentsDelemeter, timeout, command);
 
 507                                 CliResponse += tmpResponse;
 
 511                 } catch (NoSuchElementException e) {
 
 512                     debugLog.printRTAriDebug(fnName, "Caught a NoSuchElementException: e=" + e);
 
 514                 sshJcraftWrapper.closeConnection();
 
 515                 sshJcraftWrapper = null;
 
 516                 debugLog.printRTAriDebug(fnName, ":Escaping all the single and double quotes in the response");
 
 517                 CliResponse = CliResponse.replaceAll("\"", "\\\\\"");
 
 518                 CliResponse = CliResponse.replaceAll("\'", "\\\\'");
 
 519                 debugLog.printRTAriDebug(fnName, "CliResponse=\n" + CliResponse);
 
 520                 ctx.setAttribute("cliOutput", CliResponse);
 
 522                 return (setResponseStatus(ctx, r));
 
 523             } catch (IOException e) {
 
 524                 debugLog.printRTAriDebug(fnName, "DownloadCliConfig: Caught a IOException e=" + e);
 
 525                 log.debug(fnName + " : DownloadCliConfig: Caught a IOException e=" + e);
 
 526                 sshJcraftWrapper.closeConnection();
 
 527                 r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
 
 528                 r.message = e.getMessage();
 
 529                 sshJcraftWrapper = null;
 
 530                 debugLog.printRTAriDebug(fnName, "DownloadCliConfig: Returning error message");
 
 531                 return (setResponseStatus(ctx, r));
 
 535         debugLog.printRTAriDebug(fnName, "Unsupported action - " + action);
 
 536         log.error("Unsupported action - " + action);
 
 537         return ConfigStatus.FAILURE;
 
 540     private void log(String fileName, String messg) {
 
 541         debugLog.printRTAriDebug(fileName, messg);
 
 542         log.debug(fileName + ": " + messg);
 
 545     private ConfigStatus prepare(SvcLogicContext ctx, String requestType, String operation) {
 
 546         String templateName = requestType.equals("BASE") ? "/config-base.xml" : "/config-data.xml";
 
 547         String ndTemplate = readFile(templateName);
 
 548         String nd = buildNetworkData2(ctx, ndTemplate, operation);
 
 550         String reqTemplate = readFile("/config-request.xml");
 
 551         Map<String, String> param = new HashMap<String, String>();
 
 552         param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id"));
 
 553         param.put("request-type", requestType);
 
 554         param.put("callback-url", configCallbackUrl);
 
 555         if (operation.equals("create") || operation.equals("change") || operation.equals("scale")) {
 
 556             param.put("action", "GenerateOnly");
 
 558         param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id"));
 
 559         param.put("equipment-ip-address", ctx.getAttribute("service-data.vnf-config-information.vnf-host-ip-address"));
 
 560         param.put("vendor", ctx.getAttribute("service-data.vnf-config-information.vendor"));
 
 561         param.put("network-data", nd);
 
 565             req = buildXmlRequest(param, reqTemplate);
 
 566         } catch (Exception e) {
 
 567             log.error("Error building the XML request: ", e);
 
 569             HttpResponse r = new HttpResponse();
 
 570             r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
 
 571             r.message = e.getMessage();
 
 572             return setResponseStatus(ctx, r);
 
 575         HttpResponse r = sendXmlRequest(req, configUrl, configUser, configPassword);
 
 576         return setResponseStatus(ctx, r);
 
 579     private ConfigStatus activate(SvcLogicContext ctx, boolean change) {
 
 580         String reqTemplate = readFile("/config-request.xml");
 
 581         Map<String, String> param = new HashMap<String, String>();
 
 582         param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id"));
 
 583         param.put("callback-url", configCallbackUrl);
 
 584         param.put("action", change ? "DownloadChange" : "DownloadBase");
 
 585         param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id"));
 
 589             req = buildXmlRequest(param, reqTemplate);
 
 590         } catch (Exception e) {
 
 591             log.error("Error building the XML request: ", e);
 
 593             HttpResponse r = new HttpResponse();
 
 594             r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
 
 595             r.message = e.getMessage();
 
 596             return setResponseStatus(ctx, r);
 
 599         HttpResponse r = sendXmlRequest(req, configUrl, configUser, configPassword);
 
 600         return setResponseStatus(ctx, r);
 
 603     private ConfigStatus audit(SvcLogicContext ctx, String auditLevel) {
 
 604         String reqTemplate = readFile("/audit-request.xml");
 
 605         Map<String, String> param = new HashMap<String, String>();
 
 606         param.put("request-id", ctx.getAttribute("service-data.appc-request-header.svc-request-id"));
 
 607         param.put("callback-url", auditCallbackUrl);
 
 608         param.put("equipment-name", ctx.getAttribute("service-data.service-information.service-instance-id"));
 
 609         param.put("audit-level", auditLevel);
 
 613             req = buildXmlRequest(param, reqTemplate);
 
 614         } catch (Exception e) {
 
 615             log.error("Error building the XML request: ", e);
 
 617             HttpResponse r = new HttpResponse();
 
 618             r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
 
 619             r.message = e.getMessage();
 
 620             return setResponseStatus(ctx, r);
 
 623         HttpResponse r = sendXmlRequest(req, auditUrl, auditUser, auditPassword);
 
 624         return setResponseStatus(ctx, r);
 
 628     public ConfigStatus activate(String key, SvcLogicContext ctx) {
 
 629         return ConfigStatus.SUCCESS;
 
 633     public ConfigStatus deactivate(String key, SvcLogicContext ctx) {
 
 634         return ConfigStatus.SUCCESS;
 
 637     private String escapeMySql(String input) {
 
 642         input = input.replace("\\", "\\\\");
 
 643         input = input.replace("\'", "\\'");
 
 648     private String readFile(String fileName) {
 
 649         InputStream is = getClass().getResourceAsStream(fileName);
 
 650         InputStreamReader isr = new InputStreamReader(is);
 
 651         BufferedReader in = new BufferedReader(isr);
 
 652         StringBuilder ss = new StringBuilder();
 
 654             String s = in.readLine();
 
 656                 ss.append(s).append('\n');
 
 659         } catch (IOException e) {
 
 660             System.out.println("Error reading " + fileName + ": " + e.getMessage());
 
 661             throw new RuntimeException("Error reading " + fileName + ": " + e.getMessage(), e);
 
 665             } catch (Exception e) {
 
 666                 log.warn("Could not close BufferedReader", e);
 
 670             } catch (Exception e) {
 
 671                 log.warn("Could not close InputStreamReader", e);
 
 675             } catch (Exception e) {
 
 676                 log.warn("Could not close InputStream", e);
 
 679         return ss.toString();
 
 682     private String buildXmlRequest(Map<String, String> param, String template) {
 
 683         StringBuilder ss = new StringBuilder();
 
 685         while (i < template.length()) {
 
 686             int i1 = template.indexOf("${", i);
 
 688                 ss.append(template.substring(i));
 
 692             int i2 = template.indexOf('}', i1 + 2);
 
 694                 throw new RuntimeException("Template error: Matching } not found");
 
 697             String var1 = template.substring(i1 + 2, i2);
 
 698             String value1 = param.get(var1);
 
 699             if (value1 == null || value1.trim().length() == 0) {
 
 700                 // delete the whole element (line)
 
 701                 int i3 = template.lastIndexOf('\n', i1);
 
 705                 int i4 = template.indexOf('\n', i1);
 
 707                     i4 = template.length();
 
 711                     ss.append(template.substring(i, i3));
 
 715                 ss.append(template.substring(i, i1)).append(value1);
 
 720         return ss.toString();
 
 723     private String buildNetworkData2(SvcLogicContext ctx, String template, String operation) {
 
 724         log.info("Building XML started");
 
 725         long t1 = System.currentTimeMillis();
 
 727         template = expandRepeats(ctx, template, 1);
 
 729         Map<String, String> mm = new HashMap<>();
 
 730         for (String s : ctx.getAttributeKeySet()) {
 
 731             mm.put(s, ctx.getAttribute(s));
 
 733         mm.put("operation", operation);
 
 735         StringBuilder ss = new StringBuilder();
 
 737         while (i < template.length()) {
 
 738             int i1 = template.indexOf("${", i);
 
 740                 ss.append(template.substring(i));
 
 744             int i2 = template.indexOf('}', i1 + 2);
 
 746                 throw new RuntimeException("Template error: Matching } not found");
 
 749             String var1 = template.substring(i1 + 2, i2);
 
 750             String value1 = XmlUtil.getXml(mm, var1);
 
 751             if (value1 == null || value1.trim().length() == 0) {
 
 752                 int i3 = template.lastIndexOf('\n', i1);
 
 756                 int i4 = template.indexOf('\n', i1);
 
 758                     i4 = template.length();
 
 762                     ss.append(template.substring(i, i3));
 
 766                 ss.append(template.substring(i, i1)).append(value1);
 
 771         long t2 = System.currentTimeMillis();
 
 772         log.info("Building XML completed. Time: " + (t2 - t1));
 
 774         return ss.toString();
 
 777     private String expandRepeats(SvcLogicContext ctx, String template, int level) {
 
 778         StringBuilder newTemplate = new StringBuilder();
 
 780         while (k < template.length()) {
 
 781             int i1 = template.indexOf("${repeat:", k);
 
 783                 newTemplate.append(template.substring(k));
 
 787             int i2 = template.indexOf(':', i1 + 9);
 
 789                 throw new RuntimeException(
 
 790                     "Template error: Context variable name followed by : is required after repeat");
 
 793             // Find the closing }, store in i3
 
 797             while (nn > 0 && i < template.length()) {
 
 798                 i3 = template.indexOf('}', i);
 
 800                     throw new RuntimeException("Template error: Matching } not found");
 
 802                 int i32 = template.indexOf('{', i);
 
 803                 if (i32 >= 0 && i32 < i3) {
 
 812             String var1 = template.substring(i1 + 9, i2);
 
 813             String value1 = ctx.getAttribute(var1);
 
 814             log.info("     " + var1 + ": " + value1);
 
 817                 n = Integer.parseInt(value1);
 
 818             } catch (Exception e) {
 
 822             newTemplate.append(template.substring(k, i1));
 
 824             String rpt = template.substring(i2 + 1, i3);
 
 826             for (int ii = 0; ii < n; ii++) {
 
 827                 String ss = rpt.replaceAll("\\[\\$\\{" + level + "\\}\\]", "[" + ii + "]");
 
 828                 newTemplate.append(ss);
 
 835             return newTemplate.toString();
 
 838         return expandRepeats(ctx, newTemplate.toString(), level + 1);
 
 841     private HttpResponse sendXmlRequest(String xmlRequest, String url, String user, String password) {
 
 843             Client client = Client.create();
 
 844             client.setConnectTimeout(5000);
 
 845             WebResource webResource = client.resource(url);
 
 847             log.info("SENDING...............");
 
 848             log.info(xmlRequest);
 
 850             String authString = user + ":" + password;
 
 851             byte[] authEncBytes = Base64.encode(authString);
 
 852             String authStringEnc = new String(authEncBytes);
 
 853             authString = "Basic " + authStringEnc;
 
 855             ClientResponse response =
 
 856                 webResource.header("Authorization", authString).accept("UTF-8").type("application/xml").post(
 
 857                     ClientResponse.class, xmlRequest);
 
 859             int code = response.getStatus();
 
 860             String message = null;
 
 862             log.info("RESPONSE...............");
 
 863             log.info("HTTP response code: " + code);
 
 864             log.info("HTTP response message: " + message);
 
 867             HttpResponse r = new HttpResponse();
 
 872         } catch (Exception e) {
 
 873             log.error("Error sending the request: ", e);
 
 875             HttpResponse r = new HttpResponse();
 
 876             r.code = HttpURLConnection.HTTP_INTERNAL_ERROR;
 
 877             r.message = e.getMessage();
 
 882     private static class HttpResponse {
 
 885         public String message;
 
 888     private ConfigStatus setResponseStatus(SvcLogicContext ctx, HttpResponse r) {
 
 889         ctx.setAttribute("error-code", String.valueOf(r.code));
 
 890         ctx.setAttribute("error-message", r.message);
 
 892         return r.code > 299 ? ConfigStatus.FAILURE : ConfigStatus.SUCCESS;
 
 895     private String getStringBetweenQuotes(String string) {
 
 896         String fnName = "ConfigComponentAdaptor.getStringBetweenQuotes";
 
 897         debugLog.printRTAriDebug(fnName, "string=" + string);
 
 898         String retString = null;
 
 899         int start = string.indexOf("\"");
 
 900         int end = string.lastIndexOf("\"");
 
 901         retString = string.substring(start + 1, end);
 
 902         debugLog.printRTAriDebug(fnName, "retString=" + retString);
 
 906     public static String _readFile(String fileName) {
 
 907         StringBuffer strBuff = new StringBuffer();
 
 910             BufferedReader in = new BufferedReader(new FileReader(fileName));
 
 911             while ((line = in.readLine()) != null) {
 
 912                 strBuff.append(line + "\n");
 
 915         } catch (IOException e) {
 
 916             System.out.println("Caught an IOException in method readFile(): e=" + e.toString());
 
 918         return (strBuff.toString());
 
 921     private String trimResponse(String response) {
 
 922         StringTokenizer line = new StringTokenizer(response, "\n");
 
 923         StringBuffer sb = new StringBuffer();
 
 924         boolean captureText = false;
 
 925         while (line.hasMoreTokens()) {
 
 926             String token = line.nextToken();
 
 927             if (token.indexOf("<configuration xmlns=") != -1) {
 
 931                 sb.append(token + "\n");
 
 933             if (token.indexOf("</configuration>") != -1) {
 
 937         return (sb.toString());
 
 940     public static void main(String args[]) throws Exception {
 
 941         Properties props = null;
 
 942         System.out.println("*************************Hello*****************************");
 
 943         ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props);
 
 944         String Get_config_template = _readFile("/home/userID/data/Get_config_template");
 
 945         String Download_config_template = _readFile("/home/userID/data/Download_config_template_2");
 
 946         String key = "GetCliRunningConfig";
 
 947         Map<String, String> parameters = new HashMap();
 
 948         parameters.put("Host_ip_address", "000.00.000.00");
 
 949         parameters.put("User_name", "root");
 
 950         parameters.put("Password", "!bootstrap");
 
 951         parameters.put("Port_number", "22");
 
 952         parameters.put("Get_config_template", Get_config_template);
 
 953         SvcLogicContext ctx = null;
 
 954         System.out.println("*************************TRACE 1*****************************");
 
 955         cca.configure(key, parameters, ctx);