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