Renamed local variable to match the regular expression
[appc.git] / appc-config / appc-config-adaptor / provider / src / main / java / org / onap / appc / ccadaptor / ConfigComponentAdaptor.java
index 0199895..e0cbc79 100644 (file)
 
 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.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 {
 
@@ -124,9 +149,9 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor {
         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));
+        for (Map.Entry<String, String> entry : parameters.entrySet()) {
+            log.debug("        " + entry.getKey() + " = " + entry.getValue());
+            DebugLog.printRTAriDebug(fnName, "        " + entry.getKey() + " = " + entry.getValue());
         }
 
         String parmval = parameters.get("config-component-configUrl");
@@ -137,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;
         }
 
@@ -231,14 +256,12 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor {
                     ctx.setAttribute("fileContents", response);
                     log.debug("SCP: Closing the SFTP connection");
                 }
-                sshJcraftWrapper = null;
                 return (setResponseStatus(ctx, r));
             } catch (IOException 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));
             }
         }
@@ -247,7 +270,6 @@ 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 = getSshJcraftWrapper();
             try {
@@ -296,33 +318,32 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor {
         if (key.equals("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");
+            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");
             try {
-                DebugLog.printAriDebug(fnName, "GetCliRunningConfig: User_name=" + User_name +
-                        " Host_ip_address=" + Host_ip_address + " Port_number="
-                        + Port_number);
-                log.debug("GetCliRunningConfig: Attempting to login: Host_ip_address=" + Host_ip_address +
-                        " User_name=" + User_name + " 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,
+                sshJcraftWrapper.connect(hostIpAddress,
+                        userName,
+                        password,
                         "",
                         30000,
-                        Integer.parseInt(Port_number));
+                        Integer.parseInt(portNumber));
                 DebugLog.printAriDebug(fnName, "GetCliRunningConfig: On the VNF device");
-                StringTokenizer st = new StringTokenizer(Get_config_template, "\n");
+                StringTokenizer st = new StringTokenizer(getConfigTemplate, "\n");
                 String command = null;
                 try {
                     while (st.hasMoreTokens()) {
@@ -354,7 +375,7 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor {
                                 //    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";
                                     }
                                 }
@@ -383,27 +404,27 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor {
         }
         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");
+            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 = "<?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>";
             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 ]]>]]>";
             String commitCmd = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\" message-id=\"1\"> <commit/> </rpc>\n ]]>]]>";
 
             log(fnName,
-                    "xml-download: User_name=" + User_name + " Host_ip_address=" + Host_ip_address
-                    + " Port_number=" + Port_number);
+                    "xml-download: User_name=" + userName + " Host_ip_address=" + hostIpAddress
+                    + " Port_number=" + portNumber);
             SshJcraftWrapper sshJcraftWrapper = getSshJcraftWrapper();
             try {
-                sshJcraftWrapper.connect(Host_ip_address,
-                        User_name,
-                        Password,
+                sshJcraftWrapper.connect(hostIpAddress,
+                        userName,
+                        password,
                         "]]>]]>",
                         30000,
-                        Integer.parseInt(Port_number),
+                        Integer.parseInt(portNumber),
                         "netconf");
                 String NetconfHelloCmd = netconfHelloCmd;
                 NetconfHelloCmd = NetconfHelloCmd + "]]>]]>";
@@ -462,26 +483,26 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor {
         if (key.equals("xml-getrunningconfig")) {
             log(fnName, "key was: : xml-getrunningconfig");
             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";
-            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 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 = "<?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>";
             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 ]]>]]>";
             log(fnName,
-                    "xml-getrunningconfig: User_name=" + User_name + " Host_ip_address=" + Host_ip_address
-                    + " Port_number=" + Port_number);
+                    "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,
+                sshJcraftWrapper.connect(hostIpAddress,
+                        userName,
+                        password,
                         "]]>]]>",
                         30000,
-                        Integer.parseInt(Port_number),
+                        Integer.parseInt(portNumber),
                         "netconf");
                 NetconfHelloCmd = NetconfHelloCmd + "]]>]]>";
                 log(fnName, ":Sending the hello command");
@@ -512,12 +533,12 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor {
         if (key.equals("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.printAriDebug(fnName, "Contents of the 'Config_contents' are: " + Config_contents);
             SshJcraftWrapper sshJcraftWrapper = getSshJcraftWrapper();
@@ -525,22 +546,20 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor {
             DebugLog.printRTAriDebug(fnName, "DownloadCliConfig: sshJcraftWrapper was instantiated");
             int timeout = 4 * 60 * 1000;
             try {
-                DebugLog.printAriDebug(fnName, "DownloadCliConfig: User_name=" + User_name +
-                        " Host_ip_address=" + Host_ip_address + " Port_number="
-                        + Port_number);
-                log.debug("DownloadCliConfig: Attempting to login: Host_ip_address=" + Host_ip_address +
-                        " User_name=" + User_name + " 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,
+                sshJcraftWrapper.connect(hostIpAddress,
+                        userName,
+                        password,
                         "",
                         30000,
-                        Integer.parseInt(Port_number));
+                        Integer.parseInt(portNumber));
                 DebugLog.printAriDebug(fnName, "DownloadCliConfig: On the VNF device");
-                StringTokenizer st = new StringTokenizer(Download_config_template, "\n");
+                StringTokenizer st = new StringTokenizer(downloadConfigTemplate, "\n");
                 String command = null;
                 String executeConfigContentsDelemeter = null;
                 try {
@@ -559,7 +578,6 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor {
                             String delemeter = getStringBetweenQuotes(line);
                             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.printAriDebug(fnName, "Found a 'Execute_config_contents Response:' line=" + line);
@@ -912,8 +930,7 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor {
     private HttpResponse sendXmlRequest(String xmlRequest, String url, String user, String password) {
         try {
             Client client = getClient();
-            client.setConnectTimeout(5000);
-            WebResource webResource = client.resource(url);
+            WebTarget webResource = client.target(url);
 
             log.info("SENDING...............");
             if (log.isTraceEnabled()) {
@@ -930,15 +947,13 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor {
                 }
             }
             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 = getClientResponse(webResource, authString, 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);
@@ -977,8 +992,8 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor {
         String fnName = "ConfigComponentAdaptor.getStringBetweenQuotes";
         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.printAriDebug(fnName, "retString=" + retString);
         return (retString);
@@ -997,7 +1012,45 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor {
         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();
@@ -1007,7 +1060,7 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor {
             String token = line.nextToken();
             if (token.indexOf("<configuration xmlns=") != -1) {
                 captureText = true;
-            }else if(token.indexOf("<data>") != -1) {
+            }else if(token.indexOf("<data") != -1) {
                 log.debug("token-line:with in Data: "+token);
                 captureText = true;
                 continue;
@@ -1049,15 +1102,15 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor {
         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<String, String> 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*****************************");
@@ -1069,11 +1122,13 @@ public class ConfigComponentAdaptor implements SvcLogicAdaptor {
     }
 
     protected Client getClient() {
-        return Client.create();
+        ClientConfig clientConfig = new ClientConfig();
+        clientConfig.property(ClientProperties.CONNECT_TIMEOUT, 5000);
+        return ClientBuilder.newClient(clientConfig);
     }
 
-    protected ClientResponse getClientResponse(WebResource webResource, String authString, String xmlRequest) {
-        return webResource.header("Authorization", authString).accept("UTF-8").type("application/xml").post(
-                ClientResponse.class, xmlRequest);
+    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);
     }
 }