Clean up of Pair classes - models
[policy/models.git] / models-interactions / model-impl / aai / src / main / java / org / onap / policy / aai / AaiManager.java
index 20998ae..76817df 100644 (file)
@@ -2,8 +2,8 @@
  * ============LICENSE_START=======================================================
  * aai
  * ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2019 Nordix Foundation.
+ * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019-2020 Nordix Foundation.
  * Modifications Copyright (C) 2019 Samsung Electronics Co., Ltd.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
 
 package org.onap.policy.aai;
 
-import com.google.gson.JsonSyntaxException;
+import java.io.UnsupportedEncodingException;
+import java.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
 import java.util.HashMap;
 import java.util.Map;
 import java.util.UUID;
+import java.util.stream.Collectors;
+import org.apache.commons.lang3.tuple.Pair;
 import org.json.JSONArray;
 import org.json.JSONObject;
-import org.onap.policy.aai.util.Serialization;
 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
 import org.onap.policy.common.endpoints.utils.NetLoggerUtil;
 import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType;
+import org.onap.policy.common.utils.coder.CoderException;
+import org.onap.policy.common.utils.coder.StandardCoder;
 import org.onap.policy.rest.RestManager;
-import org.onap.policy.rest.RestManager.Pair;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -42,21 +46,25 @@ import org.slf4j.LoggerFactory;
  */
 public final class AaiManager {
 
+    // TODO remove this class
+
     /** The Constant logger. */
     private static final Logger logger = LoggerFactory.getLogger(AaiManager.class);
 
     private static final String APPLICATION_JSON = "application/json";
 
-    /** The rest manager. */
+    private static final StandardCoder CODER = new StandardCoder();
+
     // The REST manager used for processing REST calls for this AAI manager
     private final RestManager restManager;
 
-    /** custom query URLs. */
+    /** custom query and other AAI resource URLs. */
     private static final String CQ_URL = "/aai/v16/query?format=resource";
-    private static final String TENANT_URL =
-            "/aai/v16/search/nodes-query?search-node-type=vserver&filter=vserver-name:EQUALS:";
+    private static final String TENANT_URL = "/aai/v16/search/nodes-query?"
+                    + "search-node-type=vserver&filter=vserver-name:EQUALS:";
     private static final String PREFIX = "/aai/v16";
-
+    private static final String PNF_URL = PREFIX + "/network/pnfs/pnf/";
+    private static final String AAI_DEPTH_SUFFIX = "?depth=0";
 
     /**
      * Constructor, create the AAI manager with the specified REST manager.
@@ -96,7 +104,6 @@ public final class AaiManager {
         }
     }
 
-
     /**
      * This method is used to get the information for custom query.
      *
@@ -108,7 +115,7 @@ public final class AaiManager {
      * @return String
      */
     private String getCustomQueryRequestPayload(String url, String username, String password, UUID requestId,
-            String vserver) {
+                    String vserver) {
 
         String urlGet = url + TENANT_URL;
 
@@ -116,8 +123,6 @@ public final class AaiManager {
         return createCustomQueryPayload(getResponse);
     }
 
-
-
     /**
      * Calls Aai and returns a custom query response for a vserver.
      *
@@ -129,7 +134,7 @@ public final class AaiManager {
      * @return AaiCqResponse response from Aai for custom query
      */
     public AaiCqResponse getCustomQueryResponse(String url, String username, String password, UUID requestId,
-            String vserver) {
+                    String vserver) {
 
         final Map<String, String> headers = createHeaders(requestId);
 
@@ -139,30 +144,31 @@ public final class AaiManager {
 
         url = url + CQ_URL;
 
-        Pair<Integer, String> httpDetails =
-                this.restManager.put(url, username, password, headers, APPLICATION_JSON, requestJson);
+        Pair<Integer, String> httpDetails = this.restManager.put(url, username, password, headers, APPLICATION_JSON,
+                        requestJson);
         logger.debug("RestManager.put after");
 
         if (httpDetails == null) {
-            logger.info("AAI POST Null Response to {}", url);
+            NetLoggerUtil.log(EventType.IN, CommInfrastructure.REST, url, "AAI POST Null Response");
+            logger.debug("AAI POST Null Response to {}", url);
             return null;
         }
 
-        int httpResponseCode = httpDetails.first;
+        int httpResponseCode = httpDetails.getLeft();
+
+        NetLoggerUtil.log(EventType.IN, CommInfrastructure.REST, url, "Response code: " + httpResponseCode);
+        NetLoggerUtil.getNetworkLogger().debug(httpDetails.getRight());
 
-        logger.info(url);
-        logger.info("{}", httpResponseCode);
-        logger.info(httpDetails.second);
+        logger.debug(url);
+        logger.debug("{}", httpResponseCode);
+        logger.debug(httpDetails.getRight());
 
-        if (httpDetails.second != null) {
-            String resp = httpDetails.second;
-            return new AaiCqResponse(resp);
+        if (httpDetails.getRight() != null) {
+            return new AaiCqResponse(httpDetails.getRight());
         }
         return null;
     }
 
-
-
     /**
      * Returns the string response of a get query.
      *
@@ -174,7 +180,7 @@ public final class AaiManager {
      * @return String returns the string from the get query
      */
     private String getStringQuery(final String url, final String username, final String password, final UUID requestId,
-            final String key) {
+                    final String key) {
 
         Map<String, String> headers = createHeaders(requestId);
 
@@ -186,159 +192,22 @@ public final class AaiManager {
             NetLoggerUtil.getNetworkLogger().info("[OUT|{}|{}|]", CommInfrastructure.REST, urlGet);
             Pair<Integer, String> httpDetailsGet = restManager.get(urlGet, username, password, headers);
             if (httpDetailsGet == null) {
-                logger.info("AAI GET Null Response to {}", urlGet);
+                NetLoggerUtil.log(EventType.IN, CommInfrastructure.REST, url, "AAI POST Null Response");
+                logger.debug("AAI GET Null Response to {}", urlGet);
                 return null;
             }
 
-            int httpResponseCode = httpDetailsGet.first;
-
-            logger.info(urlGet);
-            logger.info("{}", httpResponseCode);
-            logger.info(httpDetailsGet.second);
-
-            if (httpResponseCode == 200) {
-                String responseGet = httpDetailsGet.second;
-                if (responseGet != null) {
-                    return responseGet;
-                }
-            }
-            try {
-                Thread.sleep(1000);
-            } catch (InterruptedException e) {
-                Thread.currentThread().interrupt();
-            }
-
-        }
-
-        return null;
-    }
-
-
-    /**
-     * Post a query to A&AI.
-     *
-     * @param url the A&AI URL
-     * @param username the user name for authentication
-     * @param password the password for authentication
-     * @param request the request to issue towards A&AI
-     * @param requestId the UUID of the request
-     * @return the response from A&AI
-     */
-    public AaiNqResponse postQuery(String url, String username, String password, AaiNqRequest request, UUID requestId) {
-
-        final Map<String, String> headers = createHeaders(requestId);
-
-        url = url + "/aai/search/named-query";
-
-        logger.debug("RestManager.post before");
-        String requestJson = Serialization.gsonPretty.toJson(request);
-        NetLoggerUtil.log(EventType.OUT, CommInfrastructure.REST, url, requestJson);
-        Pair<Integer, String> httpDetails =
-                restManager.post(url, username, password, headers, APPLICATION_JSON, requestJson);
-        logger.debug("RestManager.post after");
-
-        if (httpDetails == null) {
-            logger.info("AAI POST Null Response to {}", url);
-            return null;
-        }
-
-        int httpResponseCode = httpDetails.first;
-
-        logger.info(url);
-        logger.info("{}", httpResponseCode);
-        logger.info(httpDetails.second);
-
-        if (httpDetails.second != null) {
-            return composeResponse(httpDetails, url, AaiNqResponse.class);
-        }
-        return null;
-    }
-
-    /**
-     * Perform a GET request for a particular virtual server towards A&AI.
-     *
-     * @param urlGet the A&AI URL
-     * @param username the user name for authentication
-     * @param password the password for authentication
-     * @param requestId the UUID of the request
-     * @param key the key of the virtual server
-     * @return the response for the virtual server from A&AI
-     */
-    public AaiGetVserverResponse getQueryByVserverName(String urlGet, String username, String password, UUID requestId,
-            String key) {
-        return getQuery(urlGet, username, password, requestId, key, AaiGetVserverResponse.class);
-    }
-
-    /**
-     * Perform a GET request for a particular VNF by VNF ID towards A&AI.
-     *
-     * @param urlGet the A&AI URL
-     * @param username the user name for authentication
-     * @param password the password for authentication
-     * @param requestId the UUID of the request
-     * @param key the ID of the VNF
-     * @return the response for the virtual server from A&AI
-     */
-    public AaiGetVnfResponse getQueryByVnfId(String urlGet, String username, String password, UUID requestId,
-            String key) {
-        return getQuery(urlGet, username, password, requestId, key, AaiGetVnfResponse.class);
-    }
-
-    /**
-     * Perform a GET request for a particular VNF by VNF name towards A&AI.
-     *
-     * @param urlGet the A&AI URL
-     * @param username the user name for authentication
-     * @param password the password for authentication
-     * @param requestId the UUID of the request
-     * @param key the name of the VNF
-     * @return the response for the virtual server from A&AI
-     */
-    public AaiGetVnfResponse getQueryByVnfName(String urlGet, String username, String password, UUID requestId,
-            String key) {
-        return getQuery(urlGet, username, password, requestId, key, AaiGetVnfResponse.class);
-    }
-
-    /**
-     * Perform a GET query for a particular entity towards A&AI.
-     *
-     * @param <T> the generic type for the response
-     * @param urlGet the A&AI URL
-     * @param username the user name for authentication
-     * @param password the password for authentication
-     * @param requestId the UUID of the request
-     * @param key the name of the VNF
-     * @param classOfT the class of the response to return
-     * @return the response for the virtual server from A&AI
-     */
-    private <T> T getQuery(final String url, final String username, final String password, final UUID requestId,
-            final String key, final Class<T> classOfResponse) {
-
-        Map<String, String> headers = createHeaders(requestId);
+            int httpResponseCode = httpDetailsGet.getLeft();
 
-        String urlGet = url + key;
+            NetLoggerUtil.log(EventType.IN, CommInfrastructure.REST, url, "Response code: " + httpResponseCode);
+            NetLoggerUtil.getNetworkLogger().debug(httpDetailsGet.getRight());
 
-        int attemptsLeft = 3;
+            logger.debug(urlGet);
+            logger.debug("{}", httpResponseCode);
+            logger.debug(httpDetailsGet.getRight());
 
-        while (attemptsLeft-- > 0) {
-            NetLoggerUtil.getNetworkLogger().info("[OUT|{}|{}|]", CommInfrastructure.REST, urlGet);
-            Pair<Integer, String> httpDetailsGet = restManager.get(urlGet, username, password, headers);
-            if (httpDetailsGet == null) {
-                logger.info("AAI GET Null Response to {}", urlGet);
-                return null;
-            }
-
-            int httpResponseCode = httpDetailsGet.first;
-
-            logger.info(urlGet);
-            logger.info("{}", httpResponseCode);
-            logger.info(httpDetailsGet.second);
-
-            if (httpResponseCode == 200) {
-                T responseGet = composeResponse(httpDetailsGet, urlGet, classOfResponse);
-                if (responseGet != null) {
-                    return responseGet;
-                }
+            if (httpResponseCode == 200 && httpDetailsGet.getRight() != null) {
+                return httpDetailsGet.getRight();
             }
             try {
                 Thread.sleep(1000);
@@ -367,25 +236,38 @@ public final class AaiManager {
         return headers;
     }
 
-
     /**
-     * This method uses Google's GSON to create a response object from a JSON string.
+     * Perform a GET request for a particular PNF by PNF ID towards A&AI.
      *
-     * @param <T> the generic type
-     * @param httpDetails the HTTP response
-     * @param url the URL from which the response came
-     * @param classOfResponse The response class
-     * @return an instance of the response class
-     * @throws JsonSyntaxException on GSON errors instantiating the response
+     * @param url the A&AI URL
+     * @param username the user name for authentication
+     * @param password the password for authentication
+     * @param requestId the UUID of the request
+     * @param pnfName the AAI unique identifier for PNF object
+     * @return HashMap of PNF properties
      */
-    private <T> T composeResponse(final Pair<Integer, String> httpDetails, final String url,
-            final Class<T> classOfResponse) {
+    public Map<String, String> getPnf(String url, String username, String password, UUID requestId, String pnfName) {
+        String urlGet;
+        try {
+            urlGet = url + PNF_URL;
+            pnfName = URLEncoder.encode(pnfName, StandardCharsets.UTF_8.toString()) + AAI_DEPTH_SUFFIX;
+        } catch (UnsupportedEncodingException e) {
+            logger.error("Failed to encode the pnfName: {} using UTF-8", pnfName, e);
+            return null;
+        }
+        String responseGet = getStringQuery(urlGet, username, password, requestId, pnfName);
+        if (responseGet == null) {
+            logger.error("Null response from AAI for the url: {}.", urlGet);
+            return null;
+        }
         try {
-            T response = Serialization.gsonPretty.fromJson(httpDetails.second, classOfResponse);
-            NetLoggerUtil.log(EventType.IN, CommInfrastructure.REST, url, httpDetails.second);
-            return response;
-        } catch (JsonSyntaxException e) {
-            logger.error("postQuery threw: ", e);
+            @SuppressWarnings("unchecked")
+            Map<String, String> pnfParams = CODER.decode(responseGet, HashMap.class);
+            // Map to AAI node.attribute notation
+            return pnfParams.entrySet().stream()
+                            .collect(Collectors.toMap(e -> "pnf." + e.getKey(), Map.Entry::getValue));
+        } catch (CoderException e) {
+            logger.error("Failed to fetch PNF from AAI", e);
             return null;
         }
     }