X-Git-Url: https://gerrit.onap.org/r/gitweb?a=blobdiff_plain;f=appc-config%2Fappc-config-adaptor%2Fprovider%2Fsrc%2Fmain%2Fjava%2Forg%2Fonap%2Fappc%2Fccadaptor%2FConfigComponentAdaptor.java;h=e0cbc798455b3ad9da45d5685771917bb78a5c08;hb=ee2eb7f226eb6e4faf6aa020acf379cbd2e2b254;hp=d70f6d5698baa599c0d49db8b636bde84cb40fdc;hpb=331a0c05382516535755f179a29ced7a4924139d;p=appc.git diff --git a/appc-config/appc-config-adaptor/provider/src/main/java/org/onap/appc/ccadaptor/ConfigComponentAdaptor.java b/appc-config/appc-config-adaptor/provider/src/main/java/org/onap/appc/ccadaptor/ConfigComponentAdaptor.java index d70f6d569..e0cbc7984 100644 --- a/appc-config/appc-config-adaptor/provider/src/main/java/org/onap/appc/ccadaptor/ConfigComponentAdaptor.java +++ b/appc-config/appc-config-adaptor/provider/src/main/java/org/onap/appc/ccadaptor/ConfigComponentAdaptor.java @@ -1,60 +1,122 @@ /*- * ============LICENSE_START======================================================= - * ONAP : APP-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property.All rights reserved. + * ONAP : APPC * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ============================================================================= + * Modifications Copyright (C) 2018-2019 IBM. + * ============================================================================= + * Modifications Copyright (C) 2018-2019 Ericsson + * ============================================================================= * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. + * * ============LICENSE_END========================================================= */ package org.onap.appc.ccadaptor; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.sun.jersey.api.client.Client; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.WebResource; -import com.sun.jersey.core.util.Base64; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; +import java.io.StringReader; +import java.io.StringWriter; import java.net.HttpURLConnection; -import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; import java.util.NoSuchElementException; import java.util.Properties; import java.util.StringTokenizer; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathConstants; +import javax.xml.xpath.XPathExpressionException; +import javax.xml.xpath.XPathFactory; +import org.onap.appc.exceptions.APPCException; import org.onap.ccsdk.sli.core.sli.SvcLogicAdaptor; import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.w3c.dom.Document; +import org.w3c.dom.Node; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.glassfish.jersey.oauth1.signature.Base64; +import org.glassfish.jersey.client.ClientConfig; +import org.glassfish.jersey.client.ClientProperties; + +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.Entity; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.Response; public class ConfigComponentAdaptor implements SvcLogicAdaptor { - private static final EELFLogger log = EELFManager.getInstance().getLogger(ConfigComponentAdaptor.class); - private static final DebugLog debugLog = new DebugLog(Paths.get(DebugLog.LOG_FILE)); + private static EELFLogger log = EELFManager.getInstance().getLogger(ConfigComponentAdaptor.class); + DebugLog debugLog = new DebugLog(); + private String configUrl = null; + private String configUser = null; + private String configPassword = null; + private String auditUrl = null; + private String auditUser = null; + private String auditPassword = null; + + public String getConfigUrl() { + return configUrl; + } + + public String getConfigUser() { + return configUser; + } + + public String getConfigPassword() { + return configPassword; + } + + public String getAuditUrl() { + return auditUrl; + } + + public String getAuditUser() { + return auditUser; + } + + public String getAuditPassword() { + return auditPassword; + } + + public String getConfigCallbackUrl() { + return configCallbackUrl; + } + + public String getAuditCallbackUrl() { + return auditCallbackUrl; + } - private String configUrl; - private String configUser; - private String configPassword; - private String auditUrl; - private String auditUser; - private String auditPassword; - private String configCallbackUrl; - private String auditCallbackUrl; + private String configCallbackUrl = null; + private String auditCallbackUrl = null; + private int DEFAULT_TIMEOUT_GETRUNNING_CLI = 120 * 1000 ; public ConfigComponentAdaptor(Properties props) { if (props != null) { @@ -66,7 +128,16 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor { auditPassword = props.getProperty("auditComponent.passwd", ""); configCallbackUrl = props.getProperty("service-configuration-notification-url", ""); auditCallbackUrl = props.getProperty("audit-configuration-notification-url", ""); - } + } else { + configUrl = ""; + configUser = ""; + configPassword = ""; + auditUrl = ""; + auditUser = ""; + auditPassword = ""; + configCallbackUrl = ""; + auditCallbackUrl = ""; + } } @Override @@ -75,12 +146,12 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor { HttpResponse r = new HttpResponse(); r.code = 200; log.debug("ConfigComponentAdaptor.configure - key = " + key); - debugLog.printRTAriDebug(fnName, "key = " + key); + DebugLog.printRTAriDebug(fnName, "key = " + key); log.debug("Parameters:"); - debugLog.printRTAriDebug(fnName, "Parameters:"); - for (String parmName : parameters.keySet()) { - log.debug(" " + parmName + " = " + parameters.get(parmName)); - debugLog.printRTAriDebug(fnName, " " + parmName + " = " + parameters.get(parmName)); + DebugLog.printRTAriDebug(fnName, "Parameters:"); + for (Map.Entry entry : parameters.entrySet()) { + log.debug(" " + entry.getKey() + " = " + entry.getValue()); + DebugLog.printRTAriDebug(fnName, " " + entry.getKey() + " = " + entry.getValue()); } String parmval = parameters.get("config-component-configUrl"); @@ -91,7 +162,7 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor { parmval = parameters.get("config-component-configPassword"); if ((parmval != null) && (parmval.length() > 0)) { - log.debug("Overwriting configPassword with " + parmval); + //log.debug("Overwriting configPassword with " + parmval); configPassword = parmval; } @@ -104,7 +175,7 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor { String action = parameters.get("action"); String chg = ctx.getAttribute( - "service-data.vnf-config-parameters-list.vnf-config-parameters[0].update-configuration[0].block-key-name"); + "service-data.vnf-config-parameters-list.vnf-config-parameters[0].update-configuration[0].block-key-name"); if (chg != null && "prepare".equalsIgnoreCase(action)) { return prepare(ctx, "CHANGE", "change"); } @@ -113,7 +184,7 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor { } String scale = ctx.getAttribute( - "service-data.vnf-config-parameters-list.vnf-config-parameters[0].scale-configuration[0].network-type"); + "service-data.vnf-config-parameters-list.vnf-config-parameters[0].scale-configuration[0].network-type"); if (scale != null && "prepare".equalsIgnoreCase(action)) { return prepare(ctx, "CHANGE", "scale"); } @@ -144,51 +215,53 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor { return audit(ctx, "RUNNING"); } - if ((key.equals("put")) || (key.equals("get"))) { + if (("put".equals(key)) || ("get".equals(key))) { String loginId = parameters.get("loginId"); String host = parameters.get("host"); String password = parameters.get("password"); password = EncryptionTool.getInstance().decrypt(password); String fullPathFileName = parameters.get("fullPathFileName"); String data = null; - if (key.equals("put")) { - data = parameters.get("data"); - } - SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper(); + SshJcraftWrapper sshJcraftWrapper = getSshJcraftWrapper(); log.debug("SCP: SshJcraftWrapper has been instantiated"); - debugLog.printRTAriDebug(fnName, "SCP: SshJcraftWrapper has been instantiated"); + DebugLog.printRTAriDebug(fnName, "SCP: SshJcraftWrapper has been instantiated"); try { if (key.equals("put")) { - debugLog.printRTAriDebug(fnName, "Command is for put: Length of data is: " + data.length()); - InputStream is = new ByteArrayInputStream(data.getBytes()); - log.debug("SCP: Doing a put: fullPathFileName=" + fullPathFileName); - debugLog.printRTAriDebug(fnName, "SCP: Doing a put: fullPathFileName=" + fullPathFileName); - sshJcraftWrapper.put(is, fullPathFileName, host, loginId, password); - try { - debugLog.printRTAriDebug(fnName, "Sleeping for 180 seconds...."); - Thread.sleep(1000 * 180); - debugLog.printRTAriDebug(fnName, "Woke up...."); - } catch (java.lang.InterruptedException ee) { - boolean ignore = true; + data = parameters.get("data"); + if (data != null) { + DebugLog.printRTAriDebug(fnName, "Command is for put: Length of data is: " + data.length()); + InputStream is = new ByteArrayInputStream(data.getBytes()); + log.debug("SCP: Doing a put: fullPathFileName=" + fullPathFileName); + DebugLog.printRTAriDebug(fnName, "SCP: Doing a put: fullPathFileName=" + fullPathFileName); + sshJcraftWrapper.put(is, fullPathFileName, host, loginId, password); + try { + DebugLog.printRTAriDebug(fnName, "Sleeping for 180 seconds...."); + Thread.sleep(1000l * 180); + DebugLog.printRTAriDebug(fnName, "Woke up...."); + } catch (java.lang.InterruptedException ee) { + boolean ignore = true; + Thread.currentThread().interrupt(); + } + } else { + r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; + log.debug(fnName + " Command is for put: data is null"); } - } else // Must be a get + } else // Must be a get { log.debug("SCP: Doing a get: fullPathFileName=" + fullPathFileName); - debugLog.printRTAriDebug(fnName, "SCP: Doing a get: fullPathFileName=" + fullPathFileName); + DebugLog.printRTAriDebug(fnName, "SCP: Doing a get: fullPathFileName=" + fullPathFileName); String response = sshJcraftWrapper.get(fullPathFileName, host, loginId, password); - debugLog.printRTAriDebug(fnName, "Got the response and putting into the ctx object"); + DebugLog.printRTAriDebug(fnName, "Got the response and putting into the ctx object"); ctx.setAttribute("fileContents", response); log.debug("SCP: Closing the SFTP connection"); } - sshJcraftWrapper = null; return (setResponseStatus(ctx, r)); } catch (IOException e) { - debugLog.printRTAriDebug(fnName, "Caught a IOException e=" + e); + DebugLog.printAriDebug(fnName, "Caught a IOException e=" + e); log.debug(fnName + " : Caught a IOException e=" + e); r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; r.message = e.getMessage(); - sshJcraftWrapper = null; return (setResponseStatus(ctx, r)); } } @@ -197,42 +270,41 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor { String host = parameters.get("host"); String password = parameters.get("password"); password = EncryptionTool.getInstance().decrypt(password); - String cliCommand = parameters.get("cli"); String portNumber = parameters.get("portNumber"); - SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper(); + SshJcraftWrapper sshJcraftWrapper = getSshJcraftWrapper(); try { - log.debug("CLI: Attempting to login: host=" + host + " loginId=" + loginId + " password=" + password + - " portNumber=" + portNumber); - debugLog.printRTAriDebug(fnName, "CLI: Attempting to login: host=" + host + " loginId=" + loginId + - " password=" + password + " portNumber=" + portNumber); + log.debug("CLI: Attempting to login: host=" + host + " loginId=" + loginId + + " portNumber=" + portNumber); + DebugLog.printRTAriDebug(fnName, "CLI: Attempting to login: host=" + host + " loginId=" + loginId + + " portNumber=" + portNumber); sshJcraftWrapper.connect(host, loginId, password, Integer.parseInt(portNumber)); - debugLog.printRTAriDebug(fnName, "Sending 'sdc'"); + DebugLog.printAriDebug(fnName, "Sending 'sdc'"); String response = sshJcraftWrapper.send("sdc", ":"); - debugLog.printRTAriDebug(fnName, "Sending 1"); + DebugLog.printAriDebug(fnName, "Sending 1"); response = sshJcraftWrapper.send("1", ":"); - debugLog.printRTAriDebug(fnName, "Sending 1, the second time"); + DebugLog.printAriDebug(fnName, "Sending 1, the second time"); response = sshJcraftWrapper.send("1", "#"); - debugLog.printRTAriDebug(fnName, "Sending paging-options disable"); + DebugLog.printAriDebug(fnName, "Sending paging-options disable"); response = sshJcraftWrapper.send("paging-options disable", "#"); - debugLog.printRTAriDebug(fnName, "Sending show config"); + DebugLog.printAriDebug(fnName, "Sending show config"); response = sshJcraftWrapper.send("show config", "#"); - debugLog.printRTAriDebug(fnName, "response is now:'" + response + "'"); - debugLog.printRTAriDebug(fnName, "Populating the ctx object with the response"); + DebugLog.printAriDebug(fnName, "response is now:'" + response + "'"); + DebugLog.printAriDebug(fnName, "Populating the ctx object with the response"); ctx.setAttribute("cliOutput", response); sshJcraftWrapper.closeConnection(); r.code = 200; sshJcraftWrapper = null; return (setResponseStatus(ctx, r)); } catch (IOException e) { - debugLog.printRTAriDebug(fnName, "Caught a IOException e=" + e); + DebugLog.printAriDebug(fnName, "Caught a IOException e=" + e); log.debug(fnName + " : Caught a IOException e=" + e); sshJcraftWrapper.closeConnection(); r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; r.message = e.getMessage(); sshJcraftWrapper = null; - debugLog.printRTAriDebug(fnName, "Returning error message"); + DebugLog.printAriDebug(fnName, "Returning error message"); return (setResponseStatus(ctx, r)); } } @@ -244,60 +316,66 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor { return (setResponseStatus(ctx, r)); } if (key.equals("GetCliRunningConfig")) { - debugLog.printRTAriDebug(fnName, "key was: GetCliRunningConfig: "); + DebugLog.printRTAriDebug(fnName, "key was: GetCliRunningConfig: "); log.debug("key was: GetCliRunningConfig: "); - String User_name = parameters.get("User_name"); - String Host_ip_address = parameters.get("Host_ip_address"); - String Password = parameters.get("Password"); - Password = EncryptionTool.getInstance().decrypt(Password); - String Port_number = parameters.get("Port_number"); - String Get_config_template = parameters.get("Get_config_template"); - SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper(); + String userName = parameters.get("User_name"); + String hostIpAddress = parameters.get("Host_ip_address"); + String password = parameters.get("Password"); + password = EncryptionTool.getInstance().decrypt(password); + String portNumber = parameters.get("Port_number"); + String getConfigTemplate = parameters.get("Get_config_template"); + SshJcraftWrapper sshJcraftWrapper = getSshJcraftWrapper(); log.debug("GetCliRunningConfig: sshJcraftWrapper was instantiated"); - debugLog.printRTAriDebug(fnName, "GetCliRunningConfig: sshJcraftWrapper was instantiated"); + DebugLog.printRTAriDebug(fnName, "GetCliRunningConfig: sshJcraftWrapper was instantiated"); try { - debugLog.printRTAriDebug(fnName, - "GetCliRunningConfig: User_name=" + User_name + " Host_ip_address=" + Host_ip_address + " Password=" - + Password + " Port_number=" + Port_number); - log.debug("GetCliRunningConfig: Attempting to login: Host_ip_address=" + Host_ip_address + " User_name=" - + User_name + " Password=" + Password + " Port_number=" + Port_number); - StringBuffer sb = new StringBuffer(); + DebugLog.printAriDebug(fnName, "GetCliRunningConfig: User_name=" + userName + + " Host_ip_address=" + hostIpAddress + " Port_number=" + + portNumber); + log.debug("GetCliRunningConfig: Attempting to login: Host_ip_address=" + hostIpAddress + + " User_name=" + userName + " Port_number=" + portNumber); String response = ""; String CliResponse = ""; boolean showConfigFlag = false; - sshJcraftWrapper - .connect(Host_ip_address, User_name, Password, "", 30000, Integer.parseInt(Port_number)); - debugLog.printRTAriDebug(fnName, "GetCliRunningConfig: On the VNF device"); - StringTokenizer st = new StringTokenizer(Get_config_template, "\n"); + sshJcraftWrapper.connect(hostIpAddress, + userName, + password, + "", + 30000, + Integer.parseInt(portNumber)); + DebugLog.printAriDebug(fnName, "GetCliRunningConfig: On the VNF device"); + StringTokenizer st = new StringTokenizer(getConfigTemplate, "\n"); String command = null; try { while (st.hasMoreTokens()) { String line = st.nextToken(); - debugLog.printRTAriDebug(fnName, "line=" + line); + DebugLog.printAriDebug(fnName, "line=" + line); if (line.indexOf("Request:") != -1) { - debugLog.printRTAriDebug(fnName, "Found a Request line: line=" + line); + DebugLog.printAriDebug(fnName, "Found a Request line: line=" + line); command = getStringBetweenQuotes(line); - debugLog.printRTAriDebug(fnName, "Sending command=" + command); + DebugLog.printAriDebug(fnName, "Sending command=" + command); sshJcraftWrapper.send(command); - debugLog.printRTAriDebug(fnName, "command has been sent"); + DebugLog.printAriDebug(fnName, "command has been sent"); if (line.indexOf("show config") != -1) { showConfigFlag = true; - debugLog.printRTAriDebug(fnName, "GetCliRunningConfig: setting 'showConfigFlag' to true"); + DebugLog.printAriDebug(fnName, "GetCliRunningConfig: setting 'showConfigFlag' to true"); log.debug("GetCliRunningConfig: GetCliRunningConfig: setting 'showConfigFlag' to true"); } } if (line.indexOf("Response: Ends_With") != -1) { - debugLog.printRTAriDebug(fnName, "Found a Response line: line=" + line); + DebugLog.printAriDebug(fnName, "Found a Response line: line=" + line); String delemeter = getStringBetweenQuotes(line); - debugLog.printRTAriDebug(fnName, "The delemeter=" + delemeter); - String tmpResponse = sshJcraftWrapper.receiveUntil(delemeter, 120 * 1000, command); + DebugLog.printAriDebug(fnName, "The delemeter=" + delemeter); + //DEFAULT_TIMEOUT_GETRUNNING_CLI : changed the default time out to 2 mins in 1806 + String tmpResponse = sshJcraftWrapper.receiveUntil(delemeter, + DEFAULT_TIMEOUT_GETRUNNING_CLI, command); response += tmpResponse; if (showConfigFlag) { showConfigFlag = false; StringTokenizer st2 = new StringTokenizer(tmpResponse, "\n"); + // Strip off the last line which is the command prompt from the VNF device. while (st2.hasMoreTokens()) { String line2 = st2.nextToken(); - if (line2.indexOf("#") == -1) { + if (line2.indexOf('#') == -1) { CliResponse += line2 + "\n"; } } @@ -305,44 +383,48 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor { } } } catch (NoSuchElementException e) { - debugLog.printRTAriDebug(fnName, "Caught a NoSuchElementException: e=" + e); + DebugLog.printAriDebug(fnName, "Caught a NoSuchElementException: e=" + e); } - debugLog.printRTAriDebug(fnName, "CliResponse=\n" + CliResponse); + DebugLog.printAriDebug(fnName, "CliResponse=\n" + CliResponse); ctx.setAttribute("cliOutput", CliResponse); sshJcraftWrapper.closeConnection(); r.code = 200; sshJcraftWrapper = null; return (setResponseStatus(ctx, r)); } catch (IOException e) { - debugLog.printRTAriDebug(fnName, "GetCliRunningConfig: Caught a IOException e=" + e); + DebugLog.printAriDebug(fnName, "GetCliRunningConfig: Caught a IOException e=" + e); log.debug(fnName + " : GetCliRunningConfig: Caught a IOException e=" + e); sshJcraftWrapper.closeConnection(); r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; r.message = e.getMessage(); sshJcraftWrapper = null; - debugLog.printRTAriDebug(fnName, "GetCliRunningConfig: Returning error message"); + DebugLog.printAriDebug(fnName, "GetCliRunningConfig: Returning error message"); return (setResponseStatus(ctx, r)); } } if (key.equals("xml-download")) { - log(fnName, "key was: xml-download"); - String User_name = parameters.get("User_name"); - String Host_ip_address = parameters.get("Host_ip_address"); - String Password = parameters.get("Password"); - Password = EncryptionTool.getInstance().decrypt(Password); - String Port_number = parameters.get("Port_number"); + log(fnName, "key was: xml-download"); + String userName = parameters.get("User_name"); + String hostIpAddress = parameters.get("Host_ip_address"); + String password = parameters.get("Password"); + password = EncryptionTool.getInstance().decrypt(password); + String portNumber = parameters.get("Port_number"); String Contents = parameters.get("Contents"); - String netconfHelloCmd = "\n \n \n urn:ietf:params:netconf:base:1.0\n urn:com:ericsson:ebase:1.1.0 \n "; - String terminateConnectionCmd = "\n \n \n \n ]]>]]>"; - String commitCmd = "\n \n ]]>]]>"; + String netconfHelloCmd = "\n \n \n urn:ietf:params:netconf:base:1.0\n urn:com:ericsson:ebase:1.1.0 \n "; + String terminateConnectionCmd = "\n \n \n \n ]]>]]>"; + String commitCmd = "\n \n ]]>]]>"; log(fnName, - "xml-download: User_name=" + User_name + " Host_ip_address=" + Host_ip_address + " Password=" + Password - + " Port_number=" + Port_number); - SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper(); + "xml-download: User_name=" + userName + " Host_ip_address=" + hostIpAddress + + " Port_number=" + portNumber); + SshJcraftWrapper sshJcraftWrapper = getSshJcraftWrapper(); try { - sshJcraftWrapper - .connect(Host_ip_address, User_name, Password, "]]>]]>", 30000, Integer.parseInt(Port_number), + sshJcraftWrapper.connect(hostIpAddress, + userName, + password, + "]]>]]>", + 30000, + Integer.parseInt(portNumber), "netconf"); String NetconfHelloCmd = netconfHelloCmd; NetconfHelloCmd = NetconfHelloCmd + "]]>]]>"; @@ -354,32 +436,32 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor { String messageId = "1"; messageId = "\"" + messageId + "\""; String loadConfigurationString = - " merge " - + xmlCmd + " "; + " merge " + + xmlCmd + " "; loadConfigurationString = loadConfigurationString + "]]>]]>"; sshJcraftWrapper.send(loadConfigurationString); - debugLog.printRTAriDebug(fnName, ":After sending loadConfigurationString"); + DebugLog.printAriDebug(fnName, ":After sending loadConfigurationString"); response = sshJcraftWrapper.receiveUntil("", 600000, ""); if (response.indexOf("rpc-error") != -1) { - debugLog.printRTAriDebug(fnName, "Error from device: Response from device had 'rpc-error'"); - debugLog.printRTAriDebug(fnName, "response=\n" + response + "\n"); + DebugLog.printAriDebug(fnName, "Error from device: Response from device had 'rpc-error'"); + DebugLog.printAriDebug(fnName, "response=\n" + response + "\n"); r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; r.message = response; } else { - debugLog.printRTAriDebug(fnName, ":LoadConfiguration was a success, sending commit cmd"); + DebugLog.printAriDebug(fnName, ":LoadConfiguration was a success, sending commit cmd"); sshJcraftWrapper.send(commitCmd); - debugLog.printRTAriDebug(fnName, ":After sending commitCmd"); + DebugLog.printAriDebug(fnName, ":After sending commitCmd"); response = sshJcraftWrapper.receiveUntil("", 180000, ""); if (response.indexOf("rpc-error") != -1) { - debugLog.printRTAriDebug(fnName, "Error from device: Response from device had 'rpc-error'"); - debugLog.printRTAriDebug(fnName, "response=\n" + response + "\n"); + DebugLog.printAriDebug(fnName, "Error from device: Response from device had 'rpc-error'"); + DebugLog.printAriDebug(fnName, "response=\n" + response + "\n"); r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; r.message = response; } else { - debugLog.printRTAriDebug(fnName, ":Looks like a success"); - debugLog.printRTAriDebug(fnName, "response=\n" + response + "\n"); + DebugLog.printAriDebug(fnName, ":Looks like a success"); + DebugLog.printAriDebug(fnName, "response=\n" + response + "\n"); r.code = 200; } } @@ -389,7 +471,7 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor { return (setResponseStatus(ctx, r)); } catch (Exception e) { log(fnName, "Caught an Exception, e=" + e); - debugLog.outputStackTrace(e); + log(fnName, "StackTrace=" + DebugLog.getStackTraceString(e)); sshJcraftWrapper.closeConnection(); r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; r.message = e.getMessage(); @@ -400,23 +482,27 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor { } if (key.equals("xml-getrunningconfig")) { log(fnName, "key was: : xml-getrunningconfig"); - String xmlGetRunningConfigCmd = " \n"; - String Host_ip_address = parameters.get("Host_ip_address"); - String User_name = parameters.get("User_name"); - String Password = parameters.get("Password"); - Password = EncryptionTool.getInstance().decrypt(Password); - String Port_number = parameters.get("Port_number"); + String xmlGetRunningConfigCmd = " \n"; + String hostIpAddress = parameters.get("Host_ip_address"); + String userName = parameters.get("User_name"); + String password = parameters.get("Password"); + password = EncryptionTool.getInstance().decrypt(password); + String portNumber = parameters.get("Port_number"); String Protocol = parameters.get("Protocol"); - String netconfHelloCmd = "\n \n \n urn:ietf:params:netconf:base:1.0\n urn:com:ericsson:ebase:1.1.0 \n "; - String terminateConnectionCmd = "\n \n \n \n ]]>]]>"; + String netconfHelloCmd = "\n \n \n urn:ietf:params:netconf:base:1.0\n urn:com:ericsson:ebase:1.1.0 \n "; + String terminateConnectionCmd = "\n \n \n \n ]]>]]>"; log(fnName, - "xml-getrunningconfig: User_name=" + User_name + " Host_ip_address=" + Host_ip_address + " Password=" - + Password + " Port_number=" + Port_number); - SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper(); + "xml-getrunningconfig: User_name=" + userName + " Host_ip_address=" + hostIpAddress + + " Port_number=" + portNumber); + SshJcraftWrapper sshJcraftWrapper = getSshJcraftWrapper(); try { String NetconfHelloCmd = netconfHelloCmd; - sshJcraftWrapper - .connect(Host_ip_address, User_name, Password, "]]>]]>", 30000, Integer.parseInt(Port_number), + sshJcraftWrapper.connect(hostIpAddress, + userName, + password, + "]]>]]>", + 30000, + Integer.parseInt(portNumber), "netconf"); NetconfHelloCmd = NetconfHelloCmd + "]]>]]>"; log(fnName, ":Sending the hello command"); @@ -425,7 +511,7 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor { log(fnName, "Sending get running config command"); sshJcraftWrapper.send(xmlGetRunningConfigCmd + "]]>]]>\n"); response = sshJcraftWrapper.receiveUntil("", 180000, ""); - debugLog.printRTAriDebug(fnName, "Response from getRunningconfigCmd=" + response); + DebugLog.printAriDebug(fnName, "Response from getRunningconfigCmd=" + response); response = trimResponse(response); ctx.setAttribute("xmlRunningConfigOutput", response); sshJcraftWrapper.send(terminateConnectionCmd); @@ -435,7 +521,7 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor { return (setResponseStatus(ctx, r)); } catch (Exception e) { log(fnName, "Caught an Exception, e=" + e); - debugLog.outputStackTrace(e); + log(fnName, "StackTrace=" + DebugLog.getStackTraceString(e)); sshJcraftWrapper.closeConnection(); r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; r.message = e.getMessage(); @@ -445,100 +531,102 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor { } } if (key.equals("DownloadCliConfig")) { - debugLog.printRTAriDebug(fnName, "key was: DownloadCliConfig: "); + DebugLog.printRTAriDebug(fnName, "key was: DownloadCliConfig: "); log.debug("key was: DownloadCliConfig: "); - String User_name = parameters.get("User_name"); - String Host_ip_address = parameters.get("Host_ip_address"); - String Password = parameters.get("Password"); - Password = EncryptionTool.getInstance().decrypt(Password); - String Port_number = parameters.get("Port_number"); - String Download_config_template = parameters.get("Download_config_template"); + String userName = parameters.get("User_name"); + String hostIpAddress = parameters.get("Host_ip_address"); + String password = parameters.get("Password"); + password = EncryptionTool.getInstance().decrypt(password); + String portNumber = parameters.get("Port_number"); + String downloadConfigTemplate = parameters.get("Download_config_template"); String Config_contents = parameters.get("Config_contents"); - debugLog.printRTAriDebug(fnName, "Contents of the 'Config_contents' are: " + Config_contents); - SshJcraftWrapper sshJcraftWrapper = new SshJcraftWrapper(); + DebugLog.printAriDebug(fnName, "Contents of the 'Config_contents' are: " + Config_contents); + SshJcraftWrapper sshJcraftWrapper = getSshJcraftWrapper(); log.debug("DownloadCliConfig: sshJcraftWrapper was instantiated"); - debugLog.printRTAriDebug(fnName, "DownloadCliConfig: sshJcraftWrapper was instantiated"); + DebugLog.printRTAriDebug(fnName, "DownloadCliConfig: sshJcraftWrapper was instantiated"); int timeout = 4 * 60 * 1000; try { - debugLog.printRTAriDebug(fnName, - "DownloadCliConfig: User_name=" + User_name + " Host_ip_address=" + Host_ip_address + " Password=" - + Password + " Port_number=" + Port_number); - log.debug("DownloadCliConfig: Attempting to login: Host_ip_address=" + Host_ip_address + " User_name=" - + User_name + " Password=" + Password + " Port_number=" + Port_number); - StringBuffer sb = new StringBuffer(); - String response = ""; + DebugLog.printAriDebug(fnName, "DownloadCliConfig: User_name=" + userName + + " Host_ip_address=" + hostIpAddress + " Port_number=" + + portNumber); + log.debug("DownloadCliConfig: Attempting to login: Host_ip_address=" + hostIpAddress + + " User_name=" + userName + " Port_number=" + portNumber); String CliResponse = ""; - sshJcraftWrapper - .connect(Host_ip_address, User_name, Password, "", 30000, Integer.parseInt(Port_number)); - debugLog.printRTAriDebug(fnName, "DownloadCliConfig: On the VNF device"); - StringTokenizer st = new StringTokenizer(Download_config_template, "\n"); + sshJcraftWrapper.connect(hostIpAddress, + userName, + password, + "", + 30000, + Integer.parseInt(portNumber)); + DebugLog.printAriDebug(fnName, "DownloadCliConfig: On the VNF device"); + StringTokenizer st = new StringTokenizer(downloadConfigTemplate, "\n"); String command = null; String executeConfigContentsDelemeter = null; try { while (st.hasMoreTokens()) { String line = st.nextToken(); - debugLog.printRTAriDebug(fnName, "line=" + line); + DebugLog.printAriDebug(fnName, "line=" + line); if (line.indexOf("Request:") != -1) { - debugLog.printRTAriDebug(fnName, "Found a Request line: line=" + line); + DebugLog.printAriDebug(fnName, "Found a Request line: line=" + line); command = getStringBetweenQuotes(line); - debugLog.printRTAriDebug(fnName, "Sending command=" + command); + DebugLog.printAriDebug(fnName, "Sending command=" + command); sshJcraftWrapper.send(command); - debugLog.printRTAriDebug(fnName, "command has been sent"); + DebugLog.printAriDebug(fnName, "command has been sent"); } else if ((line.indexOf("Response: Ends_With") != -1) && ( - line.indexOf("Execute_config_contents Response: Ends_With") == -1)) { - debugLog.printRTAriDebug(fnName, "Found a Response line: line=" + line); + line.indexOf("Execute_config_contents Response: Ends_With") == -1)) { + DebugLog.printAriDebug(fnName, "Found a Response line: line=" + line); String delemeter = getStringBetweenQuotes(line); - debugLog.printRTAriDebug(fnName, "The delemeter=" + delemeter); + DebugLog.printAriDebug(fnName, "The delemeter=" + delemeter); String tmpResponse = sshJcraftWrapper.receiveUntil(delemeter, timeout, command); - response += tmpResponse; CliResponse += tmpResponse; } else if (line.indexOf("Execute_config_contents Response: Ends_With") != -1) { - debugLog.printRTAriDebug(fnName, "Found a 'Execute_config_contents Response:' line=" + line); + DebugLog.printAriDebug(fnName, "Found a 'Execute_config_contents Response:' line=" + line); executeConfigContentsDelemeter = getStringBetweenQuotes(line); - debugLog.printRTAriDebug(fnName, - "executeConfigContentsDelemeter=" + executeConfigContentsDelemeter); + DebugLog.printAriDebug(fnName, + "executeConfigContentsDelemeter=" + executeConfigContentsDelemeter); StringTokenizer st2 = new StringTokenizer(Config_contents, "\n"); while (st2.hasMoreTokens()) { String cmd = st2.nextToken(); - debugLog.printRTAriDebug(fnName, "Config_contents: cmd=" + cmd); + DebugLog.printAriDebug(fnName, "Config_contents: cmd=" + cmd); sshJcraftWrapper.send(cmd); - String tmpResponse = sshJcraftWrapper - .receiveUntil(executeConfigContentsDelemeter, timeout, command); + String tmpResponse = sshJcraftWrapper.receiveUntil(executeConfigContentsDelemeter, + timeout, + command); CliResponse += tmpResponse; } } } } catch (NoSuchElementException e) { - debugLog.printRTAriDebug(fnName, "Caught a NoSuchElementException: e=" + e); + DebugLog.printAriDebug(fnName, "Caught a NoSuchElementException: e=" + e); } sshJcraftWrapper.closeConnection(); sshJcraftWrapper = null; - debugLog.printRTAriDebug(fnName, ":Escaping all the single and double quotes in the response"); + DebugLog.printAriDebug(fnName, ":Escaping all the single and double quotes in the response"); CliResponse = CliResponse.replaceAll("\"", "\\\\\""); CliResponse = CliResponse.replaceAll("\'", "\\\\'"); - debugLog.printRTAriDebug(fnName, "CliResponse=\n" + CliResponse); + DebugLog.printAriDebug(fnName, "CliResponse=\n" + CliResponse); ctx.setAttribute("cliOutput", CliResponse); r.code = 200; return (setResponseStatus(ctx, r)); } catch (IOException e) { - debugLog.printRTAriDebug(fnName, "DownloadCliConfig: Caught a IOException e=" + e); + DebugLog.printAriDebug(fnName, "DownloadCliConfig: Caught a IOException e=" + e); log.debug(fnName + " : DownloadCliConfig: Caught a IOException e=" + e); sshJcraftWrapper.closeConnection(); r.code = HttpURLConnection.HTTP_INTERNAL_ERROR; r.message = e.getMessage(); sshJcraftWrapper = null; - debugLog.printRTAriDebug(fnName, "DownloadCliConfig: Returning error message"); + DebugLog.printAriDebug(fnName, "DownloadCliConfig: Returning error message"); return (setResponseStatus(ctx, r)); } } - debugLog.printRTAriDebug(fnName, "Unsupported action - " + action); + DebugLog.printRTAriDebug(fnName, "Unsupported action - " + action); log.error("Unsupported action - " + action); return ConfigStatus.FAILURE; } private void log(String fileName, String messg) { - debugLog.printRTAriDebug(fileName, messg); + DebugLog.printRTAriDebug(fileName, messg); log.debug(fileName + ": " + messg); } @@ -641,11 +729,11 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor { input = input.replace("\\", "\\\\"); input = input.replace("\'", "\\'"); - return input; + return input; } - private String readFile(String fileName) { + protected String readFile(String fileName) { InputStream is = getClass().getResourceAsStream(fileName); InputStreamReader isr = new InputStreamReader(is); BufferedReader in = new BufferedReader(isr); @@ -749,6 +837,7 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor { String var1 = template.substring(i1 + 2, i2); String value1 = XmlUtil.getXml(mm, var1); if (value1 == null || value1.trim().length() == 0) { + // delete the whole element (line) int i3 = template.lastIndexOf('\n', i1); if (i3 < 0) { i3 = 0; @@ -787,7 +876,7 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor { int i2 = template.indexOf(':', i1 + 9); if (i2 < 0) { throw new RuntimeException( - "Template error: Context variable name followed by : is required after repeat"); + "Template error: Context variable name followed by : is required after repeat"); } // Find the closing }, store in i3 @@ -811,7 +900,7 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor { String var1 = template.substring(i1 + 9, i2); String value1 = ctx.getAttribute(var1); - log.info(" " + var1 + ": " + value1); + log.info(" " + var1 + ": " + value1); int n = 0; try { n = Integer.parseInt(value1); @@ -840,25 +929,31 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor { private HttpResponse sendXmlRequest(String xmlRequest, String url, String user, String password) { try { - Client client = Client.create(); - client.setConnectTimeout(5000); - WebResource webResource = client.resource(url); + Client client = getClient(); + WebTarget webResource = client.target(url); log.info("SENDING..............."); - log.info(xmlRequest); - + if (log.isTraceEnabled()) { + log.trace(xmlRequest); + } + else { + if(xmlRequest.length() > 255 ) { + log.info(xmlRequest.substring(0, 255)); + log.info("\n...\n" + xmlRequest.length() + + " characters in request, turn on TRACE logging to log entire request"); + } + else { + log.info(xmlRequest); + } + } String authString = user + ":" + password; - byte[] authEncBytes = Base64.encode(authString); - String authStringEnc = new String(authEncBytes); + String authStringEnc = Base64.encode(authString.getBytes()); authString = "Basic " + authStringEnc; - ClientResponse response = - webResource.header("Authorization", authString).accept("UTF-8").type("application/xml").post( - ClientResponse.class, xmlRequest); + Response response = getClientResponse(webResource, authString, xmlRequest); int code = response.getStatus(); - String message = null; - + String message = response.getStatusInfo().getReasonPhrase(); log.info("RESPONSE..............."); log.info("HTTP response code: " + code); log.info("HTTP response message: " + message); @@ -882,6 +977,7 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor { private static class HttpResponse { public int code; + public String message; } @@ -894,38 +990,85 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor { private String getStringBetweenQuotes(String string) { String fnName = "ConfigComponentAdaptor.getStringBetweenQuotes"; - debugLog.printRTAriDebug(fnName, "string=" + string); + DebugLog.printAriDebug(fnName, "string=" + string); String retString = null; - int start = string.indexOf("\""); - int end = string.lastIndexOf("\""); + int start = string.indexOf('\"'); + int end = string.lastIndexOf('\"'); retString = string.substring(start + 1, end); - debugLog.printRTAriDebug(fnName, "retString=" + retString); + DebugLog.printAriDebug(fnName, "retString=" + retString); return (retString); } public static String _readFile(String fileName) { StringBuffer strBuff = new StringBuffer(); String line; - try { - BufferedReader in = new BufferedReader(new FileReader(fileName)); + try (BufferedReader in = new BufferedReader(new FileReader(fileName))) { while ((line = in.readLine()) != null) { strBuff.append(line + "\n"); } - in.close(); } catch (IOException e) { System.out.println("Caught an IOException in method readFile(): e=" + e.toString()); } return (strBuff.toString()); } - private String trimResponse(String response) { + /** + * A supporting method to extract the data and configuration element from the NETCONF-XML response + * from the node and create well formatted xml. + * + * @param requestData The unformatted NETCONF-XML + * @return responseBuilder the extracted data + * @throws APPCException Exception during parsing xml data + */ + private String extractFromNetconfXml(String requestData) throws APPCException { + log.debug("extractFromNetconfXml -- Start"); + StringBuilder responseBuilder = new StringBuilder(); + StringWriter stringBuffer = new StringWriter(); + try { + requestData = requestData.replaceAll("]]>]]>", ""); + DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); + Document document = documentBuilder.parse(new InputSource(new StringReader(requestData))); + document.getDocumentElement().normalize(); + XPath xPath = XPathFactory.newInstance().newXPath(); + Node dataNode = (Node) xPath.evaluate("//data", document, XPathConstants.NODE); + Transformer xform = TransformerFactory.newInstance().newTransformer(); + xform.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); + xform.setOutputProperty(OutputKeys.INDENT, "yes"); + xform.transform(new DOMSource(dataNode), new StreamResult(stringBuffer)); + responseBuilder.append(stringBuffer.toString()); + if (log.isTraceEnabled()) { + log.trace("ConfigComponentAdaptor:extractFromNetconfXml after Extract: " + + responseBuilder.toString()); + } + } catch (SAXException | IOException | ParserConfigurationException | TransformerException + | XPathExpressionException exception) { + throw new APPCException("Error Occured during parsing Netconf-XML", exception); + + } + log.debug("extractFromNetconfXml -- End"); + return responseBuilder.toString(); + } + + private String trimResponse(String response) throws APPCException { + response = extractFromNetconfXml(response); + log.debug("runningConfig before trimResponse : " + response); StringTokenizer line = new StringTokenizer(response, "\n"); StringBuffer sb = new StringBuffer(); + String runningConfig = "" ; boolean captureText = false; while (line.hasMoreTokens()) { String token = line.nextToken(); if (token.indexOf("") != -1) { + log.debug("token-line:with in "+token); + captureText = false; } if (captureText) { sb.append(token + "\n"); @@ -934,25 +1077,58 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor { captureText = false; } } - return (sb.toString()); + runningConfig = sb.toString(); + + if (log.isTraceEnabled()) { + log.trace("ConfigComponentAdaptor:RunningConfig after trimResponse : " + runningConfig); + } + else { + if (runningConfig.length() > 255) { + log.info("ConfigComponentAdaptor:RunningConfig after trimResponse : " + + runningConfig.substring(0, 255)); + log.info("\n...\n" + runningConfig.length() + + " characters in config, turn on TRACE logging to log entire config"); + } + else { + log.info("ConfigComponentAdaptor:RunningConfig after trimResponse : " + + runningConfig); + } + } + log.info("ConfigComponentAdaptor:RunningConfig after trimResponse : " + runningConfig); + return runningConfig; } public static void main(String args[]) throws Exception { Properties props = null; System.out.println("*************************Hello*****************************"); ConfigComponentAdaptor cca = new ConfigComponentAdaptor(props); - String Get_config_template = _readFile("/home/userID/data/Get_config_template"); - String Download_config_template = _readFile("/home/userID/data/Download_config_template_2"); + String getConfigTemplate = _readFile("/home/userID/data/Get_config_template"); + String downloadConfigTemplate = _readFile("/home/userID/data/Download_config_template_2"); String key = "GetCliRunningConfig"; Map parameters = new HashMap(); parameters.put("Host_ip_address", "000.00.000.00"); parameters.put("User_name", "root"); parameters.put("Password", "!bootstrap"); parameters.put("Port_number", "22"); - parameters.put("Get_config_template", Get_config_template); + parameters.put("Get_config_template", getConfigTemplate); + SvcLogicContext ctx = null; System.out.println("*************************TRACE 1*****************************"); cca.configure(key, parameters, ctx); } -} \ No newline at end of file + protected SshJcraftWrapper getSshJcraftWrapper() { + return new SshJcraftWrapper(); + } + + protected Client getClient() { + ClientConfig clientConfig = new ClientConfig(); + clientConfig.property(ClientProperties.CONNECT_TIMEOUT, 5000); + return ClientBuilder.newClient(clientConfig); + } + + protected Response getClientResponse(WebTarget webResource, String authString, String xmlRequest) { + return webResource.request("UTF-8").header("Authorization", authString).header("Content-Type", "application/xml").post( + Entity.xml(xmlRequest),Response.class); + } +}