ca4cfa25920c7da5a06d32747faf0700e1a99a7c
[aai/babel.git] / src / main / java / org / onap / aai / babel / xml / generator / api / AaiArtifactGenerator.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * Copyright © 2017-2018 European Software Marketing Ltd.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *       http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21 package org.onap.aai.babel.xml.generator.api;
22
23 import java.io.IOException;
24 import java.nio.file.Files;
25 import java.nio.file.Path;
26 import java.util.HashMap;
27 import java.util.List;
28 import java.util.Map;
29 import org.apache.commons.io.FileUtils;
30 import org.onap.aai.babel.logging.ApplicationMsgs;
31 import org.onap.aai.babel.logging.LogHelper;
32 import org.onap.aai.babel.parser.ArtifactGeneratorToscaParser;
33 import org.onap.aai.babel.xml.generator.data.AdditionalParams;
34 import org.onap.aai.babel.xml.generator.data.Artifact;
35 import org.onap.aai.babel.xml.generator.data.ArtifactType;
36 import org.onap.aai.babel.xml.generator.data.GenerationData;
37 import org.onap.aai.babel.xml.generator.data.GeneratorUtil;
38 import org.onap.aai.babel.xml.generator.data.GroupType;
39 import org.onap.aai.babel.xml.generator.model.Model;
40 import org.onap.aai.babel.xml.generator.model.Resource;
41 import org.onap.aai.babel.xml.generator.model.Service;
42 import org.onap.aai.cl.api.Logger;
43 import org.onap.sdc.tosca.parser.api.ISdcCsarHelper;
44 import org.onap.sdc.tosca.parser.impl.SdcToscaParserFactory;
45 import org.onap.sdc.toscaparser.api.NodeTemplate;
46 import org.slf4j.MDC;
47
48 public class AaiArtifactGenerator implements ArtifactGenerator {
49
50     private static Logger log = LogHelper.INSTANCE;
51
52     private static final String MDC_PARAM_MODEL_INFO = "ARTIFACT_MODEL_INFO";
53     private static final String GENERATOR_AAI_GENERATED_ARTIFACT_EXTENSION = "xml";
54     private static final String GENERATOR_AAI_ERROR_MISSING_SERVICE_TOSCA = "Service tosca missing from list of input artifacts";
55     private static final String GENERATOR_AAI_ERROR_MISSING_SERVICE_VERSION = "Cannot generate artifacts. Service version is not specified";
56     private static final String GENERATOR_AAI_INVALID_SERVICE_VERSION = "Cannot generate artifacts. Service version is incorrect";
57
58     private AaiModelGenerator modelGenerator = new AaiModelGeneratorImpl();
59
60     @Override
61     public GenerationData generateArtifact(byte[] csarArchive, List<Artifact> input,
62             Map<String, String> additionalParams) {
63         Path path = null;
64
65         try {
66             ArtifactGeneratorToscaParser.initWidgetConfiguration();
67             ArtifactGeneratorToscaParser.initGroupFilterConfiguration();
68             String serviceVersion = validateServiceVersion(additionalParams);
69             GenerationData generationData = new GenerationData();
70
71             path = createTempFile(csarArchive);
72             if (path != null) {
73                 ISdcCsarHelper csarHelper = SdcToscaParserFactory.getInstance()
74                         .getSdcCsarHelper(path.toAbsolutePath().toString());
75
76                 List<NodeTemplate> serviceNodes = csarHelper.getServiceNodeTemplates();
77                 Map<String, String> serviceMetaData = csarHelper.getServiceMetadataAllProperties();
78
79                 if (serviceNodes == null) {
80                     throw new IllegalArgumentException(GENERATOR_AAI_ERROR_MISSING_SERVICE_TOSCA);
81                 }
82
83                 // Populate basic service model metadata
84                 Service serviceModel = new Service();
85                 serviceModel.populateModelIdentificationInformation(serviceMetaData);
86                 serviceModel.setModelVersion(serviceVersion);
87
88                 Map<String, String> idTypeStore = new HashMap<>();
89
90                 ArtifactGeneratorToscaParser parser = new ArtifactGeneratorToscaParser(csarHelper);
91                 if (!serviceNodes.isEmpty()) {
92                     parser.processServiceTosca(serviceModel, idTypeStore, serviceNodes);
93                 }
94
95                 // Process the resource TOSCA files
96                 List<Resource> resources = parser.processResourceToscas(serviceNodes, idTypeStore);
97
98                 MDC.put(MDC_PARAM_MODEL_INFO, serviceModel.getModelName() + "," + getArtifactLabel(serviceModel));
99                 String aaiServiceModel = modelGenerator.generateModelFor(serviceModel);
100                 generationData.add(getServiceArtifact(serviceModel, aaiServiceModel));
101
102                 // Generate AAI XML resource model
103                 for (Resource res : resources) {
104                     log.info(ApplicationMsgs.DISTRIBUTION_EVENT, "Generating resource model");
105                     MDC.put(MDC_PARAM_MODEL_INFO, res.getModelName() + "," + getArtifactLabel(res));
106                     String aaiResourceModel = modelGenerator.generateModelFor(res);
107                     generationData.add(getResourceArtifact(res, aaiResourceModel));
108                 }
109             }
110             return generationData;
111         } catch (Exception e) {
112             log.error(ApplicationMsgs.INVALID_CSAR_FILE, e);
113             GenerationData generationData = new GenerationData();
114             generationData.add(ArtifactType.AAI.name(), e.getMessage());
115             return generationData;
116
117         } finally {
118             if (path != null) {
119                 FileUtils.deleteQuietly(path.toFile());
120             }
121         }
122     }
123
124     private Path createTempFile(byte[] bytes) {
125         Path path = null;
126         try {
127             log.debug("Creating temp file on file system for the csar");
128             path = Files.createTempFile("temp", ".csar");
129             Files.write(path, bytes);
130         } catch (IOException e) {
131             log.error(ApplicationMsgs.TEMP_FILE_ERROR, e);
132         }
133         return path;
134     }
135
136     /**
137      * Method to generate the artifact label for AAI model
138      *
139      * @param model
140      * @return the artifact label as String
141      */
142     public String getArtifactLabel(Model model) {
143         StringBuilder artifactName = new StringBuilder(ArtifactType.AAI.name());
144         artifactName.append("-");
145         artifactName.append(model.getModelType().name().toLowerCase());
146         artifactName.append("-");
147         artifactName.append(hashCodeUuId(model.getModelNameVersionId()));
148         return (artifactName.toString()).replaceAll("[^a-zA-Z0-9 +]+", "-");
149     }
150
151     /**
152      * Method to generate the artifact name for an AAI model.
153      *
154      * @param model
155      *            AAI artifact model
156      * @return Model artifact name
157      */
158     private String getArtifactName(Model model) {
159         StringBuilder artifactName = new StringBuilder(ArtifactType.AAI.name());
160         artifactName.append("-");
161
162         String truncatedArtifactName = truncateName(model.getModelName());
163         artifactName.append(truncatedArtifactName);
164
165         artifactName.append("-");
166         artifactName.append(model.getModelType().name().toLowerCase());
167         artifactName.append("-");
168         artifactName.append(model.getModelVersion());
169
170         artifactName.append(".");
171         artifactName.append(GENERATOR_AAI_GENERATED_ARTIFACT_EXTENSION);
172         return artifactName.toString();
173     }
174
175     /**
176      * Create Resource artifact model from the AAI xml model string.
177      *
178      * @param resourceModel
179      *            Model of the resource artifact
180      * @param aaiResourceModel
181      *            AAI model as string
182      * @return Generated {@link Artifact} model for the resource
183      */
184     private Artifact getResourceArtifact(Model resourceModel, String aaiResourceModel) {
185         Artifact artifact = new Artifact(ArtifactType.MODEL_INVENTORY_PROFILE.name(), GroupType.DEPLOYMENT.name(),
186                 GeneratorUtil.checkSum(aaiResourceModel.getBytes()), GeneratorUtil.encode(aaiResourceModel.getBytes()));
187         String resourceArtifactName = getArtifactName(resourceModel);
188         String resourceArtifactLabel = getArtifactLabel(resourceModel);
189         artifact.setName(resourceArtifactName);
190         artifact.setLabel(resourceArtifactLabel);
191         String description = ArtifactGeneratorToscaParser.getArtifactDescription(resourceModel);
192         artifact.setDescription(description);
193         return artifact;
194     }
195
196     /**
197      * Create Service artifact model from the AAI xml model string.
198      *
199      * @param serviceModel
200      *            Model of the service artifact
201      * @param aaiServiceModel
202      *            AAI model as string
203      * @return Generated {@link Artifact} model for the service
204      */
205     private Artifact getServiceArtifact(Service serviceModel, String aaiServiceModel) {
206         Artifact artifact = new Artifact(ArtifactType.MODEL_INVENTORY_PROFILE.name(), GroupType.DEPLOYMENT.name(),
207                 GeneratorUtil.checkSum(aaiServiceModel.getBytes()), GeneratorUtil.encode(aaiServiceModel.getBytes()));
208         String serviceArtifactName = getArtifactName(serviceModel);
209         String serviceArtifactLabel = getArtifactLabel(serviceModel);
210         artifact.setName(serviceArtifactName);
211         artifact.setLabel(serviceArtifactLabel);
212         String description = ArtifactGeneratorToscaParser.getArtifactDescription(serviceModel);
213         artifact.setDescription(description);
214         return artifact;
215     }
216
217     private int hashCodeUuId(String uuId) {
218         int hashcode = 0;
219         for (int i = 0; i < uuId.length(); i++) {
220             hashcode = 31 * hashcode + uuId.charAt(i);
221         }
222         return hashcode;
223     }
224
225     private String truncateName(String name) {
226         String truncatedName = name;
227         if (name.length() >= 200) {
228             truncatedName = name.substring(0, 199);
229         }
230         return truncatedName;
231     }
232
233     private String validateServiceVersion(Map<String, String> additionalParams) {
234         String serviceVersion;
235         serviceVersion = additionalParams.get(AdditionalParams.SERVICE_VERSION.getName());
236         if (serviceVersion == null) {
237             throw new IllegalArgumentException(GENERATOR_AAI_ERROR_MISSING_SERVICE_VERSION);
238         } else {
239             String versionRegex = "^[1-9]\\d*(\\.0)$";
240             if (!(serviceVersion.matches(versionRegex))) {
241                 throw new IllegalArgumentException(String.format(GENERATOR_AAI_INVALID_SERVICE_VERSION));
242             }
243         }
244         return serviceVersion;
245     }
246 }