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