Multiple Sonar Fixes
[holmes/common.git] / holmes-actions / src / main / java / org / onap / holmes / common / aai / AaiQuery4Ccvpn.java
index 42b7bd7..d60a31b 100644 (file)
 
 package org.onap.holmes.common.aai;
 
-
+import com.alibaba.fastjson.JSON;
 import com.alibaba.fastjson.JSONArray;
 import com.alibaba.fastjson.JSONObject;
-import lombok.extern.slf4j.Slf4j;
+import org.glassfish.jersey.client.HttpUrlConnectorProvider;
 import org.onap.holmes.common.aai.config.AaiConfig;
 import org.onap.holmes.common.config.MicroServiceConfig;
 import org.onap.holmes.common.exception.CorrelationException;
@@ -34,53 +34,85 @@ import java.util.Map;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 
-@Slf4j
 public class AaiQuery4Ccvpn {
 
     private MultivaluedMap<String, Object> headers;
 
-    public AaiQuery4Ccvpn() {
+    public static AaiQuery4Ccvpn newInstance() {
+        return new AaiQuery4Ccvpn();
+    }
+
+    private AaiQuery4Ccvpn() {
         headers = new MultivaluedHashMap<>();
         headers.add("X-TransactionId", AaiConfig.X_TRANSACTION_ID);
         headers.add("X-FromAppId", AaiConfig.X_FROMAPP_ID);
         headers.add("Authorization", AaiConfig.getAuthenticationCredentials());
         headers.add("Accept", "application/json");
+        headers.add("Content-Type", "application/json");
     }
 
-    public String getLogicLink(String networkId, String pnfName, String ifName, String status) {
+    /**
+     * Query the logic link information for AAI. This method is based on the API:
+     * https://<AAI host>:<AAI port>/aai/v14/network/network-resources/network-resource/{networkId}/pnfs/pnf/{pnfName}/p-interfaces?interface-name={ifName}&operational-status={status}
+     * provided by AAI.
+     *
+     * @param networkId
+     * @param pnfName
+     * @param ifName
+     * @param status
+     * @return the ID of the logic link
+     */
+    public String getLogicLink(String networkId, String pnfName, String ifName, String status) throws CorrelationException {
         Map<String, String> params = new HashMap<>();
         params.put("networkId", networkId);
         params.put("pnfName", pnfName);
         params.put("ifName", ifName);
-        params.put("status", status);
-        Response response = get(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_LINK_UPDATE, params));
-        if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
-            throw new RuntimeException("Failed to connect to AAI. Cause: "
-                    + response.getStatusInfo().getReasonPhrase());
-        }
 
-        JSONObject linkInfo = getInfo(JSONObject.toJSONString(response.getEntity()), "p-interface", "logical-link");
+        Response response = get(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_LINK_QUERY, params)
+                + (status == null ? "" : String.format("&operational-status=%s", status)));
+        JSONObject linkInfo = getInfo(response.readEntity(String.class), "p-interface", "logical-link");
         return extractValueFromJsonArray(linkInfo.getJSONArray("relationship-data"), "logical-link.link-name");
     }
 
-    public JSONArray getServiceInstances(String networkId, String pnfName, String ifName, String status) {
+    /**
+     * Query the service instances related to a terminal point. This method is mainly based on the API:
+     * https://<AAI host>:<AAI port>/aai/v14/network/connectivities?connectivity-id={connectivityId}
+     * and
+     * https://<AAI host>:<AAI port>/aai/v14/business/customers/customer/{global-customer-id}/service-subscriptions/service-subscription/{service-type}
+     * provided by AAI. The path for getting the required instance information is: p-interface → vpn-vpnbinding → connectivity → service instance
+     *
+     * @param networkId
+     * @param pnfName
+     * @param ifName
+     * @param status
+     * @return service instances in JSONObject format
+     */
+    public JSONObject getServiceInstance(String networkId, String pnfName, String ifName, String status) {
         try {
             JSONObject vpnBindingInfo = getVpnBindingInfo(networkId, pnfName, ifName, status);
             String vpnBindingId = extractValueFromJsonArray(vpnBindingInfo.getJSONArray("relationship-data"),
-                    "vpn-binding.vpn-id");
+                                                            "vpn-binding.vpn-id");
             JSONObject connectivityInfo = getConnectivityInfo(vpnBindingId);
             String connectivityId = extractValueFromJsonArray(connectivityInfo.getJSONArray("relationship-data"),
-                    "connectivity. connectivity-id");
+                                                              "connectivity.connectivity-id");
             JSONObject serviceInstanceInfo = getServiceInstanceByConn(connectivityId);
             String serviceInstancePath = serviceInstanceInfo.getString("related-link");
-            serviceInstancePath = serviceInstancePath.substring(0, serviceInstancePath.lastIndexOf('/'));
 
             Response response = get(getHostAddr(), getPath(serviceInstancePath));
-            if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
-                throw new RuntimeException("Failed to connect to AAI. Cause: "
-                        + response.getStatusInfo().getReasonPhrase());
+            JSONObject instance = JSON.parseObject(response.readEntity(String.class));
+
+            String[] params = new String[2];
+            Pattern pattern = Pattern.compile("/aai/v\\d+/business/customers/customer/(.+)" +
+                                                      "/service-subscriptions/service-subscription/(.+)" +
+                                                      "/service-instances/service-instance/(.+)");
+            Matcher matcher = pattern.matcher(serviceInstancePath);
+            if (matcher.find()) {
+                params[0] = matcher.group(1);
+                params[1] = matcher.group(2);
             }
-            return getInstances(JSONObject.toJSONString(response.getEntity()));
+            instance.put("globalSubscriberId", params[0]);
+            instance.put("serviceType", params[1]);
+            return instance;
         } catch (CorrelationException e) {
             throw new RuntimeException(e.getMessage(), e);
         }
