Merge "Removed deprecated Matcher imports"
[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.nio.file.Paths;
26 import java.util.ArrayList;
27 import java.util.HashMap;
28 import java.util.LinkedHashMap;
29 import java.util.List;
30 import java.util.Map;
31 import java.util.Optional;
32
33 import javax.ws.rs.core.Response;
34 import javax.ws.rs.core.UriBuilder;
35
36 import org.camunda.bpm.engine.runtime.Execution;
37 import org.onap.sdc.tosca.parser.api.ISdcCsarHelper;
38 import org.onap.sdc.tosca.parser.exceptions.SdcToscaParserException;
39 import org.onap.sdc.tosca.parser.impl.SdcToscaParserFactory;
40 import org.onap.sdc.toscaparser.api.NodeTemplate;
41 import org.onap.sdc.toscaparser.api.Property;
42 import org.onap.sdc.toscaparser.api.RequirementAssignment;
43 import org.onap.sdc.toscaparser.api.RequirementAssignments;
44 import org.onap.sdc.toscaparser.api.functions.GetInput;
45 import org.onap.sdc.toscaparser.api.parameters.Input;
46 import org.onap.so.bpmn.core.UrnPropertiesReader;
47 import org.onap.so.bpmn.core.json.JsonUtils;
48 import org.onap.so.client.HttpClient;
49 import org.onap.so.client.HttpClientFactory;
50 import org.onap.so.logger.MsoLogger;
51 import org.onap.so.utils.TargetEntity;
52
53 import com.fasterxml.jackson.core.JsonProcessingException;
54 import com.fasterxml.jackson.databind.ObjectMapper;
55 import com.fasterxml.jackson.databind.SerializationFeature;
56 import com.google.gson.Gson;
57 import com.google.gson.reflect.TypeToken;
58
59 public class ResourceRequestBuilder {
60
61     private static String CUSTOMIZATION_UUID = "customizationUUID";
62
63     private static String SERVICE_URL_TOSCA_CSAR = "/v3/serviceToscaCsar";
64
65     private static MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA, ResourceRequestBuilder.class);
66
67     static JsonUtils jsonUtil = new JsonUtils();
68
69         public static List<String> getResourceSequence(Execution execution, String serviceUuid) {
70                 List<String> resouceSequence = new ArrayList<String>();
71                 List<NodeTemplate> resultList = new ArrayList<NodeTemplate>();
72                 String csarpath = null;
73                 try {
74                         csarpath = getCsarFromUuid(serviceUuid);
75
76                         SdcToscaParserFactory toscaParser = SdcToscaParserFactory.getInstance();
77                         ISdcCsarHelper iSdcCsarHelper = toscaParser.getSdcCsarHelper(csarpath, false);
78                         List<NodeTemplate> nodeTemplates = iSdcCsarHelper.getServiceNodeTemplates();
79                         List<NodeTemplate> nodes = new ArrayList<NodeTemplate>();
80                         nodes.addAll(nodeTemplates);
81
82                         for (NodeTemplate nodeTemplate : nodeTemplates) {
83                                 RequirementAssignments requirement = iSdcCsarHelper.getRequirementsOf(nodeTemplate);
84
85                                 if (requirement == null || requirement.getAll() == null || requirement.getAll().isEmpty()) {
86                                         resultList.add(nodeTemplate);
87                                         nodes.remove(nodeTemplate);
88                                 }
89                         }
90
91                         resultList = getRequirementList(resultList, nodes, iSdcCsarHelper);
92                         
93                         for (NodeTemplate node : resultList) {
94                                 String templateName = node.getMetaData().getValue("name");
95                                 if (!resouceSequence.contains(templateName)) {
96                                         resouceSequence.add(templateName);
97                                 }
98                         }
99
100                 } catch (SdcToscaParserException toscarParserE) {
101                         LOGGER.debug("sdc tosca parser failed for csar: " + csarpath, toscarParserE);
102                         return resouceSequence;
103                 } catch (Exception e) {
104                         LOGGER.debug("csar file is not available for service uuid:" + serviceUuid, e);
105                         return resouceSequence;
106                 }
107                 
108                 return resouceSequence;
109         }
110
111         private static List<NodeTemplate> getRequirementList(List<NodeTemplate> resultList, List<NodeTemplate> nodeTemplates,
112                         ISdcCsarHelper iSdcCsarHelper) {
113
114                 List<NodeTemplate> nodes = new ArrayList<NodeTemplate>();
115                 nodes.addAll(nodeTemplates);
116
117                 for (NodeTemplate nodeTemplate : nodeTemplates) {
118                         RequirementAssignments requirement = iSdcCsarHelper.getRequirementsOf(nodeTemplate);
119                         List<RequirementAssignment> reqAs = requirement.getAll();
120                         for (RequirementAssignment ra : reqAs) {
121                                 String reqNode = ra.getNodeTemplateName();
122                                 for (NodeTemplate rNode : resultList) {
123                                         if (rNode.getName().equals(reqNode)) {
124                                                 if(!resultList.contains(nodeTemplate)) {
125                                                         resultList.add(nodeTemplate);
126                                                 }
127                                                 if(nodes.contains(nodeTemplate)) {
128                                                         nodes.remove(nodeTemplate);
129                                                 }
130                                                 break;
131                                         }
132                                 }
133                         }
134                 }
135
136                 if (!nodes.isEmpty()) {
137                         getRequirementList(resultList, nodes, iSdcCsarHelper);
138                 }
139
140                 return resultList;
141         }
142
143      /* build the resource Parameters detail.
144      * It's a json string for resource instantiant
145      * {
146      *     "locationConstraints":[...]
147      *     "requestInputs":{K,V}
148      * }
149      * <br>
150      *
151      * @param execution Execution context
152      * @param serviceUuid The service template uuid
153      * @param resourceCustomizationUuid The resource customization uuid
154      * @param serviceParameters the service parameters passed from the API
155      * @return the resource instantiate parameters
156      * @since ONAP Beijing Release
157      */
158     @SuppressWarnings("unchecked")
159     public static String buildResourceRequestParameters(Execution execution, String serviceUuid, String resourceCustomizationUuid, String serviceParameters) {
160         List<String> resourceList = jsonUtil.StringArrayToList(execution, (String)JsonUtils.getJsonValue(serviceParameters, "resources"));
161         //Get the right location str for resource. default is an empty array.
162         String locationConstraints ="[]";
163         String resourceInputsFromUui = "";
164         for(String resource: resourceList){
165             String resCusUuid = (String)JsonUtils.getJsonValue(resource, "resourceCustomizationUuid");
166             if(resourceCustomizationUuid.equals(resCusUuid)){
167                 String resourceParameters = JsonUtils.getJsonValue(resource, "parameters");
168                 locationConstraints = JsonUtils.getJsonValue(resourceParameters, "locationConstraints");
169                 resourceInputsFromUui = JsonUtils.getJsonValue(resourceParameters, "requestInputs");
170             }
171         }
172         Map<String, Object> serviceInput = null;
173         if (JsonUtils.getJsonValue(serviceParameters, "requestInputs") != null) {
174             serviceInput = getJsonObject((String)JsonUtils.getJsonValue(serviceParameters, "requestInputs"), Map.class);
175         }
176
177         Map<String, Object> resourceInputsFromUuiMap = getJsonObject(resourceInputsFromUui, Map.class);
178
179         if (serviceInput == null) {
180             serviceInput = new HashMap();
181         }
182
183         if (resourceInputsFromUuiMap == null) {
184             resourceInputsFromUuiMap = new HashMap();
185         }
186
187         try {
188             Map<String, Object> resourceInputsFromServiceDeclaredLevel = buildResouceRequest(serviceUuid, resourceCustomizationUuid, serviceInput);
189             resourceInputsFromUuiMap.putAll(resourceInputsFromServiceDeclaredLevel);
190         } catch(SdcToscaParserException e) {
191                 LOGGER.error("SdcToscaParserException", e);
192         }
193         String resourceInputsStr = getJsonString(resourceInputsFromUuiMap);
194         String result = "{\n"
195                 + "\"locationConstraints\":" + locationConstraints +",\n"
196                 + "\"requestInputs\":" + resourceInputsStr +"\n"
197                 +"}";
198         return result;
199     }
200
201     public static Map<String, Object> buildResouceRequest(String serviceUuid, String resourceCustomizationUuid, Map<String, Object> serviceInputs)
202             throws SdcToscaParserException {
203
204         Map<String, Object> resouceRequest = new HashMap<>();
205
206         String csarpath = null;
207         try {
208             csarpath = getCsarFromUuid(serviceUuid);
209         } catch(Exception e) {
210             LOGGER.debug("csar file is not available for service uuid:" + serviceUuid, e);
211             return resouceRequest;
212         }
213
214         SdcToscaParserFactory toscaParser = SdcToscaParserFactory.getInstance();
215         ISdcCsarHelper iSdcCsarHelper = toscaParser.getSdcCsarHelper(csarpath, false);
216
217         List<Input> serInput = iSdcCsarHelper.getServiceInputs();
218         Optional<NodeTemplate> nodeTemplateOpt = iSdcCsarHelper.getServiceNodeTemplates().stream()
219                 .filter(e -> e.getMetaData().getValue(CUSTOMIZATION_UUID).equals(resourceCustomizationUuid)).findFirst();
220
221         if(nodeTemplateOpt.isPresent()) {
222             NodeTemplate nodeTemplate = nodeTemplateOpt.get();
223             LinkedHashMap<String, Property> resourceProperties = nodeTemplate.getProperties();
224
225             for(String key : resourceProperties.keySet()) {
226                 Property property = resourceProperties.get(key);
227
228                 Object value = getValue(property.getValue(), serviceInputs, serInput);
229                 resouceRequest.put(key, value);
230             }
231         }
232         return resouceRequest;
233     }
234
235     private static Object getValue(Object value, Map<String, Object> serviceInputs, List<Input> servInputs) {
236         if(value instanceof Map) {
237             Map<String, Object> valueMap = new HashMap<>();
238
239             Map<String, Object> propertyMap = (Map<String, Object>)value;
240
241             for(String key : propertyMap.keySet()) {
242                 valueMap.put(key, getValue(propertyMap.get(key), serviceInputs, servInputs));
243             }
244             return valueMap; // return if the value is nested hashmap
245         } else if(value instanceof GetInput) {
246             String inputName = ((GetInput)value).getInputName();
247
248             if(serviceInputs.get(inputName) != null) {
249                 value = serviceInputs.get(inputName);
250             } else {
251                 for(Input input : servInputs) {
252                     if(input.getName().equals(inputName)) {
253                         return input.getDefault(); // return default value
254                     }
255                 }
256             }
257         }
258         return value; // return property value
259     }
260
261     private static String getCsarFromUuid(String uuid) throws Exception {
262                 String catalogEndPoint = UrnPropertiesReader.getVariable("mso.catalog.db.endpoint");
263         HttpClient client = new HttpClientFactory().newJsonClient(
264             UriBuilder.fromUri(catalogEndPoint).path(SERVICE_URL_TOSCA_CSAR).queryParam("serviceModelUuid", uuid).build().toURL(),
265             TargetEntity.CATALOG_DB);
266         
267         client.addAdditionalHeader("Accept", "application/json");
268 //      client.addBasicAuthHeader (UrnPropertiesReader.getVariable("mso.adapters.db.auth"), UrnPropertiesReader.getVariable("mso.msoKey"));
269         client.addAdditionalHeader("Authorization", UrnPropertiesReader.getVariable("mso.db.auth"));
270         Response response = client.get();
271         String value = response.readEntity(String.class);
272
273         HashMap<String, String> map = new Gson().fromJson(value, new TypeToken<HashMap<String, String>>() {}.getType());
274
275         String filePath = Paths.get(System.getProperty("mso.config.path"), "ASDC",  map.get("version"), map.get("name")).normalize().toString();
276
277         File csarFile = new File(filePath);
278
279         if(!csarFile.exists()) {
280             throw new Exception("csar file does not exist in filePath:" + csarFile.getAbsolutePath());
281         }
282
283         return csarFile.getAbsolutePath();
284     }
285     
286     public static <T> T getJsonObject(String jsonstr, Class<T> type) {
287         ObjectMapper mapper = new ObjectMapper();
288         mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
289         try {
290             return mapper.readValue(jsonstr, type);
291         } catch(IOException e) {
292             LOGGER.error("fail to unMarshal json" + e.getMessage ());
293         }
294         return null;
295     }
296
297     public static String getJsonString(Object srcObj)  {
298         ObjectMapper mapper = new ObjectMapper();
299         mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
300         String jsonStr = null;
301         try {
302             jsonStr = mapper.writeValueAsString(srcObj);
303         } catch(JsonProcessingException e) {
304                 LOGGER.error("SdcToscaParserException", e);
305         }
306         return jsonStr;
307     }
308 }