2 * ============LICENSE_START=======================================================
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.aai.babel.xml.generator.api;
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;
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;
48 public class AaiArtifactGenerator implements ArtifactGenerator {
50 private static Logger log = LogHelper.INSTANCE;
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";
58 private AaiModelGenerator modelGenerator = new AaiModelGeneratorImpl();
61 public GenerationData generateArtifact(byte[] csarArchive, List<Artifact> input,
62 Map<String, String> additionalParams) {
66 ArtifactGeneratorToscaParser.initWidgetConfiguration();
67 ArtifactGeneratorToscaParser.initGroupFilterConfiguration();
68 String serviceVersion = validateServiceVersion(additionalParams);
69 GenerationData generationData = new GenerationData();
71 path = createTempFile(csarArchive);
73 ISdcCsarHelper csarHelper = SdcToscaParserFactory.getInstance()
74 .getSdcCsarHelper(path.toAbsolutePath().toString());
76 List<NodeTemplate> serviceNodes = csarHelper.getServiceNodeTemplates();
77 Map<String, String> serviceMetaData = csarHelper.getServiceMetadataAllProperties();
79 if (serviceNodes == null) {
80 throw new IllegalArgumentException(GENERATOR_AAI_ERROR_MISSING_SERVICE_TOSCA);
83 // Populate basic service model metadata
84 Service serviceModel = new Service();
85 serviceModel.populateModelIdentificationInformation(serviceMetaData);
86 serviceModel.setModelVersion(serviceVersion);
88 Map<String, String> idTypeStore = new HashMap<>();
90 ArtifactGeneratorToscaParser parser = new ArtifactGeneratorToscaParser(csarHelper);
91 if (!serviceNodes.isEmpty()) {
92 parser.processServiceTosca(serviceModel, idTypeStore, serviceNodes);
95 // Process the resource TOSCA files
96 List<Resource> resources = parser.processResourceToscas(serviceNodes, idTypeStore);
98 MDC.put(MDC_PARAM_MODEL_INFO, serviceModel.getModelName() + "," + getArtifactLabel(serviceModel));
99 String aaiServiceModel = modelGenerator.generateModelFor(serviceModel);
100 generationData.add(getServiceArtifact(serviceModel, aaiServiceModel));
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));
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;
119 FileUtils.deleteQuietly(path.toFile());
124 private Path createTempFile(byte[] bytes) {
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);
137 * Method to generate the artifact label for AAI model
140 * @return the artifact label as String
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 +]+", "-");
152 * Method to generate the artifact name for an AAI model.
156 * @return Model artifact name
158 private String getArtifactName(Model model) {
159 StringBuilder artifactName = new StringBuilder(ArtifactType.AAI.name());
160 artifactName.append("-");
162 String truncatedArtifactName = truncateName(model.getModelName());
163 artifactName.append(truncatedArtifactName);
165 artifactName.append("-");
166 artifactName.append(model.getModelType().name().toLowerCase());
167 artifactName.append("-");
168 artifactName.append(model.getModelVersion());
170 artifactName.append(".");
171 artifactName.append(GENERATOR_AAI_GENERATED_ARTIFACT_EXTENSION);
172 return artifactName.toString();
176 * Create Resource artifact model from the AAI xml model string.
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
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);
197 * Create Service artifact model from the AAI xml model string.
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
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);
217 private int hashCodeUuId(String uuId) {
219 for (int i = 0; i < uuId.length(); i++) {
220 hashcode = 31 * hashcode + uuId.charAt(i);
225 private String truncateName(String name) {
226 String truncatedName = name;
227 if (name.length() >= 200) {
228 truncatedName = name.substring(0, 199);
230 return truncatedName;
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);
239 String versionRegex = "^[1-9]\\d*(\\.0)$";
240 if (!(serviceVersion.matches(versionRegex))) {
241 throw new IllegalArgumentException(String.format(GENERATOR_AAI_INVALID_SERVICE_VERSION));
244 return serviceVersion;