@@ -92,72 +124,55 @@ public class AaiQuery4Ccvpn {
         params.put("networkId", networkId);
         params.put("pnfName", pnfName);
         params.put("ifName", ifName);
-        Response response = patch(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_TP_UPDATE, params), body);
-        if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
-            throw new CorrelationException("Failed to connecto to AAI. Cause: "
-                    + response.getStatusInfo().getReasonPhrase());
-        }
+        Response r = get(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_TP_UPDATE, params));
+        JSONObject jsonObject = JSONObject.parseObject(r.readEntity(String.class));
+        body.put("resource-version", jsonObject.get("resource-version").toString());
+
+        put(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_TP_UPDATE, params), body);
     }
 
     public void updateLogicLinkStatus(String linkName, Map<String, Object> body) throws CorrelationException {
-        Response response = patch(getHostAddr(),
-                getPath(AaiConfig.MsbConsts.AAI_TP_UPDATE, "linkName", linkName), body);
-        if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
-            throw new CorrelationException("Failed to connecto to AAI. Cause: "
-                    + response.getStatusInfo().getReasonPhrase());
-        }
+        Response r = get(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_LINK_UPDATE, "linkName", linkName));
+        JSONObject jsonObject = JSONObject.parseObject(r.readEntity(String.class));
+        body.put("resource-version", jsonObject.get("resource-version").toString());
+        body.put("link-type", jsonObject.get("link-type").toString());
+        put(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_LINK_UPDATE, "linkName", linkName), body);
     }
 
-    public JSONObject getVpnBindingInfo(String networkId, String pnfName,
-                                        String ifName, String status) throws CorrelationException {
+    private JSONObject getVpnBindingInfo(String networkId, String pnfName,
+                                         String ifName, String status) throws CorrelationException {
         Map<String, String> params = new HashMap();
         params.put("networkId", networkId);
         params.put("pnfName", pnfName);
         params.put("ifName", ifName);
         params.put("status", status);
         Response response = get(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_VPN_ADDR, params));
-        if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
-            throw new CorrelationException("Failed to connecto to AAI. Cause: "
-                    + response.getStatusInfo().getReasonPhrase());
-        }
-        return getInfo(JSONObject.toJSONString(response.getEntity()), "p-interface", "vpn-binding");
+        return getInfo(response.readEntity(String.class), "p-interface", "vpn-binding");
     }
 
-    public JSONObject getConnectivityInfo(String vpnId) throws CorrelationException {
+    private JSONObject getConnectivityInfo(String vpnId) throws CorrelationException {
         Response response = get(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_CONN_ADDR, "vpnId", vpnId));
-        if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
-            throw new CorrelationException("Failed to connect to AAI. Cause: "
-                    + response.getStatusInfo().getReasonPhrase());
-        }
-        return getInfo(JSONObject.toJSONString(response.getEntity()), "vpn-binding", "connectivity");
+        return getInfo(response.readEntity(String.class), "vpn-binding", "connectivity");
     }
 
-    public JSONObject getServiceInstanceByConn(String connectivityId) throws CorrelationException {
+    private JSONObject getServiceInstanceByConn(String connectivityId) throws CorrelationException {
         Response response = get(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_SERVICE_INSTANCE_ADDR_4_CCVPN,
-                "connectivityId", connectivityId));
-        if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
-            throw new CorrelationException("Failed to connect to AAI. Cause: "
-                    + response.getStatusInfo().getReasonPhrase());
-        }
-        return getInfo(JSONObject.toJSONString(response.getEntity()), "connectivity", "service-instance");
+                                                       "connectivityId", connectivityId));
+        return getInfo(response.readEntity(String.class), "connectivity", "service-instance");
     }
 
