Merge 'origin/casablanca' into master
[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.IOException;
24 import java.lang.reflect.Type;
25 import java.util.ArrayList;
26 import java.util.Arrays;
27 import java.util.HashMap;
28 import java.util.List;
29 import java.util.Map;
30
31 import javax.ws.rs.core.Response;
32 import javax.ws.rs.core.UriBuilder;
33
34 import org.camunda.bpm.engine.runtime.Execution;
35 import org.onap.so.bpmn.core.UrnPropertiesReader;
36 import org.onap.so.bpmn.core.json.JsonUtils;
37 import org.onap.so.client.HttpClient;
38 import org.onap.so.client.HttpClientFactory;
39 import org.onap.so.logger.MsoLogger;
40 import org.onap.so.utils.TargetEntity;
41
42 import com.fasterxml.jackson.core.JsonProcessingException;
43 import com.fasterxml.jackson.databind.ObjectMapper;
44 import com.fasterxml.jackson.databind.SerializationFeature;
45 import com.google.gson.Gson;
46 import com.google.gson.reflect.TypeToken;
47
48 public class ResourceRequestBuilder {
49
50     private static String CUSTOMIZATION_UUID = "cuserviceResourcesstomizationUUID";
51
52     private static String SERVICE_URL_SERVICE_INSTANCE = "/v2/serviceResources";
53
54     private static MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA, ResourceRequestBuilder.class);
55
56     static JsonUtils jsonUtil = new JsonUtils();
57
58         public static List<String> getResourceSequence(String serviceUuid) {
59
60         List<String> resourceSequence = new ArrayList();
61         try {
62             Map<String, Object> serviceResponse = getServiceInstnace(serviceUuid);
63
64             if (serviceResponse.containsKey("serviceResources")) {
65                 Map<String, Object> serviceResources = (Map<String, Object>) serviceResponse.get("serviceResources");
66
67                 if (serviceResources.containsKey("resourceOrder")) {
68                     String resourceOrder = (String) serviceResources.get("resourceOrder");
69                     if (resourceOrder!= null) {
70                         resourceSequence.addAll(Arrays.asList(resourceOrder.split(",")));
71                     }
72                 }
73             }
74         } catch (Exception e) {
75             LOGGER.error("not able to retrieve service order.");
76         }
77         return resourceSequence;
78         }
79
80      /* build the resource Parameters detail.
81      * It's a json string for resource instantiant
82      * {
83      *     "locationConstraints":[...]
84      *     "requestInputs":{K,V}
85      * }
86      * <br>
87      *
88      * @param execution Execution context
89      * @param serviceUuid The service template uuid
90      * @param resourceCustomizationUuid The resource customization uuid
91      * @param serviceParameters the service parameters passed from the API
92      * @return the resource instantiate parameters
93      * @since ONAP Beijing Release
94      */
95     @SuppressWarnings("unchecked")
96     public static String buildResourceRequestParameters(Execution execution, String serviceUuid, String resourceCustomizationUuid, String serviceParameters) {
97         List<String> resourceList = jsonUtil.StringArrayToList(execution, (String)JsonUtils.getJsonValue(serviceParameters, "resources"));
98         //Get the right location str for resource. default is an empty array.
99         String locationConstraints ="[]";
100         String resourceInputsFromUui = "";
101         for(String resource: resourceList){
102             String resCusUuid = (String)JsonUtils.getJsonValue(resource, "resourceCustomizationUuid");
103             if(resourceCustomizationUuid.equals(resCusUuid)){
104                 String resourceParameters = JsonUtils.getJsonValue(resource, "parameters");
105                 locationConstraints = JsonUtils.getJsonValue(resourceParameters, "locationConstraints");
106                 resourceInputsFromUui = JsonUtils.getJsonValue(resourceParameters, "requestInputs");
107             }
108         }
109         Map<String, Object> serviceInput = null;
110         if (JsonUtils.getJsonValue(serviceParameters, "requestInputs") != null) {
111             serviceInput = getJsonObject((String)JsonUtils.getJsonValue(serviceParameters, "requestInputs"), Map.class);
112         }
113
114         Map<String, Object> resourceInputsFromUuiMap = getJsonObject(resourceInputsFromUui, Map.class);
115
116         if (serviceInput == null) {
117             serviceInput = new HashMap();
118         }
119
120         if (resourceInputsFromUuiMap == null) {
121             resourceInputsFromUuiMap = new HashMap();
122         }
123
124         Map<String, Object> resourceInputsFromServiceDeclaredLevel = buildResouceRequest(serviceUuid, resourceCustomizationUuid, serviceInput);
125         resourceInputsFromUuiMap.putAll(resourceInputsFromServiceDeclaredLevel);
126         String resourceInputsStr = getJsonString(resourceInputsFromUuiMap);
127         String result = "{\n"
128                 + "\"locationConstraints\":" + locationConstraints +",\n"
129                 + "\"requestInputs\":" + resourceInputsStr +"\n"
130                 +"}";
131         return result;
132     }
133
134     @SuppressWarnings("unchecked")
135     public static Map<String, Object> buildResouceRequest(String serviceUuid, String resourceCustomizationUuid, Map<String, Object> serviceInputs) {
136         try {
137             Map<String, Object> serviceInstnace = getServiceInstnace(serviceUuid);
138
139             // find match of customization uuid in vnf
140             Map<String, Map<String, Object>> serviceResources = (Map<String, Map<String, Object>>) serviceInstnace.get("serviceResources");
141
142             List<Map<String, Object>> serviceVnfCust = (List<Map<String, Object>>) serviceResources.get("serviceVnfs");
143             String resourceInputStr = getResourceInputStr(serviceVnfCust, resourceCustomizationUuid);
144
145             // find match in network resource
146             if (resourceInputStr == null) {
147                 List<Map<String, Object>> serviceNetworkCust = (List<Map<String, Object>>) serviceResources.get("serviceNetworks");
148                 resourceInputStr = getResourceInputStr(serviceNetworkCust, resourceCustomizationUuid);
149
150                 // find match in AR resource
151                 if (resourceInputStr == null) {
152                     List<Map<String, Object>> serviceArCust = (List<Map<String, Object>>) serviceResources.get("serviceAllottedResources");
153                     resourceInputStr = getResourceInputStr(serviceArCust, resourceCustomizationUuid);
154                 }
155             }
156
157            if (resourceInputStr != null || !resourceInputStr.equals("")) {
158                 return getResourceInput(resourceInputStr, serviceInputs);
159            }
160
161         } catch (Exception e) {
162             LOGGER.error("not able to retrieve service instance");
163         }
164         return new HashMap();
165     }
166
167     private static String getResourceInputStr(List<Map<String, Object>> resources, String resCustomizationUuid) {
168
169         for (Map<String, Object> resource : resources) {
170             Map<String, String> modelInfo = (Map<String, String>) resource.get("modelInfo");
171
172             if (modelInfo.get("modelCustomizationUuid").equalsIgnoreCase(resCustomizationUuid)) {
173                 return (String) resource.get("resourceInput");
174             }
175         }
176         return null;
177     }
178
179     // this method combines resource input with service input
180     private static Map<String, Object> getResourceInput(String resourceInputStr, Map<String, Object> serviceInputs) {
181         Gson gson = new Gson();
182         Type type = new TypeToken<Map<String, String>>(){}.getType();
183         Map<String, Object> resourceInput = gson.fromJson(resourceInputStr, type);
184
185         // replace value if key is available in service input
186         for (String key: resourceInput.keySet()) {
187             String value = (String) resourceInput.get(key);
188
189             if (value.contains("|")) {
190                 // node it type of getinput
191                 String[] split = value.split("\\|");
192                 String tmpKey = split[0];
193                 if (serviceInputs.containsKey(tmpKey)) {
194                     value = (String) serviceInputs.get(tmpKey);
195                 } else {
196                     value = split[1];
197                 }
198             }
199             resourceInput.put(key,value);
200         }
201         return resourceInput;
202     }
203
204     public static Map<String, Object> getServiceInstnace(String uuid) throws Exception {
205         String catalogEndPoint = UrnPropertiesReader.getVariable("mso.catalog.db.endpoint");
206
207         HttpClient client = new HttpClientFactory().newJsonClient(
208                     UriBuilder.fromUri(catalogEndPoint).path(SERVICE_URL_SERVICE_INSTANCE).queryParam("serviceModelUuid", uuid).build().toURL(),
209                 TargetEntity.CATALOG_DB);
210
211         client.addAdditionalHeader("Accept", "application/json");
212         client.addAdditionalHeader("Authorization", UrnPropertiesReader.getVariable("mso.db.auth"));
213
214         Response apiResponse = client.get();
215
216         String value = apiResponse.readEntity(String.class);
217
218         ObjectMapper objectMapper = new ObjectMapper();
219         HashMap<String, Object> map = objectMapper.readValue(value, HashMap.class);
220         return map;
221     }
222
223     public static <T> T getJsonObject(String jsonstr, Class<T> type) {
224         ObjectMapper mapper = new ObjectMapper();
225         mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
226         try {
227             return mapper.readValue(jsonstr, type);
228         } catch(IOException e) {
229             LOGGER.error("fail to unMarshal json" + e.getMessage ());
230         }
231         return null;
232     }
233
234     public static String getJsonString(Object srcObj)  {
235         ObjectMapper mapper = new ObjectMapper();
236         mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
237         String jsonStr = null;
238         try {
239             jsonStr = mapper.writeValueAsString(srcObj);
240         } catch(JsonProcessingException e) {
241                 LOGGER.error("SdcToscaParserException", e);
242         }
243         return jsonStr;
244     }
245 }