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.apache.commons.lang3.StringUtils;
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.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.ProvidingService;
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;
50 public class AaiArtifactGenerator implements ArtifactGenerator {
52 private static Logger log = LogHelper.INSTANCE;
54 private static final String MDC_PARAM_MODEL_INFO = "ARTIFACT_MODEL_INFO";
55 private static final String GENERATOR_AAI_GENERATED_ARTIFACT_EXTENSION = "xml";
56 private static final String GENERATOR_AAI_ERROR_MISSING_SERVICE_TOSCA =
57 "Service tosca missing from list of input artifacts";
58 private static final String GENERATOR_AAI_ERROR_MISSING_SERVICE_VERSION =
59 "Cannot generate artifacts. Service version is not specified";
60 private static final String GENERATOR_AAI_INVALID_SERVICE_VERSION =
61 "Cannot generate artifacts. Service version is incorrect";
63 private AaiModelGenerator modelGenerator = new AaiModelGeneratorImpl();
66 public GenerationData generateArtifact(byte[] csarArchive, List<Artifact> input,
67 Map<String, String> additionalParams) {
71 csarPath = createTempFile(csarArchive);
72 } catch (IOException e) {
73 log.error(ApplicationMsgs.TEMP_FILE_ERROR, e);
74 return createErrorData(e);
78 ArtifactGeneratorToscaParser.initWidgetConfiguration();
79 ArtifactGeneratorToscaParser.initGroupFilterConfiguration();
80 ISdcCsarHelper csarHelper =
81 SdcToscaParserFactory.getInstance().getSdcCsarHelper(csarPath.toAbsolutePath().toString());
82 return generateService(validateServiceVersion(additionalParams), csarHelper);
83 } catch (Exception e) {
84 log.error(ApplicationMsgs.INVALID_CSAR_FILE, e);
85 return createErrorData(e);
87 FileUtils.deleteQuietly(csarPath.toFile());
91 private GenerationData createErrorData(Exception e) {
92 GenerationData generationData = new GenerationData();
93 generationData.add(ArtifactType.AAI.name(), e.getMessage());
94 return generationData;
98 * Generate model artifacts for the Service and its associated Resources.
100 * @param serviceVersion
101 * @param csarHelper TOSCA parser
102 * @return the generated Artifacts
104 private GenerationData generateService(final String serviceVersion, ISdcCsarHelper csarHelper) {
105 List<NodeTemplate> serviceNodes = csarHelper.getServiceNodeTemplates();
106 if (serviceNodes == null) {
107 throw new IllegalArgumentException(GENERATOR_AAI_ERROR_MISSING_SERVICE_TOSCA);
110 // Populate basic service model metadata
111 Service serviceModel = new Service();
112 serviceModel.setModelVersion(serviceVersion);
113 serviceModel.populateModelIdentificationInformation(csarHelper.getServiceMetadataAllProperties());
115 Map<String, String> idTypeStore = new HashMap<>();
117 ArtifactGeneratorToscaParser parser = new ArtifactGeneratorToscaParser(csarHelper);
118 if (!serviceNodes.isEmpty()) {
119 parser.processServiceTosca(serviceModel, idTypeStore, serviceNodes);
122 // Process the resource TOSCA files
123 List<Resource> resources = parser.processResourceToscas(serviceNodes, idTypeStore);
125 MDC.put(MDC_PARAM_MODEL_INFO, serviceModel.getModelName() + "," + getArtifactLabel(serviceModel));
126 String aaiServiceModel = modelGenerator.generateModelFor(serviceModel);
128 GenerationData generationData = new GenerationData();
129 generationData.add(getServiceArtifact(serviceModel, aaiServiceModel));
131 // Generate AAI XML resource model
132 for (Resource resource : resources) {
133 generateResourceArtifact(generationData, resource);
134 for (Resource childResource : resource.getResources()) {
135 if (!(childResource instanceof ProvidingService)) {
136 generateResourceArtifact(generationData, childResource);
141 return generationData;
145 * @param generationData
148 private void generateResourceArtifact(GenerationData generationData, Resource resource) {
149 if (!isContained(generationData, getArtifactName(resource))) {
150 log.info(ApplicationMsgs.DISTRIBUTION_EVENT, "Generating resource model");
151 Artifact resourceArtifact = getResourceArtifact(resource, modelGenerator.generateModelFor(resource));
152 generationData.add(resourceArtifact);
156 private Path createTempFile(byte[] bytes) throws IOException {
157 log.debug("Creating temp file on file system for the csar");
158 Path path = Files.createTempFile("temp", ".csar");
159 Files.write(path, bytes);
164 * Create the artifact label for an AAI model.
167 * @return the artifact label as String
169 private String getArtifactLabel(Model model) {
170 StringBuilder artifactName = new StringBuilder(ArtifactType.AAI.name());
171 artifactName.append("-");
172 artifactName.append(model.getModelType().name().toLowerCase());
173 artifactName.append("-");
174 artifactName.append(hashCodeUuId(model.getModelNameVersionId()));
175 return (artifactName.toString()).replaceAll("[^a-zA-Z0-9 +]+", "-");
179 * Method to generate the artifact name for an AAI model.
181 * @param model AAI artifact model
182 * @return Model artifact name
184 private String getArtifactName(Model model) {
185 StringBuilder artifactName = new StringBuilder(ArtifactType.AAI.name());
186 artifactName.append("-");
188 String truncatedArtifactName = truncateName(model.getModelName());
189 artifactName.append(truncatedArtifactName);
191 artifactName.append("-");
192 artifactName.append(model.getModelType().name().toLowerCase());
193 artifactName.append("-");
194 artifactName.append(model.getModelVersion());
196 artifactName.append(".");
197 artifactName.append(GENERATOR_AAI_GENERATED_ARTIFACT_EXTENSION);
198 return artifactName.toString();
202 * Create Resource artifact model from the AAI xml model string.
204 * @param resourceModel Model of the resource artifact
205 * @param aaiResourceModel AAI model as string
206 * @return Generated {@link Artifact} model for the resource
208 private Artifact getResourceArtifact(Model resourceModel, String aaiResourceModel) {
209 final String resourceArtifactLabel = getArtifactLabel(resourceModel);
210 MDC.put(MDC_PARAM_MODEL_INFO, resourceModel.getModelName() + "," + resourceArtifactLabel);
211 final byte[] bytes = aaiResourceModel.getBytes();
213 Artifact artifact = new Artifact(ArtifactType.MODEL_INVENTORY_PROFILE.name(), GroupType.DEPLOYMENT.name(),
214 GeneratorUtil.checkSum(bytes), GeneratorUtil.encode(bytes));
215 artifact.setName(getArtifactName(resourceModel));
216 artifact.setLabel(resourceArtifactLabel);
217 artifact.setDescription(ArtifactGeneratorToscaParser.getArtifactDescription(resourceModel));
222 * @param generationData
223 * @param artifactName
226 private boolean isContained(GenerationData generationData, final String artifactName) {
227 return generationData.getResultData().stream()
228 .anyMatch(artifact -> StringUtils.equals(artifact.getName(), artifactName));
232 * Create Service artifact model from the AAI xml model string.
234 * @param serviceModel Model of the service artifact
235 * @param aaiServiceModel AAI model as string
236 * @return Generated {@link Artifact} model for the service
238 private Artifact getServiceArtifact(Service serviceModel, String aaiServiceModel) {
239 Artifact artifact = new Artifact(ArtifactType.MODEL_INVENTORY_PROFILE.name(), GroupType.DEPLOYMENT.name(),
240 GeneratorUtil.checkSum(aaiServiceModel.getBytes()), GeneratorUtil.encode(aaiServiceModel.getBytes()));
241 String serviceArtifactName = getArtifactName(serviceModel);
242 String serviceArtifactLabel = getArtifactLabel(serviceModel);
243 artifact.setName(serviceArtifactName);
244 artifact.setLabel(serviceArtifactLabel);
245 String description = ArtifactGeneratorToscaParser.getArtifactDescription(serviceModel);
246 artifact.setDescription(description);
250 private int hashCodeUuId(String uuId) {
252 for (int i = 0; i < uuId.length(); i++) {
253 hashcode = 31 * hashcode + uuId.charAt(i);
258 private String truncateName(String name) {
259 String truncatedName = name;
260 if (name.length() >= 200) {
261 truncatedName = name.substring(0, 199);
263 return truncatedName;
266 private String validateServiceVersion(Map<String, String> additionalParams) {
267 String serviceVersion = additionalParams.get(AdditionalParams.SERVICE_VERSION.getName());
268 if (serviceVersion == null) {
269 throw new IllegalArgumentException(GENERATOR_AAI_ERROR_MISSING_SERVICE_VERSION);
271 String versionRegex = "^[1-9]\\d*(\\.0)$";
272 if (!(serviceVersion.matches(versionRegex))) {
273 throw new IllegalArgumentException(String.format(GENERATOR_AAI_INVALID_SERVICE_VERSION));
276 return serviceVersion;