-    public JSONArray getServiceInstances(String globalCustomerId, String serviceType) throws CorrelationException {
+    private JSONObject getServiceInstance(String globalCustomerId, String serviceType) throws CorrelationException {
         Map<String, String> params = new HashMap();
         params.put("global-customer-id", globalCustomerId);
         params.put("service-type", serviceType);
         Response response = get(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_SERVICE_INSTANCES_ADDR_4_CCVPN, params));
-        if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
-            throw new CorrelationException("Failed to connect to AAI. Cause: "
-                    + response.getStatusInfo().getReasonPhrase());
-        }
-        return getInstances(JSONObject.toJSONString(response.getEntity()));
+        return JSON.parseObject(response.readEntity(String.class));
     }
 
     private String getPath(String urlTemplate, Map<String, String> pathParams) {
         String url = urlTemplate;
-        for (String key : pathParams.keySet()) {
-            url = url.replaceAll("\\{" + key + "\\}", pathParams.get(key));
+        for(Map.Entry<String, String> entry : pathParams.entrySet()){
+            url = url.replaceAll("\\{" + entry.getKey() + "\\}", entry.getValue());
         }
         return url;
     }
@@ -177,21 +192,50 @@ public class AaiQuery4Ccvpn {
         return ret;
     }
 
-    public Response get(String host, String path) {
+    private Response get(String host, String path) throws CorrelationException {
         Client client = ClientBuilder.newClient();
         WebTarget target = client.target(host).path(path);
-        return target.request().headers(getAaiHeaders()).get();
+        try {
+            Response response = target.request().headers(getAaiHeaders()).get();
+            if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
+                throw new CorrelationException("Failed to connect to AAI. \nCause: "
+                                                       + response.getStatusInfo().getReasonPhrase() + "\nDetails: \n"
+                                                       + getErrorMsg(String.format("%s%s", host, path), null, response));
+            }
+            return response;
+        } catch (CorrelationException e) {
+            throw e;
+        } catch (Exception e) {
+            throw new CorrelationException(e.getMessage() + "More info: "
+                                                   + getErrorMsg(String.format("%s%s", host, path), null, null), e);
+        }
     }
 
-    public Response patch(String host, String path, Map<String, Object> body) {
+    private void put(String host, String path, Map<String, Object> body) throws CorrelationException {
         Client client = ClientBuilder.newClient();
         WebTarget target = client.target(host).path(path);
-        return target.request().headers(getAaiHeaders()).method("PATCH", Entity.json(body));
+        try {
+            Response response = target.request().headers(getAaiHeaders()).build("PUT", Entity.json(body))
+                    .property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true).invoke();
+            if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
+                throw new CorrelationException("Failed to connect to AAI. \nCause: "
+                                                       + response.getStatusInfo().getReasonPhrase() + "\nDetails: \n"
+                                                       + getErrorMsg(String.format("%s%s", host, path), body, response));
+            }
+        } catch (CorrelationException e) {
+            throw e;
+        } catch (Exception e) {
+            throw new CorrelationException(e.getMessage() + "More info: "
+                                                   + getErrorMsg(String.format("%s%s", host, path), body, null), e);
+        }
     }
 
     private JSONObject getInfo(String response, String pField, String field) {
-        JSONArray results = extractJsonArray(JSONObject.parseObject(response), "results");
-        JSONObject pInterface = extractJsonObject(results.getJSONObject(0), pField);
+        JSONObject jObject = JSONObject.parseObject(response);
+        JSONObject pInterface = extractJsonObject(jObject, pField);
+        if (pInterface == null) {
+            pInterface = jObject;
+        }
         JSONObject relationshipList = extractJsonObject(pInterface, "relationship-list");
         JSONArray relationShip = extractJsonArray(relationshipList, "relationship");
         if (relationShip != null) {
@@ -205,14 +249,6 @@ public class AaiQuery4Ccvpn {
         return null;
     }
 
-    private JSONArray getInstances(String response) {
-        JSONArray results = extractJsonArray(JSONObject.parseObject(response), "results");
-        JSONObject pInterface = extractJsonObject(results.getJSONObject(0), "service-subscription");
-        JSONObject serviceInstances = extractJsonObject(pInterface, "service-instances");
-        JSONArray instance = extractJsonArray(serviceInstances, "service-instance");
-        return instance;
-    }
-
     private JSONObject extractJsonObject(JSONObject obj, String key) {
         if (obj != null && key != null && obj.containsKey(key)) {
             return obj.getJSONObject(key);
@@ -232,10 +268,7 @@ public class AaiQuery4Ccvpn {
     }
 
     private String getHostAddr() {
-        String[] msbInfo = MicroServiceConfig.getMsbServerAddrWithHttpPrefix().split(":");
-        StringBuilder sb = new StringBuilder("http://");
-        sb.append(msbInfo[0]).append(msbInfo[1]);
-        return sb.toString();
+        return MicroServiceConfig.getMsbServerAddrWithHttpPrefix();
     }
 
     private String extractValueFromJsonArray(JSONArray relationshipData, String keyName) {
@@ -247,4 +280,17 @@ public class AaiQuery4Ccvpn {
         }
         return null;
     }
+
+    private String getErrorMsg(String url, Map<String, Object> body, Response response) {
+        StringBuilder sb = new StringBuilder();
+        sb.append("Rerquest URL: ").append(url).append("\n");
+        sb.append("Request Header: ").append(JSONObject.toJSONString(headers)).append("\n");
+        if (body != null) {
+            sb.append("Request Body: ").append(JSONObject.toJSONString(body)).append("\n");
+        }
+        if (response != null) {
+            sb.append("Request Body: ").append(response.readEntity(String.class));
+        }
+        return sb.toString();
+    }
 }