diff options
author | Sébastien Determe <sebastien.determe@intl.att.com> | 2019-02-07 12:33:19 +0000 |
---|---|---|
committer | Gerrit Code Review <gerrit@onap.org> | 2019-02-07 12:33:19 +0000 |
commit | 8695c6f7b72e2d0899aa580b6080b885469b9099 (patch) | |
tree | 535cdc90a5d34ae09858868abb5307356587d217 /src/main | |
parent | 3506f9b3cf62b89089e4d9a7d5f63c5be063405a (diff) | |
parent | cdfe48cf32c83f3e0a3921499cd6c494a4b40107 (diff) |
Merge "Replace jackson usages with GSON"
Diffstat (limited to 'src/main')
30 files changed, 641 insertions, 671 deletions
diff --git a/src/main/java/org/onap/clamp/clds/client/DcaeDispatcherServices.java b/src/main/java/org/onap/clamp/clds/client/DcaeDispatcherServices.java index 4151c7aa..68454525 100644 --- a/src/main/java/org/onap/clamp/clds/client/DcaeDispatcherServices.java +++ b/src/main/java/org/onap/clamp/clds/client/DcaeDispatcherServices.java @@ -25,9 +25,8 @@ package org.onap.clamp.clds.client; import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
-import com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.node.ObjectNode;
+import com.google.gson.JsonObject;
import java.io.IOException;
import java.util.Date;
@@ -122,16 +121,16 @@ public class DcaeDispatcherServices { * The value for each blueprint parameters in a flat JSON
* @return The status URL
*/
- public String createNewDeployment(String deploymentId, String serviceTypeId, JsonNode blueprintInputJson) {
+ public String createNewDeployment(String deploymentId, String serviceTypeId, JsonObject blueprintInputJson) {
Date startTime = new Date();
LoggingUtils.setTargetContext("DCAE", "createNewDeployment");
try {
- ObjectNode rootNode = (ObjectNode) refProp.getJsonTemplate("dcae.deployment.template");
- rootNode.put("serviceTypeId", serviceTypeId);
+ JsonObject rootObject = refProp.getJsonTemplate("dcae.deployment.template").getAsJsonObject();
+ rootObject.addProperty("serviceTypeId", serviceTypeId);
if (blueprintInputJson != null) {
- rootNode.set("inputs", blueprintInputJson);
+ rootObject.add("inputs", blueprintInputJson);
}
- String apiBodyString = rootNode.toString();
+ String apiBodyString = rootObject.toString();
logger.info("Dcae api Body String - " + apiBodyString);
String url = refProp.getStringValue(DCAE_URL_PROPERTY_NAME) + DCAE_URL_PREFIX + deploymentId;
String statusUrl = getDcaeResponse(url, "PUT", apiBodyString, "application/json", DCAE_LINK_FIELD,
diff --git a/src/main/java/org/onap/clamp/clds/client/DcaeInventoryServices.java b/src/main/java/org/onap/clamp/clds/client/DcaeInventoryServices.java index 327aff1d..77023078 100644 --- a/src/main/java/org/onap/clamp/clds/client/DcaeInventoryServices.java +++ b/src/main/java/org/onap/clamp/clds/client/DcaeInventoryServices.java @@ -44,7 +44,7 @@ import org.onap.clamp.clds.model.DcaeEvent; import org.onap.clamp.clds.model.dcae.DcaeInventoryResponse;
import org.onap.clamp.clds.model.properties.Global;
import org.onap.clamp.clds.model.properties.ModelProperties;
-import org.onap.clamp.clds.util.JacksonUtils;
+import org.onap.clamp.clds.util.JsonUtils;
import org.onap.clamp.clds.util.LoggingUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@@ -155,14 +155,13 @@ public class DcaeInventoryServices { }
private DcaeInventoryResponse getItemsFromDcaeInventoryResponse(String responseStr)
- throws ParseException, IOException {
+ throws ParseException {
JSONParser parser = new JSONParser();
Object obj0 = parser.parse(responseStr);
JSONObject jsonObj = (JSONObject) obj0;
JSONArray itemsArray = (JSONArray) jsonObj.get("items");
JSONObject dcaeServiceType0 = (JSONObject) itemsArray.get(0);
- return JacksonUtils.getObjectMapperInstance().readValue(dcaeServiceType0.toString(),
- DcaeInventoryResponse.class);
+ return JsonUtils.GSON.fromJson(dcaeServiceType0.toString(), DcaeInventoryResponse.class);
}
/**
diff --git a/src/main/java/org/onap/clamp/clds/client/req/sdc/SdcCatalogServices.java b/src/main/java/org/onap/clamp/clds/client/req/sdc/SdcCatalogServices.java index cd7d4f2c..37c62576 100644 --- a/src/main/java/org/onap/clamp/clds/client/req/sdc/SdcCatalogServices.java +++ b/src/main/java/org/onap/clamp/clds/client/req/sdc/SdcCatalogServices.java @@ -26,18 +26,19 @@ package org.onap.clamp.clds.client.req.sdc; import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
-import com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.databind.node.ArrayNode;
-import com.fasterxml.jackson.databind.node.ObjectNode;
-import com.fasterxml.jackson.databind.node.TextNode;
+import com.google.gson.JsonArray;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParseException;
+import com.google.gson.reflect.TypeToken;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
+import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
@@ -68,7 +69,7 @@ import org.onap.clamp.clds.model.sdc.SdcServiceDetail; import org.onap.clamp.clds.model.sdc.SdcServiceInfo;
import org.onap.clamp.clds.service.CldsService;
import org.onap.clamp.clds.util.CryptoUtils;
-import org.onap.clamp.clds.util.JacksonUtils;
+import org.onap.clamp.clds.util.JsonUtils;
import org.onap.clamp.clds.util.LoggingUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
@@ -80,17 +81,24 @@ public class SdcCatalogServices { private static final EELFLogger logger = EELFManager.getInstance().getLogger(SdcCatalogServices.class);
private static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
- public static final String RESOURCE_VF_TYPE = "VF";
- public static final String RESOURCE_VFC_TYPE = "VFC";
- public static final String RESOURCE_CVFC_TYPE = "CVFC";
- public static final String SDC_REQUESTID_PROPERTY_NAME = "sdc.header.requestId";
- public static final String SDC_METADATA_URL_PREFIX = "/metadata";
- public static final String SDC_INSTANCE_ID_PROPERTY_NAME = "sdc.InstanceID";
- public static final String SDC_CATALOG_URL_PROPERTY_NAME = "sdc.catalog.url";
- public static final String SDC_SERVICE_URL_PROPERTY_NAME = "sdc.serviceUrl";
- public static final String SDC_INSTANCE_ID_CLAMP = "CLAMP-Tool";
- public static final String RESOURCE_URL_PREFIX = "resources";
+ private static final String RESOURCE_VF_TYPE = "VF";
+ private static final String RESOURCE_VFC_TYPE = "VFC";
+ private static final String RESOURCE_CVFC_TYPE = "CVFC";
+ private static final String SDC_REQUESTID_PROPERTY_NAME = "sdc.header.requestId";
+ private static final String SDC_METADATA_URL_PREFIX = "/metadata";
+ private static final String SDC_INSTANCE_ID_PROPERTY_NAME = "sdc.InstanceID";
+ private static final String SDC_CATALOG_URL_PROPERTY_NAME = "sdc.catalog.url";
+ private static final String SDC_SERVICE_URL_PROPERTY_NAME = "sdc.serviceUrl";
+ private static final String SDC_INSTANCE_ID_CLAMP = "CLAMP-Tool";
+ private static final String RESOURCE_URL_PREFIX = "resources";
private static final LoggingUtils utils = new LoggingUtils(logger);
+
+ private static final Type LIST_SDC_SERVICE_INFO_TYPE = new TypeToken<List<SdcServiceInfo>>() {
+ }.getType();
+
+ private static final Type LIST_SDC_RESOURCE_BASIC_INFO_TYPE = new TypeToken<List<SdcResourceBasicInfo>>() {
+ }.getType();
+
@Autowired
private ClampProperties refProp;
@@ -285,9 +293,8 @@ public class SdcCatalogServices { return new ArrayList<>();
}
try {
- return JacksonUtils.getObjectMapperInstance().readValue(jsonStr, JacksonUtils.getObjectMapperInstance()
- .getTypeFactory().constructCollectionType(List.class, SdcServiceInfo.class));
- } catch (IOException e) {
+ return JsonUtils.GSON.fromJson(jsonStr, LIST_SDC_SERVICE_INFO_TYPE);
+ } catch (JsonParseException e) {
logger.error("Error when attempting to decode the JSON containing CldsSdcServiceInfo", e);
return new ArrayList<>();
}
@@ -305,9 +312,8 @@ public class SdcCatalogServices { return new ArrayList<>();
}
try {
- return JacksonUtils.getObjectMapperInstance().readValue(jsonStr, JacksonUtils.getObjectMapperInstance()
- .getTypeFactory().constructCollectionType(List.class, SdcResourceBasicInfo.class));
- } catch (IOException e) {
+ return JsonUtils.GSON.fromJson(jsonStr, LIST_SDC_RESOURCE_BASIC_INFO_TYPE);
+ } catch (JsonParseException e) {
logger.error("Exception occurred when attempting to decode the list of CldsSdcResourceBasicInfo JSON", e);
return new ArrayList<>();
}
@@ -321,8 +327,8 @@ public class SdcCatalogServices { */
public SdcServiceDetail decodeCldsSdcServiceDetailFromJson(String jsonStr) {
try {
- return JacksonUtils.getObjectMapperInstance().readValue(jsonStr, SdcServiceDetail.class);
- } catch (IOException e) {
+ return JsonUtils.GSON.fromJson(jsonStr, SdcServiceDetail.class);
+ } catch (JsonParseException e) {
logger.error("Exception when attempting to decode the CldsSdcServiceDetail JSON", e);
return null;
}
@@ -402,9 +408,8 @@ public class SdcCatalogServices { if (responseStr != null) {
SdcServiceDetail cldsSdcServiceDetail;
try {
- cldsSdcServiceDetail = JacksonUtils.getObjectMapperInstance().readValue(responseStr,
- SdcServiceDetail.class);
- } catch (IOException e) {
+ cldsSdcServiceDetail = JsonUtils.GSON.fromJson(responseStr, SdcServiceDetail.class);
+ } catch (JsonParseException e) {
logger.error("Exception when decoding the CldsServiceData JSON from SDC", e);
throw new SdcCommunicationException("Exception when decoding the CldsServiceData JSON from SDC", e);
}
@@ -497,41 +502,43 @@ public class SdcCatalogServices { }
private List<CldsVfcData> getVfcDataListFromVfResponse(String vfResponse) {
- ObjectNode vfResponseNode;
+ JsonObject vfResponseNode;
try {
- vfResponseNode = (ObjectNode) JacksonUtils.getObjectMapperInstance().readTree(vfResponse);
- } catch (IOException e) {
+ vfResponseNode = JsonUtils.GSON.fromJson(vfResponse, JsonObject.class);
+ } catch (JsonParseException e) {
logger.error("Exception when decoding the JSON list of CldsVfcData", e);
return new ArrayList<>();
}
- ArrayNode vfcArrayNode = (ArrayNode) vfResponseNode.get("resources");
+ JsonArray vfcArrayNode = vfResponseNode.get("resources").getAsJsonArray();
List<CldsVfcData> cldsVfcDataList = new ArrayList<>();
if (vfcArrayNode != null) {
- for (JsonNode vfcjsonNode : vfcArrayNode) {
- ObjectNode currVfcNode = (ObjectNode) vfcjsonNode;
- TextNode resourceTypeNode = (TextNode) currVfcNode.get("resoucreType");
- if (resourceTypeNode != null && "VFC".equalsIgnoreCase(resourceTypeNode.textValue())) {
- handleVFCtypeNode(currVfcNode, cldsVfcDataList);
- } else if (resourceTypeNode != null && "CVFC".equalsIgnoreCase(resourceTypeNode.textValue())) {
- handleCVFCtypeNode(currVfcNode, cldsVfcDataList);
+ for (JsonElement vfcjsonNode : vfcArrayNode) {
+ JsonObject currVfcNode = vfcjsonNode.getAsJsonObject();
+ JsonElement resourceTypeNode = currVfcNode.get("resoucreType");
+ if (resourceTypeNode != null && resourceTypeNode.isJsonPrimitive()) {
+ if ("VFC".equalsIgnoreCase(resourceTypeNode.getAsString())) {
+ handleVFCtypeNode(currVfcNode, cldsVfcDataList);
+ } else if ("CVFC".equalsIgnoreCase(resourceTypeNode.getAsString())) {
+ handleCVFCtypeNode(currVfcNode, cldsVfcDataList);
+ }
}
}
}
return cldsVfcDataList;
}
- private void handleVFCtypeNode(ObjectNode currVfcNode, List<CldsVfcData> cldsVfcDataList) {
+ private void handleVFCtypeNode(JsonObject currVfcNode, List<CldsVfcData> cldsVfcDataList) {
CldsVfcData currCldsVfcData = new CldsVfcData();
- TextNode vfcResourceName = (TextNode) currVfcNode.get("resourceInstanceName");
- TextNode vfcInvariantResourceUuid = (TextNode) currVfcNode.get("resourceInvariantUUID");
- currCldsVfcData.setVfcName(vfcResourceName.textValue());
- currCldsVfcData.setVfcInvariantResourceUUID(vfcInvariantResourceUuid.textValue());
+ String vfcResourceName = currVfcNode.get("resourceInstanceName").getAsString();
+ String vfcInvariantResourceUuid = currVfcNode.get("resourceInvariantUUID").getAsString();
+ currCldsVfcData.setVfcName(vfcResourceName);
+ currCldsVfcData.setVfcInvariantResourceUUID(vfcInvariantResourceUuid);
cldsVfcDataList.add(currCldsVfcData);
}
- private void handleCVFCtypeNode(ObjectNode currVfcNode, List<CldsVfcData> cldsVfcDataList) {
+ private void handleCVFCtypeNode(JsonObject currVfcNode, List<CldsVfcData> cldsVfcDataList) {
handleVFCtypeNode(currVfcNode, cldsVfcDataList);
- cldsVfcDataList.addAll(getVFCfromCVFC(currVfcNode.get("resourceUUID").textValue()));
+ cldsVfcDataList.addAll(getVFCfromCVFC(currVfcNode.get("resourceUUID").getAsString()));
}
private List<CldsVfcData> getVFCfromCVFC(String resourceUUID) {
@@ -541,18 +548,18 @@ public class SdcCatalogServices { String vfcResourceUUIDUrl = catalogUrl + RESOURCE_URL_PREFIX + "/" + resourceUUID + SDC_METADATA_URL_PREFIX;
try {
String vfcResponse = getCldsServicesOrResourcesBasedOnURL(vfcResourceUUIDUrl);
- ObjectNode vfResponseNode = (ObjectNode) JacksonUtils.getObjectMapperInstance().readTree(vfcResponse);
- ArrayNode vfcArrayNode = (ArrayNode) vfResponseNode.get("resources");
+ JsonObject vfResponseNode = JsonUtils.GSON.fromJson(vfcResponse, JsonObject.class);
+ JsonArray vfcArrayNode = vfResponseNode.get("resources").getAsJsonArray();
if (vfcArrayNode != null) {
- for (JsonNode vfcjsonNode : vfcArrayNode) {
- ObjectNode currVfcNode = (ObjectNode) vfcjsonNode;
- TextNode resourceTypeNode = (TextNode) currVfcNode.get("resoucreType");
- if (resourceTypeNode != null && "VFC".equalsIgnoreCase(resourceTypeNode.textValue())) {
+ for (JsonElement vfcjsonNode : vfcArrayNode) {
+ JsonObject currVfcNode = vfcjsonNode.getAsJsonObject();
+ JsonElement resourceTypeNode = currVfcNode.get("resoucreType");
+ if (resourceTypeNode != null && resourceTypeNode.isJsonPrimitive() && "VFC".equalsIgnoreCase(resourceTypeNode.getAsString())) {
handleVFCtypeNode(currVfcNode, cldsVfcDataList);
}
}
}
- } catch (IOException e) {
+ } catch (JsonParseException e) {
logger.error("Exception during JSON analyzis", e);
}
}
@@ -565,20 +572,21 @@ public class SdcCatalogServices { private List<CldsAlarmCondition> getAlarmCondtionsFromVfc(String vfcResponse) throws GeneralSecurityException {
List<CldsAlarmCondition> cldsAlarmConditionList = new ArrayList<>();
- ObjectNode vfcResponseNode;
+ JsonObject vfcResponseNode;
try {
- vfcResponseNode = (ObjectNode) JacksonUtils.getObjectMapperInstance().readTree(vfcResponse);
- } catch (IOException e) {
+ vfcResponseNode = JsonUtils.GSON.fromJson(vfcResponse, JsonObject.class);
+ } catch (JsonParseException e) {
logger.error("Exception when decoding the JSON list of CldsAlarmCondition", e);
return cldsAlarmConditionList;
}
- ArrayNode artifactsArrayNode = (ArrayNode) vfcResponseNode.get("artifacts");
- if (artifactsArrayNode != null && artifactsArrayNode.size() > 0) {
- for (int index = 0; index < artifactsArrayNode.size(); index++) {
- ObjectNode currArtifactNode = (ObjectNode) artifactsArrayNode.get(index);
- TextNode artifactUrlNode = (TextNode) currArtifactNode.get("artifactURL");
- if (artifactUrlNode != null) {
- String responsesFromArtifactUrl = getResponsesFromArtifactUrl(artifactUrlNode.textValue());
+ JsonElement artifactsNode = vfcResponseNode.get("artifacts");
+ if (artifactsNode != null && artifactsNode.isJsonArray() && artifactsNode.getAsJsonArray().size() > 0) {
+ JsonArray artifactsList = artifactsNode.getAsJsonArray();
+ for (int index = 0; index < artifactsList.size(); index++) {
+ JsonObject currArtifactNode = artifactsList.get(index).getAsJsonObject();
+ JsonElement artifactUrlNode = currArtifactNode.get("artifactURL");
+ if (artifactUrlNode != null && artifactUrlNode.isJsonPrimitive()) {
+ String responsesFromArtifactUrl = getResponsesFromArtifactUrl(artifactUrlNode.getAsString());
cldsAlarmConditionList.addAll(parseCsvToGetAlarmConditions(responsesFromArtifactUrl));
logger.info(responsesFromArtifactUrl);
}
@@ -609,26 +617,26 @@ public class SdcCatalogServices { // Method to get the artifact for any particular VF
private List<CldsVfKPIData> getFieldPathFromVF(String vfResponse) throws GeneralSecurityException {
List<CldsVfKPIData> cldsVfKPIDataList = new ArrayList<>();
- ObjectNode vfResponseNode;
+ JsonObject vfResponseNode;
try {
- vfResponseNode = (ObjectNode) JacksonUtils.getObjectMapperInstance().readTree(vfResponse);
- } catch (IOException e) {
+ vfResponseNode = JsonUtils.GSON.fromJson(vfResponse, JsonObject.class);
+ } catch (JsonParseException e) {
logger.error("Exception when decoding the JSON list of CldsVfKPIData", e);
return cldsVfKPIDataList;
}
- ArrayNode artifactsArrayNode = (ArrayNode) vfResponseNode.get("artifacts");
+ JsonArray artifactsArrayNode = vfResponseNode.get("artifacts").getAsJsonArray();
if (artifactsArrayNode != null && artifactsArrayNode.size() > 0) {
for (int index = 0; index < artifactsArrayNode.size(); index++) {
- ObjectNode currArtifactNode = (ObjectNode) artifactsArrayNode.get(index);
- TextNode artifactUrlNode = (TextNode) currArtifactNode.get("artifactURL");
- TextNode artifactNameNode = (TextNode) currArtifactNode.get("artifactName");
+ JsonObject currArtifactNode = artifactsArrayNode.get(index).getAsJsonObject();
+ JsonElement artifactUrlNode = currArtifactNode.get("artifactURL");
+ JsonElement artifactNameNode = currArtifactNode.get("artifactName");
String artifactName = "";
if (artifactNameNode != null) {
- artifactName = artifactNameNode.textValue();
+ artifactName = artifactNameNode.getAsString();
artifactName = artifactName.substring(artifactName.lastIndexOf('.') + 1);
}
if (artifactUrlNode != null && "csv".equalsIgnoreCase(artifactName)) {
- String responsesFromArtifactUrl = getResponsesFromArtifactUrl(artifactUrlNode.textValue());
+ String responsesFromArtifactUrl = getResponsesFromArtifactUrl(artifactUrlNode.getAsString());
cldsVfKPIDataList.addAll(parseCsvToGetFieldPath(responsesFromArtifactUrl));
logger.info(responsesFromArtifactUrl);
}
@@ -760,37 +768,32 @@ public class SdcCatalogServices { /**
* To create properties object by using cldsServicedata.
*
- * @param globalProps
- * @param cldsServiceData
- * @return
- * @throws IOException
- * In case of issues during the parsing of the Global Properties
+ * @throws IOException In case of issues during the parsing of the Global Properties
*/
public String createPropertiesObjectByUUID(CldsServiceData cldsServiceData) throws IOException {
String totalPropsStr;
- ObjectMapper mapper = JacksonUtils.getObjectMapperInstance();
- ObjectNode globalPropsJson = (ObjectNode) refProp.getJsonTemplate(CldsService.GLOBAL_PROPERTIES_KEY);
+ JsonObject globalPropsJson = refProp.getJsonTemplate(CldsService.GLOBAL_PROPERTIES_KEY).getAsJsonObject();
if (cldsServiceData != null && cldsServiceData.getServiceUUID() != null) {
// Objectnode to save all byservice, byvf , byvfc and byalarm nodes
- ObjectNode byIdObjectNode = mapper.createObjectNode();
+ JsonObject byIdObjectNode = new JsonObject();
// To create vf ResourceUUID node with serviceInvariantUUID
- ObjectNode invariantUuidObjectNodeWithVf = createVfObjectNodeByServiceInvariantUuid(cldsServiceData);
- byIdObjectNode.putPOJO("byService", invariantUuidObjectNodeWithVf);
+ JsonObject invariantUuidObjectNodeWithVf = createVfObjectNodeByServiceInvariantUuid(cldsServiceData);
+ byIdObjectNode.add("byService", invariantUuidObjectNodeWithVf);
// To create byVf and vfcResourceNode with vfResourceUUID
- ObjectNode vfcObjectNodeByVfUuid = createVfcObjectNodeByVfUuid(cldsServiceData.getCldsVfs());
- byIdObjectNode.putPOJO("byVf", vfcObjectNodeByVfUuid);
+ JsonObject vfcObjectNodeByVfUuid = createVfcObjectNodeByVfUuid(cldsServiceData.getCldsVfs());
+ byIdObjectNode.add("byVf", vfcObjectNodeByVfUuid);
// To create byKpi
- ObjectNode kpiObjectNode = mapper.createObjectNode();
+ JsonObject kpiJsonObject = new JsonObject();
if (cldsServiceData.getCldsVfs() != null && !cldsServiceData.getCldsVfs().isEmpty()) {
for (CldsVfData currCldsVfData : cldsServiceData.getCldsVfs()) {
if (currCldsVfData != null) {
- createKpiObjectNodeByVfUuid(kpiObjectNode, currCldsVfData.getCldsKPIList());
+ createKpiObjectNodeByVfUuid(kpiJsonObject, currCldsVfData.getCldsKPIList());
}
}
}
- byIdObjectNode.putPOJO("byKpi", kpiObjectNode);
+ byIdObjectNode.add("byKpi", kpiJsonObject);
// To create byVfc and alarmCondition with vfcResourceUUID
- ObjectNode vfcResourceUuidObjectNode = mapper.createObjectNode();
+ JsonObject vfcResourceUuidObjectNode = new JsonObject();
if (cldsServiceData.getCldsVfs() != null && !cldsServiceData.getCldsVfs().isEmpty()) {
for (CldsVfData currCldsVfData : cldsServiceData.getCldsVfs()) {
if (currCldsVfData != null) {
@@ -798,18 +801,18 @@ public class SdcCatalogServices { }
}
}
- byIdObjectNode.putPOJO("byVfc", vfcResourceUuidObjectNode);
+ byIdObjectNode.add("byVfc", vfcResourceUuidObjectNode);
// To create byAlarmCondition with alarmConditionKey
List<CldsAlarmCondition> allAlarmConditions = getAllAlarmConditionsFromCldsServiceData(cldsServiceData,
"alarmCondition");
- ObjectNode alarmCondObjectNodeByAlarmKey = createAlarmCondObjectNodeByAlarmKey(allAlarmConditions);
- byIdObjectNode.putPOJO("byAlarmCondition", alarmCondObjectNodeByAlarmKey);
+ JsonObject alarmCondObjectNodeByAlarmKey = createAlarmCondObjectNodeByAlarmKey(allAlarmConditions);
+ byIdObjectNode.add("byAlarmCondition", alarmCondObjectNodeByAlarmKey);
// To create byAlertDescription with AlertDescription
List<CldsAlarmCondition> allAlertDescriptions = getAllAlarmConditionsFromCldsServiceData(cldsServiceData,
"alertDescription");
- ObjectNode alertDescObjectNodeByAlert = createAlarmCondObjectNodeByAlarmKey(allAlertDescriptions);
- byIdObjectNode.putPOJO("byAlertDescription", alertDescObjectNodeByAlert);
- globalPropsJson.putPOJO("shared", byIdObjectNode);
+ JsonObject alertDescObjectNodeByAlert = createAlarmCondObjectNodeByAlarmKey(allAlertDescriptions);
+ byIdObjectNode.add("byAlertDescription", alertDescObjectNodeByAlert);
+ globalPropsJson.add("shared", byIdObjectNode);
logger.info("Global properties JSON created with SDC info:" + globalPropsJson);
}
totalPropsStr = globalPropsJson.toString();
@@ -880,73 +883,69 @@ public class SdcCatalogServices { return alarmCondList;
}
- private ObjectNode createAlarmCondObjectNodeByAlarmKey(List<CldsAlarmCondition> cldsAlarmCondList) {
- ObjectMapper mapper = JacksonUtils.getObjectMapperInstance();
- ObjectNode alarmCondKeyNode = mapper.createObjectNode();
+ private JsonObject createAlarmCondObjectNodeByAlarmKey(List<CldsAlarmCondition> cldsAlarmCondList) {
+ JsonObject alarmCondKeyNode = new JsonObject();
if (cldsAlarmCondList != null && !cldsAlarmCondList.isEmpty()) {
for (CldsAlarmCondition currCldsAlarmCondition : cldsAlarmCondList) {
if (currCldsAlarmCondition != null) {
- ObjectNode alarmCondNode = mapper.createObjectNode();
- alarmCondNode.put("eventSourceType", currCldsAlarmCondition.getEventSourceType());
- alarmCondNode.put("eventSeverity", currCldsAlarmCondition.getSeverity());
- alarmCondKeyNode.putPOJO(currCldsAlarmCondition.getAlarmConditionKey(), alarmCondNode);
+ JsonObject alarmCondNode = new JsonObject();
+ alarmCondNode.addProperty("eventSourceType", currCldsAlarmCondition.getEventSourceType());
+ alarmCondNode.addProperty("eventSeverity", currCldsAlarmCondition.getSeverity());
+ alarmCondKeyNode.add(currCldsAlarmCondition.getAlarmConditionKey(), alarmCondNode);
}
}
} else {
- ObjectNode alarmCondNode = mapper.createObjectNode();
- alarmCondNode.put("eventSourceType", "");
- alarmCondNode.put("eventSeverity", "");
- alarmCondKeyNode.putPOJO("", alarmCondNode);
+ JsonObject alarmCondNode = new JsonObject();
+ alarmCondNode.addProperty("eventSourceType", "");
+ alarmCondNode.addProperty("eventSeverity", "");
+ alarmCondKeyNode.add("", alarmCondNode);
}
return alarmCondKeyNode;
}
- private ObjectNode createVfObjectNodeByServiceInvariantUuid(CldsServiceData cldsServiceData) {
- ObjectMapper mapper = JacksonUtils.getObjectMapperInstance();
- ObjectNode invariantUuidObjectNode = mapper.createObjectNode();
- ObjectNode vfObjectNode = mapper.createObjectNode();
- ObjectNode vfUuidNode = mapper.createObjectNode();
+ private JsonObject createVfObjectNodeByServiceInvariantUuid(CldsServiceData cldsServiceData) {
+ JsonObject invariantUuidObjectNode = new JsonObject();
+ JsonObject vfObjectNode = new JsonObject();
+ JsonObject vfUuidNode = new JsonObject();
List<CldsVfData> cldsVfsList = cldsServiceData.getCldsVfs();
if (cldsVfsList != null && !cldsVfsList.isEmpty()) {
for (CldsVfData currCldsVfData : cldsVfsList) {
if (currCldsVfData != null) {
- vfUuidNode.put(currCldsVfData.getVfInvariantResourceUUID(), currCldsVfData.getVfName());
+ vfUuidNode.addProperty(currCldsVfData.getVfInvariantResourceUUID(), currCldsVfData.getVfName());
}
}
} else {
- vfUuidNode.put("", "");
+ vfUuidNode.addProperty("", "");
}
- vfObjectNode.putPOJO("vf", vfUuidNode);
- invariantUuidObjectNode.putPOJO(cldsServiceData.getServiceInvariantUUID(), vfObjectNode);
+ vfObjectNode.add("vf", vfUuidNode);
+ invariantUuidObjectNode.add(cldsServiceData.getServiceInvariantUUID(), vfObjectNode);
return invariantUuidObjectNode;
}
- private void createKpiObjectNodeByVfUuid(ObjectNode vfResourceUuidObjectNode,
+ private void createKpiObjectNodeByVfUuid(JsonObject vfResourceUuidObjectNode,
List<CldsVfKPIData> cldsVfKpiDataList) {
- ObjectMapper mapper = JacksonUtils.getObjectMapperInstance();
if (cldsVfKpiDataList != null && !cldsVfKpiDataList.isEmpty()) {
for (CldsVfKPIData currCldsVfKpiData : cldsVfKpiDataList) {
if (currCldsVfKpiData != null) {
- ObjectNode thresholdNameObjectNode = mapper.createObjectNode();
- ObjectNode fieldPathObjectNode = mapper.createObjectNode();
- ObjectNode nfNamingCodeNode = mapper.createObjectNode();
- fieldPathObjectNode.put(currCldsVfKpiData.getFieldPathValue(),
+ JsonObject thresholdNameObjectNode = new JsonObject();
+ JsonObject fieldPathObjectNode = new JsonObject();
+ JsonObject nfNamingCodeNode = new JsonObject();
+ fieldPathObjectNode.addProperty(currCldsVfKpiData.getFieldPathValue(),
currCldsVfKpiData.getFieldPathValue());
- nfNamingCodeNode.put(currCldsVfKpiData.getNfNamingValue(), currCldsVfKpiData.getNfNamingValue());
- thresholdNameObjectNode.putPOJO("fieldPath", fieldPathObjectNode);
- thresholdNameObjectNode.putPOJO("nfNamingCode", nfNamingCodeNode);
- vfResourceUuidObjectNode.putPOJO(currCldsVfKpiData.getThresholdValue(), thresholdNameObjectNode);
+ nfNamingCodeNode.addProperty(currCldsVfKpiData.getNfNamingValue(), currCldsVfKpiData.getNfNamingValue());
+ thresholdNameObjectNode.add("fieldPath", fieldPathObjectNode);
+ thresholdNameObjectNode.add("nfNamingCode", nfNamingCodeNode);
+ vfResourceUuidObjectNode.add(currCldsVfKpiData.getThresholdValue(), thresholdNameObjectNode);
}
}
}
}
- private void createAlarmCondObjectNodeByVfcUuid(ObjectNode vfcResourceUuidObjectNode,
+ private void createAlarmCondObjectNodeByVfcUuid(JsonObject vfcResourceUuidObjectNode,
List<CldsVfcData> cldsVfcDataList) {
- ObjectMapper mapper = JacksonUtils.getObjectMapperInstance();
- ObjectNode vfcObjectNode = mapper.createObjectNode();
- ObjectNode alarmCondNode = mapper.createObjectNode();
- ObjectNode alertDescNode = mapper.createObjectNode();
+ JsonObject vfcObjectNode = new JsonObject();
+ JsonObject alarmCondNode = new JsonObject();
+ JsonObject alertDescNode = new JsonObject();
if (cldsVfcDataList != null && !cldsVfcDataList.isEmpty()) {
for (CldsVfcData currCldsVfcData : cldsVfcDataList) {
if (currCldsVfcData != null) {
@@ -954,25 +953,25 @@ public class SdcCatalogServices { && !currCldsVfcData.getCldsAlarmConditions().isEmpty()) {
for (CldsAlarmCondition currCldsAlarmCondition : currCldsVfcData.getCldsAlarmConditions()) {
if ("alarmCondition".equalsIgnoreCase(currCldsAlarmCondition.getEventName())) {
- alarmCondNode.put(currCldsAlarmCondition.getAlarmConditionKey(),
+ alarmCondNode.addProperty(currCldsAlarmCondition.getAlarmConditionKey(),
currCldsAlarmCondition.getAlarmConditionKey());
} else {
- alertDescNode.put(currCldsAlarmCondition.getAlarmConditionKey(),
+ alertDescNode.addProperty(currCldsAlarmCondition.getAlarmConditionKey(),
currCldsAlarmCondition.getAlarmConditionKey());
}
}
}
- vfcObjectNode.putPOJO("alarmCondition", alarmCondNode);
- vfcObjectNode.putPOJO("alertDescription", alertDescNode);
- vfcResourceUuidObjectNode.putPOJO(currCldsVfcData.getVfcInvariantResourceUUID(), vfcObjectNode);
+ vfcObjectNode.add("alarmCondition", alarmCondNode);
+ vfcObjectNode.add("alertDescription", alertDescNode);
+ vfcResourceUuidObjectNode.add(currCldsVfcData.getVfcInvariantResourceUUID(), vfcObjectNode);
}
}
} else {
- alarmCondNode.put("", "");
- vfcObjectNode.putPOJO("alarmCondition", alarmCondNode);
- alertDescNode.put("", "");
- vfcObjectNode.putPOJO("alertDescription", alarmCondNode);
- vfcResourceUuidObjectNode.putPOJO("", vfcObjectNode);
+ alarmCondNode.addProperty("", "");
+ vfcObjectNode.add("alarmCondition", alarmCondNode);
+ alertDescNode.addProperty("", "");
+ vfcObjectNode.add("alertDescription", alarmCondNode);
+ vfcResourceUuidObjectNode.add("", vfcObjectNode);
}
}
@@ -983,45 +982,45 @@ public class SdcCatalogServices { * @param cldsVfDataList
* @return
*/
- private ObjectNode createVfcObjectNodeByVfUuid(List<CldsVfData> cldsVfDataList) {
- ObjectMapper mapper = JacksonUtils.getObjectMapperInstance();
- ObjectNode vfUuidObjectNode = mapper.createObjectNode();
+ private JsonObject createVfcObjectNodeByVfUuid(List<CldsVfData> cldsVfDataList) {
+ JsonObject vfUuidObjectNode = new JsonObject();
if (cldsVfDataList != null && !cldsVfDataList.isEmpty()) {
for (CldsVfData currCldsVfData : cldsVfDataList) {
if (currCldsVfData != null) {
- ObjectNode vfObjectNode = mapper.createObjectNode();
- ObjectNode vfcUuidNode = mapper.createObjectNode();
- ObjectNode kpiObjectNode = mapper.createObjectNode();
+ JsonObject vfObjectNode = new JsonObject();
+ JsonObject vfcUuidNode = new JsonObject();
+ JsonObject kpiObjectNode = new JsonObject();
if (currCldsVfData.getCldsVfcs() != null && !currCldsVfData.getCldsVfcs().isEmpty()) {
for (CldsVfcData currCldsVfcData : currCldsVfData.getCldsVfcs()) {
if (currCldsVfcData.getCldsAlarmConditions() != null
&& !currCldsVfcData.getCldsAlarmConditions().isEmpty()) {
- vfcUuidNode.put(currCldsVfcData.getVfcInvariantResourceUUID(),
+ vfcUuidNode.addProperty(currCldsVfcData.getVfcInvariantResourceUUID(),
currCldsVfcData.getVfcName());
}
}
} else {
- vfcUuidNode.put("", "");
+ vfcUuidNode.addProperty("", "");
}
if (currCldsVfData.getCldsKPIList() != null && !currCldsVfData.getCldsKPIList().isEmpty()) {
for (CldsVfKPIData currCldsVfKPIData : currCldsVfData.getCldsKPIList()) {
- kpiObjectNode.put(currCldsVfKPIData.getThresholdValue(),
+ // ToDo: something wrong happened here
+ kpiObjectNode.addProperty(currCldsVfKPIData.getThresholdValue(),
currCldsVfKPIData.getThresholdValue());
}
} else {
- kpiObjectNode.put("", "");
+ kpiObjectNode.addProperty("", "");
}
- vfObjectNode.putPOJO("vfc", vfcUuidNode);
- vfObjectNode.putPOJO("kpi", kpiObjectNode);
- vfUuidObjectNode.putPOJO(currCldsVfData.getVfInvariantResourceUUID(), vfObjectNode);
+ vfObjectNode.add("vfc", vfcUuidNode);
+ vfObjectNode.add("kpi", kpiObjectNode);
+ vfUuidObjectNode.add(currCldsVfData.getVfInvariantResourceUUID(), vfObjectNode);
}
}
} else {
- ObjectNode vfcUuidNode = mapper.createObjectNode();
- vfcUuidNode.put("", "");
- ObjectNode vfcObjectNode = mapper.createObjectNode();
- vfcObjectNode.putPOJO("vfc", vfcUuidNode);
- vfUuidObjectNode.putPOJO("", vfcObjectNode);
+ JsonObject vfcUuidNode = new JsonObject();
+ vfcUuidNode.addProperty("", "");
+ JsonObject vfcObjectNode = new JsonObject();
+ vfcObjectNode.add("vfc", vfcUuidNode);
+ vfUuidObjectNode.add("", vfcObjectNode);
}
return vfUuidObjectNode;
}
diff --git a/src/main/java/org/onap/clamp/clds/client/req/sdc/SdcRequests.java b/src/main/java/org/onap/clamp/clds/client/req/sdc/SdcRequests.java index efd664c6..d9093f4e 100644 --- a/src/main/java/org/onap/clamp/clds/client/req/sdc/SdcRequests.java +++ b/src/main/java/org/onap/clamp/clds/client/req/sdc/SdcRequests.java @@ -25,11 +25,10 @@ package org.onap.clamp.clds.client.req.sdc; import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFManager; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.ArrayNode; -import com.fasterxml.jackson.databind.node.ObjectNode; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.security.GeneralSecurityException; @@ -47,7 +46,7 @@ import org.onap.clamp.clds.model.properties.ModelProperties; import org.onap.clamp.clds.model.properties.Tca; import org.onap.clamp.clds.model.sdc.SdcResource; import org.onap.clamp.clds.model.sdc.SdcServiceDetail; -import org.onap.clamp.clds.util.JacksonUtils; +import org.onap.clamp.clds.util.JsonUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Primary; import org.springframework.stereotype.Component; @@ -98,16 +97,15 @@ public class SdcRequests { * @return SDC Locations request in the JSON Format */ public String formatSdcLocationsReq(ModelProperties prop, String artifactName) { - ObjectMapper objectMapper = JacksonUtils.getObjectMapperInstance(); Global global = prop.getGlobal(); List<String> locationsList = global.getLocation(); - ArrayNode locationsArrayNode = objectMapper.createArrayNode(); - ObjectNode locationObject = objectMapper.createObjectNode(); + JsonArray locationsArrayNode = new JsonArray(); + JsonObject locationObject = new JsonObject(); for (String currLocation : locationsList) { locationsArrayNode.add(currLocation); } - locationObject.put("artifactName", artifactName); - locationObject.putPOJO("locations", locationsArrayNode); + locationObject.addProperty("artifactName", artifactName); + locationObject.add("locations", locationsArrayNode); String locationJsonFormat = locationObject.toString(); logger.info("Value of location Json Artifact:" + locationsArrayNode); return locationJsonFormat; @@ -207,18 +205,18 @@ public class SdcRequests { */ protected String getYamlvalue(String jsonGlobal) throws IOException { String yamlFileValue = ""; - ObjectNode root = JacksonUtils.getObjectMapperInstance().readValue(jsonGlobal, ObjectNode.class); - Iterator<Entry<String, JsonNode>> entryItr = root.fields(); + JsonObject root = JsonUtils.GSON.fromJson(jsonGlobal, JsonObject.class); + Iterator<Entry<String, JsonElement>> entryItr = root.entrySet().iterator(); while (entryItr.hasNext()) { - Entry<String, JsonNode> entry = entryItr.next(); + Entry<String, JsonElement> entry = entryItr.next(); String key = entry.getKey(); if (key != null && key.equalsIgnoreCase("global")) { - ArrayNode arrayNode = (ArrayNode) entry.getValue(); - for (JsonNode anArrayNode : arrayNode) { - ObjectNode node = (ObjectNode) anArrayNode; - ArrayNode arrayValueNode = (ArrayNode) node.get("value"); - JsonNode jsonNode = arrayValueNode.get(0); - yamlFileValue = jsonNode.asText(); + JsonArray arrayNode = entry.getValue().getAsJsonArray(); + for (JsonElement anArrayNode : arrayNode) { + JsonObject node = anArrayNode.getAsJsonObject(); + JsonArray arrayValueNode = node.get("value").getAsJsonArray(); + JsonElement jsonNode = arrayValueNode.get(0); + yamlFileValue = jsonNode.getAsString(); logger.info("value:" + yamlFileValue); } break; diff --git a/src/main/java/org/onap/clamp/clds/client/req/tca/TcaRequestFormatter.java b/src/main/java/org/onap/clamp/clds/client/req/tca/TcaRequestFormatter.java index 1478342c..6b8f0439 100644 --- a/src/main/java/org/onap/clamp/clds/client/req/tca/TcaRequestFormatter.java +++ b/src/main/java/org/onap/clamp/clds/client/req/tca/TcaRequestFormatter.java @@ -25,10 +25,9 @@ package org.onap.clamp.clds.client.req.tca; import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFManager; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.node.ArrayNode; -import com.fasterxml.jackson.databind.node.ObjectNode; +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; import java.io.IOException; import java.util.Map; @@ -38,6 +37,7 @@ import org.onap.clamp.clds.model.properties.ModelProperties; import org.onap.clamp.clds.model.properties.Tca; import org.onap.clamp.clds.model.properties.TcaItem; import org.onap.clamp.clds.model.properties.TcaThreshold; +import org.onap.clamp.clds.util.JsonUtils; import org.yaml.snakeyaml.Yaml; /** @@ -71,10 +71,10 @@ public class TcaRequestFormatter { modelProperties.setCurrentModelElementId(tca.getId()); // Always one tcaItem so must be set to id 0 modelProperties.setPolicyUniqueId("0"); - ObjectNode rootNode = (ObjectNode) refProp.getJsonTemplate("tca.policy.template", service); + JsonObject rootNode = refProp.getJsonTemplate("tca.policy.template", service ).getAsJsonObject(); String policyName = modelProperties.getCurrentPolicyScopeAndPolicyName(); - rootNode.put("policyName", policyName); - ((ObjectNode) rootNode.get("content")).replace("tca_policy", + rootNode.addProperty("policyName", policyName); + rootNode.get("content").getAsJsonObject().add("tca_policy", createPolicyContent(refProp, modelProperties, service, policyName, tca)); String tcaPolicyReq = rootNode.toString(); logger.info("tcaPolicyReq=" + tcaPolicyReq); @@ -104,7 +104,7 @@ public class TcaRequestFormatter { * modelProperties.setCurrentModelElementId will be used * @return The Json node containing what should be sent to policy */ - public static JsonNode createPolicyContent(ClampProperties refProp, ModelProperties modelProperties, String service, + public static JsonObject createPolicyContent(ClampProperties refProp, ModelProperties modelProperties, String service, String policyName, Tca tca) { try { String serviceToUse = service; @@ -120,14 +120,12 @@ public class TcaRequestFormatter { if (policyNameToUse == null) { policyNameToUse = modelProperties.getCurrentPolicyScopeAndPolicyName(); } - ObjectNode rootNode = (ObjectNode) refProp.getJsonTemplate("tca.template", serviceToUse); - ((ObjectNode) rootNode.get("metricsPerEventName").get(0)).put("eventName", - tcaToUse.getTcaItem().getEventName()); - ((ObjectNode) rootNode.get("metricsPerEventName").get(0)).put("policyName", policyNameToUse); - ((ObjectNode) rootNode.get("metricsPerEventName").get(0)).put("controlLoopSchemaType", - tcaToUse.getTcaItem().getControlLoopSchemaType()); - ObjectNode thresholdsParent = ((ObjectNode) rootNode.get("metricsPerEventName").get(0)); - addThresholds(refProp, serviceToUse, thresholdsParent, tcaToUse.getTcaItem(), modelProperties); + JsonObject rootNode = refProp.getJsonTemplate("tca.template", serviceToUse).getAsJsonObject(); + JsonObject metricsPerEventName = rootNode.get("metricsPerEventName").getAsJsonArray().get(0).getAsJsonObject(); + metricsPerEventName.addProperty("eventName", tcaToUse.getTcaItem().getEventName()); + metricsPerEventName.addProperty("policyName", policyNameToUse); + metricsPerEventName.addProperty("controlLoopSchemaType",tcaToUse.getTcaItem().getControlLoopSchemaType()); + addThresholds(refProp, serviceToUse, metricsPerEventName, tcaToUse.getTcaItem(), modelProperties); logger.info("tcaPolicyContent=" + rootNode.toString()); return rootNode; } catch (IOException e) { @@ -154,17 +152,17 @@ public class TcaRequestFormatter { * The Model Properties created from BPMN JSON and BPMN * properties JSON */ - private static void addThresholds(ClampProperties refProp, String service, ObjectNode appendToNode, TcaItem tcaItem, + private static void addThresholds(ClampProperties refProp, String service, JsonObject appendToNode, TcaItem tcaItem, ModelProperties modelProperties) { - ArrayNode tcaNodes = appendToNode.withArray("thresholds"); + JsonArray tcaNodes = appendToNode.get("thresholds").getAsJsonArray(); try { for (TcaThreshold tcaThreshold : tcaItem.getTcaThresholds()) { - ObjectNode tcaNode = (ObjectNode) refProp.getJsonTemplate("tca.thresholds.template", service); - tcaNode.put("closedLoopControlName", modelProperties.getControlNameAndPolicyUniqueId()); - tcaNode.put("fieldPath", tcaThreshold.getFieldPath()); - tcaNode.put("thresholdValue", tcaThreshold.getThreshold()); - tcaNode.put("direction", tcaThreshold.getOperator()); - tcaNode.put("closedLoopEventStatus", tcaThreshold.getClosedLoopEventStatus()); + JsonObject tcaNode = refProp.getJsonTemplate("tca.thresholds.template", service).getAsJsonObject(); + tcaNode.addProperty("closedLoopControlName", modelProperties.getControlNameAndPolicyUniqueId()); + tcaNode.addProperty("fieldPath", tcaThreshold.getFieldPath()); + tcaNode.addProperty("thresholdValue", tcaThreshold.getThreshold()); + tcaNode.addProperty("direction", tcaThreshold.getOperator()); + tcaNode.addProperty("closedLoopEventStatus", tcaThreshold.getClosedLoopEventStatus()); tcaNodes.add(tcaNode); } } catch (IOException e) { @@ -187,7 +185,7 @@ public class TcaRequestFormatter { */ public static String updatedBlueprintWithConfiguration(ClampProperties refProp, ModelProperties modelProperties, String yamlValue) { - String jsonPolicy = ((ObjectNode) createPolicyContent(refProp, modelProperties, null, null, null)).toString(); + String jsonPolicy = JsonUtils.GSON.toJson(createPolicyContent(refProp, modelProperties, null, null, null)); logger.info("Yaml that will be updated:" + yamlValue); Yaml yaml = new Yaml(); Map<String, Object> loadedYaml = (Map<String, Object>) yaml.load(yamlValue); diff --git a/src/main/java/org/onap/clamp/clds/config/ClampProperties.java b/src/main/java/org/onap/clamp/clds/config/ClampProperties.java index 9acad94a..4f1e8a28 100644 --- a/src/main/java/org/onap/clamp/clds/config/ClampProperties.java +++ b/src/main/java/org/onap/clamp/clds/config/ClampProperties.java @@ -23,16 +23,16 @@ package org.onap.clamp.clds.config; -import com.fasterxml.jackson.databind.JsonNode; import com.google.common.base.Splitter; +import com.google.gson.JsonElement; import java.io.IOException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.List; import org.apache.commons.io.IOUtils; -import org.onap.clamp.clds.util.JacksonUtils; +import org.onap.clamp.clds.util.JsonUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.core.env.Environment; @@ -89,10 +89,10 @@ public class ClampProperties { * @throws IOException * In case of issues with the JSON parser */ - public JsonNode getJsonTemplate(String key) throws IOException { + public JsonElement getJsonTemplate(String key) throws IOException { String fileReference = getStringValue(key); return (fileReference != null) - ? JacksonUtils.getObjectMapperInstance().readValue(getFileContentFromPath(fileReference), JsonNode.class) + ? JsonUtils.GSON.fromJson(getFileContentFromPath(fileReference), JsonElement.class) : null; } @@ -109,10 +109,10 @@ public class ClampProperties { * @throws IOException * In case of issues with the JSON parser */ - public JsonNode getJsonTemplate(String key1, String key2) throws IOException { + public JsonElement getJsonTemplate(String key1, String key2) throws IOException { String fileReference = getStringValue(key1, key2); return (fileReference != null) - ? JacksonUtils.getObjectMapperInstance().readValue(getFileContentFromPath(fileReference), JsonNode.class) + ? JsonUtils.GSON.fromJson(getFileContentFromPath(fileReference), JsonElement.class) : null; } diff --git a/src/main/java/org/onap/clamp/clds/config/CldsUserJsonDecoder.java b/src/main/java/org/onap/clamp/clds/config/CldsUserJsonDecoder.java index 0b873335..d1beb956 100644 --- a/src/main/java/org/onap/clamp/clds/config/CldsUserJsonDecoder.java +++ b/src/main/java/org/onap/clamp/clds/config/CldsUserJsonDecoder.java @@ -23,14 +23,18 @@ package org.onap.clamp.clds.config; +import com.google.gson.JsonParseException; +import com.google.gson.reflect.TypeToken; import java.io.IOException; import java.io.InputStream; +import java.lang.reflect.Type; import java.nio.charset.StandardCharsets; +import java.util.List; import org.apache.commons.io.IOUtils; import org.onap.clamp.clds.exception.CldsUsersException; import org.onap.clamp.clds.service.CldsUser; -import org.onap.clamp.clds.util.JacksonUtils; +import org.onap.clamp.clds.util.JsonUtils; public class CldsUserJsonDecoder { @@ -55,8 +59,8 @@ public class CldsUserJsonDecoder { try { // the ObjectMapper readValue method closes the stream no need to do // it - return JacksonUtils.getObjectMapperInstance().readValue(cldsUsersString, CldsUser[].class); - } catch (IOException e) { + return JsonUtils.GSON.fromJson(cldsUsersString, CldsUser[].class); + } catch (JsonParseException e) { throw new CldsUsersException("Exception occurred during the decoding of the clds-users.json", e); } } diff --git a/src/main/java/org/onap/clamp/clds/config/sdc/BlueprintParserMappingConfiguration.java b/src/main/java/org/onap/clamp/clds/config/sdc/BlueprintParserMappingConfiguration.java index 2cab17b3..2f0e698c 100644 --- a/src/main/java/org/onap/clamp/clds/config/sdc/BlueprintParserMappingConfiguration.java +++ b/src/main/java/org/onap/clamp/clds/config/sdc/BlueprintParserMappingConfiguration.java @@ -23,13 +23,16 @@ package org.onap.clamp.clds.config.sdc; -import com.fasterxml.jackson.core.type.TypeReference; -import java.io.IOException; +import com.google.gson.JsonElement; +import com.google.gson.JsonParser; +import com.google.gson.reflect.TypeToken; import java.io.InputStream; +import java.io.InputStreamReader; +import java.lang.reflect.Type; +import java.nio.charset.StandardCharsets; import java.util.List; - -import org.onap.clamp.clds.util.JacksonUtils; +import org.onap.clamp.clds.util.JsonUtils; /** * This class is used to decode the configuration found in @@ -39,6 +42,8 @@ import org.onap.clamp.clds.util.JacksonUtils; */ public class BlueprintParserMappingConfiguration { + private static final Type BLUEPRINT_MAP_CONF_TYPE = new TypeToken<List<BlueprintParserMappingConfiguration>>() { + }.getType(); private String blueprintKey; private boolean dcaeDeployable; private BlueprintParserFilesConfiguration files; @@ -63,9 +68,7 @@ public class BlueprintParserMappingConfiguration { return dcaeDeployable; } - public static List<BlueprintParserMappingConfiguration> createFromJson(InputStream json) throws IOException { - TypeReference<List<BlueprintParserMappingConfiguration>> mapType = new TypeReference<List<BlueprintParserMappingConfiguration>>() { - }; - return JacksonUtils.getObjectMapperInstance().readValue(json, mapType); + public static List<BlueprintParserMappingConfiguration> createFromJson(InputStream json) { + return JsonUtils.GSON.fromJson(new InputStreamReader(json, StandardCharsets.UTF_8), BLUEPRINT_MAP_CONF_TYPE); } } diff --git a/src/main/java/org/onap/clamp/clds/config/sdc/SdcControllersConfiguration.java b/src/main/java/org/onap/clamp/clds/config/sdc/SdcControllersConfiguration.java index 0f75d46e..b21c75f2 100644 --- a/src/main/java/org/onap/clamp/clds/config/sdc/SdcControllersConfiguration.java +++ b/src/main/java/org/onap/clamp/clds/config/sdc/SdcControllersConfiguration.java @@ -25,16 +25,18 @@ package org.onap.clamp.clds.config.sdc; import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFManager; -import com.fasterxml.jackson.databind.JsonNode; +import com.google.gson.JsonObject; import java.io.IOException; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; import javax.annotation.PostConstruct; import org.onap.clamp.clds.exception.sdc.controller.SdcParametersException; -import org.onap.clamp.clds.util.JacksonUtils; +import org.onap.clamp.clds.util.JsonUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.ApplicationContext; @@ -59,13 +61,13 @@ public class SdcControllersConfiguration { /** * The root of the JSON. */ - private JsonNode jsonRootNode; + private JsonObject jsonRootNode; @PostConstruct public void loadConfiguration() throws IOException { Resource resource = appContext.getResource(sdcControllerFile); // Try to load json tree - jsonRootNode = JacksonUtils.getObjectMapperInstance().readValue(resource.getInputStream(), JsonNode.class); + jsonRootNode = JsonUtils.GSON.fromJson(new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8), JsonObject.class); } public SdcSingleControllerConfiguration getSdcSingleControllerConfiguration(String controllerName) { @@ -80,8 +82,9 @@ public class SdcControllersConfiguration { public Map<String, SdcSingleControllerConfiguration> getAllDefinedControllers() { Map<String, SdcSingleControllerConfiguration> result = new HashMap<>(); if (jsonRootNode.get(CONTROLLER_SUBTREE_KEY) != null) { - jsonRootNode.get(CONTROLLER_SUBTREE_KEY).fields().forEachRemaining(entry -> result.put(entry.getKey(), - new SdcSingleControllerConfiguration(entry.getValue(), entry.getKey()))); + jsonRootNode.get(CONTROLLER_SUBTREE_KEY).getAsJsonObject().entrySet().forEach( + entry -> result.put(entry.getKey(), + new SdcSingleControllerConfiguration(entry.getValue().getAsJsonObject(), entry.getKey()))); } else { throw new SdcParametersException( CONTROLLER_SUBTREE_KEY + " key not found in the file: " + sdcControllerFile); diff --git a/src/main/java/org/onap/clamp/clds/config/sdc/SdcSingleControllerConfiguration.java b/src/main/java/org/onap/clamp/clds/config/sdc/SdcSingleControllerConfiguration.java index ca756aa0..564e01f1 100644 --- a/src/main/java/org/onap/clamp/clds/config/sdc/SdcSingleControllerConfiguration.java +++ b/src/main/java/org/onap/clamp/clds/config/sdc/SdcSingleControllerConfiguration.java @@ -25,8 +25,8 @@ package org.onap.clamp.clds.config.sdc; import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFManager; -import com.fasterxml.jackson.databind.JsonNode; +import com.google.gson.JsonObject; import java.security.GeneralSecurityException; import java.util.ArrayList; import java.util.Arrays; @@ -52,7 +52,7 @@ public class SdcSingleControllerConfiguration implements IConfiguration { /** * The root of the JSON. */ - private JsonNode jsonRootNode; + private JsonObject jsonRootNode; // All keys that can be present in the JSON public static final String CONSUMER_GROUP_ATTRIBUTE_NAME = "consumerGroup"; public static final String CONSUMER_ID_ATTRIBUTE_NAME = "consumerId"; @@ -90,12 +90,12 @@ public class SdcSingleControllerConfiguration implements IConfiguration { * This constructor builds a SdcSingleControllerConfiguration from the * corresponding json. * - * @param jsonRootNode + * @param jsonNode * The JSON node * @param controllerName * The controller name that must appear in the JSON */ - public SdcSingleControllerConfiguration(JsonNode jsonNode, String controllerName) { + public SdcSingleControllerConfiguration(JsonObject jsonNode, String controllerName) { jsonRootNode = jsonNode; setSdcControllerName(controllerName); testAllRequiredParameters(); @@ -113,7 +113,7 @@ public class SdcSingleControllerConfiguration implements IConfiguration { private String getStringConfig(String key) { if (jsonRootNode != null && jsonRootNode.get(key) != null) { - String config = jsonRootNode.get(key).asText(); + String config = jsonRootNode.get(key).getAsString(); return config.isEmpty() ? null : config; } return null; @@ -121,7 +121,7 @@ public class SdcSingleControllerConfiguration implements IConfiguration { private Integer getIntConfig(String key) { if (jsonRootNode != null && jsonRootNode.get(key) != null) { - return jsonRootNode.get(key).asInt(); + return jsonRootNode.get(key).getAsInt(); } else { return 0; } @@ -129,8 +129,8 @@ public class SdcSingleControllerConfiguration implements IConfiguration { private String getEncryptedStringConfig(String key) throws GeneralSecurityException, DecoderException { if (jsonRootNode != null && jsonRootNode.get(key) != null) { - return jsonRootNode.get(key).asText().isEmpty() ? null - : CryptoUtils.decrypt(jsonRootNode.get(key).asText()); + return jsonRootNode.get(key).getAsString().isEmpty() ? null + : CryptoUtils.decrypt(jsonRootNode.get(key).getAsString()); } return null; } @@ -143,7 +143,7 @@ public class SdcSingleControllerConfiguration implements IConfiguration { @Override public String getConsumerGroup() { if (jsonRootNode != null && jsonRootNode.get(CONSUMER_GROUP_ATTRIBUTE_NAME) != null) { - String config = jsonRootNode.get(CONSUMER_GROUP_ATTRIBUTE_NAME).asText(); + String config = jsonRootNode.get(CONSUMER_GROUP_ATTRIBUTE_NAME).getAsString(); return "NULL".equals(config) || config.isEmpty() ? null : config; } return null; @@ -198,8 +198,8 @@ public class SdcSingleControllerConfiguration implements IConfiguration { @Override public boolean activateServerTLSAuth() { - if (jsonRootNode != null && jsonRootNode.get(ACTIVATE_SERVER_TLS_AUTH) != null) { - return jsonRootNode.get(ACTIVATE_SERVER_TLS_AUTH).asBoolean(false); + if (jsonRootNode != null && jsonRootNode.get(ACTIVATE_SERVER_TLS_AUTH) != null && jsonRootNode.get(ACTIVATE_SERVER_TLS_AUTH).isJsonPrimitive()) { + return jsonRootNode.get(ACTIVATE_SERVER_TLS_AUTH).getAsBoolean(); } else { return false; } @@ -231,7 +231,7 @@ public class SdcSingleControllerConfiguration implements IConfiguration { throw new SdcParametersException("Json is null for controller " + this.getSdcControllerName()); } if (this.getConsumerGroup() == null && (jsonRootNode.get(CONSUMER_GROUP_ATTRIBUTE_NAME) == null - || !"NULL".equals(jsonRootNode.get(CONSUMER_GROUP_ATTRIBUTE_NAME).asText()))) { + || !"NULL".equals(jsonRootNode.get(CONSUMER_GROUP_ATTRIBUTE_NAME).getAsString()))) { throw new SdcParametersException(CONSUMER_GROUP_ATTRIBUTE_NAME + errorMessageKeyNotFound); } if (this.getConsumerID() == null || this.getConsumerID().isEmpty()) { @@ -277,7 +277,7 @@ public class SdcSingleControllerConfiguration implements IConfiguration { public List<String> getMsgBusAddress() { List<String> addressesList = new ArrayList<>(); if (jsonRootNode != null && jsonRootNode.get(MESSAGE_BUS_ADDRESSES) != null) { - jsonRootNode.get(MESSAGE_BUS_ADDRESSES).forEach(k -> addressesList.add(k.asText())); + jsonRootNode.get(MESSAGE_BUS_ADDRESSES).getAsJsonArray().forEach(k -> addressesList.add(k.getAsString())); return addressesList; } else { return addressesList; diff --git a/src/main/java/org/onap/clamp/clds/model/CldsModelInstance.java b/src/main/java/org/onap/clamp/clds/model/CldsModelInstance.java index 75801ae2..082bfe33 100644 --- a/src/main/java/org/onap/clamp/clds/model/CldsModelInstance.java +++ b/src/main/java/org/onap/clamp/clds/model/CldsModelInstance.java @@ -23,9 +23,6 @@ package org.onap.clamp.clds.model; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -@JsonIgnoreProperties(ignoreUnknown = true) public class CldsModelInstance { private String modelInstanceId; diff --git a/src/main/java/org/onap/clamp/clds/model/actions/ActionsHandler.java b/src/main/java/org/onap/clamp/clds/model/actions/ActionsHandler.java index 1c54dae0..bafe48d9 100644 --- a/src/main/java/org/onap/clamp/clds/model/actions/ActionsHandler.java +++ b/src/main/java/org/onap/clamp/clds/model/actions/ActionsHandler.java @@ -24,14 +24,13 @@ package org.onap.clamp.clds.model.actions; import com.att.eelf.configuration.EELFLogger; -import com.fasterxml.jackson.databind.JsonNode; - -import java.io.IOException; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; import java.util.Arrays; import java.util.List; - import org.onap.clamp.clds.model.CldsEvent; -import org.onap.clamp.clds.util.JacksonUtils; +import org.onap.clamp.clds.util.JsonUtils; /** * Interface for actions that the user can do according to the last event. @@ -44,7 +43,7 @@ public interface ActionsHandler { SIMPLE_MODEL("simpleModel"), POLICY_MODEL("policyModel"); private final String type; - private ModelType(String type) { + ModelType(String type) { this.type = type; } @@ -53,7 +52,7 @@ public interface ActionsHandler { } } - public EELFLogger getLogger(); + EELFLogger getLogger(); /** * This method determines a list of actions that the user can do according to @@ -155,13 +154,15 @@ public interface ActionsHandler { boolean result = false; try { if (propText != null) { - JsonNode modelJson = JacksonUtils.getObjectMapperInstance().readTree(propText); - JsonNode modelJsonOfType = modelJson.get(key.getType()); - if (modelJsonOfType != null && modelJsonOfType.asBoolean()) { + JsonObject modelJson = JsonUtils.GSON.fromJson(propText, JsonObject.class); + JsonElement modelJsonOfType = modelJson.get(key.getType()); + if (modelJsonOfType != null + && modelJsonOfType.isJsonPrimitive() + && modelJsonOfType.getAsJsonPrimitive().getAsBoolean()) { result = true; } } - } catch (IOException e) { + } catch (JsonParseException e) { getLogger().error("Error while parsing propText json", e); } return result; diff --git a/src/main/java/org/onap/clamp/clds/model/properties/AbstractModelElement.java b/src/main/java/org/onap/clamp/clds/model/properties/AbstractModelElement.java index 571e5b1b..8e8debe8 100644 --- a/src/main/java/org/onap/clamp/clds/model/properties/AbstractModelElement.java +++ b/src/main/java/org/onap/clamp/clds/model/properties/AbstractModelElement.java @@ -25,15 +25,12 @@ package org.onap.clamp.clds.model.properties; import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFManager; -import com.fasterxml.jackson.databind.JsonNode; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; /** - * Provide base ModelElement functionality. Perform base parsing of properties - * for a ModelElement (such as, VesCollector, Policy, Tca, Holmes, ...) + * Provide base ModelElement functionality. Perform base parsing of properties for a ModelElement (such as, + * VesCollector, Policy, Tca, Holmes, ...) */ public abstract class AbstractModelElement { @@ -43,17 +40,14 @@ public abstract class AbstractModelElement { private final ModelBpmn modelBpmn; private final String id; protected String topicPublishes; - protected final JsonNode modelElementJsonNode; + protected final JsonElement modelElementJsonNode; private boolean isFound; private final ModelProperties modelProp; - private static final String LOG_ELEMENT_NOT_FOUND = "Value '{}' for key 'name' not found in JSON"; - private static final String LOG_ELEMENT_NOT_FOUND_IN_JSON = "Value '{}' for key 'name' not found in JSON {}"; /** - * Perform base parsing of properties for a ModelElement (such as, VesCollector, - * Policy and Tca) + * Perform base parsing of properties for a ModelElement (such as, VesCollector, Policy and Tca) */ - protected AbstractModelElement(String type, ModelProperties modelProp, ModelBpmn modelBpmn, JsonNode modelJson) { + protected AbstractModelElement(String type, ModelProperties modelProp, ModelBpmn modelBpmn, JsonObject modelJson) { this.type = type; this.modelProp = modelProp; this.modelBpmn = modelBpmn; @@ -69,163 +63,6 @@ public abstract class AbstractModelElement { return topicPublishes; } - /** - * Return the value field of the json node element that has a name field equals - * to the given name. - */ - public static String getValueByName(JsonNode nodeIn, String name) { - String value = null; - if (nodeIn != null) { - for (JsonNode node : nodeIn) { - if (node.path("name").asText().equals(name)) { - JsonNode vnode = node.path("value"); - if (vnode.isArray()) { - // if array, assume value is in first element - value = vnode.path(0).asText(); - } else { - // otherwise, just return text - value = vnode.asText(); - } - } - } - } - if (value == null || value.length() == 0) { - logger.warn(LOG_ELEMENT_NOT_FOUND, name); - } else { - logger.debug(LOG_ELEMENT_NOT_FOUND_IN_JSON, name, nodeIn.toString()); - } - return value; - } - - /** - * Return the Json value field of the json node element that has a name field - * equals to the given name. - */ - public static JsonNode getJsonNodeByName(JsonNode nodeIn, String name) { - JsonNode vnode = null; - if (nodeIn != null) { - for (JsonNode node : nodeIn) { - if (node.path("name").asText().equals(name)) { - vnode = node.path("value"); - } - } - } - if (vnode == null) { - logger.warn(LOG_ELEMENT_NOT_FOUND, name); - } else { - logger.debug(LOG_ELEMENT_NOT_FOUND_IN_JSON, name, nodeIn.toString()); - } - return vnode; - } - - /** - * Return the value field of the json node element that has a name field that - * equals the given name. - */ - public static String getNodeValueByName(JsonNode nodeIn, String name) { - String value = null; - if (nodeIn != null) { - value = nodeIn.path(name).asText(); - } - if (value == null || value.length() == 0) { - logger.warn(LOG_ELEMENT_NOT_FOUND, name); - } else { - logger.debug(LOG_ELEMENT_NOT_FOUND_IN_JSON, name, nodeIn.toString()); - } - return value; - } - - /** - * Return the value field of the json node element that has a name field that - * equals the given name. - */ - public static List<String> getNodeValuesByName(JsonNode nodeIn, String name) { - List<String> values = new ArrayList<>(); - if (nodeIn != null) { - for (JsonNode node : nodeIn) { - if (node.path("name").asText().equals(name)) { - JsonNode vnode = node.path("value"); - if (vnode.isArray()) { - // if array, assume value is in first element - values.add(vnode.path(0).asText()); - } else { - // otherwise, just return text - values.add(vnode.asText()); - } - } - } - } - return values; - } - - /** - * Return the int value field of the json node element that has a name field - * equals to the given name. - */ - public static Integer getIntValueByName(JsonNode nodeIn, String name) { - String value = getValueByName(nodeIn, name); - return Integer.valueOf(value); - } - - /** - * Return an array of values for the field of the json node element that has a - * name field equals to the given name. - */ - public static List<String> getValuesByName(JsonNode nodeIn, String name) { - List<String> values = null; - if (nodeIn != null) { - for (JsonNode node : nodeIn) { - if (node.path("name").asText().equals(name)) { - values = getValuesList(node); - } - } - } - if (values == null || values.isEmpty()) { - logger.warn(LOG_ELEMENT_NOT_FOUND, name); - } else { - logger.debug(LOG_ELEMENT_NOT_FOUND_IN_JSON, name, nodeIn.toString()); - } - return values; - } - - /** - * Return an array of String values. - */ - public static List<String> getValuesList(JsonNode nodeIn) { - ArrayList<String> al = new ArrayList<>(); - if (nodeIn != null) { - Iterator<JsonNode> itr = nodeIn.path("value").elements(); - while (itr.hasNext()) { - JsonNode node = itr.next(); - al.add(node.asText()); - } - } - return al; - } - - /** - * Return the value field of the json node element that has a name field equals - * to the given name. - */ - public String getValueByName(String name) { - return getValueByName(modelElementJsonNode, name); - } - - /** - * Return the int value field of the json node element that has a name field - * equals to the given name. - */ - public Integer getIntValueByName(String name) { - return getIntValueByName(modelElementJsonNode, name); - } - - /** - * Return an array of values for the field of the json node element that has a - * name field equals to the given name. - */ - public List<String> getValuesByName(String name) { - return getValuesByName(modelElementJsonNode, name); - } /** * @return the id diff --git a/src/main/java/org/onap/clamp/clds/model/properties/Global.java b/src/main/java/org/onap/clamp/clds/model/properties/Global.java index e8674072..66491489 100644 --- a/src/main/java/org/onap/clamp/clds/model/properties/Global.java +++ b/src/main/java/org/onap/clamp/clds/model/properties/Global.java @@ -25,9 +25,11 @@ package org.onap.clamp.clds.model.properties; import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFManager; -import com.fasterxml.jackson.databind.JsonNode; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; import java.util.List; +import org.onap.clamp.clds.util.JsonUtils; /** * Parse global json properties. @@ -45,7 +47,7 @@ public class Global { private String actionSet; private List<String> resourceVf; private List<String> resourceVfc; - private JsonNode deployParameters; + private JsonObject deployParameters; private List<String> location; private String vnfScope; @@ -54,15 +56,15 @@ public class Global { * * @param modelJson */ - public Global(JsonNode modelJson) { - JsonNode globalNode = modelJson.get("global"); - service = AbstractModelElement.getValueByName(globalNode, "service"); - actionSet = AbstractModelElement.getValueByName(globalNode, "actionSet"); - resourceVf = AbstractModelElement.getValuesByName(globalNode, "vf"); - resourceVfc = AbstractModelElement.getValuesByName(globalNode, "vfc"); - deployParameters = AbstractModelElement.getJsonNodeByName(globalNode, "deployParameters"); - location = AbstractModelElement.getValuesByName(globalNode, "location"); - vnfScope = AbstractModelElement.getValueByName(globalNode, "vnf"); + public Global(JsonObject modelJson) { + JsonElement globalNode = modelJson.get("global"); + service = JsonUtils.getStringValueByName(globalNode, "service"); + actionSet = JsonUtils.getStringValueByName(globalNode, "actionSet"); + resourceVf = JsonUtils.getStringValuesByName(globalNode, "vf"); + resourceVfc = JsonUtils.getStringValuesByName(globalNode, "vfc"); + deployParameters = JsonUtils.getJsonObjectByName(globalNode, "deployParameters"); + location = JsonUtils.getStringValuesByName(globalNode, "location"); + vnfScope = JsonUtils.getStringValueByName(globalNode, "vnf"); } /** @@ -136,11 +138,11 @@ public class Global { this.location = location; } - public JsonNode getDeployParameters() { + public JsonObject getDeployParameters() { return deployParameters; } - public void setDeployParameters(JsonNode deployParameters) { + public void setDeployParameters(JsonObject deployParameters) { this.deployParameters = deployParameters; } diff --git a/src/main/java/org/onap/clamp/clds/model/properties/Holmes.java b/src/main/java/org/onap/clamp/clds/model/properties/Holmes.java index 530e2db9..b0607e91 100644 --- a/src/main/java/org/onap/clamp/clds/model/properties/Holmes.java +++ b/src/main/java/org/onap/clamp/clds/model/properties/Holmes.java @@ -23,7 +23,8 @@ package org.onap.clamp.clds.model.properties; -import com.fasterxml.jackson.databind.JsonNode; +import com.google.gson.JsonObject; +import org.onap.clamp.clds.util.JsonUtils; /** * Parse Holmes bpmn parameters json properties. @@ -49,11 +50,11 @@ public class Holmes extends AbstractModelElement { * @param modelBpmn * @param modelJson */ - public Holmes(ModelProperties modelProp, ModelBpmn modelBpmn, JsonNode modelJson) { + public Holmes(ModelProperties modelProp, ModelBpmn modelBpmn, JsonObject modelJson) { super(TYPE_HOLMES, modelProp, modelBpmn, modelJson); - correlationLogic = this.getValueByName("correlationalLogic"); - configPolicyName = this.getValueByName("configPolicyName"); + correlationLogic = JsonUtils.getStringValueByName(modelElementJsonNode, "correlationalLogic"); + configPolicyName = JsonUtils.getStringValueByName(modelElementJsonNode, "configPolicyName"); } public static final String getType() { diff --git a/src/main/java/org/onap/clamp/clds/model/properties/ModelBpmn.java b/src/main/java/org/onap/clamp/clds/model/properties/ModelBpmn.java index dbd5d8a4..248a52fc 100644 --- a/src/main/java/org/onap/clamp/clds/model/properties/ModelBpmn.java +++ b/src/main/java/org/onap/clamp/clds/model/properties/ModelBpmn.java @@ -25,11 +25,11 @@ package org.onap.clamp.clds.model.properties; import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFManager; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.node.ArrayNode; -import com.fasterxml.jackson.databind.node.ObjectNode; -import java.io.IOException; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; @@ -39,7 +39,7 @@ import java.util.Map.Entry; import org.onap.clamp.clds.exception.ModelBpmnException; import org.onap.clamp.clds.service.CldsService; -import org.onap.clamp.clds.util.JacksonUtils; +import org.onap.clamp.clds.util.JsonUtils; /** * Parse Model BPMN properties. @@ -66,22 +66,22 @@ public class ModelBpmn { public static ModelBpmn create(String modelBpmnPropText) { try { ModelBpmn modelBpmn = new ModelBpmn(); - ObjectNode root = JacksonUtils.getObjectMapperInstance().readValue(modelBpmnPropText, ObjectNode.class); + JsonObject root = JsonUtils.GSON.fromJson(modelBpmnPropText, JsonObject.class); // iterate over each entry like: // "Policy":[{"id":"Policy","from":"StartEvent_1"}] - Iterator<Entry<String, JsonNode>> entryItr = root.fields(); + Iterator<Entry<String, JsonElement>> entryItr = root.entrySet().iterator(); List<String> bpmnElementIdList = new ArrayList<>(); while (entryItr.hasNext()) { // process the entry - Entry<String, JsonNode> entry = entryItr.next(); + Entry<String, JsonElement> entry = entryItr.next(); String type = entry.getKey(); - ArrayNode arrayNode = (ArrayNode) entry.getValue(); + JsonArray arrayNode = entry.getValue().getAsJsonArray(); // process each id/from object, like: // {"id":"Policy","from":"StartEvent_1"} - for (JsonNode anArrayNode : arrayNode) { - ObjectNode node = (ObjectNode) anArrayNode; - String id = node.get("id").asText(); - String fromId = node.get("from").asText(); + for (JsonElement anArrayNode : arrayNode) { + JsonObject node = anArrayNode.getAsJsonObject(); + String id = node.get("id").getAsString(); + String fromId = node.get("from").getAsString(); ModelBpmnEntry modelBpmnEntry = new ModelBpmnEntry(type, id, fromId); modelBpmn.addEntry(modelBpmnEntry); bpmnElementIdList.add(id); @@ -89,7 +89,7 @@ public class ModelBpmn { modelBpmn.setBpmnElementIds(bpmnElementIdList); } return modelBpmn; - } catch (IOException e) { + } catch (JsonParseException e) { throw new ModelBpmnException("Exception occurred during the decoding of the bpmn JSON", e); } } diff --git a/src/main/java/org/onap/clamp/clds/model/properties/ModelProperties.java b/src/main/java/org/onap/clamp/clds/model/properties/ModelProperties.java index 3d7bbcc3..61eeac10 100644 --- a/src/main/java/org/onap/clamp/clds/model/properties/ModelProperties.java +++ b/src/main/java/org/onap/clamp/clds/model/properties/ModelProperties.java @@ -25,23 +25,21 @@ package org.onap.clamp.clds.model.properties; import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFManager; -import com.fasterxml.jackson.databind.JsonNode; - -import java.io.IOException; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; import java.lang.reflect.InvocationTargetException; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; - import org.apache.camel.Exchange; import org.onap.clamp.clds.client.req.policy.PolicyClient; import org.onap.clamp.clds.config.ClampProperties; import org.onap.clamp.clds.exception.ModelBpmnException; import org.onap.clamp.clds.model.CldsModel; import org.onap.clamp.clds.service.CldsService; -import org.onap.clamp.clds.util.JacksonUtils; +import org.onap.clamp.clds.util.JsonUtils; /** * Parse model properties. @@ -51,7 +49,7 @@ public class ModelProperties { protected static final EELFLogger logger = EELFManager.getInstance().getLogger(CldsService.class); protected static final EELFLogger auditLogger = EELFManager.getInstance().getAuditLogger(); private ModelBpmn modelBpmn; - private JsonNode modelJson; + private JsonObject modelJson; private final String modelName; private final String controlName; private final String actionCd; @@ -65,6 +63,7 @@ public class ModelProperties { public static final String POLICY_GUARD_SUFFIX = "_Guard_"; private static final Object lock = new Object(); private static Map<Class<? extends AbstractModelElement>, String> modelElementClasses = new ConcurrentHashMap<>(); + static { synchronized (lock) { modelElementClasses.put(Policy.class, Policy.getType()); @@ -99,9 +98,9 @@ public class ModelProperties { this.actionCd = actionCd; this.testOnly = isATest; modelBpmn = ModelBpmn.create(modelBpmnText); - modelJson = JacksonUtils.getObjectMapperInstance().readTree(modelPropText); + modelJson = JsonUtils.GSON.fromJson(modelPropText, JsonObject.class); instantiateMissingModelElements(); - } catch (IOException e) { + } catch (JsonParseException e) { throw new ModelBpmnException("Exception occurred when trying to decode the BPMN Properties JSON", e); } } @@ -112,7 +111,7 @@ public class ModelProperties { * after instantiation of this ModelProperties, we need to build the missing * ModelElement instances. */ - private final void instantiateMissingModelElements() { + private void instantiateMissingModelElements() { if (modelElementClasses.size() != modelElements.size()) { Set<String> missingTypes = new HashSet<>(modelElementClasses.values()); missingTypes.removeAll(modelElements.keySet()); @@ -124,11 +123,11 @@ public class ModelProperties { .forEach(entry -> { try { modelElements.put(entry.getValue(), - (entry.getKey().getConstructor(ModelProperties.class, ModelBpmn.class, JsonNode.class) + (entry.getKey().getConstructor(ModelProperties.class, ModelBpmn.class, JsonObject.class) .newInstance(this, modelBpmn, modelJson))); } catch (InstantiationException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { - logger.warn("Unable to instantiate a ModelElement, exception follows: ", e); + logger.warn("Unable to instantiate a ModelElement "+ entry.getValue()+", exception follows: ", e); } }); } @@ -143,10 +142,10 @@ public class ModelProperties { public static String getVf(CldsModel model) { List<String> vfs = null; try { - JsonNode modelJson = JacksonUtils.getObjectMapperInstance().readTree(model.getPropText()); + JsonObject modelJson = JsonUtils.GSON.fromJson(model.getPropText(), JsonObject.class); Global global = new Global(modelJson); vfs = global.getResourceVf(); - } catch (IOException e) { + } catch (JsonParseException e) { logger.warn("no VF found", e); } String vf = null; diff --git a/src/main/java/org/onap/clamp/clds/model/properties/Policy.java b/src/main/java/org/onap/clamp/clds/model/properties/Policy.java index 501eb807..059d7329 100644 --- a/src/main/java/org/onap/clamp/clds/model/properties/Policy.java +++ b/src/main/java/org/onap/clamp/clds/model/properties/Policy.java @@ -25,12 +25,14 @@ package org.onap.clamp.clds.model.properties; import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFManager; -import com.fasterxml.jackson.databind.JsonNode; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; +import java.util.Map.Entry; /** * Parse Policy json properties. @@ -65,15 +67,15 @@ public class Policy extends AbstractModelElement { * @param modelJson * @throws IOException */ - public Policy(ModelProperties modelProp, ModelBpmn modelBpmn, JsonNode modelJson) throws IOException { + public Policy(ModelProperties modelProp, ModelBpmn modelBpmn, JsonObject modelJson) throws IOException { super(TYPE_POLICY, modelProp, modelBpmn, modelJson); // process policies if (modelElementJsonNode != null) { - Iterator<JsonNode> itr = modelElementJsonNode.elements(); + Iterator<Entry<String, JsonElement>> itr = modelElementJsonNode.getAsJsonObject().entrySet().iterator(); policyChains = new ArrayList<>(); while (itr.hasNext()) { - policyChains.add(new PolicyChain(itr.next())); + policyChains.add(new PolicyChain(itr.next().getValue())); } } } diff --git a/src/main/java/org/onap/clamp/clds/model/properties/PolicyChain.java b/src/main/java/org/onap/clamp/clds/model/properties/PolicyChain.java index cf24c781..f29ba160 100644 --- a/src/main/java/org/onap/clamp/clds/model/properties/PolicyChain.java +++ b/src/main/java/org/onap/clamp/clds/model/properties/PolicyChain.java @@ -25,12 +25,13 @@ package org.onap.clamp.clds.model.properties; import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFManager; -import com.fasterxml.jackson.databind.JsonNode; - +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; +import org.onap.clamp.clds.util.JsonUtils; /** * Parse Policy json properties. @@ -66,20 +67,21 @@ public class PolicyChain { private List<PolicyItem> policyItems; private String policyType; - public PolicyChain(JsonNode node) throws IOException { - - policyId = AbstractModelElement.getValueByName(node, "pid"); - timeout = AbstractModelElement.getIntValueByName(node, "timeout"); - policyType = AbstractModelElement.getValueByName(node, "policyType"); + public PolicyChain(JsonElement node) throws IOException { + if (node != null && node.isJsonArray() && node.getAsJsonArray().size() > 0) { + JsonArray operationalPolicyParameters = node.getAsJsonArray(); + policyId = JsonUtils.getStringValueByName(node, "pid"); + timeout = JsonUtils.getIntValueByName(node, "timeout"); + policyType = JsonUtils.getStringValueByName(node, "policyType"); - if(node != null && node.size() > 0) { - JsonNode policyNode = node.get(node.size() - 1).get("policyConfigurations"); - if(policyNode != null) { - Iterator<JsonNode> itr = policyNode.elements(); - policyItems = new ArrayList<>(); - while (itr.hasNext()) { - policyItems.add(new PolicyItem(itr.next())); - } + JsonArray policyConfigurations = operationalPolicyParameters.get(operationalPolicyParameters.size() - 1) + .getAsJsonObject() + .get("policyConfigurations") + .getAsJsonArray(); + Iterator<JsonElement> itr = policyConfigurations.iterator(); + policyItems = new ArrayList<>(); + while (itr.hasNext()) { + policyItems.add(new PolicyItem(itr.next())); } } diff --git a/src/main/java/org/onap/clamp/clds/model/properties/PolicyItem.java b/src/main/java/org/onap/clamp/clds/model/properties/PolicyItem.java index d6deddc6..bb57d5dc 100644 --- a/src/main/java/org/onap/clamp/clds/model/properties/PolicyItem.java +++ b/src/main/java/org/onap/clamp/clds/model/properties/PolicyItem.java @@ -25,14 +25,14 @@ package org.onap.clamp.clds.model.properties; import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFManager; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.JsonNode; +import com.google.gson.JsonElement; +import com.google.gson.reflect.TypeToken; import java.io.IOException; import java.util.List; import java.util.Map; -import org.onap.clamp.clds.util.JacksonUtils; +import org.onap.clamp.clds.util.JsonUtils; import org.yaml.snakeyaml.Yaml; /** @@ -86,51 +86,48 @@ public class PolicyItem implements Cloneable { /** * Parse Policy given json node. * - * @param node + * @param item * @throws IOException */ - public PolicyItem(JsonNode node) throws IOException { - id = AbstractModelElement.getValueByName(node, "_id"); - recipe = AbstractModelElement.getValueByName(node, "recipe"); - maxRetries = AbstractModelElement.getIntValueByName(node, "maxRetries"); - retryTimeLimit = AbstractModelElement.getIntValueByName(node, "retryTimeLimit"); - parentPolicy = AbstractModelElement.getValueByName(node, "parentPolicy"); - parentPolicyConditions = AbstractModelElement.getValuesByName(node, "parentPolicyConditions"); - targetResourceId = AbstractModelElement.getValueByName(node, "targetResourceId"); + public PolicyItem(JsonElement item) throws IOException { + id = JsonUtils.getStringValueByName(item, "_id"); + recipe = JsonUtils.getStringValueByName(item, "recipe"); + maxRetries = JsonUtils.getIntValueByName(item, "maxRetries"); + retryTimeLimit = JsonUtils.getIntValueByName(item, "retryTimeLimit"); + parentPolicy = JsonUtils.getStringValueByName(item, "parentPolicy"); + parentPolicyConditions = JsonUtils.getStringValuesByName(item, "parentPolicyConditions"); + targetResourceId = JsonUtils.getStringValueByName(item, "targetResourceId"); if (targetResourceId != null && targetResourceId.isEmpty()) { this.setTargetResourceId(null); } - recipeInfo = AbstractModelElement.getValueByName(node, "recipeInfo"); - recipeLevel = AbstractModelElement.getValueByName(node, "recipeLevel"); - recipeInput = AbstractModelElement.getValueByName(node, "recipeInput"); - String payload = AbstractModelElement.getValueByName(node, "recipePayload"); + recipeInfo = JsonUtils.getStringValueByName(item, "recipeInfo"); + recipeLevel = JsonUtils.getStringValueByName(item, "recipeLevel"); + recipeInput = JsonUtils.getStringValueByName(item, "recipeInput"); + String payload = JsonUtils.getStringValueByName(item, "recipePayload"); if (payload != null && !payload.isEmpty()) { if (payload.trim().startsWith("{") && payload.trim().endsWith("}")) { // Seems to be a JSON - recipePayload = JacksonUtils.getObjectMapperInstance().readValue(payload, - new TypeReference<Map<String, String>>() { - }); + recipePayload = JsonUtils.GSON.fromJson(payload, new TypeToken<Map<String, String>>() {}.getType()); } else { // SHould be a YAML then - Yaml yaml = new Yaml(); - recipePayload = (Map<String, String>) yaml.load(payload); + recipePayload = new Yaml().load(payload); } } - oapRop = AbstractModelElement.getValueByName(node, "oapRop"); - oapLimit = AbstractModelElement.getValueByName(node, "oapLimit"); - actor = AbstractModelElement.getValueByName(node, "actor"); - - enableGuardPolicy = AbstractModelElement.getValueByName(node, "enableGuardPolicy"); - guardPolicyType = AbstractModelElement.getValueByName(node, "guardPolicyType"); - guardTargets = AbstractModelElement.getValueByName(node, "guardTargets"); - minGuard = AbstractModelElement.getValueByName(node, "minGuard"); - maxGuard = AbstractModelElement.getValueByName(node, "maxGuard"); - limitGuard = AbstractModelElement.getValueByName(node, "limitGuard"); - timeUnitsGuard = AbstractModelElement.getValueByName(node, "timeUnitsGuard"); - timeWindowGuard = AbstractModelElement.getValueByName(node, "timeWindowGuard"); - guardActiveStart = AbstractModelElement.getValueByName(node, "guardActiveStart"); - guardActiveEnd = AbstractModelElement.getValueByName(node, "guardActiveEnd"); + oapRop = JsonUtils.getStringValueByName(item, "oapRop"); + oapLimit = JsonUtils.getStringValueByName(item, "oapLimit"); + actor = JsonUtils.getStringValueByName(item, "actor"); + + enableGuardPolicy = JsonUtils.getStringValueByName(item, "enableGuardPolicy"); + guardPolicyType = JsonUtils.getStringValueByName(item, "guardPolicyType"); + guardTargets = JsonUtils.getStringValueByName(item, "guardTargets"); + minGuard = JsonUtils.getStringValueByName(item, "minGuard"); + maxGuard = JsonUtils.getStringValueByName(item, "maxGuard"); + limitGuard = JsonUtils.getStringValueByName(item, "limitGuard"); + timeUnitsGuard = JsonUtils.getStringValueByName(item, "timeUnitsGuard"); + timeWindowGuard = JsonUtils.getStringValueByName(item, "timeWindowGuard"); + guardActiveStart = JsonUtils.getStringValueByName(item, "guardActiveStart"); + guardActiveEnd = JsonUtils.getStringValueByName(item, "guardActiveEnd"); } /** diff --git a/src/main/java/org/onap/clamp/clds/model/properties/Tca.java b/src/main/java/org/onap/clamp/clds/model/properties/Tca.java index 7297ccbd..50808229 100644 --- a/src/main/java/org/onap/clamp/clds/model/properties/Tca.java +++ b/src/main/java/org/onap/clamp/clds/model/properties/Tca.java @@ -25,7 +25,10 @@ package org.onap.clamp.clds.model.properties; import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFManager; -import com.fasterxml.jackson.databind.JsonNode; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import java.util.Map.Entry; +import java.util.Set; /** * Parse ONAP Tca json properties. @@ -47,12 +50,14 @@ public class Tca extends AbstractModelElement { * @param modelBpmn * @param modelJson */ - public Tca(ModelProperties modelProp, ModelBpmn modelBpmn, JsonNode modelJson) { + public Tca(ModelProperties modelProp, ModelBpmn modelBpmn, JsonObject modelJson) { super(TYPE_TCA, modelProp, modelBpmn, modelJson); // process Server_Configurations if (modelElementJsonNode != null) { - tcaItem = new TcaItem(modelElementJsonNode.elements().next()); + //this is wrong assumption that there is only one property object + Set<Entry<String, JsonElement>> entries = modelElementJsonNode.getAsJsonObject().entrySet(); + tcaItem = new TcaItem(entries.iterator().next().getValue()); } } diff --git a/src/main/java/org/onap/clamp/clds/model/properties/TcaItem.java b/src/main/java/org/onap/clamp/clds/model/properties/TcaItem.java index 3a4ea712..987b7765 100644 --- a/src/main/java/org/onap/clamp/clds/model/properties/TcaItem.java +++ b/src/main/java/org/onap/clamp/clds/model/properties/TcaItem.java @@ -25,11 +25,13 @@ package org.onap.clamp.clds.model.properties; import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFManager; -import com.fasterxml.jackson.databind.JsonNode; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; import java.util.ArrayList; import java.util.Iterator; import java.util.List; +import org.onap.clamp.clds.util.JsonUtils; /** * Parse ONAP Tca Item json properties. @@ -50,21 +52,23 @@ public class TcaItem { /** * Parse Tca Item given json node * - * @param node + * @param tcaJson */ - public TcaItem(JsonNode node) { + public TcaItem(JsonElement tcaJson) { - tcaName = AbstractModelElement.getValueByName(node, "tname"); - tcaUuId = AbstractModelElement.getValueByName(node, "tuuid"); - policyId = AbstractModelElement.getValueByName(node, "tcaPolId"); - eventName = AbstractModelElement.getValueByName(node, "eventName"); - controlLoopSchemaType = AbstractModelElement.getValueByName(node, "controlLoopSchemaType"); + tcaName = JsonUtils.getStringValueByName(tcaJson, "tname"); + tcaUuId = JsonUtils.getStringValueByName(tcaJson, "tuuid"); + policyId = JsonUtils.getStringValueByName(tcaJson, "tcaPolId"); + eventName = JsonUtils.getStringValueByName(tcaJson, "eventName"); + controlLoopSchemaType = JsonUtils.getStringValueByName(tcaJson, "controlLoopSchemaType"); // process service Configurations - JsonNode serviceConfigurationsNode = node.get(node.size() - 1).get("serviceConfigurations"); - Iterator<JsonNode> itr = serviceConfigurationsNode.elements(); + JsonArray tcaConfigurationArray = tcaJson.getAsJsonArray(); + JsonArray serviceConfigurationsNode = tcaConfigurationArray.get(tcaConfigurationArray.size() - 1) + .getAsJsonObject().get("serviceConfigurations").getAsJsonArray(); + Iterator<JsonElement> itr = serviceConfigurationsNode.iterator(); tcaThresholds = new ArrayList<>(); while (itr.hasNext()) { - tcaThresholds.add(new TcaThreshold(itr.next())); + tcaThresholds.add(new TcaThreshold(itr.next().getAsJsonArray())); } } diff --git a/src/main/java/org/onap/clamp/clds/model/properties/TcaThreshold.java b/src/main/java/org/onap/clamp/clds/model/properties/TcaThreshold.java index 05b8ae35..0903d72f 100644 --- a/src/main/java/org/onap/clamp/clds/model/properties/TcaThreshold.java +++ b/src/main/java/org/onap/clamp/clds/model/properties/TcaThreshold.java @@ -25,7 +25,7 @@ package org.onap.clamp.clds.model.properties; import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFManager; -import com.fasterxml.jackson.databind.JsonNode; +import com.google.gson.JsonArray; /** * Parse ONAP Tca Threshold json properties. @@ -44,21 +44,21 @@ public class TcaThreshold { /** * Parse Tca Threshhold given json node * - * @param node + * @param tcaTresholdConfiguration */ - public TcaThreshold(JsonNode node) { + public TcaThreshold(JsonArray tcaTresholdConfiguration) { - if (node.get(0) != null) { - fieldPath = node.get(0).asText(); + if (tcaTresholdConfiguration.get(0) != null) { + fieldPath = tcaTresholdConfiguration.get(0).getAsString(); } - if (node.get(1) != null) { - operator = node.get(1).asText(); + if (tcaTresholdConfiguration.get(1) != null) { + operator = tcaTresholdConfiguration.get(1).getAsString(); } - if (node.get(2) != null) { - threshold = Integer.valueOf(node.get(2).asText()); + if (tcaTresholdConfiguration.get(2) != null) { + threshold = Integer.valueOf(tcaTresholdConfiguration.get(2).getAsString()); } - if (node.get(3) != null) { - closedLoopEventStatus = node.get(3).asText(); + if (tcaTresholdConfiguration.get(3) != null) { + closedLoopEventStatus = tcaTresholdConfiguration.get(3).getAsString(); } } diff --git a/src/main/java/org/onap/clamp/clds/sdc/controller/installer/CsarInstallerImpl.java b/src/main/java/org/onap/clamp/clds/sdc/controller/installer/CsarInstallerImpl.java index 382c1d77..94cffbb7 100644 --- a/src/main/java/org/onap/clamp/clds/sdc/controller/installer/CsarInstallerImpl.java +++ b/src/main/java/org/onap/clamp/clds/sdc/controller/installer/CsarInstallerImpl.java @@ -25,8 +25,8 @@ package org.onap.clamp.clds.sdc.controller.installer; import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFManager; -import com.fasterxml.jackson.databind.node.ObjectNode; +import com.google.gson.JsonObject; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; @@ -51,7 +51,7 @@ import org.onap.clamp.clds.model.properties.ModelProperties; import org.onap.clamp.clds.service.CldsService; import org.onap.clamp.clds.service.CldsTemplateService; import org.onap.clamp.clds.transform.XslTransformer; -import org.onap.clamp.clds.util.JacksonUtils; +import org.onap.clamp.clds.util.JsonUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.ApplicationContext; @@ -59,9 +59,8 @@ import org.springframework.transaction.annotation.Transactional; import org.yaml.snakeyaml.Yaml; /** - * This class will be instantiated by spring config, and used by Sdc Controller. - * There is no state kept by the bean. It's used to deploy the csar/notification - * received from SDC in DB. + * This class will be instantiated by spring config, and used by Sdc Controller. There is no state kept by the bean. + * It's used to deploy the csar/notification received from SDC in DB. */ public class CsarInstallerImpl implements CsarInstaller { @@ -103,7 +102,7 @@ public class CsarInstallerImpl implements CsarInstaller { for (Entry<String, BlueprintArtifact> blueprint : csar.getMapOfBlueprints().entrySet()) { alreadyInstalled = alreadyInstalled && (CldsModel.retrieve(cldsDao, buildModelName(csar, blueprint.getKey()), true).getId() != null) ? true - : false; + : false; } return alreadyInstalled; } @@ -165,22 +164,20 @@ public class CsarInstallerImpl implements CsarInstaller { return listConfig.get(0); } - private static String getAllBlueprintParametersInJson(BlueprintArtifact blueprintArtifact) { - ObjectNode node = JacksonUtils.getObjectMapperInstance().createObjectNode(); + String getAllBlueprintParametersInJson(BlueprintArtifact blueprintArtifact) { + JsonObject node = new JsonObject(); Yaml yaml = new Yaml(); Map<String, Object> inputsNodes = ((Map<String, Object>) ((Map<String, Object>) yaml .load(blueprintArtifact.getDcaeBlueprint())).get("inputs")); inputsNodes.entrySet().stream().filter(e -> !e.getKey().contains("policy_id")).forEach(elem -> { - Object defaultNode = ((Map<String, Object>) elem.getValue()).get("default"); - if (defaultNode != null && defaultNode instanceof String) { - node.put(elem.getKey(), (String) defaultNode); - } else if (defaultNode != null) { - node.putPOJO(elem.getKey(), defaultNode); + Object defaultValue = ((Map<String, Object>) elem.getValue()).get("default"); + if (defaultValue != null) { + addPropertyToNode(node, elem.getKey(), defaultValue); } else { - node.put(elem.getKey(), ""); + node.addProperty(elem.getKey(), ""); } }); - node.put("policy_id", "AUTO_GENERATED_POLICY_ID_AT_SUBMIT"); + node.addProperty("policy_id", "AUTO_GENERATED_POLICY_ID_AT_SUBMIT"); return node.toString(); } @@ -217,14 +214,10 @@ public class CsarInstallerImpl implements CsarInstaller { } /** - * This call must be done when deploying the SDC notification as this call get - * the latest version of the artifact (version can be specified to DCAE call) + * This call must be done when deploying the SDC notification as this call get the latest version of the artifact + * (version can be specified to DCAE call) * - * @param blueprintArtifact * @return The DcaeInventoryResponse object containing the dcae values - * @throws IOException - * @throws ParseException - * @throws InterruptedException */ private DcaeInventoryResponse queryDcaeToGetServiceTypeId(BlueprintArtifact blueprintArtifact) throws IOException, ParseException, InterruptedException { @@ -292,4 +285,18 @@ public class CsarInstallerImpl implements CsarInstaller { + inputParams + "]}"); return cldsModel.save(cldsDao, null); } + + private void addPropertyToNode(JsonObject node, String key, Object value) { + if (value instanceof String) { + node.addProperty(key, (String) value); + } else if (value instanceof Number) { + node.addProperty(key, (Number) value); + } else if (value instanceof Boolean) { + node.addProperty(key, (Boolean) value); + } else if (value instanceof Character) { + node.addProperty(key, (Character) value); + } else { + node.addProperty(key, JsonUtils.GSON.toJson(value)); + } + } } diff --git a/src/main/java/org/onap/clamp/clds/service/CldsService.java b/src/main/java/org/onap/clamp/clds/service/CldsService.java index 206a4246..2bad07f4 100644 --- a/src/main/java/org/onap/clamp/clds/service/CldsService.java +++ b/src/main/java/org/onap/clamp/clds/service/CldsService.java @@ -26,11 +26,12 @@ package org.onap.clamp.clds.service; import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFManager; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.ObjectNode; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.reflect.TypeToken; import java.io.IOException; +import java.lang.reflect.Type; import java.security.GeneralSecurityException; import java.util.Date; import java.util.List; @@ -64,12 +65,11 @@ import org.onap.clamp.clds.model.CldsServiceData; import org.onap.clamp.clds.model.CldsTemplate; import org.onap.clamp.clds.model.DcaeEvent; import org.onap.clamp.clds.model.ValueItem; -import org.onap.clamp.clds.model.properties.AbstractModelElement; import org.onap.clamp.clds.model.properties.ModelProperties; import org.onap.clamp.clds.model.sdc.SdcServiceInfo; import org.onap.clamp.clds.sdc.controller.installer.CsarInstallerImpl; import org.onap.clamp.clds.transform.XslTransformer; -import org.onap.clamp.clds.util.JacksonUtils; +import org.onap.clamp.clds.util.JsonUtils; import org.onap.clamp.clds.util.LoggingUtils; import org.onap.clamp.clds.util.ONAPLogConstants; import org.slf4j.event.Level; @@ -86,6 +86,8 @@ import org.springframework.web.client.HttpClientErrorException; @Component public class CldsService extends SecureServiceBase { + public static final Type LIST_OF_SDC_SERVICE_INFO_TYPE = new TypeToken<List<SdcServiceInfo>>() { + }.getType(); @Produce(uri = "direct:processSubmit") private CamelProxy camelProxy; protected static final EELFLogger securityLogger = EELFManager.getInstance().getSecurityLogger(); @@ -333,7 +335,7 @@ public class CldsService extends SecureServiceBase { * * @param action * @param modelName - * @param validateFlag + * @param test * @param model * @return * @throws TransformerException @@ -500,7 +502,7 @@ public class CldsService extends SecureServiceBase { * In case of issues */ public String getSdcProperties() throws IOException { - return ((ObjectNode) refProp.getJsonTemplate(GLOBAL_PROPERTIES_KEY)).toString(); + return refProp.getJsonTemplate(GLOBAL_PROPERTIES_KEY).toString(); } /** @@ -581,21 +583,19 @@ public class CldsService extends SecureServiceBase { if (StringUtils.isBlank(responseStr)) { return ""; } - ObjectMapper objectMapper = JacksonUtils.getObjectMapperInstance(); - List<SdcServiceInfo> rawList = objectMapper.readValue(responseStr, - objectMapper.getTypeFactory().constructCollectionType(List.class, SdcServiceInfo.class)); - ObjectNode invariantIdServiceNode = objectMapper.createObjectNode(); - ObjectNode serviceNode = objectMapper.createObjectNode(); + List<SdcServiceInfo> rawList = JsonUtils.GSON.fromJson(responseStr, LIST_OF_SDC_SERVICE_INFO_TYPE); + JsonObject invariantIdServiceNode = new JsonObject(); + JsonObject serviceNode = new JsonObject(); logger.info("value of cldsserviceiNfolist: {}", rawList); if (rawList != null && !rawList.isEmpty()) { List<SdcServiceInfo> cldsSdcServiceInfoList = sdcCatalogServices.removeDuplicateServices(rawList); for (SdcServiceInfo currCldsSdcServiceInfo : cldsSdcServiceInfoList) { if (currCldsSdcServiceInfo != null) { - invariantIdServiceNode.put(currCldsSdcServiceInfo.getInvariantUUID(), + invariantIdServiceNode.addProperty(currCldsSdcServiceInfo.getInvariantUUID(), currCldsSdcServiceInfo.getName()); } } - serviceNode.putPOJO("service", invariantIdServiceNode); + serviceNode.add("service", invariantIdServiceNode); } return serviceNode.toString(); } @@ -710,16 +710,17 @@ public class CldsService extends SecureServiceBase { } private void checkForDuplicateServiceVf(String modelName, String modelPropText) throws IOException { - JsonNode globalNode = JacksonUtils.getObjectMapperInstance().readTree(modelPropText).get("global"); - String service = AbstractModelElement.getValueByName(globalNode, "service"); - List<String> resourceVf = AbstractModelElement.getValuesByName(globalNode, "vf"); + JsonElement globalNode = JsonUtils.GSON.fromJson(modelPropText, JsonObject.class).get("global"); + String service = JsonUtils.getStringValueByName(globalNode, "service"); + List<String> resourceVf = JsonUtils.getStringValuesByName(globalNode, "vf"); if (service != null && resourceVf != null && !resourceVf.isEmpty()) { List<CldsModelProp> cldsModelPropList = cldsDao.getDeployedModelProperties(); for (CldsModelProp cldsModelProp : cldsModelPropList) { - JsonNode currentNode = JacksonUtils.getObjectMapperInstance().readTree(cldsModelProp.getPropText()) + JsonElement currentNode = JsonUtils.GSON + .fromJson(cldsModelProp.getPropText(), JsonObject.class) .get("global"); - String currentService = AbstractModelElement.getValueByName(currentNode, "service"); - List<String> currentVf = AbstractModelElement.getValuesByName(currentNode, "vf"); + String currentService = JsonUtils.getStringValueByName(currentNode, "service"); + List<String> currentVf = JsonUtils.getStringValuesByName(currentNode, "vf"); if (currentVf != null && !currentVf.isEmpty()) { if (!modelName.equalsIgnoreCase(cldsModelProp.getName()) && service.equalsIgnoreCase(currentService) && resourceVf.get(0).equalsIgnoreCase(currentVf.get(0))) { diff --git a/src/main/java/org/onap/clamp/clds/service/CldsUser.java b/src/main/java/org/onap/clamp/clds/service/CldsUser.java index b30397db..82b7727b 100644 --- a/src/main/java/org/onap/clamp/clds/service/CldsUser.java +++ b/src/main/java/org/onap/clamp/clds/service/CldsUser.java @@ -87,7 +87,7 @@ public class CldsUser { /** * Sets the permissions. - * + * * @param permissionsArray * the permissions to set */ diff --git a/src/main/java/org/onap/clamp/clds/service/JacksonObjectMapperProvider.java b/src/main/java/org/onap/clamp/clds/service/SecureServicePermissionDeserializer.java index d6a4d2f5..9cbf711c 100644 --- a/src/main/java/org/onap/clamp/clds/service/JacksonObjectMapperProvider.java +++ b/src/main/java/org/onap/clamp/clds/service/SecureServicePermissionDeserializer.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP CLAMP * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights + * Copyright (C) 2019 Nokia Intellectual Property. All rights * reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -18,34 +18,28 @@ * limitations under the License. * ============LICENSE_END============================================ * =================================================================== - * + * */ package org.onap.clamp.clds.service; -import com.fasterxml.jackson.databind.ObjectMapper; - -import javax.ws.rs.ext.ContextResolver; - -import org.onap.clamp.clds.util.JacksonUtils; - -/** - * This class is to restrcit the class type that can be de-serialized. - */ -public class JacksonObjectMapperProvider implements ContextResolver<ObjectMapper> { +import com.google.gson.Gson; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonParseException; +import java.lang.reflect.Type; - private final ObjectMapper defaultObjectMapper; - - public JacksonObjectMapperProvider() { - defaultObjectMapper = createDefaultMapper(); - } +public class SecureServicePermissionDeserializer implements JsonDeserializer<SecureServicePermission> { @Override - public ObjectMapper getContext(Class<?> type) { - return defaultObjectMapper; - } - - private static ObjectMapper createDefaultMapper() { - return JacksonUtils.getObjectMapperInstance(); + public SecureServicePermission deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) + throws JsonParseException { + if (json.isJsonPrimitive()) { + return new SecureServicePermission(json.getAsString()); + } else { + // if not string try default deserialization + return new Gson().fromJson(json, SecureServicePermission.class); + } } } diff --git a/src/main/java/org/onap/clamp/clds/util/JacksonUtils.java b/src/main/java/org/onap/clamp/clds/util/JacksonUtils.java deleted file mode 100644 index 1f5419d7..00000000 --- a/src/main/java/org/onap/clamp/clds/util/JacksonUtils.java +++ /dev/null @@ -1,53 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP CLAMP - * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * 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 - * - * 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.clamp.clds.util; - -import com.fasterxml.jackson.databind.ObjectMapper; - -/** - * This class is used to access the jackson with restricted type access. - */ -public class JacksonUtils { - - private static ObjectMapper objectMapper; - - private JacksonUtils() { - } - - /** - * Call this method to retrieve a secure ObjectMapper. - * - * @return an ObjectMapper instance (same for clamp) - */ - public static synchronized ObjectMapper getObjectMapperInstance() { - if (objectMapper == null) { - objectMapper = new ObjectMapper(); - // This is to disable the security hole that could be opened for - // json deserialization, if needed do this - // objectMapper.enableDefaultTyping(DefaultTyping.NON_FINAL); - objectMapper.disableDefaultTyping(); - } - return objectMapper; - } -} diff --git a/src/main/java/org/onap/clamp/clds/util/JsonUtils.java b/src/main/java/org/onap/clamp/clds/util/JsonUtils.java new file mode 100644 index 00000000..96ddc292 --- /dev/null +++ b/src/main/java/org/onap/clamp/clds/util/JsonUtils.java @@ -0,0 +1,170 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP CLAMP + * ================================================================================ + * Copyright (C) 2018 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * 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 + * + * 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.clamp.clds.util; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.google.common.collect.Lists; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonPrimitive; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.Spliterator; +import java.util.Spliterators; +import java.util.stream.Collectors; +import java.util.stream.StreamSupport; +import org.onap.clamp.clds.model.properties.AbstractModelElement; +import org.onap.clamp.clds.service.SecureServicePermission; +import org.onap.clamp.clds.service.SecureServicePermissionDeserializer; + +/** + * This class is used to access the jackson with restricted type access. + */ +public class JsonUtils { + + protected static final EELFLogger logger = EELFManager.getInstance().getLogger(AbstractModelElement.class); + private static final String LOG_ELEMENT_NOT_FOUND = "Value '{}' for key 'name' not found in JSON"; + private static final String LOG_ELEMENT_NOT_FOUND_IN_JSON = "Value '{}' for key 'name' not found in JSON {}"; + + public static final Gson GSON = new GsonBuilder() + .registerTypeAdapter(SecureServicePermission.class, new SecureServicePermissionDeserializer()) + .create(); + + private JsonUtils() { + } + + + /** + * Return the value field of the json node element that has a name field equals to the given name. + */ + public static String getStringValueByName(JsonElement jsonElement, String name) { + String value = extractJsonValueFromElement(jsonElement, name) + .map(JsonUtils::extractStringValueFromElement) + .orElse(null); + if (value == null) { + if (logger.isDebugEnabled()) { + logger.debug(LOG_ELEMENT_NOT_FOUND_IN_JSON, name, jsonElement.toString()); + } else { + logger.warn(LOG_ELEMENT_NOT_FOUND, name); + } + } + return value; + } + + /** + * Return an array of values for the field of the json node element that has a name field equals to the given name. + */ + public static List<String> getStringValuesByName(JsonElement jsonElement, String name) { + List<String> values = extractJsonValueFromElement(jsonElement, name) + .map(JsonUtils::extractStringValuesFromElement).orElse(new ArrayList<>()); + if (values.isEmpty()) { + if (logger.isDebugEnabled()) { + logger.debug(LOG_ELEMENT_NOT_FOUND_IN_JSON, name, jsonElement.toString()); + } else { + logger.warn(LOG_ELEMENT_NOT_FOUND, name); + } + } + return values; + } + + /** + * Return the int value field of the json node element that has a name field equals to the given name. + */ + public static Integer getIntValueByName(JsonElement element, String name) { + String value = getStringValueByName(element, name); + return Integer.valueOf(value); + } + + + /** + * Return the Json value field of the json node element that has a name field equals to the given name. + */ + public static JsonObject getJsonObjectByName(JsonElement jsonElement, String name) { + JsonObject jsonObject = extractJsonValueFromElement(jsonElement, name).map(JsonElement::getAsJsonObject) + .orElse(null); + if (jsonObject == null) { + logger.warn(LOG_ELEMENT_NOT_FOUND, name); + } else { + logger.debug(LOG_ELEMENT_NOT_FOUND_IN_JSON, name, jsonElement.toString()); + } + return jsonObject; + } + + private static Optional<JsonElement> extractJsonValueFromElement(JsonElement jsonElement, String name) { + if(jsonElement != null ){ + if (jsonElement.isJsonArray()) { + return extractValueJsonFromArray(jsonElement, name); + } else if (hasMatchingParameterName(name, jsonElement)) { + return Optional.of(jsonElement); + } + } + return Optional.empty(); + } + + private static Optional<JsonElement> extractValueJsonFromArray(JsonElement jsonElement, String name) { + for (JsonElement element : jsonElement.getAsJsonArray()) { + if (hasMatchingParameterName(name, element)) { + return Optional.of(element.getAsJsonObject().get("value")); + } + } + return Optional.empty(); + } + + private static boolean hasMatchingParameterName(String name, JsonElement element) { + return element.isJsonObject() + && element.getAsJsonObject().has("name") + && name.equals(element.getAsJsonObject().get("name").getAsString()); + } + + private static String extractStringValueFromElement(JsonElement element) { + if (element.isJsonArray()) { + return element.getAsJsonArray().get(0).getAsString(); + } else if (element.isJsonPrimitive()) { + return element.getAsJsonPrimitive().getAsString(); + } else { + return GSON.toJson(element); + } + } + + private static List<String> extractStringValuesFromElement(JsonElement element) { + if (element.isJsonArray()) { + return StreamSupport.stream( + Spliterators.spliteratorUnknownSize(element.getAsJsonArray().iterator(), Spliterator.ORDERED), + false) + .filter(JsonElement::isJsonPrimitive) + .map(JsonElement::getAsJsonPrimitive) + .filter(JsonPrimitive::isString) + .map(JsonPrimitive::getAsString) + .collect(Collectors.toList()); + } else { + String value = extractStringValueFromElement(element); + return Lists.newArrayList(value); + } + + } +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index c492f74d..91a4cab7 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -73,6 +73,7 @@ server.http-to-https-redirection.port=8080 server.servlet.context-path=/ #Modified engine-rest applicationpath spring.profiles.active=clamp-default,clamp-aaf-authentication,clamp-sdc-controller +spring.http.converters.preferred-json-mapper=gson #The max number of active threads in this pool server.tomcat.max-threads=200 |