Merge "SO API document"
[so.git] / bpmn / MSOCommonBPMN / src / main / java / org / openecomp / mso / 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.openecomp.mso.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
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;
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?serviceModelUuid=";
61
62     private static MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA);
63
64    
65     static JsonUtils jsonUtil = new JsonUtils();
66
67         /**
68      * build the resource Parameters detail.
69      * It's a json string for resource instantiant
70      * {
71      *     "locationConstraints":[...]
72      *     "requestInputs":{K,V}
73      * }
74      * <br>
75      *
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
82      */
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");
95             }
96         }
97         Map<String, Object> serviceInput =getJsonObject((String)JsonUtils.getJsonValue(serviceParameters, "requestInputs"), Map.class);
98         Map<String, Object> resourceInputsFromUuiMap = getJsonObject(resourceInputsFromUui, Map.class);
99
100         if (serviceInput == null) {
101             serviceInput = new HashMap();
102         }
103
104         if (resourceInputsFromUuiMap == null) {
105             resourceInputsFromUuiMap = new HashMap();
106         }
107
108         try {
109             Map<String, Object> resourceInputsFromServiceDeclaredLevel = buildResouceRequest(serviceUuid, resourceCustomizationUuid, serviceInput);
110             resourceInputsFromUuiMap.putAll(resourceInputsFromServiceDeclaredLevel);
111         } catch(SdcToscaParserException e) {
112                 LOGGER.debug("SdcToscaParserException", e);
113             e.printStackTrace();
114         }
115         String resourceInputsStr = getJsonString(resourceInputsFromUuiMap);
116         String result = "{\n"
117                 + "\"locationConstraints\":" + locationConstraints +",\n"
118                 + "\"requestInputs\":" + resourceInputsStr +"\n"
119                 +"}";
120         return result;
121     }
122
123     public static Map<String, Object> buildResouceRequest(String serviceUuid, String resourceCustomizationUuid, Map<String, Object> serviceInputs)
124             throws SdcToscaParserException {
125
126         Map<String, Object> resouceRequest = new HashMap<>();
127         String csarpath = null;
128         try {
129             csarpath = getCsarFromUuid(serviceUuid);
130         } catch(Exception e) {
131             LOGGER.debug("csar file is not available for service uuid:" + serviceUuid, e);
132             return resouceRequest;
133         }
134
135         SdcToscaParserFactory toscaParser = SdcToscaParserFactory.getInstance();
136         ISdcCsarHelper iSdcCsarHelper = toscaParser.getSdcCsarHelper(csarpath, false);
137
138         List<Input> serInput = iSdcCsarHelper.getServiceInputs();
139         Optional<NodeTemplate> nodeTemplateOpt = iSdcCsarHelper.getServiceNodeTemplates().stream()
140                 .filter(e -> e.getMetaData().getValue(CUSTOMIZATION_UUID).equals(resourceCustomizationUuid)).findFirst();
141
142         if(nodeTemplateOpt.isPresent()) {
143             NodeTemplate nodeTemplate = nodeTemplateOpt.get();
144             LinkedHashMap<String, Property> resourceProperties = nodeTemplate.getProperties();
145
146             for(String key : resourceProperties.keySet()) {
147                 Property property = resourceProperties.get(key);
148
149                 Object value = getValue(property.getValue(), serviceInputs, serInput);
150                 resouceRequest.put(key, value);
151             }
152         }
153         return resouceRequest;
154     }
155
156     private static Object getValue(Object value, Map<String, Object> serviceInputs, List<Input> servInputs) {
157         if(value instanceof Map) {
158             Map<String, Object> valueMap = new HashMap<>();
159
160             Map<String, Object> propertyMap = (Map<String, Object>)value;
161
162             for(String key : propertyMap.keySet()) {
163                 valueMap.put(key, getValue(propertyMap.get(key), serviceInputs, servInputs));
164             }
165             return valueMap; // return if the value is nested hashmap
166         } else if(value instanceof GetInput) {
167             String inputName = ((GetInput)value).getInputName();
168
169             if(serviceInputs.get(inputName) != null) {
170                 value = serviceInputs.get(inputName);
171             } else {
172                 for(Input input : servInputs) {
173                     if(input.getName().equals(inputName)) {
174                         return input.getDefault(); // return default value
175                     }
176                 }
177             }
178         }
179         return value; // return property value
180     }
181
182     private static String getCsarFromUuid(String uuid) throws Exception {
183
184         ResteasyClient client = new ResteasyClientBuilder().build();
185                 Map<String, String> properties = PropertyConfiguration.getInstance().getProperties("mso.bpmn.urn.properties");
186                 String catalogEndPoint = properties.get("mso.catalog.db.endpoint");
187                 ResteasyWebTarget target = client.target(catalogEndPoint + SERVICE_URL_TOSCA_CSAR + uuid);
188         Response response = target.request().get();
189         String value = response.readEntity(String.class);
190
191         HashMap<String, String> map = new Gson().fromJson(value, new TypeToken<HashMap<String, String>>() {}.getType());
192
193         File csarFile = new File(System.getProperty("mso.config.path") + "ASDC/" + map.get("name"));
194
195         if(!csarFile.exists()) {
196             throw new Exception("csar file does not exist.");
197         }
198
199         return csarFile.getAbsolutePath();
200     }
201     
202     public static <T> T getJsonObject(String jsonstr, Class<T> type) {
203         ObjectMapper mapper = new ObjectMapper();
204         mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
205         try {
206             return mapper.readValue(jsonstr, type);
207         } catch(IOException e) {
208             LOGGER.error(MessageEnum.RA_NS_EXC, "", "", MsoLogger.ErrorCode.BusinessProcesssError, "fail to unMarshal json", e);
209         }
210         return null;
211     }
212
213     public static String getJsonString(Object srcObj)  {
214         ObjectMapper mapper = new ObjectMapper();
215         mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
216         String jsonStr = null;
217         try {
218             jsonStr = mapper.writeValueAsString(srcObj);
219         } catch(JsonProcessingException e) {
220                 LOGGER.debug("SdcToscaParserException", e);
221             e.printStackTrace();
222         }
223         return jsonStr;
224     }
225 }