Removed dead and duplicate code in onboarding
[sdc.git] / common / onap-sdc-artifact-generator-lib / onap-sdc-artifact-generator-core / src / main / java / org / onap / sdc / generator / aai / AaiArtifactGenerator.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.sdc.generator.aai;
22
23 import java.io.File;
24 import java.io.FileInputStream;
25 import java.io.IOException;
26 import java.util.Collection;
27 import java.util.HashMap;
28 import java.util.HashSet;
29 import java.util.Iterator;
30 import java.util.LinkedList;
31 import java.util.List;
32 import java.util.Map;
33 import java.util.Objects;
34 import java.util.Properties;
35 import java.util.Set;
36 import org.onap.sdc.generator.aai.model.AllotedResource;
37 import org.onap.sdc.generator.aai.model.L3NetworkWidget;
38 import org.onap.sdc.generator.aai.model.Model;
39 import org.onap.sdc.generator.aai.model.ProvidingService;
40 import org.onap.sdc.generator.aai.model.Resource;
41 import org.onap.sdc.generator.aai.model.Service;
42 import org.onap.sdc.generator.aai.model.TunnelXconnectWidget;
43 import org.onap.sdc.generator.aai.model.VfModule;
44 import org.onap.sdc.generator.aai.model.Widget;
45 import org.onap.sdc.generator.aai.tosca.GroupDefinition;
46 import org.onap.sdc.generator.aai.tosca.NodeTemplate;
47 import org.onap.sdc.generator.aai.tosca.ToscaTemplate;
48 import org.onap.sdc.generator.aai.types.ModelType;
49 import org.onap.sdc.generator.data.AdditionalParams;
50 import org.onap.sdc.generator.data.Artifact;
51 import org.onap.sdc.generator.data.ArtifactType;
52 import org.onap.sdc.generator.data.GenerationData;
53 import org.onap.sdc.generator.data.GeneratorConstants;
54 import org.onap.sdc.generator.data.GeneratorUtil;
55 import org.onap.sdc.generator.data.GroupType;
56 import org.onap.sdc.generator.data.WidgetConfigurationUtil;
57 import org.onap.sdc.generator.intf.ArtifactGenerator;
58 import org.onap.sdc.generator.intf.Generator;
59 import org.onap.sdc.generator.logging.annotations.Audit;
60 import org.onap.sdc.generator.util.ArtifactGeneratorUtil;
61 import org.openecomp.sdc.logging.api.Logger;
62 import org.openecomp.sdc.logging.api.LoggerFactory;
63 import org.slf4j.MDC;
64
65 @Generator(artifactType = ArtifactType.AAI)
66 public class AaiArtifactGenerator implements ArtifactGenerator {
67
68   private static final Logger log = LoggerFactory.getLogger(AaiArtifactGenerator.class.getName());
69
70   /**
71    * Implementation of the method to generate AAI artifacts.
72    *
73    * @param input List of input tosca files
74    * @return Translated/Error data as a {@link GenerationData} object
75    */
76   @Override
77   @Audit
78   public GenerationData generateArtifact(List<Artifact> input,
79                                          Map<String, String> additionalParams) {
80     try {
81       if (input != null && input.size() != 0 ) {
82         ArtifactGeneratorUtil.initializeArtifactLoggingContext(input.get(0));
83       }
84       initWidgetConfiguration();
85       return generateArtifactInternal(input, additionalParams);
86     } catch (Exception exception) {
87       ArtifactGeneratorUtil.logError(exception.getMessage(), exception);
88       GenerationData generationData = new GenerationData();
89       generationData.add(ArtifactType.AAI.name(), exception.getMessage());
90       return generationData;
91     }
92   }
93
94   /**
95    * Helper method to generate AAI artifacts.
96    *
97    * @param input List of input tosca files
98    * @return Translated/Error data as a {@link GenerationData} object
99    */
100   private GenerationData generateArtifactInternal(List<Artifact> input,
101                                                   Map<String, String> additionalParams) {
102     final GenerationData generationData = new GenerationData();
103
104     List<Resource> resources = new LinkedList<>();
105     Map<String, String> idTypeStore = new HashMap<>();
106     Map<String, String> resourcesVersion = new HashMap<>();
107
108     List<ToscaTemplate> toscas = new LinkedList<>();
109
110     String serviceVersion = additionalParams.get(AdditionalParams.ServiceVersion.getName());
111     if (serviceVersion == null) {
112       throw new IllegalArgumentException(GeneratorConstants
113           .GENERATOR_AAI_ERROR_MISSING_SERVICE_VERSION);
114     } else {
115       String versionRegex = "^[1-9]\\d*(\\.0)$";
116       if (! (serviceVersion.matches(versionRegex))) {
117         throw new IllegalArgumentException(GeneratorConstants
118             .GENERATOR_AAI_INVALID_SERVICE_VERSION);
119       }
120     }
121
122     for (Artifact inputArtifact : input) {
123       ToscaTemplate tosca = getToscaModel(inputArtifact, serviceVersion);
124       validateTosca(tosca, inputArtifact);
125       ToscaTemplate processedTosca = preProcessingTosca(tosca);
126       toscas.add(processedTosca);
127     }
128
129     //Get the service tosca from the list of artifacts
130     ToscaTemplate serviceTosca = getServiceTosca(toscas);
131     if (serviceTosca == null) {
132       throw new IllegalArgumentException(GeneratorConstants
133           .GENERATOR_AAI_ERROR_MISSING_SERVICE_TOSCA);
134     }
135
136     Service service = new Service();
137     //Populate basic service model metadata
138     service.populateModelIdentificationInformation(serviceTosca.getMetadata());
139
140     if (serviceTosca.getTopology_template() != null
141         && serviceTosca.getTopology_template().getNode_templates() != null) {
142       processServiceTosca(service, idTypeStore,resourcesVersion, serviceTosca);
143     }
144     validateResourceToscaAgainstService(idTypeStore, toscas);
145
146     //Process the resource tosca files
147     List<Resource> currentToscaResources = new LinkedList<>();
148     while (toscas.size() > 0) {
149       ToscaTemplate resourceTemplate = toscas.remove(0);
150       String resourceUuId = resourceTemplate.getMetadata().get("UUID");
151       String mapValue = idTypeStore.get(resourceUuId);
152       if (mapValue == null) {
153         log.warn(
154             "Additional tosca file found with resource version id : "
155                 + resourceUuId);
156         continue;
157       }
158       //update resource version with version from service tosca
159       String resourceVersion = resourcesVersion.get(resourceUuId);
160       resourceTemplate.getMetadata().put("version", resourceVersion);
161       Model model = Model.getModelFor(idTypeStore.get(resourceTemplate.getModelVersionId()));
162
163       log.debug("Inside Resource artifact generation for resource");
164       model.populateModelIdentificationInformation(
165           resourceTemplate.getMetadata());  //Get base resource metadata information
166       //Found model from the type store so removing the same
167       idTypeStore.remove(model.getModelNameVersionId());
168       if (resourceTemplate.getTopology_template() != null
169           && resourceTemplate.getTopology_template().getNode_templates() != null) {
170         processVfTosca(idTypeStore, resourceTemplate, model);
171       }
172
173       //Process group information from tosca for vfModules
174       if (resourceTemplate.getTopology_template() != null
175           && resourceTemplate.getTopology_template().getGroups() != null) {
176         processVfModule(resources, currentToscaResources, resourceTemplate, model);
177       } else {
178         model.getWidgets().clear();
179       }
180
181       if ("Tunnel XConnect".equals(resourceTemplate.getMetadata().get("subcategory"))
182           && "Allotted Resource".equals(resourceTemplate.getMetadata().get("category"))) {
183         model.addWidget(new TunnelXconnectWidget());
184       }
185
186       resources.add((Resource) model);
187       currentToscaResources
188           .clear();    //Clearing the current tosca resource list for the next iteration
189     }
190
191     AaiModelGenerator modelGenerator = AaiModelGenerator.getInstance();
192     //Generate AAI XML service model
193     MDC.put(GeneratorConstants.ARTIFACT_MODEL_INFO , service.getModelName() + "," + getArtifactLabel(service));
194     String aaiServiceModel = modelGenerator.generateModelFor(service);
195     generationData.add(getServiceArtifact(service, aaiServiceModel));
196
197     //Generate AAI XML resource model
198     for (Resource res : resources) {
199       MDC.put(GeneratorConstants.ARTIFACT_MODEL_INFO , res.getModelName() + "," + getArtifactLabel(res));
200       String aaiResourceModel = modelGenerator.generateModelFor(res);
201       generationData.add(getResourceArtifact(res, aaiResourceModel));
202     }
203
204     //Resetting logging parameters since they get overridden while writing metrics logs
205     // recursively for service, resource and widgets.
206     if (input != null && input.size() != 0 ) {
207       ArtifactGeneratorUtil.initializeArtifactLoggingContext(input.get(0));
208     }
209
210     return generationData;
211   }
212
213   private void validateResourceToscaAgainstService(Map<String, String> idTypeStore,
214                                                    List<ToscaTemplate> toscas) {
215     for (String resourceUuidFromService : idTypeStore.keySet()) {
216       Iterator<ToscaTemplate> itr = toscas.iterator();
217       boolean toscaFound = false;
218       while (itr.hasNext()) {
219         ToscaTemplate toscaTemplate = itr.next();
220         String resourceUuId = toscaTemplate.getMetadata().get("UUID");
221         if (resourceUuidFromService.equals(resourceUuId)) {
222           toscaFound = true;
223           break;
224         }
225       }
226       if (!toscaFound) {
227         throw new IllegalArgumentException(
228                 String.format(GeneratorConstants.GENERATOR_AAI_ERROR_MISSING_RESOURCE_TOSCA, resourceUuidFromService));
229       }
230     }
231
232   }
233
234   private ToscaTemplate preProcessingTosca(ToscaTemplate tosca) {
235     if (tosca.getTopology_template() != null
236         && tosca.getTopology_template().getNode_templates() != null) {
237       Collection<NodeTemplate> coll =
238           tosca.getTopology_template().getNode_templates().values();
239       for (NodeTemplate node : coll) {
240
241         if (node.getType().contains("org.openecomp.resource.vf.") && node.getMetadata().get("category")
242             .equals("Allotted Resource")) {
243           node.setType("org.openecomp.resource.vf.allottedResource");
244         }
245         if (node.getType().contains("org.openecomp.resource.vfc.") && node.getMetadata().get
246             ("category")
247             .equals("Allotted Resource")) {
248           node.setType("org.openecomp.resource.vfc.AllottedResource");
249         }
250       }
251     }
252     return tosca;
253   }
254
255   private void processVfTosca(Map<String, String> idTypeStore, ToscaTemplate resourceTemplate,
256                               Model model) {
257     Set<String> keys = resourceTemplate.getTopology_template().getNode_templates().keySet();
258     boolean flag = false;
259     for (String key : keys) {
260       NodeTemplate node = resourceTemplate.getTopology_template().getNode_templates().get(key);
261       Model resourceNode = Model.getModelFor(node.getType());
262       if (resourceNode != null) {
263         if (resourceNode instanceof ProvidingService) {
264           flag = true;
265           Map<String, String> properties = new HashMap<>();
266           Map<String, Object> nodeProperties = node.getProperties();
267           if (nodeProperties.get("providing_service_uuid") == null || nodeProperties.get(
268               "providing_service_invariant_uuid") == null) {
269             throw new IllegalArgumentException(String.format(
270                 GeneratorConstants.GENERATOR_AAI_PROVIDING_SERVICE_METADATA_MISSING
271                 , model.getModelId()));
272           }
273           for (String key1 : nodeProperties.keySet()) {
274             if (nodeProperties.get(key1) instanceof String) {
275               properties.put(key1, nodeProperties.get(key1).toString());
276             }
277           }
278           properties.put("version","1.0");
279           resourceNode.populateModelIdentificationInformation(properties);
280           model.addResource((Resource) resourceNode);
281         } else if (resourceNode instanceof Resource && !(resourceNode.getWidgetType().equals(
282             Widget.Type
283             .L3_NET))) {
284           idTypeStore.put(resourceNode.getModelNameVersionId(), node.getType());
285           model.addResource((Resource) resourceNode);
286         }
287       }
288     }
289     if(model instanceof AllotedResource){
290       if(!flag) {
291         throw new IllegalArgumentException(String.format(
292             GeneratorConstants.GENERATOR_AAI_PROVIDING_SERVICE_MISSING,
293             model.getModelId()));
294       }
295     }
296   }
297
298   /*  private void vfWarnScenario(Map<String, String> idTypeStore, ToscaTemplate resourceTemplate) {
299     if (idTypeStore.size() == 0) {
300       //Log message for extra model file
301       log.warn(
302           "Additional tosca file found with resource version id : "
303               + resourceTemplate.getModelVersionId());
304     } else {
305       //Log message for missing model files.. Replace with logger statement
306       log.warn("Service-Resource Tosca mapping not found for  : "
307           + idTypeStore.keySet().toString());
308     }
309     return;
310   }*/
311
312   private void processVfModule(List<Resource> resources, List<Resource> currentToscaResources,
313                                ToscaTemplate resourceTemplate, Model model) {
314     log.debug("Inside Resource artifact generation for group/vfModule");
315     Collection<GroupDefinition> groups =
316         resourceTemplate.getTopology_template().getGroups().values();
317     Set<String> nodeNameListForGroups = new HashSet<>();
318     for (GroupDefinition gd : groups) {
319       Model group = Model.getModelFor(gd.getType());
320       if (group != null) {
321         group.populateModelIdentificationInformation(gd.getMetadata());
322         Map<String, String> properties = new HashMap<>();
323         Map<String, Object> groupProperties = gd.getProperties();
324         for (String key : groupProperties.keySet()) {
325           if (groupProperties.get(key) instanceof String) {
326             properties.put(key, groupProperties.get(key).toString());
327           }
328         }
329         group.populateModelIdentificationInformation(properties);
330         if (group instanceof VfModule && !currentToscaResources.contains(group)) {
331           if (gd.getMembers() != null && !gd.getMembers().isEmpty()) {
332             ((VfModule) group).setMembers(gd.getMembers());
333             nodeNameListForGroups.addAll(gd.getMembers());
334             Set<String> groupMembers = new HashSet<>(gd.getMembers());
335
336             for (String member : groupMembers) {
337               NodeTemplate node =
338                   resourceTemplate.getTopology_template().getNode_templates().get(member);
339               if (node != null) {
340                 Model resourceNode;
341                 //L3-network inside vf-module to be generated as Widget a special handling.
342                 if (node.getType().contains("org.openecomp.resource.vl")) {
343                   resourceNode = new L3NetworkWidget();
344                 } else {
345                   resourceNode = Model.getModelFor(node.getType());
346                 }
347                 if (resourceNode != null) {
348                   if (!(resourceNode instanceof Resource)) {
349                     Widget widget = (Widget) resourceNode;
350                     widget.addKey(member);
351                     //Add the widget element encountered
352                     // in the resource tosca in the resource model
353                     boolean isAdded = group.addWidget(widget);
354
355                     //Add only widgets which are members of vf module and remove others
356                     if (isAdded) {
357                       model.addWidget(widget);
358                     }
359                   }
360                 }
361               }
362             }
363           }
364
365           model.addResource((Resource) group); //Added group (VfModule) to the (VF) model
366           currentToscaResources
367               .add((Resource) group); //Adding the VfModule group to file specific resources
368           //Check if we have already encountered the same VfModule across all the artifacts
369           if (!resources.contains(group)) {
370             resources.add((Resource) group);
371           }
372         }
373       }
374     }
375
376     Iterator<Widget> iter = model.getWidgets().iterator();
377     while (iter.hasNext()) {
378       iter.next().allInstancesUsed(nodeNameListForGroups);
379       iter.remove();
380     }
381   }
382
383   private void processServiceTosca(Service service, Map<String, String> idTypeStore,Map<String,
384       String> resourcesVersion,ToscaTemplate serviceTosca) {
385     Collection<NodeTemplate> coll =
386         serviceTosca.getTopology_template().getNode_templates().values();
387     log.debug("Inside Service Tosca ");
388     //Get the resource/widgets in the service according to the node-template types
389     for (NodeTemplate node : coll) {
390       Model model = Model.getModelFor(node.getType());
391       if (model != null) {
392         model.populateModelIdentificationInformation(node.getMetadata());
393         if (model instanceof Resource) {
394           String resourceVersion = node.getMetadata().get("version");
395           validateVersion(resourceVersion,model.getModelNameVersionId());
396           //Keeping track of resource types and
397           // their uuid for identification during resource tosca processing
398           idTypeStore.put(model.getModelNameVersionId(), node.getType());
399           resourcesVersion.put(model.getModelNameVersionId(),resourceVersion);
400           service.addResource((Resource) model);
401         } else {
402           service.addWidget((Widget) model);
403         }
404       }
405     }
406   }
407
408   /**
409    * Create Service artifact model from the AAI xml model string.
410    *
411    * @param serviceModel    Model of the service artifact
412    * @param aaiServiceModel AAI model as string
413    * @return Generated {@link Artifact} model for the service
414    */
415   private Artifact getServiceArtifact(Model serviceModel, String aaiServiceModel) {
416     return getArtifactForModel(serviceModel, aaiServiceModel);
417   }
418
419   private Artifact getArtifactForModel(Model serviceModel, String aaiServiceModel) {
420     Artifact artifact =
421         new Artifact(ArtifactType.MODEL_INVENTORY_PROFILE.name(), GroupType.DEPLOYMENT.name(),
422             GeneratorUtil.checkSum(aaiServiceModel.getBytes()),
423             GeneratorUtil.encode(aaiServiceModel.getBytes()));
424     String serviceArtifactName = getArtifactName(serviceModel);
425     String serviceArtifactLabel = getArtifactLabel(serviceModel);
426     artifact.setName(serviceArtifactName);
427     artifact.setLabel(serviceArtifactLabel);
428     String description = getArtifactDescription(serviceModel);
429     artifact.setDescription(description);
430     return artifact;
431   }
432
433   /**
434    * Create Resource artifact model from the AAI xml model string.
435    *
436    * @param resourceModel    Model of the resource artifact
437    * @param aaiResourceModel AAI model as string
438    * @return Generated {@link Artifact} model for the resource
439    */
440   private Artifact getResourceArtifact(Model resourceModel, String aaiResourceModel) {
441     return getArtifactForModel(resourceModel, aaiResourceModel);
442   }
443
444   /**
445    * Method to generate the artifact name for an AAI model.
446    *
447    * @param model AAI artifact model
448    * @return Model artifact name
449    */
450   private String getArtifactName(Model model) {
451     StringBuilder artifactName = new StringBuilder(ArtifactType.AAI.name());
452     artifactName.append("-");
453
454     String truncatedArtifactName = truncateName(model.getModelName());
455     artifactName.append(truncatedArtifactName);
456
457     artifactName.append("-");
458     artifactName.append(model.getModelType().name().toLowerCase());
459     artifactName.append("-");
460     artifactName.append(model.getModelVersion());
461     artifactName.append(".");
462     artifactName.append(GeneratorConstants.GENERATOR_AAI_GENERATED_ARTIFACT_EXTENSION);
463     return artifactName.toString();
464   }
465
466   private String getArtifactLabel(Model model) {
467     StringBuilder artifactName = new StringBuilder(ArtifactType.AAI.name());
468     artifactName.append("-");
469     artifactName.append(model.getModelType().name().toLowerCase());
470     artifactName.append("-");
471     artifactName.append(hashCodeUuId(model.getModelNameVersionId()));
472     return (artifactName.toString()).replaceAll("[^a-zA-Z0-9 +]+", "-");
473   }
474
475   private int hashCodeUuId(String uuId) {
476     int hashcode = 0;
477     for (int i = 0; i < uuId.length(); i++) {
478       hashcode = 31 * hashcode + uuId.charAt(i);
479     }
480     return hashcode;
481   }
482
483
484   private String truncateName(String name) {
485     String truncatedName = name;
486     if (name.length() >= 200) {
487       truncatedName = name.substring(0, 199);
488     }
489     return truncatedName;
490   }
491
492   private String getArtifactDescription(Model model) {
493     String artifactDesc = model.getModelDescription();
494     if (model.getModelType().equals(ModelType.SERVICE)) {
495       artifactDesc = "AAI Service Model";
496     } else if (model.getModelType().equals(ModelType.RESOURCE)) {
497       artifactDesc = "AAI Resource Model";
498     }
499     return artifactDesc;
500   }
501
502   private void validateVersion(String version, String uuId) {
503     String versionRegex = "^[0-9]\\d*(\\.\\d+)$";
504     if (null == version  || Objects.equals(version, "")) {
505       throw new IllegalArgumentException(String
506           .format(GeneratorConstants.GENERATOR_AAI_ERROR_NULL_RESOURCE_VERSION_IN_SERVICE_TOSCA,
507                uuId));
508     } else if ( version.equals("0.0") || !(version.matches(versionRegex))) {
509       throw new IllegalArgumentException(String
510           .format(GeneratorConstants.GENERATOR_AAI_ERROR_INVALID_RESOURCE_VERSION_IN_SERVICE_TOSCA,
511                uuId));
512     }
513   }
514   /**
515    * Get the tosca java model from the tosca input artifact.
516    *
517    * @param input Input tosca file and its metadata information as {@link Artifact} object
518    * @return Translated {@link ToscaTemplate tosca} object
519    */
520
521   private ToscaTemplate getToscaModel(Artifact input, String serviceVersion)
522       throws SecurityException {
523     byte[] decodedInput = GeneratorUtil.decoder(input.getPayload());
524     String checksum = GeneratorUtil.checkSum(decodedInput);
525     ToscaTemplate tosca;
526     if (checksum.equalsIgnoreCase(input.getChecksum())) {
527       try {
528         log.debug("Input yaml name " + input.getName() + "payload " + new String(decodedInput));
529         tosca = GeneratorUtil.translateTosca(new String(decodedInput), ToscaTemplate.class);
530         tosca.getMetadata().put("version", serviceVersion);
531         return tosca;
532       } catch (Exception exception) {
533         throw new IllegalArgumentException(
534             String.format(GeneratorConstants.GENERATOR_AAI_ERROR_INVALID_TOSCA, input.getName()), exception);
535       }
536     } else {
537       throw new SecurityException(GeneratorConstants.GENERATOR_AAI_ERROR_CHECKSUM_MISMATCH);
538     }
539   }
540
541   private void validateTosca(ToscaTemplate tosca, Artifact input) {
542     log.debug("Validating tosca for Artifact: " + input.getName());
543     if (tosca.getMetadata().containsKey("invariantUUID")) {
544       if (tosca.getMetadata().get("invariantUUID") == null
545           || Objects.equals(tosca.getMetadata().get("invariantUUID"), "")) {
546         throw new IllegalArgumentException(String
547             .format(GeneratorConstants.GENERATOR_AAI_ERROR_MANDATORY_METADATA_DEFINITION,
548                 "invariantUUID",
549                 input.getName()));
550       } else if (tosca.getMetadata().get("invariantUUID").length() != GeneratorConstants.ID_LENGTH) {
551         throw new IllegalArgumentException(String.format(
552             GeneratorConstants.GENERATOR_AAI_ERROR_INVALID_ID, "invariantUUID", input.getName()));
553       }
554     }
555
556     if (tosca.getMetadata().containsKey("UUID")) {
557       if (tosca.getMetadata().get("UUID") == null || Objects.equals(tosca.getMetadata().get("UUID"), "")) {
558         throw new IllegalArgumentException(String
559             .format(GeneratorConstants.GENERATOR_AAI_ERROR_MANDATORY_METADATA_DEFINITION, "UUID",
560                 input.getName()));
561       } else if (tosca.getMetadata().get("UUID").length() != GeneratorConstants.ID_LENGTH) {
562         throw new IllegalArgumentException(String
563             .format(GeneratorConstants.GENERATOR_AAI_ERROR_INVALID_ID, "UUID", input.getName()));
564       }
565
566     }
567     if (tosca.getMetadata().containsKey("name")) {
568       if (tosca.getMetadata().get("name") == null || Objects.equals(tosca.getMetadata().get("name"), "")) {
569         throw new IllegalArgumentException(String
570             .format(GeneratorConstants.GENERATOR_AAI_ERROR_MANDATORY_METADATA_DEFINITION, "name",
571                 input.getName()));
572       }
573     }
574
575     if (tosca.getTopology_template() != null && tosca.getTopology_template().getGroups() != null) {
576       validateVfModule(tosca, input);
577     }
578   }
579
580   private void validateVfModule(ToscaTemplate tosca, Artifact input) {
581
582     Collection<GroupDefinition> groups = tosca.getTopology_template().getGroups().values();
583     for (GroupDefinition gd : groups) {
584       Model group = Model.getModelFor(gd.getType());
585       if (group instanceof VfModule) {
586         if (gd.getMetadata().containsKey("vfModuleModelName")
587             && gd.getMetadata().get("vfModuleModelName") == null) {
588           throw new IllegalArgumentException(String
589               .format(GeneratorConstants.GENERATOR_AAI_ERROR_MANDATORY_METADATA_DEFINITION,
590                   "vfModuleModelName",
591                   input.getName()));
592         }
593         if (gd.getMetadata().containsKey("vfModuleModelInvariantUUID")
594             && gd.getMetadata().get("vfModuleModelInvariantUUID") == null) {
595           throw new IllegalArgumentException(String
596               .format(GeneratorConstants.GENERATOR_AAI_ERROR_MANDATORY_METADATA_DEFINITION,
597                   "vfModuleModelInvariantUUID", input.getName()));
598         } else if (gd.getMetadata().get("vfModuleModelInvariantUUID").length() != GeneratorConstants.ID_LENGTH) {
599           throw new IllegalArgumentException(String.format(
600                GeneratorConstants.GENERATOR_AAI_ERROR_INVALID_ID, "vfModuleModelInvariantUUID",
601                input.getName()));
602         }
603
604         if (gd.getMetadata().containsKey("vfModuleModelUUID")
605             && gd.getMetadata().get("vfModuleModelUUID") == null) {
606           throw new IllegalArgumentException(String
607               .format(GeneratorConstants.GENERATOR_AAI_ERROR_MANDATORY_METADATA_DEFINITION,
608                   "vfModuleModelUUID",
609                   input.getName()));
610         } else if (gd.getMetadata().get("vfModuleModelUUID").length() != GeneratorConstants.ID_LENGTH) {
611           throw new IllegalArgumentException(String.format(
612               GeneratorConstants.GENERATOR_AAI_ERROR_INVALID_ID, "vfModuleModelUUID",
613               input.getName()));
614         }
615         if (gd.getMetadata().containsKey("vfModuleModelVersion")
616             && gd.getMetadata().get("vfModuleModelVersion") == null) {
617           throw new IllegalArgumentException(String
618               .format(GeneratorConstants.GENERATOR_AAI_ERROR_MANDATORY_METADATA_DEFINITION,
619                   "vfModuleModelVersion",
620                   input.getName()));
621         }
622       }
623     }
624   }
625
626   /**
627    * Identify the service tosca artifact from the list of translated tosca inputs.
628    *
629    * @param input List of translated {@link ToscaTemplate tosca} object models
630    * @return Identified service {@link ToscaTemplate tosca}
631    */
632   private ToscaTemplate getServiceTosca(List<ToscaTemplate> input) {
633     Iterator<ToscaTemplate> iter = input.iterator();
634     while (iter.hasNext()) {
635       ToscaTemplate tosca = iter.next();
636       if (tosca.isService()) {
637         iter.remove();
638         return tosca;
639       }
640     }
641     return null;
642   }
643
644   private void initWidgetConfiguration() throws IOException {
645     log.debug("Getting Widget Configuration");
646     String configLocation = System.getProperty("artifactgenerator.config");
647     Properties properties;
648     if (configLocation != null) {
649       File file = new File(configLocation);
650       if (file.exists()) {
651         properties = new Properties();
652         properties.load(new FileInputStream(file));
653         WidgetConfigurationUtil.setConfig(properties);
654       } else {
655         throw new IllegalArgumentException(String.format(
656             GeneratorConstants.GENERATOR_AAI_CONFIGFILE_NOT_FOUND,
657             configLocation));
658       }
659     } else {
660       throw new IllegalArgumentException(GeneratorConstants.GENERATOR_AAI_CONFIGLOCATION_NOT_FOUND);
661     }
662   }
663
664 }