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