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