c6def3d249cfb1b7a452cf7a56d95d661af6f5e1
[aai/babel.git] / src / main / java / org / onap / aai / babel / xml / generator / ModelGenerator.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
6  * Copyright © 2017 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  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22  */
23 package org.onap.aai.babel.xml.generator;
24
25 import java.util.HashMap;
26 import java.util.List;
27 import java.util.Map;
28 import java.util.regex.Pattern;
29 import java.util.stream.Collectors;
30 import org.onap.aai.babel.logging.ApplicationMsgs;
31 import org.onap.aai.babel.service.data.BabelArtifact;
32 import org.onap.aai.cl.api.Logger;
33 import org.onap.aai.cl.eelf.LoggerFactory;
34 import org.openecomp.sdc.generator.data.AdditionalParams;
35 import org.openecomp.sdc.generator.data.Artifact;
36 import org.openecomp.sdc.generator.data.GenerationData;
37 import org.openecomp.sdc.generator.data.GeneratorUtil;
38 import org.openecomp.sdc.generator.data.GroupType;
39 import org.openecomp.sdc.generator.service.ArtifactGenerationService;
40
41 /**
42  * This class is responsible for generating xml model artifacts from a collection of csar file artifacts
43  */
44 public class ModelGenerator implements ArtifactGenerator {
45
46     private static Logger logger = LoggerFactory.getInstance().getLogger(ModelGenerator.class);
47
48     private static final String GENERATORCONFIG = "{\"artifactTypes\": [\"AAI\"]}";
49     private static final Pattern UUID_NORMATIVE_NEW_VERSION = Pattern.compile("^\\d{1,}.0");
50     private static final String VERSION_DELIMITER = ".";
51     private static final String VERSION_DELIMITER_REGEXP = "\\" + VERSION_DELIMITER;
52     private static final String DEFAULT_SERVICE_VERSION = "1.0";
53
54     /**
55      * Invokes the TOSCA artifact generator API with the input artifacts.
56      *
57      * @param csarArtifacts the input artifacts
58      * @return {@link List} of output artifacts
59      * @throws XmlArtifactGenerationException if there is an error trying to generate xml artifacts
60      */
61     @Override
62     public List<BabelArtifact> generateArtifacts(List<Artifact> csarArtifacts) throws XmlArtifactGenerationException {
63         logger.info(ApplicationMsgs.DISTRIBUTION_EVENT,
64                 "Generating XML for " + csarArtifacts.size() + " CSAR artifacts.");
65
66         // Get the service version to pass into the generator
67         String toscaVersion = csarArtifacts.get(0).getVersion();
68         logger.debug(
69                 "Getting the service version for Tosca Version of the yml file.  The Tosca Version is " + toscaVersion);
70         String serviceVersion = getServiceVersion(toscaVersion);
71         logger.debug("The service version is " + serviceVersion);
72         Map<String, String> additionalParams = new HashMap<>();
73         additionalParams.put(AdditionalParams.ServiceVersion.getName(), serviceVersion);
74
75         // Call ArtifactGenerator API
76         logger.debug("Obtaining instance of ArtifactGenerationService");
77         ArtifactGenerationService generationService = ArtifactGenerationService.lookup();
78         logger.debug("About to call generationService.generateArtifact()");
79         GenerationData data = generationService.generateArtifact(csarArtifacts, GENERATORCONFIG, additionalParams);
80         logger.debug("Call generationService.generateArtifact() has finished");
81
82         // Convert results into BabelArtifacts
83         if (data.getErrorData().isEmpty()) {
84             return data.getResultData().stream().map(a -> new BabelArtifact(a.getName(), a.getType(), a.getPayload()))
85                     .collect(Collectors.toList());
86         } else {
87             throw new XmlArtifactGenerationException(
88                     "Error occurred during artifact generation: " + data.getErrorData().toString());
89         }
90     }
91
92     /**
93      * Creates an instance of an input artifact for the generator.
94      *
95      * @param payload the payload downloaded from SDC
96      * @param artifactName name of the artifact to create
97      * @param artifactVersion version of the artifact to create
98      * @return an {@link Artifact} object constructed from the payload and artifactInfo
99      */
100     public static Artifact createArtifact(byte[] payload, String artifactName, String artifactVersion) {
101         logger.info(ApplicationMsgs.DISTRIBUTION_EVENT, "Creating artifact for: " + artifactName);
102
103         // Convert payload into an input Artifact
104         String checksum = GeneratorUtil.checkSum(payload);
105         byte[] encodedPayload = GeneratorUtil.encode(payload);
106         Artifact artifact = new Artifact("TOSCA", GroupType.DEPLOYMENT.name(), checksum, encodedPayload);
107         artifact.setName(artifactName);
108         artifact.setLabel(artifactName);
109         artifact.setDescription(artifactName);
110         artifact.setVersion(artifactVersion);
111         return artifact;
112     }
113
114     private static String getServiceVersion(String artifactVersion) {
115         String serviceVersion;
116
117         try {
118             if (UUID_NORMATIVE_NEW_VERSION.matcher(artifactVersion).matches()) {
119                 serviceVersion = artifactVersion;
120             } else {
121                 String[] versionParts = artifactVersion.split(VERSION_DELIMITER_REGEXP);
122                 Integer majorVersion = Integer.parseInt(versionParts[0]);
123
124                 serviceVersion = (majorVersion + 1) + VERSION_DELIMITER + "0";
125             }
126         } catch (Exception e) {
127             logger.warn(ApplicationMsgs.DISTRIBUTION_EVENT,
128                     "Error generating service version from artifact version: " + artifactVersion
129                             + ". Using default service version of: " + DEFAULT_SERVICE_VERSION + ". Error details: "
130                             + e);
131             return DEFAULT_SERVICE_VERSION;
132         }
133
134         return serviceVersion;
135     }
136 }