Refactor method processServiceTosca for Sonar
[aai/babel.git] / src / main / java / org / onap / aai / babel / parser / ArtifactGeneratorToscaParser.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * Copyright © 2017-2018 European Software Marketing Ltd.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *       http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.aai.babel.parser;
23
24 import java.io.File;
25 import java.io.FileInputStream;
26 import java.io.IOException;
27 import java.util.LinkedList;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.Properties;
31 import java.util.stream.Collectors;
32 import org.onap.aai.babel.logging.ApplicationMsgs;
33 import org.onap.aai.babel.logging.LogHelper;
34 import org.onap.aai.babel.xml.generator.data.WidgetConfigurationUtil;
35 import org.onap.aai.babel.xml.generator.model.AllotedResource;
36 import org.onap.aai.babel.xml.generator.model.L3NetworkWidget;
37 import org.onap.aai.babel.xml.generator.model.Model;
38 import org.onap.aai.babel.xml.generator.model.ProvidingService;
39 import org.onap.aai.babel.xml.generator.model.Resource;
40 import org.onap.aai.babel.xml.generator.model.Service;
41 import org.onap.aai.babel.xml.generator.model.TunnelXconnectWidget;
42 import org.onap.aai.babel.xml.generator.model.VfModule;
43 import org.onap.aai.babel.xml.generator.model.Widget;
44 import org.onap.aai.babel.xml.generator.types.ModelType;
45 import org.onap.aai.cl.api.Logger;
46 import org.onap.sdc.tosca.parser.api.ISdcCsarHelper;
47 import org.onap.sdc.toscaparser.api.Group;
48 import org.onap.sdc.toscaparser.api.NodeTemplate;
49 import org.onap.sdc.toscaparser.api.Property;
50 import org.onap.sdc.toscaparser.api.elements.Metadata;
51
52 public class ArtifactGeneratorToscaParser {
53
54     private static Logger log = LogHelper.INSTANCE;
55
56     public static final String PROPERTY_ARTIFACT_GENERATOR_CONFIG_FILE = "artifactgenerator.config";
57
58     private static final String GENERATOR_AAI_CONFIGFILE_NOT_FOUND =
59             "Cannot generate artifacts. Artifact Generator Configuration file not found at %s";
60     private static final String GENERATOR_AAI_CONFIGLOCATION_NOT_FOUND =
61             "Cannot generate artifacts. artifactgenerator.config system property not configured";
62     private static final String GENERATOR_AAI_PROVIDING_SERVICE_METADATA_MISSING =
63             "Cannot generate artifacts. Providing Service Metadata is missing for allotted resource %s";
64     private static final String GENERATOR_AAI_PROVIDING_SERVICE_MISSING =
65             "Cannot generate artifacts. Providing Service is missing for allotted resource %s";
66
67     // Metadata properties
68     private static final String CATEGORY = "category";
69     private static final String ALLOTTED_RESOURCE = "Allotted Resource";
70     private static final String SUBCATEGORY = "subcategory";
71     private static final String TUNNEL_XCONNECT = "Tunnel XConnect";
72
73     private static final String VERSION = "version";
74
75     private ISdcCsarHelper csarHelper;
76
77     /**
78      * Constructs using csarHelper
79      *
80      * @param csarHelper The csar helper
81      */
82     public ArtifactGeneratorToscaParser(ISdcCsarHelper csarHelper) {
83         this.csarHelper = csarHelper;
84     }
85
86     /**
87      * Returns the artifact description
88      *
89      * @param model the artifact model
90      * @return the artifact model's description
91      */
92     public static String getArtifactDescription(Model model) {
93         String artifactDesc = model.getModelDescription();
94         if (model.getModelType().equals(ModelType.SERVICE)) {
95             artifactDesc = "AAI Service Model";
96         } else if (model.getModelType().equals(ModelType.RESOURCE)) {
97             artifactDesc = "AAI Resource Model";
98         }
99         return artifactDesc;
100     }
101
102     /**
103      * Initialises the widget configuration.
104      *
105      * @throws IOException
106      */
107     public static void initWidgetConfiguration() throws IOException {
108         log.debug("Getting Widget Configuration");
109         String configLocation = System.getProperty(PROPERTY_ARTIFACT_GENERATOR_CONFIG_FILE);
110         if (configLocation != null) {
111             File file = new File(configLocation);
112             if (file.exists()) {
113                 Properties properties = new Properties();
114                 properties.load(new FileInputStream(file));
115                 WidgetConfigurationUtil.setConfig(properties);
116             } else {
117                 throw new IllegalArgumentException(String.format(GENERATOR_AAI_CONFIGFILE_NOT_FOUND, configLocation));
118             }
119         } else {
120             throw new IllegalArgumentException(GENERATOR_AAI_CONFIGLOCATION_NOT_FOUND);
121         }
122     }
123
124     /**
125      * Process the service TOSCA.
126      *
127      * @param service model of the service artifact
128      * @param idTypeStore ID->Type mapping
129      * @param nodeTemplates a list of service nodes
130      *
131      */
132     public void processServiceTosca(Service service, Map<String, String> idTypeStore,
133             List<NodeTemplate> nodeTemplates) {
134         log.debug("Processing (TOSCA) Service object");
135
136         for (NodeTemplate nodeTemplate : nodeTemplates) {
137             if (nodeTemplate.getMetaData() != null) {
138                 addNodeToService(idTypeStore, service, nodeTemplate);
139             } else {
140                 log.warn(ApplicationMsgs.MISSING_SERVICE_METADATA, nodeTemplate.getName());
141             }
142         }
143     }
144
145
146     /**
147      * Generates a Resource List using input Service Node Templates.
148      *
149      * @param serviceNodes input Service Node Templates
150      * @param idTypeStore ID->Type mapping
151      * @return the processed resource models
152      */
153     public List<Resource> processResourceToscas(List<NodeTemplate> serviceNodes, Map<String, String> idTypeStore) {
154         List<Resource> resources = new LinkedList<>();
155         for (NodeTemplate serviceNode : serviceNodes) {
156             if (serviceNode.getMetaData() != null) {
157                 List<NodeTemplate> resourceNodes = csarHelper.getNodeTemplateChildren(serviceNode);
158                 processResourceTosca(idTypeStore, resources, serviceNode, resourceNodes);
159             } else {
160                 log.warn(ApplicationMsgs.MISSING_SERVICE_METADATA, serviceNode.getName());
161             }
162         }
163         return resources;
164     }
165
166     private void processResourceTosca(Map<String, String> idTypeStore, List<Resource> resources,
167             NodeTemplate serviceNode, List<NodeTemplate> resourceNodes) {
168         String resourceUuId = serviceNode.getMetaData().getValue("UUID");
169         String resourceType = idTypeStore.get(resourceUuId);
170         if (resourceType != null) {
171             Model model = Model.getModelFor(resourceType);
172
173             log.debug("Inside Resource artifact generation for resource");
174             Map<String, String> serviceMetadata = serviceNode.getMetaData().getAllProperties();
175             model.populateModelIdentificationInformation(serviceMetadata);
176
177             // Found model from the type store so removing the same
178             idTypeStore.remove(model.getModelNameVersionId());
179             processVfTosca(idTypeStore, model, resourceNodes);
180
181             // Process group information from tosca for vfModules
182             if (csarHelper.getServiceVfList() != null) {
183                 processVfModules(resources, model, serviceNode);
184             }
185
186             if (hasSubCategoryTunnelXConnect(serviceMetadata) && hasAllottedResource(serviceMetadata)) {
187                 model.addWidget(new TunnelXconnectWidget());
188             }
189             resources.add((Resource) model);
190         }
191     }
192
193     /**
194      * Add the supplied Node Template to the Service, provided that it is a valid Resource or Widget. If the Node
195      * Template is a Resource type, this is also recorded in the supplied nodesById Map.
196      *
197      * @param nodesById a map of Resource node type names, keyed by UUID
198      * @param service the Service to which the Node Template should be added
199      * @param nodeTemplate the Node Template to add (only if this is a Resource or Widget type)
200      */
201     private void addNodeToService(Map<String, String> nodesById, Service service, NodeTemplate nodeTemplate) {
202         String nodeTypeName = normaliseNodeTypeName(nodeTemplate);
203         Model model = Model.getModelFor(nodeTypeName);
204         if (model != null) {
205             if (nodeTemplate.getMetaData() != null) {
206                 model.populateModelIdentificationInformation(nodeTemplate.getMetaData().getAllProperties());
207             }
208
209             if (model instanceof Resource) {
210                 nodesById.put(model.getModelNameVersionId(), nodeTypeName);
211                 service.addResource((Resource) model);
212             } else {
213                 service.addWidget((Widget) model);
214             }
215         }
216     }
217
218     private void processVfModules(List<Resource> resources, Model resourceModel, NodeTemplate serviceNode) {
219         // Get the customisation UUID for each VF node and use it to get its Groups
220         String uuid = csarHelper.getNodeTemplateCustomizationUuid(serviceNode);
221         List<Group> serviceGroups = csarHelper.getVfModulesByVf(uuid);
222
223         // Process each VF Group
224         for (Group serviceGroup : serviceGroups) {
225             Model groupModel = Model.getModelFor(serviceGroup.getType());
226             if (groupModel instanceof VfModule) {
227                 processVfModule(resources, resourceModel, serviceGroup, serviceNode, (VfModule) groupModel);
228             }
229         }
230     }
231
232     private void processVfModule(List<Resource> resources, Model model, Group groupDefinition, NodeTemplate serviceNode,
233             VfModule groupModel) {
234         // Populate group with metadata properties
235         groupModel.populateModelIdentificationInformation(groupDefinition.getMetadata().getAllProperties());
236         // Populate group with non-metadata properties
237         Map<String, Property> groupProperties = groupDefinition.getProperties();
238         Map<String, String> properties = populateStringProperties(groupProperties);
239         groupModel.populateModelIdentificationInformation(properties);
240
241         // Get names of the members of the service group
242         List<NodeTemplate> members = csarHelper.getMembersOfVfModule(serviceNode, groupDefinition);
243         if (members != null && !members.isEmpty()) {
244             List<String> memberNames = members.stream().map(NodeTemplate::getName).collect(Collectors.toList());
245             groupModel.setMembers(memberNames);
246             for (NodeTemplate member : members) {
247                 processGroupMembers(groupModel, member);
248             }
249         }
250
251         model.addResource(groupModel); // Added group (VfModule) to the (VF) model
252         // Check if we have already encountered the same VfModule across all the artifacts
253         if (!resources.contains(groupModel)) {
254             resources.add(groupModel);
255         }
256     }
257
258     private void processGroupMembers(Model group, NodeTemplate member) {
259         Model resourceNode;
260         // L3-network inside vf-module to be generated as Widget a special handling.
261         if (member.getType().contains("org.openecomp.resource.vl")) {
262             resourceNode = new L3NetworkWidget();
263         } else {
264             resourceNode = Model.getModelFor(member.getType());
265         }
266         if (resourceNode != null && !(resourceNode instanceof Resource)) {
267             Widget widget = (Widget) resourceNode;
268             widget.addKey(member.getName());
269             // Add the widget element encountered to the Group model
270             group.addWidget(widget);
271         }
272     }
273
274     private String normaliseNodeTypeName(NodeTemplate nodeType) {
275         String nodeTypeName = nodeType.getType();
276         Metadata metadata = nodeType.getMetaData();
277         if (metadata != null && hasAllottedResource(metadata.getAllProperties())) {
278             if (nodeType.getType().contains("org.openecomp.resource.vf.")) {
279                 nodeTypeName = "org.openecomp.resource.vf.allottedResource";
280             }
281             if (nodeType.getType().contains("org.openecomp.resource.vfc.")) {
282                 nodeTypeName = "org.openecomp.resource.vfc.AllottedResource";
283             }
284         }
285         return nodeTypeName;
286     }
287
288     private boolean hasAllottedResource(Map<String, String> metadata) {
289         return ALLOTTED_RESOURCE.equals(metadata.get(CATEGORY));
290     }
291
292     private boolean hasSubCategoryTunnelXConnect(Map<String, String> metadata) {
293         return TUNNEL_XCONNECT.equals(metadata.get(SUBCATEGORY));
294     }
295
296     /**
297      * Create a Map of property name against String property value from the input Map
298      *
299      * @param inputMap The input Map
300      * @return Map of property name against String property value
301      */
302     private Map<String, String> populateStringProperties(Map<String, Property> inputMap) {
303         return inputMap.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey,
304                 e -> e.getValue().getValue() == null ? "" : e.getValue().getValue().toString()));
305     }
306
307     private void processVfTosca(Map<String, String> idTypeStore, Model resourceModel,
308             List<NodeTemplate> resourceNodes) {
309         boolean providingServiceFound = false;
310
311         for (NodeTemplate resourceNodeTemplate : resourceNodes) {
312             String nodeTypeName = normaliseNodeTypeName(resourceNodeTemplate);
313             Model resourceNode = Model.getModelFor(nodeTypeName);
314             if (resourceNode instanceof ProvidingService) {
315                 providingServiceFound = true;
316                 Map<String, Property> nodeProperties = resourceNodeTemplate.getProperties();
317                 if (nodeProperties.get("providing_service_uuid") == null
318                         || nodeProperties.get("providing_service_invariant_uuid") == null) {
319                     throw new IllegalArgumentException(String.format(GENERATOR_AAI_PROVIDING_SERVICE_METADATA_MISSING,
320                             resourceModel.getModelId()));
321                 }
322                 Map<String, String> properties = populateStringProperties(nodeProperties);
323                 properties.put(VERSION, "1.0");
324                 resourceNode.populateModelIdentificationInformation(properties);
325                 resourceModel.addResource((Resource) resourceNode);
326             } else if (resourceNode instanceof Resource && !(resourceNode.getWidgetType().equals(Widget.Type.L3_NET))) {
327                 idTypeStore.put(resourceNode.getModelNameVersionId(), nodeTypeName);
328                 resourceModel.addResource((Resource) resourceNode);
329             }
330         }
331
332         if (resourceModel instanceof AllotedResource && !providingServiceFound) {
333             throw new IllegalArgumentException(
334                     String.format(GENERATOR_AAI_PROVIDING_SERVICE_MISSING, resourceModel.getModelId()));
335         }
336     }
337 }