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