added generic fabric support to SO
[so.git] / bpmn / MSOCommonBPMN / src / main / java / org / onap / so / bpmn / common / resource / ResourceRequestBuilder.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
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
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
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=========================================================
19  */
20
21 package org.onap.so.bpmn.common.resource;
22
23 import java.io.File;
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;
29 import java.util.Map;
30 import java.util.Optional;
31
32 import javax.ws.rs.core.Response;
33 import javax.ws.rs.core.UriBuilder;
34
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;
49
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;
55
56 public class ResourceRequestBuilder {
57
58     public static String CUSTOMIZATION_UUID = "customizationUUID";
59
60     public static String SERVICE_URL_TOSCA_CSAR = "/v3/serviceToscaCsar";
61
62     private static MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA, ResourceRequestBuilder.class);
63
64     static JsonUtils jsonUtil = new JsonUtils();
65
66         /**
67      * build the resource Parameters detail.
68      * It's a json string for resource instantiant
69      * {
70      *     "locationConstraints":[...]
71      *     "requestInputs":{K,V}
72      * }
73      * <br>
74      * 
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
81      */
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");
94             }
95         }
96         Map<String, Object> serviceInput = null;
97         if (JsonUtils.getJsonValue(serviceParameters, "requestInputs") != null) {
98             serviceInput = getJsonObject((String)JsonUtils.getJsonValue(serviceParameters, "requestInputs"), Map.class);
99         }
100
101         Map<String, Object> resourceInputsFromUuiMap = getJsonObject(resourceInputsFromUui, Map.class);
102
103         if (serviceInput == null) {
104             serviceInput = new HashMap();
105         }
106
107         if (resourceInputsFromUuiMap == null) {
108             resourceInputsFromUuiMap = new HashMap();
109         }
110
111         try {
112             Map<String, Object> resourceInputsFromServiceDeclaredLevel = buildResouceRequest(serviceUuid, resourceCustomizationUuid, serviceInput);
113             resourceInputsFromUuiMap.putAll(resourceInputsFromServiceDeclaredLevel);
114         } catch(SdcToscaParserException e) {
115                 LOGGER.error("SdcToscaParserException", e);
116         }
117         String resourceInputsStr = getJsonString(resourceInputsFromUuiMap);
118         String result = "{\n"
119                 + "\"locationConstraints\":" + locationConstraints +",\n"
120                 + "\"requestInputs\":" + resourceInputsStr +"\n"
121                 +"}";
122         return result;
123     }
124
125     public static Map<String, Object> buildResouceRequest(String serviceUuid, String resourceCustomizationUuid, Map<String, Object> serviceInputs)
126             throws SdcToscaParserException {
127
128         Map<String, Object> resouceRequest = new HashMap<>();
129
130         String csarpath = null;
131         try {
132             csarpath = getCsarFromUuid(serviceUuid);
133         } catch(Exception e) {
134             LOGGER.debug("csar file is not available for service uuid:" + serviceUuid, e);
135             return resouceRequest;
136         }
137
138         SdcToscaParserFactory toscaParser = SdcToscaParserFactory.getInstance();
139         ISdcCsarHelper iSdcCsarHelper = toscaParser.getSdcCsarHelper(csarpath, false);
140
141         List<Input> serInput = iSdcCsarHelper.getServiceInputs();
142         Optional<NodeTemplate> nodeTemplateOpt = iSdcCsarHelper.getServiceNodeTemplates().stream()
143                 .filter(e -> e.getMetaData().getValue(CUSTOMIZATION_UUID).equals(resourceCustomizationUuid)).findFirst();
144
145         if(nodeTemplateOpt.isPresent()) {
146             NodeTemplate nodeTemplate = nodeTemplateOpt.get();
147             LinkedHashMap<String, Property> resourceProperties = nodeTemplate.getProperties();
148
149             for(String key : resourceProperties.keySet()) {
150                 Property property = resourceProperties.get(key);
151
152                 Object value = getValue(property.getValue(), serviceInputs, serInput);
153                 resouceRequest.put(key, value);
154             }
155         }
156         return resouceRequest;
157     }
158
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<>();
162
163             Map<String, Object> propertyMap = (Map<String, Object>)value;
164
165             for(String key : propertyMap.keySet()) {
166                 valueMap.put(key, getValue(propertyMap.get(key), serviceInputs, servInputs));
167             }
168             return valueMap; // return if the value is nested hashmap
169         } else if(value instanceof GetInput) {
170             String inputName = ((GetInput)value).getInputName();
171
172             if(serviceInputs.get(inputName) != null) {
173                 value = serviceInputs.get(inputName);
174             } else {
175                 for(Input input : servInputs) {
176                     if(input.getName().equals(inputName)) {
177                         return input.getDefault(); // return default value
178                     }
179                 }
180             }
181         }
182         return value; // return property value
183     }
184
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);
188         
189         Response response = client.get();
190         String value = response.readEntity(String.class);
191
192         HashMap<String, String> map = new Gson().fromJson(value, new TypeToken<HashMap<String, String>>() {}.getType());
193
194         File csarFile = new File(System.getProperty("mso.config.path") + "ASDC/" + map.get("name"));
195
196         if(!csarFile.exists()) {
197             throw new Exception("csar file does not exist.");
198         }
199
200         return csarFile.getAbsolutePath();
201     }
202     
203     public static <T> T getJsonObject(String jsonstr, Class<T> type) {
204         ObjectMapper mapper = new ObjectMapper();
205         mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
206         try {
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);
210         }
211         return null;
212     }
213
214     public static String getJsonString(Object srcObj)  {
215         ObjectMapper mapper = new ObjectMapper();
216         mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
217         String jsonStr = null;
218         try {
219             jsonStr = mapper.writeValueAsString(srcObj);
220         } catch(JsonProcessingException e) {
221                 LOGGER.error("SdcToscaParserException", e);
222         }
223         return jsonStr;
224     }
225 }