diff options
Diffstat (limited to 'dcaedt_tools/src/main/java/tools')
-rw-r--r-- | dcaedt_tools/src/main/java/tools/DeployTemplate.java | 157 | ||||
-rw-r--r-- | dcaedt_tools/src/main/java/tools/EntitiesRetriever.java | 33 | ||||
-rw-r--r-- | dcaedt_tools/src/main/java/tools/LoggerDebug.java | 13 | ||||
-rw-r--r-- | dcaedt_tools/src/main/java/tools/LoggerError.java | 13 | ||||
-rw-r--r-- | dcaedt_tools/src/main/java/tools/Main.java | 80 | ||||
-rw-r--r-- | dcaedt_tools/src/main/java/tools/NodeData.java | 40 | ||||
-rw-r--r-- | dcaedt_tools/src/main/java/tools/TemplateContainer.java | 329 |
7 files changed, 665 insertions, 0 deletions
diff --git a/dcaedt_tools/src/main/java/tools/DeployTemplate.java b/dcaedt_tools/src/main/java/tools/DeployTemplate.java new file mode 100644 index 0000000..d5c368f --- /dev/null +++ b/dcaedt_tools/src/main/java/tools/DeployTemplate.java @@ -0,0 +1,157 @@ +package tools; +import com.google.gson.JsonObject; +import json.templateInfo.TemplateInfo; +import org.onap.sdc.dcae.composition.restmodels.CreateVFCMTRequest; +import org.onap.sdc.dcae.composition.restmodels.sdc.ResourceDetailed; +import org.onap.sdc.dcae.composition.util.DcaeBeConstants; +import org.springframework.web.client.HttpServerErrorException; +import utilities.IDcaeRestClient; +import utilities.IReport; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; + + +public class DeployTemplate { + private static final String FAILED_UPDATE_VFCMT = "Failed update vfcmt: "; + private static final String FAILED = "failed"; + private final IReport report; + private final IDcaeRestClient dcaeRestClient; + private LoggerError errLogger = LoggerError.getInstance(); + private LoggerDebug debugLogger = LoggerDebug.getInstance(); + + DeployTemplate(IReport report, IDcaeRestClient dcaeRestClient) { + + this.report = report; + this.dcaeRestClient = dcaeRestClient; + } + + public void deploy(Map<TemplateInfo, JsonObject> templateInfoToJsonObjectMap) { + List<ResourceDetailed> vfcmtList = dcaeRestClient.getAllVfcmts(); + + List<TemplateInfo> updatedTemplateInfos = new ArrayList<>(); + vfcmtList.stream().forEach(vfcmt -> + templateInfoToJsonObjectMap.keySet().stream().filter(templateInfo -> templateInfo.getName().equalsIgnoreCase(vfcmt.getName())).forEach(templateInfo -> { + update(vfcmt, templateInfo, templateInfoToJsonObjectMap.get(templateInfo)); + updatedTemplateInfos.add(templateInfo); + })); + templateInfoToJsonObjectMap.keySet().stream() + .filter(templateInfo -> !updatedTemplateInfos.contains(templateInfo)) + .forEach(templateInfo -> createNew(templateInfo, templateInfoToJsonObjectMap.get(templateInfo))); + + verify(templateInfoToJsonObjectMap); + } + + private void verify(Map<TemplateInfo, JsonObject> templateInfoToJsonObjectMap) { + AtomicInteger foundCount = new AtomicInteger(); + debugLogger.log("Starting verify deployment"); + List<ResourceDetailed> vfcmtList = dcaeRestClient.getAllVfcmts(); + + templateInfoToJsonObjectMap.keySet().stream() + .forEach(templateInfo -> vfcmtList.stream() + .filter(vfcmt -> vfcmt.getName().equalsIgnoreCase(templateInfo.getName())) + .forEach(vfcmt -> foundCount.getAndIncrement())); + if (foundCount.get() == templateInfoToJsonObjectMap.size()) { + debugLogger.log("Deployment verify finished successfully"); + } else { + errLogger.log("Deployment verify finished successfully"); + String msg = "Deployment verify finished with errors, found only: " + + foundCount.get() + " of " + templateInfoToJsonObjectMap.size() + " vfcmts"; + report.addErrorMessage(msg); + errLogger.log(msg); + } + } + + private void createNew(TemplateInfo templateInfo, JsonObject jsonObject) { + try { + CreateVFCMTRequest createVFCMTRequest = new CreateVFCMTRequest(); + createVFCMTRequest.setName(templateInfo.getName()); + createVFCMTRequest.setDescription(templateInfo.getDescription()); + createVFCMTRequest.setSubcategory(templateInfo.getSubCategory()); + createVFCMTRequest.setCategory(templateInfo.getCategory()); + ResourceDetailed vfcmt = dcaeRestClient.createResource(createVFCMTRequest); + + jsonObject.addProperty("cid", vfcmt.getUuid()); + + saveAndCertify(jsonObject, vfcmt); + + } catch (HttpServerErrorException e) { + String msg = FAILED_UPDATE_VFCMT + templateInfo.getName() + ", With general message: " + e.getMessage(); + report.addErrorMessage(msg); + errLogger.log(msg + " " + e); + } + } + + private void update(ResourceDetailed vfcmt, TemplateInfo templateInfo, JsonObject jsonObject) { + ResourceDetailed checkedoutVfcmt = vfcmt; + try { + Boolean checkoutChecking = checkUserIfResourceCheckedOut(dcaeRestClient.getUserId(), vfcmt); + if (checkoutChecking != null && checkoutChecking) { + report.addErrorMessage(FAILED_UPDATE_VFCMT + vfcmt.getName() + ", cannot checkout vfcmt"); + return; + } + if (templateInfo.getUpdateIfExist()) { + if (checkoutChecking == null) { + checkedoutVfcmt = dcaeRestClient.checkoutVfcmt(vfcmt.getUuid()); + } + if (checkedoutVfcmt != null) { + checkedoutVfcmt.setSubCategory(templateInfo.getSubCategory()); + checkedoutVfcmt.setCategory(templateInfo.getCategory()); + checkedoutVfcmt.setDescription(templateInfo.getDescription()); + dcaeRestClient.updateResource(checkedoutVfcmt); + saveAndCertify(jsonObject, checkedoutVfcmt); + } + } else { + report.addNotUpdatedMessage("vfcmt: " + vfcmt.getName() + " found, but didn't update."); + } + } catch (HttpServerErrorException e) { + String msg = FAILED_UPDATE_VFCMT + vfcmt.getName() + ", With general message: " + e.getMessage(); + report.addErrorMessage(msg); + errLogger.log( msg + " " + e); + } + } + + private void saveAndCertify(JsonObject jsonObject, ResourceDetailed checkedoutVfcmt) { + if (saveCompositionAndCertify(checkedoutVfcmt, jsonObject)) { + report.addUpdatedMessage("vfcmt: " + checkedoutVfcmt.getName() + " updated successfully"); + } else { + report.addErrorMessage("VFCMT " + checkedoutVfcmt.getName() + " failed to update"); + } + } + + private boolean saveCompositionAndCertify(ResourceDetailed vfcmt, JsonObject jsonObject) { + if (vfcmt.getUuid() == null) { + return false; + } + + debugLogger.log("Saving cdump of: " + vfcmt.getName() + " vfcmt"); + debugLogger.log(jsonObject.toString()); + + String responseEntity = dcaeRestClient.saveComposition(vfcmt.getUuid(), jsonObject.toString()); + if (responseEntity.equalsIgnoreCase(FAILED)) { + String msg = "Failed saving vfcmt: " + vfcmt.getName(); + report.addErrorMessage(msg); + errLogger.log(msg); + return false; + } + dcaeRestClient.certifyVfcmt(vfcmt.getUuid()); + return true; + } + + private Boolean checkUserIfResourceCheckedOut(String userId, ResourceDetailed asset) { + if (DcaeBeConstants.LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT == DcaeBeConstants.LifecycleStateEnum.findState(asset.getLifecycleState())) { + String lastUpdaterUserId = asset.getLastUpdaterUserId(); + if (lastUpdaterUserId != null && !lastUpdaterUserId.equals(userId)) { + String msg = "User conflicts. Operation not allowed for user "+userId+" on resource checked out by "+lastUpdaterUserId; + report.addErrorMessage(msg); + errLogger.log(msg); + return true; + } else { + return false; + } + } + return null; + } +} diff --git a/dcaedt_tools/src/main/java/tools/EntitiesRetriever.java b/dcaedt_tools/src/main/java/tools/EntitiesRetriever.java new file mode 100644 index 0000000..0c31ddf --- /dev/null +++ b/dcaedt_tools/src/main/java/tools/EntitiesRetriever.java @@ -0,0 +1,33 @@ +package tools; + +import json.response.ElementsResponse.Element; +import json.response.ItemsResponse.Item; +import utilities.IDcaeRestClient; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + +public class EntitiesRetriever { + private final IDcaeRestClient dcaeRestClient; + + EntitiesRetriever(IDcaeRestClient dcaeRestClient) { + + this.dcaeRestClient = dcaeRestClient; + } + + public Map<String, List<Item>> getElementsByFolder() { + List<Element> elementList = dcaeRestClient.getElements(); + Map<String, List<Item>> elementsByFolderNames = new HashMap<>(); + + for (Element element : elementList) { + List<Item> items = dcaeRestClient.getItem(element.getName()); + if (items == null) { + continue; + } + elementsByFolderNames.put(element.getName(), items); + } + return elementsByFolderNames; + } +} diff --git a/dcaedt_tools/src/main/java/tools/LoggerDebug.java b/dcaedt_tools/src/main/java/tools/LoggerDebug.java new file mode 100644 index 0000000..df177ed --- /dev/null +++ b/dcaedt_tools/src/main/java/tools/LoggerDebug.java @@ -0,0 +1,13 @@ +package tools; + +public class LoggerDebug { + private static LoggerDebug instance = new LoggerDebug(); + + public static LoggerDebug getInstance() { + return instance; + } + + public void log(String logLine) { + System.out.println(logLine); + } +} diff --git a/dcaedt_tools/src/main/java/tools/LoggerError.java b/dcaedt_tools/src/main/java/tools/LoggerError.java new file mode 100644 index 0000000..325bfc1 --- /dev/null +++ b/dcaedt_tools/src/main/java/tools/LoggerError.java @@ -0,0 +1,13 @@ +package tools; + +public class LoggerError { + private static LoggerError instance = new LoggerError(); + + public static LoggerError getInstance() { + return instance; + } + + public void log(String logLine) { + System.err.println(logLine); + } +} diff --git a/dcaedt_tools/src/main/java/tools/Main.java b/dcaedt_tools/src/main/java/tools/Main.java new file mode 100644 index 0000000..72b6e42 --- /dev/null +++ b/dcaedt_tools/src/main/java/tools/Main.java @@ -0,0 +1,80 @@ +package tools; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.google.gson.JsonObject; +import json.Environment; +import json.response.ItemsResponse.Item; +import json.templateInfo.DeployTemplateConfig; +import json.templateInfo.TemplateInfo; + +import utilities.IDcaeRestClient; +import utilities.IReport; +import utilities.Report; +import utilities.DcaeRestClient; + +import java.io.*; +import java.net.ConnectException; +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +public class Main { + private static final String CONFIG_FILE = "DcaeDtDeployConfigFile"; + private static final String ENVIRONMENT_CONFIG = "environment.resource"; + + private static LoggerError errLogger = LoggerError.getInstance(); + private static LoggerDebug debugLogger = LoggerDebug.getInstance(); + + private Main() { + throw new IllegalAccessError("Utility class"); + } + + public static void main(String[] args) { + System.setProperty("logback.configurationFile", "conf/logback.xml"); + debugLogger.log("Starting VFCMT template deployment"); + if (args.length != 2) { + errLogger.log("Got " + args.length + ", but expecting exactly 2 arguments ONLY!"); + return; + } + debugLogger.log("Arguments:"); + Arrays.stream(args).forEach(arg -> debugLogger.log(arg)); + + initConfiguration(args); + IReport report = new Report(); + try { + ObjectMapper mapper = new ObjectMapper(); + DeployTemplateConfig deployTemplateConfig = mapper.readValue(new File(System.getProperty(CONFIG_FILE, "conf/config.json")), DeployTemplateConfig.class); + Environment environment = mapper.readValue(new File(System.getProperty(ENVIRONMENT_CONFIG, "conf/environment.json")), Environment.class); + + IDcaeRestClient dcaeRestClient = new DcaeRestClient(environment.getCredential()); + dcaeRestClient.init(environment); + + EntitiesRetriever entitiesRetriever = new EntitiesRetriever(dcaeRestClient); + Map<String, List<Item>> elementsByFolderNames = entitiesRetriever.getElementsByFolder(); + + TemplateContainer templateContainer = new TemplateContainer(report, dcaeRestClient, deployTemplateConfig.getTemplateInfo(), elementsByFolderNames); + Map<TemplateInfo, JsonObject> templateInfoToJsonObjectMap = templateContainer.getCdumps(); + + DeployTemplate deployTemplate = new DeployTemplate(report, dcaeRestClient); + deployTemplate.deploy(templateInfoToJsonObjectMap); + + debugLogger.log( "VFCMT template deployment completed successfully"); + } catch (RuntimeException e) { + errLogger.log("ERROR - Template deployment failed with error " + e); + } catch (ConnectException e) { + errLogger.log( "ERROR - Failed connection to server, are you on AT&T network? {}" + e); + } catch (IOException e) { + errLogger.log( "ERROR - Fatal Error! " + e); + } finally { + debugLogger.log(report.toString()); + } + } + + private static void initConfiguration(String[] args) { + System.setProperty(ENVIRONMENT_CONFIG, args[0]); + System.setProperty(CONFIG_FILE, args[1]); + } + + +} diff --git a/dcaedt_tools/src/main/java/tools/NodeData.java b/dcaedt_tools/src/main/java/tools/NodeData.java new file mode 100644 index 0000000..f89105b --- /dev/null +++ b/dcaedt_tools/src/main/java/tools/NodeData.java @@ -0,0 +1,40 @@ +package tools; + +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; + +public class NodeData { + private final JsonArray capabilities; + private final JsonArray requirements; + private final JsonArray properties; + private final JsonObject typeInfo; + private final String nodeName; + + NodeData(JsonArray capabilities, JsonArray requirements, JsonArray properties, JsonObject typeInfo, String nodeName) { + this.capabilities = capabilities; + this.requirements = requirements; + this.properties = properties; + this.typeInfo = typeInfo; + this.nodeName = nodeName; + } + + public JsonArray getCapabilities() { + return capabilities; + } + + public JsonArray getRequirements() { + return requirements; + } + + public JsonArray getProperties() { + return properties; + } + + public JsonObject getTypeInfo() { + return typeInfo; + } + + public String getName() { + return nodeName; + } +} diff --git a/dcaedt_tools/src/main/java/tools/TemplateContainer.java b/dcaedt_tools/src/main/java/tools/TemplateContainer.java new file mode 100644 index 0000000..ee16d22 --- /dev/null +++ b/dcaedt_tools/src/main/java/tools/TemplateContainer.java @@ -0,0 +1,329 @@ +package tools; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import json.response.ItemsResponse.Item; +import json.templateInfo.Composition; +import json.templateInfo.Relation; +import json.templateInfo.TemplateInfo; +import org.apache.commons.lang3.StringUtils; +import utilities.IDcaeRestClient; +import utilities.IReport; + +import java.util.*; +import java.util.concurrent.atomic.AtomicReference; + + +public class TemplateContainer { + private static final String NODES = "nodes"; + private static final String RELATIONSHIP = "relationship"; + private static long nidCounter = 0; + private final IReport report; + private final IDcaeRestClient dcaeRestClient; + private final List<TemplateInfo> templateInfos; + private final Map<String, List<Item>> elementsByFolderNames; + private LoggerDebug debugLogger = LoggerDebug.getInstance(); + + + public TemplateContainer(IReport report, IDcaeRestClient dcaeRestClient, List<TemplateInfo> templateInfos, Map<String, List<Item>> elementsByFolderNames) { + this.report = report; + this.dcaeRestClient = dcaeRestClient; + this.templateInfos = templateInfos; + this.elementsByFolderNames = elementsByFolderNames; + } + + private List<Item> findTemplate(TemplateInfo templateInfo) { + AtomicReference<List<Item>> items = new AtomicReference<>(); + items.set(new ArrayList<>()); + elementsByFolderNames.keySet().stream() + .forEach(folderName -> { + List<Item> itemList = returnMatchedTemplate(folderName, templateInfo); + items.get().addAll(itemList); + }); + if (items.get().size() == templateInfo.getComposition().size()) { + return items.get(); + } + return new ArrayList<>(); + } + + private List<Item> returnMatchedTemplate(String folderName, TemplateInfo templateInfo) { + List<Item> items = new ArrayList<>(); + elementsByFolderNames.get(folderName).stream() + .forEach(item -> templateInfo.getComposition().stream().forEach(composition -> + { + if (composition.getType().equalsIgnoreCase(item.getName())) { + items.add(item); + } + })); + return items; + } + + + public Map<TemplateInfo, JsonObject> getCdumps() { + Map<TemplateInfo, JsonObject> templateInfoToJsonObjectMap = new HashMap<>(); + for (TemplateInfo templateInfo : templateInfos) { + List<Item> items = findTemplate(templateInfo); + if (items == null || items.isEmpty()) { + report.addErrorMessage("vfcmt: " + templateInfo.getName() + ". DCAE Component not found"); + continue; + } + templateInfoToJsonObjectMap.put(templateInfo, getCdumpJsonObject(items, templateInfo)); + } + return templateInfoToJsonObjectMap; + } + + private JsonObject getCdumpJsonObject(List<Item> items, TemplateInfo templateInfo) { + JsonObject cdumpJsonObject = generateCdumpInput(templateInfo); + Map<Item, Map<String, NodeData>> itemMapHashMap = new HashMap<>(); + JsonArray relationsJsonArray = new JsonArray(); + for (Item item : items) { + debugLogger.log("Creating cdump for item: " + item.getName()); + JsonArray jsonArrayNode = cdumpJsonObject.getAsJsonArray(NODES); + JsonParser jsonParser = new JsonParser(); + JsonArray allNodeTemplates = jsonParser.parse(dcaeRestClient.getItemModel(item.getItemId())).getAsJsonObject().get("data").getAsJsonObject().get("model").getAsJsonObject().get(NODES).getAsJsonArray(); + Map<String, NodeData> stringRelationsDataMap = new HashMap<>(); + for (JsonElement nodeElement : allNodeTemplates) { + JsonObject responseModelJson = nodeElement.getAsJsonObject(); + JsonObject responseTypeInfoJson = jsonParser.parse(dcaeRestClient.getItemType(item.getItemId(), responseModelJson.get("type").getAsString())).getAsJsonObject().get("data").getAsJsonObject().get("type").getAsJsonObject(); + JsonObject jsonObjectElement = newVfcmtJSON(responseModelJson.get("name").getAsString(), item.getModels().get(0).getItemId()); + jsonObjectElement.addProperty("id", responseTypeInfoJson.get("itemId").getAsString().split("/")[0]); + String nid = "n." + new Date().getTime() + "." + nidCounter++; + jsonObjectElement.addProperty("nid", nid); + NodeData nodeData = createNodeData(responseModelJson, responseTypeInfoJson, responseModelJson.get("name").getAsString()); + stringRelationsDataMap.put(nid, nodeData); + jsonObjectElement.add("capabilities", nodeData.getCapabilities()); + jsonObjectElement.add("requirements", nodeData.getRequirements()); + jsonObjectElement.add("properties", nodeData.getProperties()); + jsonObjectElement.add("typeinfo", nodeData.getTypeInfo()); + JsonObject typeJsonObject = new JsonObject(); + typeJsonObject.addProperty("name", responseModelJson.get("type").getAsString()); + jsonObjectElement.add("type", typeJsonObject); + JsonElement ndataElement = createNData(responseModelJson.get("name").getAsString(), nid); + jsonObjectElement.add("ndata", ndataElement); + jsonArrayNode.add(jsonObjectElement); + } + itemMapHashMap.put(item, stringRelationsDataMap); + } + JsonElement jsonElement = createTemplateInfoRelations(templateInfo, itemMapHashMap); + if (jsonElement != null && jsonElement.isJsonArray()) { + for (JsonElement element : jsonElement.getAsJsonArray()) { + relationsJsonArray.add(element); + } + } + jsonElement = createSelfRelations(itemMapHashMap); + if (jsonElement != null && jsonElement.isJsonArray()) { + for (JsonElement element : jsonElement.getAsJsonArray()) { + relationsJsonArray.add(element); + } + + } + cdumpJsonObject.add("relations", relationsJsonArray); + return cdumpJsonObject; + } + + //We need it only for printing the relations (front end requirement) + private JsonElement createNData(String name, String nid) { + JsonObject ndataElement = new JsonObject(); + ndataElement.addProperty("name", nid); + ndataElement.addProperty("label", name); + ndataElement.addProperty("x",438); + ndataElement.addProperty("y",435); + ndataElement.addProperty("px",437); + ndataElement.addProperty("py",434); + ndataElement.add("ports", new JsonArray()); + ndataElement.addProperty("radius", 30); + + return ndataElement; + } + + private JsonElement createSelfRelations(Map<Item, Map<String, NodeData>> nodeDataByNidByItem) { + JsonArray jsonArrayRelations = new JsonArray(); + for (Item item : nodeDataByNidByItem.keySet()) { + Map<String, NodeData> nodeDataByNid = nodeDataByNidByItem.get(item); + if (nodeDataByNid.size() < 2) { + continue; + } + Map<JsonObject, String> nidListByRequirement = new HashMap<>(); + for (String nid : nodeDataByNid.keySet()) { + JsonArray jsonArrayRequirements = nodeDataByNid.get(nid).getRequirements(); + for (JsonElement requirement : jsonArrayRequirements) { + JsonObject jsonObject = requirement.getAsJsonObject(); + if (jsonObject.has("node")) { + nidListByRequirement.put(jsonObject, nid); + } + } + } + for (JsonObject requirement : nidListByRequirement.keySet()) { + String toNodeName = requirement.get("node").toString().replaceAll("\"", ""); + boolean isFound = false; + NodeData toNodeData; + String toNId = null; + for (String nid : nodeDataByNid.keySet()) { + toNodeData = nodeDataByNid.get(nid); + toNId = nid; + if (toNodeData.getName().equalsIgnoreCase(toNodeName)) { + isFound = true; + break; + } + } + if (isFound) { + JsonObject relationElement = new JsonObject(); + NodeData fromNode = nodeDataByNidByItem.get(item).get(nidListByRequirement.get(requirement)); + relationElement.addProperty("rid", "ink." + nidListByRequirement.get(requirement) + "." + nidCounter++); + relationElement.addProperty("n1", nidListByRequirement.get(requirement)); + relationElement.addProperty("name1", fromNode.getName()); + JsonObject metaData = new JsonObject(); + metaData.addProperty("n1", nidListByRequirement.get(requirement)); + metaData.addProperty("p1", requirement.get("name").toString().replaceAll("\"", "")); + relationElement.addProperty("n2", toNId); + relationElement.addProperty("name2", toNodeName); + metaData.addProperty("n2", toNId); + String capabilityFullName = requirement.get("capability").getAsJsonObject().get("name").toString(); + String capabilityShortName = StringUtils.substringAfterLast(capabilityFullName, "."); + metaData.addProperty("p2", capabilityShortName.replaceAll("\"", "")); + JsonArray relationship = new JsonArray(); + relationship.add(fromNode.getName().replaceAll("\"", "")); + JsonElement requirementRelationship = requirement.get(RELATIONSHIP); + if (requirementRelationship != null) { + relationship.add(requirementRelationship.getAsJsonObject().get("type").toString().replaceAll("\"", "")); + } else { + relationship.add((JsonElement) null); + } + + relationship.add(requirement.get("name").toString().replaceAll("\"", "")); + metaData.add(RELATIONSHIP, relationship); + relationElement.add("meta", metaData); + jsonArrayRelations.add(relationElement); + } + } + } + return jsonArrayRelations; + } + + private NodeData createNodeData(JsonObject responseModelJson, JsonObject responseTypeInfoJson, String nodeName) { + JsonArray capabilities = responseModelJson.get("capabilities").getAsJsonArray(); + JsonArray requirements = responseModelJson.get("requirements").getAsJsonArray(); + JsonArray properties = responseModelJson.get("properties").getAsJsonArray(); + return new NodeData(capabilities, requirements, properties, responseTypeInfoJson, nodeName); + } + + private JsonArray createTemplateInfoRelations(TemplateInfo templateInfo, Map<Item, Map<String, NodeData>> nodeDataByNidByItem) { + JsonArray jsonArrayRelations = new JsonArray(); + + if (templateInfo.getRelations() == null) { + return null; + } + for (Relation relation : templateInfo.getRelations()) { + JsonObject metaData = new JsonObject(); + JsonObject relationElement = new JsonObject(); + String fromComponent = relation.getFromComponent(); + String toComponent = relation.getToComponent(); + String fromComponentAlias = StringUtils.substringBefore(fromComponent, "."); + String fromComponentNodeName = StringUtils.substringAfterLast(fromComponent, "."); + String toComponentAlias = StringUtils.substringBefore(toComponent, "."); + String toComponentNodeName = StringUtils.substringAfterLast(toComponent, "."); + boolean findTo = false; + boolean findFrom = false; + for (Item item : nodeDataByNidByItem.keySet()) { + Map<String, NodeData> nodeDataByNid = nodeDataByNidByItem.get(item); + for (String nid : nodeDataByNid.keySet()) { + NodeData currentNodeData = nodeDataByNid.get(nid); + + Optional<Composition> isFoundComposition = templateInfo.getComposition().stream() + .filter(element -> fromComponentAlias.equalsIgnoreCase(element.getAlias()) && element.getType().equalsIgnoreCase(item.getName()) && fromComponentNodeName.equalsIgnoreCase(currentNodeData.getName())).findAny(); + if (isFoundComposition.isPresent()) { + boolean isFound = findNode(relation.getFromRequirement(), currentNodeData.getRequirements()); + if (isFound) { + relationElement.addProperty("rid", "ink." + nid + "." + nidCounter++); + relationElement.addProperty("n1", nid); + relationElement.addProperty("name1", currentNodeData.getName()); + metaData.addProperty("n1", nid); + metaData.addProperty("p1", relation.getFromRequirement()); + JsonArray relationship = new JsonArray(); + relationship.add(fromComponentNodeName); + String requirementRelationshipType = findRequirementType(relation.getFromRequirement(), currentNodeData.getRequirements()); + if (requirementRelationshipType != null) { + relationship.add(requirementRelationshipType); + } else { + relationship.add((JsonElement) null); + } + relationship.add(toComponentNodeName); + metaData.add(RELATIONSHIP, relationship); + findFrom = true; + } + + } + + isFoundComposition = templateInfo.getComposition().stream() + .filter(element -> toComponentAlias.equalsIgnoreCase(element.getAlias()) && element.getType().equalsIgnoreCase(item.getName()) && toComponentNodeName.equalsIgnoreCase(currentNodeData.getName())).findAny(); + if (isFoundComposition.isPresent()) { + boolean isFound = findNode(relation.getToCapability(), currentNodeData.getCapabilities()); + if (isFound) { + relationElement.addProperty("n2", nid); + relationElement.addProperty("name2", currentNodeData.getName()); + metaData.addProperty("n2", nid); + metaData.addProperty("p2", relation.getToCapability()); + findTo = true; + } + } + } + } + if (findTo && findFrom) { + relationElement.add("meta", metaData); + jsonArrayRelations.add(relationElement); + } else { + report.addErrorMessage("Didn't find match relation from: " + relation.getFromComponent() + ", to: "+ relation.getToComponent()); + } + } + + return jsonArrayRelations; + } + + private String findRequirementType(String fromRequirement, JsonArray requirements) { + Iterator<JsonElement> jsonElements = requirements.iterator(); + while (jsonElements.hasNext()) { + JsonObject jsonObject = (JsonObject) jsonElements.next(); + String name = jsonObject.get("name").getAsString(); + if (fromRequirement.equals(name) && jsonObject.has("type")) { + return jsonObject.get("type").toString().replaceAll("\"", ""); + } + } + + return null; + } + + private boolean findNode(String endPoint, JsonArray node) { + Iterator<JsonElement> jsonElements = node.iterator(); + while (jsonElements.hasNext()) { + JsonObject jsonObject = (JsonObject) jsonElements.next(); + String name = jsonObject.get("name").getAsString(); + if (endPoint.equals(name)) { + return true; + } + } + + return false; + } + + private JsonObject newVfcmtJSON(String name, String description) { + JsonObject json = new JsonObject(); + json.addProperty("name", name); + json.addProperty("description", description); + return json; + } + + private JsonObject generateCdumpInput(TemplateInfo templateInfo) { + JsonObject json = new JsonObject(); + json.addProperty("version", 0); + json.addProperty("flowType", templateInfo.getName()); + json.add(NODES, new JsonArray()); + + json.add("inputs", new JsonArray()); + json.add("outputs", new JsonArray()); + + return json; + + } +} |