2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2018 Huawei Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.onap.so.bpmn.common.resource;
24 import java.io.IOException;
25 import java.nio.file.Paths;
26 import java.util.ArrayList;
27 import java.util.HashMap;
28 import java.util.LinkedHashMap;
29 import java.util.List;
31 import java.util.Optional;
33 import javax.ws.rs.core.Response;
34 import javax.ws.rs.core.UriBuilder;
36 import org.camunda.bpm.engine.runtime.Execution;
37 import org.onap.sdc.tosca.parser.api.ISdcCsarHelper;
38 import org.onap.sdc.tosca.parser.exceptions.SdcToscaParserException;
39 import org.onap.sdc.tosca.parser.impl.SdcToscaParserFactory;
40 import org.onap.sdc.toscaparser.api.NodeTemplate;
41 import org.onap.sdc.toscaparser.api.Property;
42 import org.onap.sdc.toscaparser.api.RequirementAssignment;
43 import org.onap.sdc.toscaparser.api.RequirementAssignments;
44 import org.onap.sdc.toscaparser.api.functions.GetInput;
45 import org.onap.sdc.toscaparser.api.parameters.Input;
46 import org.onap.so.bpmn.core.UrnPropertiesReader;
47 import org.onap.so.bpmn.core.json.JsonUtils;
48 import org.onap.so.client.HttpClient;
49 import org.onap.so.logger.MessageEnum;
50 import org.onap.so.logger.MsoLogger;
51 import org.onap.so.utils.TargetEntity;
53 import com.fasterxml.jackson.core.JsonProcessingException;
54 import com.fasterxml.jackson.databind.ObjectMapper;
55 import com.fasterxml.jackson.databind.SerializationFeature;
56 import com.google.gson.Gson;
57 import com.google.gson.reflect.TypeToken;
59 public class ResourceRequestBuilder {
61 private static String CUSTOMIZATION_UUID = "customizationUUID";
63 private static String SERVICE_URL_TOSCA_CSAR = "/v3/serviceToscaCsar";
65 private static MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA, ResourceRequestBuilder.class);
67 static JsonUtils jsonUtil = new JsonUtils();
69 public static List<String> getResourceSequence(Execution execution, String serviceUuid) {
70 List<String> resouceSequence = new ArrayList<String>();
71 List<NodeTemplate> resultList = new ArrayList<NodeTemplate>();
72 String csarpath = null;
74 csarpath = getCsarFromUuid(serviceUuid);
76 SdcToscaParserFactory toscaParser = SdcToscaParserFactory.getInstance();
77 ISdcCsarHelper iSdcCsarHelper = toscaParser.getSdcCsarHelper(csarpath, false);
78 List<NodeTemplate> nodeTemplates = iSdcCsarHelper.getServiceNodeTemplates();
79 List<NodeTemplate> nodes = new ArrayList<NodeTemplate>();
80 nodes.addAll(nodeTemplates);
82 for (NodeTemplate nodeTemplate : nodeTemplates) {
83 RequirementAssignments requirement = iSdcCsarHelper.getRequirementsOf(nodeTemplate);
85 if (requirement == null || requirement.getAll() == null || requirement.getAll().isEmpty()) {
86 resultList.add(nodeTemplate);
87 nodes.remove(nodeTemplate);
91 resultList = getRequirementList(resultList, nodes, iSdcCsarHelper);
93 for (NodeTemplate node : resultList) {
94 String templateName = node.getMetaData().getValue("name");
95 if (!resouceSequence.contains(templateName)) {
96 resouceSequence.add(templateName);
100 } catch (SdcToscaParserException toscarParserE) {
101 LOGGER.debug("sdc tosca parser failed for csar: " + csarpath, toscarParserE);
102 return resouceSequence;
103 } catch (Exception e) {
104 LOGGER.debug("csar file is not available for service uuid:" + serviceUuid, e);
105 return resouceSequence;
108 return resouceSequence;
111 private static List<NodeTemplate> getRequirementList(List<NodeTemplate> resultList, List<NodeTemplate> nodeTemplates,
112 ISdcCsarHelper iSdcCsarHelper) {
114 List<NodeTemplate> nodes = new ArrayList<NodeTemplate>();
115 nodes.addAll(nodeTemplates);
117 for (NodeTemplate nodeTemplate : nodeTemplates) {
118 RequirementAssignments requirement = iSdcCsarHelper.getRequirementsOf(nodeTemplate);
119 List<RequirementAssignment> reqAs = requirement.getAll();
120 for (RequirementAssignment ra : reqAs) {
121 String reqNode = ra.getNodeTemplateName();
122 for (NodeTemplate rNode : resultList) {
123 if (rNode.getName().equals(reqNode)) {
124 if(!resultList.contains(nodeTemplate)) {
125 resultList.add(nodeTemplate);
127 if(nodes.contains(nodeTemplate)) {
128 nodes.remove(nodeTemplate);
136 if (!nodes.isEmpty()) {
137 getRequirementList(resultList, nodes, iSdcCsarHelper);
143 /* build the resource Parameters detail.
144 * It's a json string for resource instantiant
146 * "locationConstraints":[...]
147 * "requestInputs":{K,V}
151 * @param execution Execution context
152 * @param serviceUuid The service template uuid
153 * @param resourceCustomizationUuid The resource customization uuid
154 * @param serviceParameters the service parameters passed from the API
155 * @return the resource instantiate parameters
156 * @since ONAP Beijing Release
158 @SuppressWarnings("unchecked")
159 public static String buildResourceRequestParameters(Execution execution, String serviceUuid, String resourceCustomizationUuid, String serviceParameters) {
160 List<String> resourceList = jsonUtil.StringArrayToList(execution, (String)JsonUtils.getJsonValue(serviceParameters, "resources"));
161 //Get the right location str for resource. default is an empty array.
162 String locationConstraints ="[]";
163 String resourceInputsFromUui = "";
164 for(String resource: resourceList){
165 String resCusUuid = (String)JsonUtils.getJsonValue(resource, "resourceCustomizationUuid");
166 if(resourceCustomizationUuid.equals(resCusUuid)){
167 String resourceParameters = JsonUtils.getJsonValue(resource, "parameters");
168 locationConstraints = JsonUtils.getJsonValue(resourceParameters, "locationConstraints");
169 resourceInputsFromUui = JsonUtils.getJsonValue(resourceParameters, "requestInputs");
172 Map<String, Object> serviceInput = null;
173 if (JsonUtils.getJsonValue(serviceParameters, "requestInputs") != null) {
174 serviceInput = getJsonObject((String)JsonUtils.getJsonValue(serviceParameters, "requestInputs"), Map.class);
177 Map<String, Object> resourceInputsFromUuiMap = getJsonObject(resourceInputsFromUui, Map.class);
179 if (serviceInput == null) {
180 serviceInput = new HashMap();
183 if (resourceInputsFromUuiMap == null) {
184 resourceInputsFromUuiMap = new HashMap();
188 Map<String, Object> resourceInputsFromServiceDeclaredLevel = buildResouceRequest(serviceUuid, resourceCustomizationUuid, serviceInput);
189 resourceInputsFromUuiMap.putAll(resourceInputsFromServiceDeclaredLevel);
190 } catch(SdcToscaParserException e) {
191 LOGGER.error("SdcToscaParserException", e);
193 String resourceInputsStr = getJsonString(resourceInputsFromUuiMap);
194 String result = "{\n"
195 + "\"locationConstraints\":" + locationConstraints +",\n"
196 + "\"requestInputs\":" + resourceInputsStr +"\n"
201 public static Map<String, Object> buildResouceRequest(String serviceUuid, String resourceCustomizationUuid, Map<String, Object> serviceInputs)
202 throws SdcToscaParserException {
204 Map<String, Object> resouceRequest = new HashMap<>();
206 String csarpath = null;
208 csarpath = getCsarFromUuid(serviceUuid);
209 } catch(Exception e) {
210 LOGGER.debug("csar file is not available for service uuid:" + serviceUuid, e);
211 return resouceRequest;
214 SdcToscaParserFactory toscaParser = SdcToscaParserFactory.getInstance();
215 ISdcCsarHelper iSdcCsarHelper = toscaParser.getSdcCsarHelper(csarpath, false);
217 List<Input> serInput = iSdcCsarHelper.getServiceInputs();
218 Optional<NodeTemplate> nodeTemplateOpt = iSdcCsarHelper.getServiceNodeTemplates().stream()
219 .filter(e -> e.getMetaData().getValue(CUSTOMIZATION_UUID).equals(resourceCustomizationUuid)).findFirst();
221 if(nodeTemplateOpt.isPresent()) {
222 NodeTemplate nodeTemplate = nodeTemplateOpt.get();
223 LinkedHashMap<String, Property> resourceProperties = nodeTemplate.getProperties();
225 for(String key : resourceProperties.keySet()) {
226 Property property = resourceProperties.get(key);
228 Object value = getValue(property.getValue(), serviceInputs, serInput);
229 resouceRequest.put(key, value);
232 return resouceRequest;
235 private static Object getValue(Object value, Map<String, Object> serviceInputs, List<Input> servInputs) {
236 if(value instanceof Map) {
237 Map<String, Object> valueMap = new HashMap<>();
239 Map<String, Object> propertyMap = (Map<String, Object>)value;
241 for(String key : propertyMap.keySet()) {
242 valueMap.put(key, getValue(propertyMap.get(key), serviceInputs, servInputs));
244 return valueMap; // return if the value is nested hashmap
245 } else if(value instanceof GetInput) {
246 String inputName = ((GetInput)value).getInputName();
248 if(serviceInputs.get(inputName) != null) {
249 value = serviceInputs.get(inputName);
251 for(Input input : servInputs) {
252 if(input.getName().equals(inputName)) {
253 return input.getDefault(); // return default value
258 return value; // return property value
261 private static String getCsarFromUuid(String uuid) throws Exception {
262 String catalogEndPoint = UrnPropertiesReader.getVariable("mso.catalog.db.endpoint");
263 HttpClient client = new HttpClient(UriBuilder.fromUri(catalogEndPoint).path(SERVICE_URL_TOSCA_CSAR).queryParam("serviceModelUuid", uuid).build().toURL(), "application/json", TargetEntity.CATALOG_DB);
265 client.addAdditionalHeader("Accept", "application/json");
266 // client.addBasicAuthHeader (UrnPropertiesReader.getVariable("mso.adapters.db.auth"), UrnPropertiesReader.getVariable("mso.msoKey"));
267 client.addAdditionalHeader("Authorization", UrnPropertiesReader.getVariable("mso.db.auth"));
268 Response response = client.get();
269 String value = response.readEntity(String.class);
271 HashMap<String, String> map = new Gson().fromJson(value, new TypeToken<HashMap<String, String>>() {}.getType());
273 String filePath = Paths.get(System.getProperty("mso.config.path"), "ASDC", map.get("version"), map.get("name")).normalize().toString();
275 File csarFile = new File(filePath);
277 if(!csarFile.exists()) {
278 throw new Exception("csar file does not exist in filePath:" + csarFile.getAbsolutePath());
281 return csarFile.getAbsolutePath();
284 public static <T> T getJsonObject(String jsonstr, Class<T> type) {
285 ObjectMapper mapper = new ObjectMapper();
286 mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
288 return mapper.readValue(jsonstr, type);
289 } catch(IOException e) {
290 LOGGER.error("fail to unMarshal json" + e.getMessage ());
295 public static String getJsonString(Object srcObj) {
296 ObjectMapper mapper = new ObjectMapper();
297 mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
298 String jsonStr = null;
300 jsonStr = mapper.writeValueAsString(srcObj);
301 } catch(JsonProcessingException e) {
302 LOGGER.error("SdcToscaParserException", e);