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.util.ArrayList;
26 import java.util.HashMap;
27 import java.util.LinkedHashMap;
28 import java.util.List;
30 import java.util.Optional;
32 import javax.ws.rs.core.Response;
33 import javax.ws.rs.core.UriBuilder;
35 import org.camunda.bpm.engine.runtime.Execution;
36 import org.onap.sdc.tosca.parser.api.ISdcCsarHelper;
37 import org.onap.sdc.tosca.parser.exceptions.SdcToscaParserException;
38 import org.onap.sdc.tosca.parser.impl.SdcToscaParserFactory;
39 import org.onap.sdc.toscaparser.api.NodeTemplate;
40 import org.onap.sdc.toscaparser.api.Property;
41 import org.onap.sdc.toscaparser.api.functions.GetInput;
42 import org.onap.sdc.toscaparser.api.parameters.Input;
43 import org.onap.so.bpmn.core.UrnPropertiesReader;
44 import org.onap.so.bpmn.core.json.JsonUtils;
45 import org.onap.so.client.HttpClient;
46 import org.onap.so.logger.MessageEnum;
47 import org.onap.so.logger.MsoLogger;
48 import org.onap.so.utils.TargetEntity;
50 import com.fasterxml.jackson.core.JsonProcessingException;
51 import com.fasterxml.jackson.databind.ObjectMapper;
52 import com.fasterxml.jackson.databind.SerializationFeature;
53 import com.google.gson.Gson;
54 import com.google.gson.reflect.TypeToken;
56 public class ResourceRequestBuilder {
58 public static String CUSTOMIZATION_UUID = "customizationUUID";
60 public static String SERVICE_URL_TOSCA_CSAR = "/v3/serviceToscaCsar";
62 private static MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA, ResourceRequestBuilder.class);
64 static JsonUtils jsonUtil = new JsonUtils();
67 * build the resource Parameters detail.
68 * It's a json string for resource instantiant
70 * "locationConstraints":[...]
71 * "requestInputs":{K,V}
75 * @param execution Execution context
76 * @param serviceUuid The service template uuid
77 * @param resourceCustomizationUuid The resource customization uuid
78 * @param serviceParameters the service parameters passed from the API
79 * @return the resource instantiate parameters
80 * @since ONAP Beijing Release
82 @SuppressWarnings("unchecked")
83 public static String buildResourceRequestParameters(Execution execution, String serviceUuid, String resourceCustomizationUuid, String serviceParameters) {
84 List<String> resourceList = jsonUtil.StringArrayToList(execution, (String)JsonUtils.getJsonValue(serviceParameters, "resources"));
85 //Get the right location str for resource. default is an empty array.
86 String locationConstraints ="[]";
87 String resourceInputsFromUui = "";
88 for(String resource: resourceList){
89 String resCusUuid = (String)JsonUtils.getJsonValue(resource, "resourceCustomizationUuid");
90 if(resourceCustomizationUuid.equals(resCusUuid)){
91 String resourceParameters = JsonUtils.getJsonValue(resource, "parameters");
92 locationConstraints = JsonUtils.getJsonValue(resourceParameters, "locationConstraints");
93 resourceInputsFromUui = JsonUtils.getJsonValue(resourceParameters, "requestInputs");
96 Map<String, Object> serviceInput = null;
97 if (JsonUtils.getJsonValue(serviceParameters, "requestInputs") != null) {
98 serviceInput = getJsonObject((String)JsonUtils.getJsonValue(serviceParameters, "requestInputs"), Map.class);
101 Map<String, Object> resourceInputsFromUuiMap = getJsonObject(resourceInputsFromUui, Map.class);
103 if (serviceInput == null) {
104 serviceInput = new HashMap();
107 if (resourceInputsFromUuiMap == null) {
108 resourceInputsFromUuiMap = new HashMap();
112 Map<String, Object> resourceInputsFromServiceDeclaredLevel = buildResouceRequest(serviceUuid, resourceCustomizationUuid, serviceInput);
113 resourceInputsFromUuiMap.putAll(resourceInputsFromServiceDeclaredLevel);
114 } catch(SdcToscaParserException e) {
115 LOGGER.error("SdcToscaParserException", e);
117 String resourceInputsStr = getJsonString(resourceInputsFromUuiMap);
118 String result = "{\n"
119 + "\"locationConstraints\":" + locationConstraints +",\n"
120 + "\"requestInputs\":" + resourceInputsStr +"\n"
125 public static Map<String, Object> buildResouceRequest(String serviceUuid, String resourceCustomizationUuid, Map<String, Object> serviceInputs)
126 throws SdcToscaParserException {
128 Map<String, Object> resouceRequest = new HashMap<>();
130 String csarpath = null;
132 csarpath = getCsarFromUuid(serviceUuid);
133 } catch(Exception e) {
134 LOGGER.debug("csar file is not available for service uuid:" + serviceUuid, e);
135 return resouceRequest;
138 SdcToscaParserFactory toscaParser = SdcToscaParserFactory.getInstance();
139 ISdcCsarHelper iSdcCsarHelper = toscaParser.getSdcCsarHelper(csarpath, false);
141 List<Input> serInput = iSdcCsarHelper.getServiceInputs();
142 Optional<NodeTemplate> nodeTemplateOpt = iSdcCsarHelper.getServiceNodeTemplates().stream()
143 .filter(e -> e.getMetaData().getValue(CUSTOMIZATION_UUID).equals(resourceCustomizationUuid)).findFirst();
145 if(nodeTemplateOpt.isPresent()) {
146 NodeTemplate nodeTemplate = nodeTemplateOpt.get();
147 LinkedHashMap<String, Property> resourceProperties = nodeTemplate.getProperties();
149 for(String key : resourceProperties.keySet()) {
150 Property property = resourceProperties.get(key);
152 Object value = getValue(property.getValue(), serviceInputs, serInput);
153 resouceRequest.put(key, value);
156 return resouceRequest;
159 private static Object getValue(Object value, Map<String, Object> serviceInputs, List<Input> servInputs) {
160 if(value instanceof Map) {
161 Map<String, Object> valueMap = new HashMap<>();
163 Map<String, Object> propertyMap = (Map<String, Object>)value;
165 for(String key : propertyMap.keySet()) {
166 valueMap.put(key, getValue(propertyMap.get(key), serviceInputs, servInputs));
168 return valueMap; // return if the value is nested hashmap
169 } else if(value instanceof GetInput) {
170 String inputName = ((GetInput)value).getInputName();
172 if(serviceInputs.get(inputName) != null) {
173 value = serviceInputs.get(inputName);
175 for(Input input : servInputs) {
176 if(input.getName().equals(inputName)) {
177 return input.getDefault(); // return default value
182 return value; // return property value
185 private static String getCsarFromUuid(String uuid) throws Exception {
186 String catalogEndPoint = UrnPropertiesReader.getVariable("mso.catalog.db.endpoint");
187 HttpClient client = new HttpClient(UriBuilder.fromUri(catalogEndPoint).path(SERVICE_URL_TOSCA_CSAR).queryParam("serviceModelUuid", uuid).build().toURL(), "application/json", TargetEntity.CATALOG_DB);
189 Response response = client.get();
190 String value = response.readEntity(String.class);
192 HashMap<String, String> map = new Gson().fromJson(value, new TypeToken<HashMap<String, String>>() {}.getType());
194 File csarFile = new File(System.getProperty("mso.config.path") + "ASDC/" + map.get("name"));
196 if(!csarFile.exists()) {
197 throw new Exception("csar file does not exist.");
200 return csarFile.getAbsolutePath();
203 public static <T> T getJsonObject(String jsonstr, Class<T> type) {
204 ObjectMapper mapper = new ObjectMapper();
205 mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
207 return mapper.readValue(jsonstr, type);
208 } catch(IOException e) {
209 LOGGER.error(MessageEnum.RA_NS_EXC, "", "", MsoLogger.ErrorCode.BusinessProcesssError, "fail to unMarshal json", e);
214 public static String getJsonString(Object srcObj) {
215 ObjectMapper mapper = new ObjectMapper();
216 mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
217 String jsonStr = null;
219 jsonStr = mapper.writeValueAsString(srcObj);
220 } catch(JsonProcessingException e) {
221 LOGGER.error("SdcToscaParserException", e);