Replaced all tabs with spaces in java and pom.xml
[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  * Modifications Copyright (c) 2019 Samsung
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  * 
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  * 
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.so.bpmn.common.resource;
24
25 import java.io.IOException;
26 import java.lang.reflect.Type;
27 import java.util.ArrayList;
28 import java.util.Arrays;
29 import java.util.HashMap;
30 import java.util.List;
31 import java.util.Map;
32 import javax.ws.rs.core.Response;
33 import javax.ws.rs.core.UriBuilder;
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.utils.TargetEntity;
40 import com.fasterxml.jackson.core.JsonProcessingException;
41 import com.fasterxml.jackson.databind.ObjectMapper;
42 import com.fasterxml.jackson.databind.SerializationFeature;
43 import com.google.gson.Gson;
44 import com.google.gson.reflect.TypeToken;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
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 Logger logger = LoggerFactory.getLogger(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     /*
81      * build the resource Parameters detail. It's a json string for resource instantiant { "locationConstraints":[...]
82      * "requestInputs":{K,V} } <br>
83      *
84      * @param execution Execution context
85      * 
86      * @param serviceUuid The service template uuid
87      * 
88      * @param resourceCustomizationUuid The resource customization uuid
89      * 
90      * @param serviceParameters the service parameters passed from the API
91      * 
92      * @return the resource instantiate parameters
93      * 
94      * @since ONAP Beijing Release
95      */
96     @SuppressWarnings("unchecked")
97     public static String buildResourceRequestParameters(Execution execution, String serviceUuid,
98             String resourceCustomizationUuid, String serviceParameters) {
99         List<String> resourceList =
100                 jsonUtil.StringArrayToList(execution, (String) JsonUtils.getJsonValue(serviceParameters, "resources"));
101         // Get the right location str for resource. default is an empty array.
102         String locationConstraints = "[]";
103         String resourceInputsFromUui = "";
104         for (String resource : resourceList) {
105             String resCusUuid = (String) JsonUtils.getJsonValue(resource, "resourceCustomizationUuid");
106             if (resourceCustomizationUuid.equals(resCusUuid)) {
107                 String resourceParameters = JsonUtils.getJsonValue(resource, "parameters");
108                 locationConstraints = JsonUtils.getJsonValue(resourceParameters, "locationConstraints");
109                 resourceInputsFromUui = JsonUtils.getJsonValue(resourceParameters, "requestInputs");
110             }
111         }
112         Map<String, Object> serviceInput = null;
113         if (JsonUtils.getJsonValue(serviceParameters, "requestInputs") != null) {
114             serviceInput =
115                     getJsonObject((String) JsonUtils.getJsonValue(serviceParameters, "requestInputs"), Map.class);
116         }
117
118         Map<String, Object> resourceInputsFromUuiMap = getJsonObject(resourceInputsFromUui, Map.class);
119
120         if (serviceInput == null) {
121             serviceInput = new HashMap();
122         }
123
124         if (resourceInputsFromUuiMap == null) {
125             resourceInputsFromUuiMap = new HashMap();
126         }
127
128         Map<String, Object> resourceInputsFromServiceDeclaredLevel =
129                 buildResouceRequest(serviceUuid, resourceCustomizationUuid, serviceInput);
130         resourceInputsFromUuiMap.putAll(resourceInputsFromServiceDeclaredLevel);
131         String resourceInputsStr = getJsonString(resourceInputsFromUuiMap);
132         String result = "{\n" + "\"locationConstraints\":" + locationConstraints + ",\n" + "\"requestInputs\":"
133                 + resourceInputsStr + "\n" + "}";
134         return result;
135     }
136
137     @SuppressWarnings("unchecked")
138     public static Map<String, Object> buildResouceRequest(String serviceUuid, String resourceCustomizationUuid,
139             Map<String, Object> serviceInputs) {
140         try {
141             Map<String, Object> serviceInstnace = getServiceInstnace(serviceUuid);
142
143             // find match of customization uuid in vnf
144             Map<String, Map<String, Object>> serviceResources =
145                     (Map<String, Map<String, Object>>) serviceInstnace.get("serviceResources");
146
147             List<Map<String, Object>> serviceVnfCust = (List<Map<String, Object>>) serviceResources.get("serviceVnfs");
148             String resourceInputStr = getResourceInputStr(serviceVnfCust, resourceCustomizationUuid);
149
150             // find match in network resource
151             if (resourceInputStr == null) {
152                 List<Map<String, Object>> serviceNetworkCust =
153                         (List<Map<String, Object>>) serviceResources.get("serviceNetworks");
154                 resourceInputStr = getResourceInputStr(serviceNetworkCust, resourceCustomizationUuid);
155
156                 // find match in AR resource
157                 if (resourceInputStr == null) {
158                     List<Map<String, Object>> serviceArCust =
159                             (List<Map<String, Object>>) serviceResources.get("serviceAllottedResources");
160                     resourceInputStr = getResourceInputStr(serviceArCust, resourceCustomizationUuid);
161                 }
162             }
163
164             if (resourceInputStr != null && !resourceInputStr.isEmpty()) {
165                 return getResourceInput(resourceInputStr, serviceInputs);
166             }
167
168         } catch (Exception e) {
169             logger.error("not able to retrieve service instance");
170         }
171         return new HashMap();
172     }
173
174     private static String getResourceInputStr(List<Map<String, Object>> resources, String resCustomizationUuid) {
175
176         for (Map<String, Object> resource : resources) {
177             Map<String, String> modelInfo = (Map<String, String>) resource.get("modelInfo");
178
179             if (modelInfo.get("modelCustomizationUuid").equalsIgnoreCase(resCustomizationUuid)) {
180                 return (String) resource.get("resourceInput");
181             }
182         }
183         return null;
184     }
185
186     // this method combines resource input with service input
187     private static Map<String, Object> getResourceInput(String resourceInputStr, Map<String, Object> serviceInputs) {
188         Gson gson = new Gson();
189         Type type = new TypeToken<Map<String, String>>() {}.getType();
190         Map<String, Object> resourceInput = gson.fromJson(resourceInputStr, type);
191
192         // replace value if key is available in service input
193         for (String key : resourceInput.keySet()) {
194             String value = (String) resourceInput.get(key);
195
196             if (value.contains("|")) {
197                 // node it type of getinput
198                 String[] split = value.split("\\|");
199                 String tmpKey = split[0];
200                 if (serviceInputs.containsKey(tmpKey)) {
201                     value = (String) serviceInputs.get(tmpKey);
202                 } else {
203                     value = split[1];
204                 }
205             }
206             resourceInput.put(key, value);
207         }
208         return resourceInput;
209     }
210
211     public static Map<String, Object> getServiceInstnace(String uuid) throws Exception {
212         String catalogEndPoint = UrnPropertiesReader.getVariable("mso.catalog.db.endpoint");
213
214         HttpClient client = new HttpClientFactory().newJsonClient(UriBuilder.fromUri(catalogEndPoint)
215                 .path(SERVICE_URL_SERVICE_INSTANCE).queryParam("serviceModelUuid", uuid).build().toURL(),
216                 TargetEntity.CATALOG_DB);
217
218         client.addAdditionalHeader("Accept", "application/json");
219         client.addAdditionalHeader("Authorization", UrnPropertiesReader.getVariable("mso.db.auth"));
220
221         Response apiResponse = client.get();
222
223         String value = apiResponse.readEntity(String.class);
224
225         ObjectMapper objectMapper = new ObjectMapper();
226         HashMap<String, Object> map = objectMapper.readValue(value, HashMap.class);
227         return map;
228     }
229
230     public static <T> T getJsonObject(String jsonstr, Class<T> type) {
231         ObjectMapper mapper = new ObjectMapper();
232         mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
233         try {
234             return mapper.readValue(jsonstr, type);
235         } catch (IOException e) {
236             logger.error("fail to unMarshal json {}", e.getMessage());
237         }
238         return null;
239     }
240
241     public static String getJsonString(Object srcObj) {
242         ObjectMapper mapper = new ObjectMapper();
243         mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
244         String jsonStr = null;
245         try {
246             jsonStr = mapper.writeValueAsString(srcObj);
247         } catch (JsonProcessingException e) {
248             logger.error("SdcToscaParserException", e);
249         }
250         return jsonStr;
251     }
252 }