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