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.openecomp.mso.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;
34 import org.camunda.bpm.engine.runtime.Execution;
35 import org.jboss.resteasy.client.jaxrs.ResteasyClient;
36 import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
37 import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
38 import org.onap.sdc.tosca.parser.api.ISdcCsarHelper;
39 import org.onap.sdc.tosca.parser.exceptions.SdcToscaParserException;
40 import org.onap.sdc.tosca.parser.impl.SdcToscaParserFactory;
41 import org.onap.sdc.toscaparser.api.NodeTemplate;
42 import org.onap.sdc.toscaparser.api.Property;
43 import org.onap.sdc.toscaparser.api.functions.GetInput;
44 import org.onap.sdc.toscaparser.api.parameters.Input;
45 import org.openecomp.mso.bpmn.core.PropertyConfiguration;
46 import org.openecomp.mso.bpmn.core.json.JsonUtils;
47 import org.openecomp.mso.logger.MessageEnum;
48 import org.openecomp.mso.logger.MsoLogger;
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?serviceModelUuid=";
62 private static MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA);
65 static JsonUtils jsonUtil = new JsonUtils();
68 * build the resource Parameters detail.
69 * It's a json string for resource instantiant
71 * "locationConstraints":[...]
72 * "requestInputs":{K,V}
76 * @param execution Execution context
77 * @param serviceUuid The service template uuid
78 * @param resourceCustomizationUuid The resource customization uuid
79 * @param serviceParameters the service parameters passed from the API
80 * @return the resource instantiate parameters
81 * @since ONAP Beijing Release
83 @SuppressWarnings("unchecked")
84 public static String buildResourceRequestParameters(Execution execution, String serviceUuid, String resourceCustomizationUuid, String serviceParameters) {
85 List<String> resourceList = jsonUtil.StringArrayToList(execution, (String)JsonUtils.getJsonValue(serviceParameters, "resources"));
86 //Get the right location str for resource. default is an empty array.
87 String locationConstraints ="[]";
88 String resourceInputsFromUui = "";
89 for(String resource: resourceList){
90 String resCusUuid = (String)JsonUtils.getJsonValue(resource, "resourceCustomizationUuid");
91 if(resourceCustomizationUuid.equals(resCusUuid)){
92 String resourceParameters = JsonUtils.getJsonValue(resource, "parameters");
93 locationConstraints = JsonUtils.getJsonValue(resourceParameters, "locationConstraints");
94 resourceInputsFromUui = JsonUtils.getJsonValue(resourceParameters, "requestInputs");
97 Map<String, Object> serviceInput = null;
98 if (JsonUtils.getJsonValue(serviceParameters, "requestInputs") != null) {
99 serviceInput = getJsonObject((String)JsonUtils.getJsonValue(serviceParameters, "requestInputs"), Map.class);
102 Map<String, Object> resourceInputsFromUuiMap = getJsonObject(resourceInputsFromUui, Map.class);
104 if (serviceInput == null) {
105 serviceInput = new HashMap();
108 if (resourceInputsFromUuiMap == null) {
109 resourceInputsFromUuiMap = new HashMap();
113 Map<String, Object> resourceInputsFromServiceDeclaredLevel = buildResouceRequest(serviceUuid, resourceCustomizationUuid, serviceInput);
114 resourceInputsFromUuiMap.putAll(resourceInputsFromServiceDeclaredLevel);
115 } catch(SdcToscaParserException e) {
116 LOGGER.debug("SdcToscaParserException", e);
119 String resourceInputsStr = getJsonString(resourceInputsFromUuiMap);
120 String result = "{\n"
121 + "\"locationConstraints\":" + locationConstraints +",\n"
122 + "\"requestInputs\":" + resourceInputsStr +"\n"
127 public static Map<String, Object> buildResouceRequest(String serviceUuid, String resourceCustomizationUuid, Map<String, Object> serviceInputs)
128 throws SdcToscaParserException {
130 Map<String, Object> resouceRequest = new HashMap<>();
131 String csarpath = null;
133 csarpath = getCsarFromUuid(serviceUuid);
134 } catch(Exception e) {
135 LOGGER.debug("csar file is not available for service uuid:" + serviceUuid, e);
136 return resouceRequest;
139 SdcToscaParserFactory toscaParser = SdcToscaParserFactory.getInstance();
140 ISdcCsarHelper iSdcCsarHelper = toscaParser.getSdcCsarHelper(csarpath, false);
142 List<Input> serInput = iSdcCsarHelper.getServiceInputs();
143 Optional<NodeTemplate> nodeTemplateOpt = iSdcCsarHelper.getServiceNodeTemplates().stream()
144 .filter(e -> e.getMetaData().getValue(CUSTOMIZATION_UUID).equals(resourceCustomizationUuid)).findFirst();
146 if(nodeTemplateOpt.isPresent()) {
147 NodeTemplate nodeTemplate = nodeTemplateOpt.get();
148 LinkedHashMap<String, Property> resourceProperties = nodeTemplate.getProperties();
150 for(String key : resourceProperties.keySet()) {
151 Property property = resourceProperties.get(key);
153 Object value = getValue(property.getValue(), serviceInputs, serInput);
154 resouceRequest.put(key, value);
157 return resouceRequest;
160 private static Object getValue(Object value, Map<String, Object> serviceInputs, List<Input> servInputs) {
161 if(value instanceof Map) {
162 Map<String, Object> valueMap = new HashMap<>();
164 Map<String, Object> propertyMap = (Map<String, Object>)value;
166 for(String key : propertyMap.keySet()) {
167 valueMap.put(key, getValue(propertyMap.get(key), serviceInputs, servInputs));
169 return valueMap; // return if the value is nested hashmap
170 } else if(value instanceof GetInput) {
171 String inputName = ((GetInput)value).getInputName();
173 if(serviceInputs.get(inputName) != null) {
174 value = serviceInputs.get(inputName);
176 for(Input input : servInputs) {
177 if(input.getName().equals(inputName)) {
178 return input.getDefault(); // return default value
183 return value; // return property value
186 private static String getCsarFromUuid(String uuid) throws Exception {
188 ResteasyClient client = new ResteasyClientBuilder().build();
189 Map<String, String> properties = PropertyConfiguration.getInstance().getProperties("mso.bpmn.urn.properties");
190 String catalogEndPoint = properties.get("mso.catalog.db.endpoint");
191 ResteasyWebTarget target = client.target(catalogEndPoint + SERVICE_URL_TOSCA_CSAR + uuid);
192 Response response = target.request().get();
193 String value = response.readEntity(String.class);
195 HashMap<String, String> map = new Gson().fromJson(value, new TypeToken<HashMap<String, String>>() {}.getType());
197 File csarFile = new File(System.getProperty("mso.config.path") + "ASDC/" + map.get("name"));
199 if(!csarFile.exists()) {
200 throw new Exception("csar file does not exist.");
203 return csarFile.getAbsolutePath();
206 public static <T> T getJsonObject(String jsonstr, Class<T> type) {
207 ObjectMapper mapper = new ObjectMapper();
208 mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
210 return mapper.readValue(jsonstr, type);
211 } catch(IOException e) {
212 LOGGER.error(MessageEnum.RA_NS_EXC, "", "", MsoLogger.ErrorCode.BusinessProcesssError, "fail to unMarshal json", e);
217 public static String getJsonString(Object srcObj) {
218 ObjectMapper mapper = new ObjectMapper();
219 mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
220 String jsonStr = null;
222 jsonStr = mapper.writeValueAsString(srcObj);
223 } catch(JsonProcessingException e) {
224 LOGGER.debug("SdcToscaParserException", e);