Containerization feature of SO
[so.git] / bpmn / mso-infrastructure-bpmn / src / main / java / org / onap / so / bpmn / infrastructure / workflow / service / ServicePluginFactory.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.infrastructure.workflow.service;
22
23 import java.io.IOException;
24 import java.net.SocketTimeoutException;
25 import java.util.ArrayList;
26 import java.util.HashMap;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.Map.Entry;
30
31 import org.apache.http.HttpResponse;
32 import org.apache.http.ParseException;
33 import org.apache.http.client.HttpClient;
34 import org.apache.http.client.config.RequestConfig;
35 import org.apache.http.client.methods.HttpDelete;
36 import org.apache.http.client.methods.HttpGet;
37 import org.apache.http.client.methods.HttpPost;
38 import org.apache.http.client.methods.HttpPut;
39 import org.apache.http.client.methods.HttpRequestBase;
40 import org.apache.http.conn.ConnectTimeoutException;
41 import org.apache.http.entity.ContentType;
42 import org.apache.http.entity.StringEntity;
43 import org.apache.http.impl.client.HttpClientBuilder;
44 import org.apache.http.util.EntityUtils;
45 import org.camunda.bpm.engine.runtime.Execution;
46 import org.onap.so.bpmn.core.UrnPropertiesReader;
47 import org.onap.so.bpmn.core.domain.ServiceDecomposition;
48 import org.onap.so.bpmn.core.json.JsonUtils;
49 import org.onap.so.logger.MessageEnum;
50 import org.onap.so.logger.MsoLogger;
51 import org.springframework.beans.factory.annotation.Autowired;
52 import org.springframework.core.env.Environment;
53
54 import com.fasterxml.jackson.core.JsonProcessingException;
55 import com.fasterxml.jackson.databind.ObjectMapper;
56 import com.fasterxml.jackson.databind.SerializationFeature;
57
58 public class ServicePluginFactory {
59
60         // SOTN calculate route
61         public static final String OOF_Default_EndPoint = "http://192.168.1.223:8443/oof/sotncalc";
62
63         public static final String Third_SP_Default_EndPoint = "http://192.168.1.223:8443/sp/resourcemgr/querytps";
64
65         private static final int DEFAULT_TIME_OUT = 60000;
66
67         static JsonUtils jsonUtil = new JsonUtils();
68
69         private static MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA, ServicePluginFactory.class);
70
71         private static ServicePluginFactory instance;
72         
73
74         public static synchronized ServicePluginFactory getInstance() {
75                 if (null == instance) {
76                         instance = new ServicePluginFactory();
77                 }
78                 return instance;
79         }
80         
81         private String getThirdSPEndPoint(){
82                 return UrnPropertiesReader.getVariable("mso.service-plugin.third-sp-endpoint", Third_SP_Default_EndPoint);
83         }
84
85         private String getOOFCalcEndPoint(){
86                 return UrnPropertiesReader.getVariable("mso.service-plugin.oof-calc-endpoint", OOF_Default_EndPoint);
87         }
88         
89
90         public String preProcessService(ServiceDecomposition serviceDecomposition, String uuiRequest) {
91
92                 // now only for sotn
93                 if (isSOTN(serviceDecomposition, uuiRequest)) {
94                         // We Need to query the terminalpoint of the VPN by site location
95                         // info
96                         return preProcessSOTNService(serviceDecomposition, uuiRequest);
97                 }
98                 return uuiRequest;
99         }
100
101         public String doServiceHoming(ServiceDecomposition serviceDecomposition, String uuiRequest) {
102                 // now only for sotn
103                 if (isSOTN(serviceDecomposition, uuiRequest)) {
104                         return doSOTNServiceHoming(serviceDecomposition, uuiRequest);
105                 }
106                 return uuiRequest;
107         }
108
109         private boolean isSOTN(ServiceDecomposition serviceDecomposition, String uuiRequest) {
110                 // there should be a register platform , we check it very simple here.
111                 return uuiRequest.contains("clientSignal") && uuiRequest.contains("vpnType");
112         }
113
114         private String preProcessSOTNService(ServiceDecomposition serviceDecomposition, String uuiRequest) {
115                 Map<String, Object> uuiObject = getJsonObject(uuiRequest, Map.class);
116                 Map<String, Object> serviceObject = (Map<String, Object>) uuiObject.get("service");
117                 Map<String, Object> serviceParametersObject = (Map<String, Object>) serviceObject.get("parameters");
118                 Map<String, Object> serviceRequestInputs = (Map<String, Object>) serviceParametersObject.get("requestInputs");
119                 List<Object> resources = (List<Object>) serviceParametersObject.get("resources");
120                 // This is a logic for demo , it could not be finalized to community.
121                 String srcLocation = "";
122                 String dstLocation = "";
123                 String srcClientSignal = "";
124                 String dstClientSignal = "";
125                 // support R2 uuiReq and R1 uuiReq
126                 // logic for R2 uuiRequest params in service level
127                 for (Entry<String, Object> entry : serviceRequestInputs.entrySet()) {
128                         if (entry.getKey().toLowerCase().contains("location")) {
129                                 if ("".equals(srcLocation)) {
130                                         srcLocation = (String) entry.getValue();
131                                 } else if ("".equals(dstLocation)) {
132                                         dstLocation = (String) entry.getValue();
133                                 }
134                         }
135                         if (entry.getKey().toLowerCase().contains("clientsignal")) {
136                                 if ("".equals(srcClientSignal)) {
137                                         srcClientSignal = (String) entry.getValue();
138                                 } else if ("".equals(dstClientSignal)) {
139                                         dstClientSignal = (String) entry.getValue();
140                                 }
141                         }
142                 }
143
144                 // logic for R1 uuiRequest, params in resource level
145                 for (Object resource : resources) {
146                         Map<String, Object> resourceObject = (Map<String, Object>) resource;
147                         Map<String, Object> resourceParametersObject = (Map<String, Object>) resourceObject.get("parameters");
148                         Map<String, Object> resourceRequestInputs = (Map<String, Object>) resourceParametersObject
149                                         .get("requestInputs");
150                         for (Entry<String, Object> entry : resourceRequestInputs.entrySet()) {
151                                 if (entry.getKey().toLowerCase().contains("location")) {
152                                         if ("".equals(srcLocation)) {
153                                                 srcLocation = (String) entry.getValue();
154                                         } else if ("".equals(dstLocation)) {
155                                                 dstLocation = (String) entry.getValue();
156                                         }
157                                 }
158                                 if (entry.getKey().toLowerCase().contains("clientsignal")) {
159                                         if ("".equals(srcClientSignal)) {
160                                                 srcClientSignal = (String) entry.getValue();
161                                         } else if ("".equals(dstClientSignal)) {
162                                                 dstClientSignal = (String) entry.getValue();
163                                         }
164                                 }
165                         }
166                 }
167
168                 Map<String, Object> vpnRequestInputs = getVPNResourceRequestInputs(resources);
169                 // here we put client signal to vpn resource inputs
170                 vpnRequestInputs.put("src-client-signal", srcClientSignal);
171                 vpnRequestInputs.put("dst-client-signal", dstClientSignal);
172
173                 // Now we need to query terminal points from SP resourcemgr system.
174                 List<Object> locationTerminalPointList = queryTerminalPointsFromServiceProviderSystem(srcLocation, dstLocation);
175                 Map<String, Object> tpInfoMap = (Map<String, Object>) locationTerminalPointList.get(0);
176
177                 serviceRequestInputs.put("inner-src-access-provider-id", tpInfoMap.get("access-provider-id"));
178                 serviceRequestInputs.put("inner-src-access-client-id", tpInfoMap.get("access-client-id"));
179                 serviceRequestInputs.put("inner-src-access-topology-id", tpInfoMap.get("access-topology-id"));
180                 serviceRequestInputs.put("inner-src-access-node-id", tpInfoMap.get("access-node-id"));
181                 serviceRequestInputs.put("inner-src-access-ltp-id", tpInfoMap.get("access-ltp-id"));
182                 tpInfoMap = (Map<String, Object>) locationTerminalPointList.get(1);
183
184                 serviceRequestInputs.put("inner-dst-access-provider-id", tpInfoMap.get("access-provider-id"));
185                 serviceRequestInputs.put("inner-dst-access-client-id", tpInfoMap.get("access-client-id"));
186                 serviceRequestInputs.put("inner-dst-access-topology-id", tpInfoMap.get("access-topology-id"));
187                 serviceRequestInputs.put("inner-dst-access-node-id", tpInfoMap.get("access-node-id"));
188                 serviceRequestInputs.put("inner-dst-access-ltp-id", tpInfoMap.get("access-ltp-id"));
189
190                 String newRequest = getJsonString(uuiObject);
191                 return newRequest;
192         }
193
194         private List<Object> queryTerminalPointsFromServiceProviderSystem(String srcLocation, String dstLocation) {
195                 Map<String, String> locationSrc = new HashMap<>();
196                 locationSrc.put("location", srcLocation);
197                 Map<String, String> locationDst = new HashMap<>();
198                 locationDst.put("location", dstLocation);
199                 List<Map<String, String>> locations = new ArrayList<>();
200                 locations.add(locationSrc);
201                 locations.add(locationDst);
202                 List<Object> returnList = new ArrayList<>();
203                 String reqContent = getJsonString(locations);
204                 String url = getThirdSPEndPoint();
205                 String responseContent = sendRequest(url, "POST", reqContent);
206                 if (null != responseContent) {
207                         returnList = getJsonObject(responseContent, List.class);
208                 }
209                 return returnList;
210         }
211
212         private Map<String, Object> getVPNResourceRequestInputs(List<Object> resources) {
213                 for (Object resource : resources) {
214                         Map<String, Object> resourceObject = (Map<String, Object>) resource;
215                         Map<String, Object> resourceParametersObject = (Map<String, Object>) resourceObject.get("parameters");
216                         Map<String, Object> resourceRequestInputs = (Map<String, Object>) resourceParametersObject
217                                         .get("requestInputs");
218                         for (Entry<String, Object> entry : resourceRequestInputs.entrySet()) {
219                                 if (entry.getKey().toLowerCase().contains("vpntype")) {
220                                         return resourceRequestInputs;
221                                 }
222                         }
223                 }
224                 return null;
225         }
226         
227         public static void main(String args[]){
228                 String str = "restconf/config/GENERIC-RESOURCE-API:services/service/eca7e542-12ba-48de-8544-fac59303b14e/service-data/networks/network/aec07806-1671-4af2-b722-53c8e320a633/network-data/";
229                 
230                 int index1 = str.indexOf("/network/");
231                 int index2 = str.indexOf("/network-data");
232                 
233                 String str1 = str.substring(index1 + "/network/".length(), index2);
234                 System.out.println(str1);
235                 
236         }
237
238         private String doSOTNServiceHoming(ServiceDecomposition serviceDecomposition, String uuiRequest) {
239                 // query the route for the service.
240                 Map<String, Object> uuiObject = getJsonObject(uuiRequest, Map.class);
241                 Map<String, Object> serviceObject = (Map<String, Object>) uuiObject.get("service");
242                 Map<String, Object> serviceParametersObject = (Map<String, Object>) serviceObject.get("parameters");
243                 Map<String, Object> serviceRequestInputs = (Map<String, Object>) serviceParametersObject.get("requestInputs");
244                 Map<String, Object> oofQueryObject = new HashMap<>();
245                 List<Object> resources = (List<Object>) serviceParametersObject.get("resources");
246                 oofQueryObject.put("src-access-provider-id", serviceRequestInputs.get("inner-src-access-provider-id"));
247                 oofQueryObject.put("src-access-client-id", serviceRequestInputs.get("inner-src-access-client-id"));
248                 oofQueryObject.put("src-access-topology-id", serviceRequestInputs.get("inner-src-access-topology-id"));
249                 oofQueryObject.put("src-access-node-id", serviceRequestInputs.get("inner-src-access-node-id"));
250                 oofQueryObject.put("src-access-ltp-id", serviceRequestInputs.get("inner-src-access-ltp-id"));
251                 oofQueryObject.put("dst-access-provider-id", serviceRequestInputs.get("inner-dst-access-provider-id"));
252                 oofQueryObject.put("dst-access-client-id", serviceRequestInputs.get("inner-dst-access-client-id"));
253                 oofQueryObject.put("dst-access-topology-id", serviceRequestInputs.get("inner-dst-access-topology-id"));
254                 oofQueryObject.put("dst-access-node-id", serviceRequestInputs.get("inner-dst-access-node-id"));
255                 oofQueryObject.put("dst-access-ltp-id", serviceRequestInputs.get("inner-dst-access-ltp-id"));
256                 String oofRequestReq = getJsonString(oofQueryObject);
257                 String url = getOOFCalcEndPoint();
258                 String responseContent = sendRequest(url, "POST", oofRequestReq);
259
260                 List<Object> returnList = new ArrayList<>();
261                 if (null != responseContent) {
262                         returnList = getJsonObject(responseContent, List.class);
263                 }
264                 // in demo we have only one VPN. no cross VPNs, so get first item.
265                 Map<String, Object> returnRoute = getReturnRoute(returnList);
266                 Map<String, Object> vpnRequestInputs = getVPNResourceRequestInputs(resources);
267                 vpnRequestInputs.putAll(returnRoute);
268                 String newRequest = getJsonString(uuiObject);
269                 return newRequest;
270         }
271         
272         private Map<String, Object> getReturnRoute(List<Object> returnList){
273                 Map<String, Object> returnRoute = new HashMap<>();
274                 for(Object returnVpn :returnList){
275                         Map<String, Object> returnVpnInfo = (Map<String, Object>) returnVpn;
276                     String accessTopoId = (String)returnVpnInfo.get("access-topology-id");
277                         if("100".equals(accessTopoId)){
278                                 returnRoute.putAll(returnVpnInfo);
279                         }
280                         else if("101".equals(accessTopoId)){
281                                 for(String key : returnVpnInfo.keySet()){
282                                         returnRoute.put("domain1-" + key, returnVpnInfo.get(key));
283                                 }
284                         }
285                         else if("102".equals(accessTopoId)){
286                                 for(String key : returnVpnInfo.keySet()){
287                                         returnRoute.put("domain2-" + key, returnVpnInfo.get(key));
288                                 }
289                         }
290                         else{
291                                 for(String key : returnVpnInfo.keySet()){
292                                         returnRoute.put("domain" + accessTopoId +"-" + key, returnVpnInfo.get(key));
293                                 }
294                         }
295                 }
296                 return returnRoute;
297         }
298
299         private Map<String, Object> getResourceParams(Execution execution, String resourceCustomizationUuid,
300                         String serviceParameters) {
301                 List<String> resourceList = jsonUtil.StringArrayToList(execution,
302                                 (String) JsonUtils.getJsonValue(serviceParameters, "resources"));
303                 // Get the right location str for resource. default is an empty array.
304                 String resourceInputsFromUui = "";
305                 for (String resource : resourceList) {
306                         String resCusUuid = (String) JsonUtils.getJsonValue(resource, "resourceCustomizationUuid");
307                         if (resourceCustomizationUuid.equals(resCusUuid)) {
308                                 String resourceParameters = JsonUtils.getJsonValue(resource, "parameters");
309                                 resourceInputsFromUui = JsonUtils.getJsonValue(resourceParameters, "requestInputs");
310                         }
311                 }
312                 Map<String, Object> resourceInputsFromUuiMap = getJsonObject(resourceInputsFromUui, Map.class);
313                 return resourceInputsFromUuiMap;
314         }
315
316         public static <T> T getJsonObject(String jsonstr, Class<T> type) {
317                 ObjectMapper mapper = new ObjectMapper();
318                 mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
319                 try {
320                         return mapper.readValue(jsonstr, type);
321                 } catch (IOException e) {
322                         LOGGER.error(MessageEnum.RA_NS_EXC, "", "", MsoLogger.ErrorCode.BusinessProcesssError,
323                                         "fail to unMarshal json", e);
324                 }
325                 return null;
326         }
327
328         public static String getJsonString(Object srcObj) {
329                 ObjectMapper mapper = new ObjectMapper();
330                 mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
331                 String jsonStr = null;
332                 try {
333                         jsonStr = mapper.writeValueAsString(srcObj);
334                 } catch (JsonProcessingException e) {
335                         LOGGER.debug("SdcToscaParserException", e);
336                         e.printStackTrace();
337                 }
338                 return jsonStr;
339         }
340
341         private static String sendRequest(String url, String methodType, String content) {
342                 
343                 String msbUrl = url;
344                 HttpRequestBase method = null;
345                 HttpResponse httpResponse = null;
346
347                 try {
348                         int timeout = DEFAULT_TIME_OUT;
349
350                         RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout)
351                                         .setConnectionRequestTimeout(timeout).build();
352
353                         HttpClient client = HttpClientBuilder.create().build();
354
355                         if ("POST".equals(methodType.toUpperCase())) {
356                                 HttpPost httpPost = new HttpPost(msbUrl);
357                                 httpPost.setConfig(requestConfig);
358                                 httpPost.setEntity(new StringEntity(content, ContentType.APPLICATION_JSON));
359                                 method = httpPost;
360                         } else if ("PUT".equals(methodType.toUpperCase())) {
361                                 HttpPut httpPut = new HttpPut(msbUrl);
362                                 httpPut.setConfig(requestConfig);
363                                 httpPut.setEntity(new StringEntity(content, ContentType.APPLICATION_JSON));
364                                 method = httpPut;
365                         } else if ("GET".equals(methodType.toUpperCase())) {
366                                 HttpGet httpGet = new HttpGet(msbUrl);
367                                 httpGet.setConfig(requestConfig);
368                                 method = httpGet;
369                         } else if ("DELETE".equals(methodType.toUpperCase())) {
370                                 HttpDelete httpDelete = new HttpDelete(msbUrl);
371                                 httpDelete.setConfig(requestConfig);
372                                 method = httpDelete;
373                         }
374
375                         // now have no auth
376                         // String userCredentials =
377                         // SDNCAdapterProperties.getEncryptedProperty(Constants.SDNC_AUTH_PROP,
378                         // Constants.DEFAULT_SDNC_AUTH, Constants.ENCRYPTION_KEY);
379                         // String authorization = "Basic " +
380                         // DatatypeConverter.printBase64Binary(userCredentials.getBytes());
381                         // method.setHeader("Authorization", authorization);
382
383                         httpResponse = client.execute(method);
384                         String responseContent = null;
385                         if (null != httpResponse && httpResponse.getEntity() != null) {
386                                 try {
387                                         responseContent = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
388                                 } catch (ParseException e) {
389                                         e.printStackTrace();
390                                 } catch (IOException e) {
391                                         e.printStackTrace();
392                                 }
393                         }
394                         if (null != method) {
395                                 method.reset();
396                         }
397                         method = null;
398                         return responseContent;
399
400                 } catch (SocketTimeoutException | ConnectTimeoutException e) {
401                         return null;
402
403                 } catch (Exception e) {
404                         return null;
405
406                 } finally {
407                         if (httpResponse != null) {
408                                 try {
409                                         EntityUtils.consume(httpResponse.getEntity());
410                                 } catch (Exception e) {
411                                 }
412                         }
413                         if (method != null) {
414                                 try {
415                                         method.reset();
416                                 } catch (Exception e) {
417
418                                 }
419                         }
420                 }
421         }
422 }