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;
30 import org.apache.commons.io.FileUtils;
31 import org.apache.commons.lang3.StringUtils;
32 import org.onap.aai.babel.logging.ApplicationMsgs;
33 import org.onap.aai.babel.logging.LogHelper;
34 import org.onap.aai.babel.parser.ArtifactGeneratorToscaParser;
35 import org.onap.aai.babel.xml.generator.data.AdditionalParams;
36 import org.onap.aai.babel.xml.generator.data.Artifact;
37 import org.onap.aai.babel.xml.generator.data.ArtifactType;
38 import org.onap.aai.babel.xml.generator.data.GenerationData;
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.ProvidingService;
43 import org.onap.aai.babel.xml.generator.model.Resource;
44 import org.onap.aai.babel.xml.generator.model.Service;
45 import org.onap.aai.cl.api.Logger;
46 import org.onap.sdc.tosca.parser.api.ISdcCsarHelper;
47 import org.onap.sdc.tosca.parser.impl.SdcToscaParserFactory;
48 import org.onap.sdc.toscaparser.api.NodeTemplate;
51 public class AaiArtifactGenerator implements ArtifactGenerator {
53 private static Logger log = LogHelper.INSTANCE;
55 private static final String MDC_PARAM_MODEL_INFO = "ARTIFACT_MODEL_INFO";
56 private static final String GENERATOR_AAI_GENERATED_ARTIFACT_EXTENSION = "xml";
57 private static final String GENERATOR_AAI_ERROR_MISSING_SERVICE_TOSCA =
58 "Service tosca missing from list of input artifacts";
59 private static final String GENERATOR_AAI_ERROR_MISSING_SERVICE_VERSION =
60 "Cannot generate artifacts. Service version is not specified";
61 private static final String GENERATOR_AAI_INVALID_SERVICE_VERSION =
62 "Cannot generate artifacts. Service version is incorrect";
64 private AaiModelGenerator modelGenerator = new AaiModelGeneratorImpl();
67 public GenerationData generateArtifact(byte[] csarArchive, List<Artifact> input,
68 Map<String, String> additionalParams) {
72 csarPath = createTempFile(csarArchive);
73 } catch (IOException e) {
74 log.error(ApplicationMsgs.TEMP_FILE_ERROR, e);
75 return createErrorData(e);
79 ArtifactGeneratorToscaParser.initWidgetConfiguration();
80 ArtifactGeneratorToscaParser.initGroupFilterConfiguration();
81 ISdcCsarHelper csarHelper =
82 SdcToscaParserFactory.getInstance().getSdcCsarHelper(csarPath.toAbsolutePath().toString());
83 return generateService(validateServiceVersion(additionalParams), csarHelper);
84 } catch (Exception e) {
85 log.error(ApplicationMsgs.INVALID_CSAR_FILE, e);
86 return createErrorData(e);
88 FileUtils.deleteQuietly(csarPath.toFile());
92 private GenerationData createErrorData(Exception e) {
93 GenerationData generationData = new GenerationData();
94 generationData.add(ArtifactType.AAI.name(), e.getMessage());
95 return generationData;
99 * Generate model artifacts for the Service and its associated Resources.
101 * @param serviceVersion
102 * @param csarHelper TOSCA parser
103 * @return the generated Artifacts
105 private GenerationData generateService(final String serviceVersion, ISdcCsarHelper csarHelper) {
106 List<NodeTemplate> serviceNodes = csarHelper.getServiceNodeTemplates();
107 if (serviceNodes == null) {
108 throw new IllegalArgumentException(GENERATOR_AAI_ERROR_MISSING_SERVICE_TOSCA);
111 // Populate basic service model metadata
112 Service serviceModel = new Service();
113 serviceModel.setModelVersion(serviceVersion);
114 serviceModel.populateModelIdentificationInformation(csarHelper.getServiceMetadataAllProperties());
116 Map<String, String> idTypeStore = new HashMap<>();
118 ArtifactGeneratorToscaParser parser = new ArtifactGeneratorToscaParser(csarHelper);
119 if (!serviceNodes.isEmpty()) {
120 parser.processServiceTosca(serviceModel, idTypeStore, serviceNodes);
123 // Process the resource TOSCA files
124 List<Resource> resources = parser.processResourceToscas(serviceNodes, idTypeStore);
126 MDC.put(MDC_PARAM_MODEL_INFO, serviceModel.getModelName() + "," + getArtifactLabel(serviceModel));
127 String aaiServiceModel = modelGenerator.generateModelFor(serviceModel);
129 GenerationData generationData = new GenerationData();
130 generationData.add(getServiceArtifact(serviceModel, aaiServiceModel));
132 // Generate AAI XML resource model
133 for (Resource resource : resources) {
134 generateResourceArtifact(generationData, resource);
135 for (Resource childResource : resource.getResources()) {
136 if (!(childResource instanceof ProvidingService)) {
137 generateResourceArtifact(generationData, childResource);
142 return generationData;
146 * @param generationData
149 private void generateResourceArtifact(GenerationData generationData, Resource resource) {
150 if (!isContained(generationData, getArtifactName(resource))) {
151 log.info(ApplicationMsgs.DISTRIBUTION_EVENT, "Generating resource model");
152 Artifact resourceArtifact = getResourceArtifact(resource, modelGenerator.generateModelFor(resource));
153 generationData.add(resourceArtifact);
157 private Path createTempFile(byte[] bytes) throws IOException {
158 log.debug("Creating temp file on file system for the csar");
159 Path path = Files.createTempFile("temp", ".csar");
160 Files.write(path, bytes);
165 * Create the artifact label for an AAI model.
168 * @return the artifact label as String
170 private String getArtifactLabel(Model model) {
171 StringBuilder artifactName = new StringBuilder(ArtifactType.AAI.name());
172 artifactName.append("-");
173 artifactName.append(model.getModelType().name().toLowerCase());
174 artifactName.append("-");
175 artifactName.append(hashCodeUuId(model.getModelNameVersionId()));
176 return (artifactName.toString()).replaceAll("[^a-zA-Z0-9 +]+", "-");
180 * Method to generate the artifact name for an AAI model.
182 * @param model AAI artifact model
183 * @return Model artifact name
185 private String getArtifactName(Model model) {
186 StringBuilder artifactName = new StringBuilder(ArtifactType.AAI.name());
187 artifactName.append("-");
189 String truncatedArtifactName = truncateName(model.getModelName());
190 artifactName.append(truncatedArtifactName);
192 artifactName.append("-");
193 artifactName.append(model.getModelType().name().toLowerCase());
194 artifactName.append("-");
195 artifactName.append(model.getModelVersion());
197 artifactName.append(".");
198 artifactName.append(GENERATOR_AAI_GENERATED_ARTIFACT_EXTENSION);
199 return artifactName.toString();
203 * Create Resource artifact model from the AAI xml model string.
205 * @param resourceModel Model of the resource artifact
206 * @param aaiResourceModel AAI model as string
207 * @return Generated {@link Artifact} model for the resource
209 private Artifact getResourceArtifact(Model resourceModel, String aaiResourceModel) {
210 final String resourceArtifactLabel = getArtifactLabel(resourceModel);
211 MDC.put(MDC_PARAM_MODEL_INFO, resourceModel.getModelName() + "," + resourceArtifactLabel);
212 final byte[] bytes = aaiResourceModel.getBytes();
214 Artifact artifact = new Artifact(ArtifactType.MODEL_INVENTORY_PROFILE.name(), GroupType.DEPLOYMENT.name(),
215 GeneratorUtil.checkSum(bytes), GeneratorUtil.encode(bytes));
216 artifact.setName(getArtifactName(resourceModel));
217 artifact.setLabel(resourceArtifactLabel);
218 artifact.setDescription(ArtifactGeneratorToscaParser.getArtifactDescription(resourceModel));
223 * @param generationData
224 * @param artifactName
227 private boolean isContained(GenerationData generationData, final String artifactName) {
228 return generationData.getResultData().stream()
229 .anyMatch(artifact -> StringUtils.equals(artifact.getName(), artifactName));
233 * Create Service artifact model from the AAI xml model string.
235 * @param serviceModel Model of the service artifact
236 * @param aaiServiceModel AAI model as string
237 * @return Generated {@link Artifact} model for the service
239 private Artifact getServiceArtifact(Service serviceModel, String aaiServiceModel) {
240 Artifact artifact = new Artifact(ArtifactType.MODEL_INVENTORY_PROFILE.name(), GroupType.DEPLOYMENT.name(),
241 GeneratorUtil.checkSum(aaiServiceModel.getBytes()), GeneratorUtil.encode(aaiServiceModel.getBytes()));
242 String serviceArtifactName = getArtifactName(serviceModel);
243 String serviceArtifactLabel = getArtifactLabel(serviceModel);
244 artifact.setName(serviceArtifactName);
245 artifact.setLabel(serviceArtifactLabel);
246 String description = ArtifactGeneratorToscaParser.getArtifactDescription(serviceModel);
247 artifact.setDescription(description);
251 private int hashCodeUuId(String uuId) {
253 for (int i = 0; i < uuId.length(); i++) {
254 hashcode = 31 * hashcode + uuId.charAt(i);
259 private String truncateName(String name) {
260 String truncatedName = name;
261 if (name.length() >= 200) {
262 truncatedName = name.substring(0, 199);
264 return truncatedName;
267 private String validateServiceVersion(Map<String, String> additionalParams) {
268 String serviceVersion = additionalParams.get(AdditionalParams.SERVICE_VERSION.getName());
269 if (serviceVersion == null) {
270 throw new IllegalArgumentException(GENERATOR_AAI_ERROR_MISSING_SERVICE_VERSION);
272 String versionRegex = "^[1-9]\\d*(\\.0)$";
273 if (!(serviceVersion.matches(versionRegex))) {
274 throw new IllegalArgumentException(String.format(GENERATOR_AAI_INVALID_SERVICE_VERSION));
277 return serviceVersion;