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