improved code structure
[appc.git] / appc-config / appc-config-adaptor / provider / src / main / java / org / onap / appc / ccadaptor / ConfigComponentAdaptor.java
index 00df23b..941157b 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 java.io.*;
-import java.net.HttpURLConnection;
-import java.util.*;
+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 {
 
@@ -129,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;
         }
 
@@ -897,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()) {
@@ -915,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);
@@ -982,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();
@@ -992,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;
@@ -1054,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);
     }
 }