c6ca460b218ee3d306ecfa43f8e80a15e020456c
[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
30 import org.apache.commons.io.FileUtils;
31 import org.onap.aai.babel.logging.ApplicationMsgs;
32 import org.onap.aai.babel.logging.LogHelper;
33 import org.onap.aai.babel.parser.ArtifactGeneratorToscaParser;
34 import org.onap.aai.babel.xml.generator.data.AdditionalParams;
35 import org.onap.aai.babel.xml.generator.data.Artifact;
36 import org.onap.aai.babel.xml.generator.data.ArtifactType;
37 import org.onap.aai.babel.xml.generator.data.GenerationData;
38 import org.onap.aai.babel.xml.generator.data.GeneratorConstants;
39 import org.onap.aai.babel.xml.generator.data.GeneratorUtil;
40 import org.onap.aai.babel.xml.generator.data.GroupType;
41 import org.onap.aai.babel.xml.generator.model.Model;
42 import org.onap.aai.babel.xml.generator.model.Resource;
43 import org.onap.aai.babel.xml.generator.model.Service;
44 import org.onap.aai.cl.api.Logger;
45 import org.onap.sdc.tosca.parser.api.ISdcCsarHelper;
46 import org.onap.sdc.tosca.parser.impl.SdcToscaParserFactory;
47 import org.onap.sdc.toscaparser.api.NodeTemplate;
48 import org.slf4j.MDC;
49
50 public class AaiArtifactGenerator implements ArtifactGenerator {
51
52     private static final String ARTIFACT_MODEL_INFO = "ARTIFACT_MODEL_INFO";
53
54     private static Logger log = LogHelper.INSTANCE;
55
56     @Override
57     public GenerationData generateArtifact(byte[] csarArchive, List<Artifact> input,
58             Map<String, String> additionalParams) {
59         Path path = null;
60
61         try {
62             ArtifactGeneratorToscaParser.initWidgetConfiguration();
63             String serviceVersion = validateServiceVersion(additionalParams);
64             GenerationData generationData = new GenerationData();
65
66             path = createTempFile(csarArchive);
67             if (path != null) {
68                 ISdcCsarHelper csarHelper =
69                         SdcToscaParserFactory.getInstance().getSdcCsarHelper(path.toAbsolutePath().toString());
70
71                 List<NodeTemplate> serviceNodes =
72                         csarHelper.getServiceNodeTemplates();
73                 Map<String, String> serviceMetaData = csarHelper.getServiceMetadataAllProperties();
74
75                 if (serviceNodes == null) {
76                     throw new IllegalArgumentException(GeneratorConstants.GENERATOR_AAI_ERROR_MISSING_SERVICE_TOSCA);
77                 }
78
79                 // Populate basic service model metadata
80                 Service serviceModel = new Service();
81                 serviceModel.populateModelIdentificationInformation(serviceMetaData);
82                 serviceModel.setModelVersion(serviceVersion);
83
84                 Map<String, String> idTypeStore = new HashMap<>();
85
86                 ArtifactGeneratorToscaParser parser = new ArtifactGeneratorToscaParser(csarHelper);
87                 if (!serviceNodes.isEmpty()) {
88                     parser.processServiceTosca(serviceModel, idTypeStore, serviceNodes);
89                 }
90
91                 // Process the resource TOSCA files
92                 List<Resource> resources = parser.processResourceToscas(serviceNodes, idTypeStore);
93
94                 // Generate AAI XML service model
95                 AaiModelGenerator modelGenerator = AaiModelGenerator.getInstance();
96                 MDC.put(ARTIFACT_MODEL_INFO, serviceModel.getModelName() + "," + getArtifactLabel(serviceModel));
97                 String aaiServiceModel = modelGenerator.generateModelFor(serviceModel);
98                 generationData.add(getServiceArtifact(serviceModel, aaiServiceModel));
99
100                 // Generate AAI XML resource model
101                 for (Resource res : resources) {
102                     MDC.put(ARTIFACT_MODEL_INFO, res.getModelName() + "," + getArtifactLabel(res));
103                     String aaiResourceModel = modelGenerator.generateModelFor(res);
104                     generationData.add(getResourceArtifact(res, aaiResourceModel));
105
106                 }
107             }
108             return generationData;
109         } catch (Exception e) {
110             log.error(ApplicationMsgs.INVALID_CSAR_FILE, e);
111             GenerationData generationData = new GenerationData();
112             generationData.add(ArtifactType.AAI.name(), e.getMessage());
113             return generationData;
114
115         } finally {
116             if (path != null) {
117                 FileUtils.deleteQuietly(path.toFile());
118             }
119         }
120     }
121
122     private Path createTempFile(byte[] bytes) {
123         Path path = null;
124         try {
125             log.debug("Creating temp file on file system for the csar");
126             path = Files.createTempFile("temp", ".csar");
127             Files.write(path, bytes);
128         } catch (IOException e) {
129             log.error(ApplicationMsgs.TEMP_FILE_ERROR, e);
130         }
131         return path;
132     }
133
134     /**
135      * Method to generate the artifact label for AAI model
136      *
137      * @param model
138      * @return the artifact label as String
139      */
140     public String getArtifactLabel(Model model) {
141         StringBuilder artifactName = new StringBuilder(ArtifactType.AAI.name());
142         artifactName.append("-");
143         artifactName.append(model.getModelType().name().toLowerCase());
144         artifactName.append("-");
145         artifactName.append(hashCodeUuId(model.getModelNameVersionId()));
146         return (artifactName.toString()).replaceAll("[^a-zA-Z0-9 +]+", "-");
147     }
148
149     /**
150      * Method to generate the artifact name for an AAI model.
151      *
152      * @param model AAI artifact model
153      * @return Model artifact name
154      */
155     private String getArtifactName(Model model) {
156         StringBuilder artifactName = new StringBuilder(ArtifactType.AAI.name());
157         artifactName.append("-");
158
159         String truncatedArtifactName = truncateName(model.getModelName());
160         artifactName.append(truncatedArtifactName);
161
162         artifactName.append("-");
163         artifactName.append(model.getModelType().name().toLowerCase());
164         artifactName.append("-");
165         artifactName.append(model.getModelVersion());
166
167         artifactName.append(".");
168         artifactName.append(GeneratorConstants.GENERATOR_AAI_GENERATED_ARTIFACT_EXTENSION);
169         return artifactName.toString();
170     }
171
172     /**
173      * Create Resource artifact model from the AAI xml model string.
174      *
175      * @param resourceModel Model of the resource artifact
176      * @param aaiResourceModel AAI model as string
177      * @return Generated {@link Artifact} model for the resource
178      */
179     private Artifact getResourceArtifact(Model resourceModel, String aaiResourceModel) {
180         Artifact artifact = new Artifact(ArtifactType.MODEL_INVENTORY_PROFILE.name(), GroupType.DEPLOYMENT.name(),
181                 GeneratorUtil.checkSum(aaiResourceModel.getBytes()), GeneratorUtil.encode(aaiResourceModel.getBytes()));
182         String resourceArtifactName = getArtifactName(resourceModel);
183         String resourceArtifactLabel = getArtifactLabel(resourceModel);
184         artifact.setName(resourceArtifactName);
185         artifact.setLabel(resourceArtifactLabel);
186         String description = ArtifactGeneratorToscaParser.getArtifactDescription(resourceModel);
187         artifact.setDescription(description);
188         return artifact;
189     }
190
191     /**
192      * Create Service artifact model from the AAI xml model string.
193      *
194      * @param serviceModel Model of the service artifact
195      * @param aaiServiceModel AAI model as string
196      * @return Generated {@link Artifact} model for the service
197      */
198     private Artifact getServiceArtifact(Service serviceModel, String aaiServiceModel) {
199         Artifact artifact = new Artifact(ArtifactType.MODEL_INVENTORY_PROFILE.name(), GroupType.DEPLOYMENT.name(),
200                 GeneratorUtil.checkSum(aaiServiceModel.getBytes()), GeneratorUtil.encode(aaiServiceModel.getBytes()));
201         String serviceArtifactName = getArtifactName(serviceModel);
202         String serviceArtifactLabel = getArtifactLabel(serviceModel);
203         artifact.setName(serviceArtifactName);
204         artifact.setLabel(serviceArtifactLabel);
205         String description = ArtifactGeneratorToscaParser.getArtifactDescription(serviceModel);
206         artifact.setDescription(description);
207         return artifact;
208     }
209
210     private int hashCodeUuId(String uuId) {
211         int hashcode = 0;
212         for (int i = 0; i < uuId.length(); i++) {
213             hashcode = 31 * hashcode + uuId.charAt(i);
214         }
215         return hashcode;
216     }
217
218     private String truncateName(String name) {
219         String truncatedName = name;
220         if (name.length() >= 200) {
221             truncatedName = name.substring(0, 199);
222         }
223         return truncatedName;
224     }
225
226     private String validateServiceVersion(Map<String, String> additionalParams) {
227         String serviceVersion;
228         serviceVersion = additionalParams.get(AdditionalParams.SERVICE_VERSION.getName());
229         if (serviceVersion == null) {
230             throw new IllegalArgumentException(GeneratorConstants.GENERATOR_AAI_ERROR_MISSING_SERVICE_VERSION);
231         } else {
232             String versionRegex = "^[1-9]\\d*(\\.0)$";
233             if (!(serviceVersion.matches(versionRegex))) {
234                 throw new IllegalArgumentException(
235                         String.format(GeneratorConstants.GENERATOR_AAI_INVALID_SERVICE_VERSION));
236             }
237         }
238         return serviceVersion;
239     }
240 }