9b878afb7c837ce3e96f366b970d1bfba185df3d
[so.git] / bpmn / so-bpmn-infrastructure-common / 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  * Modifications Copyright (c) 2019 Samsung
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.so.bpmn.infrastructure.workflow.service;
24
25 import com.fasterxml.jackson.core.JsonProcessingException;
26 import com.fasterxml.jackson.databind.ObjectMapper;
27 import com.fasterxml.jackson.databind.SerializationFeature;
28 import java.io.IOException;
29 import java.net.SocketTimeoutException;
30 import java.util.ArrayList;
31 import java.util.Collections;
32 import java.util.HashMap;
33 import java.util.List;
34 import java.util.Map;
35 import java.util.Map.Entry;
36 import java.util.Optional;
37 import org.apache.commons.lang3.StringUtils;
38 import org.apache.http.HttpResponse;
39 import org.apache.http.ParseException;
40 import org.apache.http.client.HttpClient;
41 import org.apache.http.client.config.RequestConfig;
42 import org.apache.http.client.methods.HttpDelete;
43 import org.apache.http.client.methods.HttpGet;
44 import org.apache.http.client.methods.HttpPost;
45 import org.apache.http.client.methods.HttpPut;
46 import org.apache.http.client.methods.HttpRequestBase;
47 import org.apache.http.conn.ConnectTimeoutException;
48 import org.apache.http.entity.ContentType;
49 import org.apache.http.entity.StringEntity;
50 import org.apache.http.impl.client.HttpClientBuilder;
51 import org.apache.http.util.EntityUtils;
52 import org.camunda.bpm.engine.delegate.DelegateExecution;
53 import org.camunda.bpm.engine.runtime.Execution;
54 import org.onap.aai.domain.yang.LogicalLink;
55 import org.onap.aai.domain.yang.LogicalLinks;
56 import org.onap.aai.domain.yang.PInterface;
57 import org.onap.so.bpmn.core.UrnPropertiesReader;
58 import org.onap.so.bpmn.core.domain.Resource;
59 import org.onap.so.bpmn.core.domain.ServiceDecomposition;
60 import org.onap.so.bpmn.core.json.JsonUtils;
61 import org.onap.so.client.aai.AAIObjectPlurals;
62 import org.onap.so.client.aai.AAIObjectType;
63 import org.onap.so.client.aai.AAIResourcesClient;
64 import org.onap.so.client.aai.entities.AAIResultWrapper;
65 import org.onap.so.client.aai.entities.Relationships;
66 import org.onap.so.client.aai.entities.uri.AAIResourceUri;
67 import org.onap.so.client.aai.entities.uri.AAIUriFactory;
68 import org.onap.so.logger.ErrorCode;
69 import org.onap.so.logger.MessageEnum;
70 import org.slf4j.Logger;
71 import org.slf4j.LoggerFactory;
72 import org.springframework.web.util.UriUtils;
73
74 public class ServicePluginFactory {
75
76         // SOTN calculate route
77         public static final String OOF_DEFAULT_ENDPOINT = "http://192.168.1.223:8443/oof/sotncalc";
78
79         public static final String THIRD_SP_DEFAULT_ENDPOINT = "http://192.168.1.223:8443/sp/resourcemgr/querytps";
80
81         public static final String INVENTORY_OSS_DEFAULT_ENDPOINT = "http://192.168.1.199:8443/oss/inventory";
82
83         private static final int DEFAULT_TIME_OUT = 60000;
84
85         static JsonUtils jsonUtil = new JsonUtils();
86
87         private static Logger logger = LoggerFactory.getLogger(ServicePluginFactory.class);
88
89         private static ServicePluginFactory instance;
90
91
92         public static synchronized ServicePluginFactory getInstance() {
93                 if (null == instance) {
94                         instance = new ServicePluginFactory();
95                 }
96                 return instance;
97         }
98
99         private ServicePluginFactory() {
100
101         }
102
103         private String getInventoryOSSEndPoint(){
104                 return UrnPropertiesReader.getVariable("mso.service-plugin.inventory-oss-endpoint", INVENTORY_OSS_DEFAULT_ENDPOINT);
105         }
106
107         private String getThirdSPEndPoint(){
108                 return UrnPropertiesReader.getVariable("mso.service-plugin.third-sp-endpoint", THIRD_SP_DEFAULT_ENDPOINT);
109         }
110
111         private String getOOFCalcEndPoint(){
112                 return UrnPropertiesReader.getVariable("mso.service-plugin.oof-calc-endpoint", OOF_DEFAULT_ENDPOINT);
113         }
114
115         @SuppressWarnings("unchecked")
116         public String doProcessSiteLocation(ServiceDecomposition serviceDecomposition, String uuiRequest) {
117                 if(!isNeedProcessSite(uuiRequest)) {
118                         return uuiRequest;
119                 }
120
121       Map<String, Object> uuiObject = getJsonObject(uuiRequest, Map.class);
122       if (uuiObject == null) {
123           return uuiRequest;
124       }
125       Map<String, Object> serviceObject = (Map<String, Object>) uuiObject
126           .getOrDefault("service", Collections.emptyMap());
127       Map<String, Object> serviceParametersObject = (Map<String, Object>) serviceObject
128           .getOrDefault("parameters", Collections.emptyMap());
129       Map<String, Object> serviceRequestInputs = (Map<String, Object>) serviceParametersObject
130           .getOrDefault("requestInputs", Collections.emptyMap());
131       List<Object> resources = (List<Object>) serviceParametersObject.getOrDefault("resources", Collections.emptyList());
132
133       if (isSiteLocationLocal(serviceRequestInputs, resources)) {
134           // resources changed : added TP info
135           return getJsonString(uuiObject);
136       }
137
138                 List<Resource> addResourceList = new ArrayList<>();
139                 addResourceList.addAll(serviceDecomposition.getServiceResources());
140                 
141                 serviceDecomposition.setVnfResources(null);
142                 serviceDecomposition.setAllottedResources(null);
143                 serviceDecomposition.setNetworkResources(null);
144                 serviceDecomposition.setConfigResources(null);
145                 for (Resource resource : addResourceList) {
146                         String resourcemodelName = resource.getModelInfo().getModelName();
147                         if (StringUtils.containsIgnoreCase(resourcemodelName, "sppartner")) {
148                                 // change serviceDecomposition
149                                 serviceDecomposition.addResource(resource);
150                                 break;
151                         }
152                 }
153
154                 return uuiRequest;
155         }
156
157         private boolean isNeedProcessSite(String uuiRequest) {
158                 return uuiRequest.toLowerCase().contains("site_address") && uuiRequest.toLowerCase().contains("sotncondition_clientsignal");
159         }
160
161         @SuppressWarnings("unchecked")
162         private boolean isSiteLocationLocal(Map<String, Object> serviceRequestInputs, List<Object> resources) {
163       Map<String, Object> tpInfoMap = getTPforVPNAttachment(serviceRequestInputs);
164
165                 if(tpInfoMap.isEmpty()) {
166                         return true;
167                 }
168                 String host = (String) tpInfoMap.get("host");
169                 // host is empty means TP is in local, not empty means TP is in remote ONAP
170                 if (!host.isEmpty()) {
171                         return false;
172                 }
173
174                 Map<String, Object> accessTPInfo = new HashMap<String, Object>();
175                 accessTPInfo.put("access-provider-id", tpInfoMap.get("access-provider-id"));
176                 accessTPInfo.put("access-client-id", tpInfoMap.get("access-client-id"));
177                 accessTPInfo.put("access-topology-id", tpInfoMap.get("access-topology-id"));
178                 accessTPInfo.put("access-node-id", tpInfoMap.get("access-node-id"));
179                 accessTPInfo.put("access-ltp-id", tpInfoMap.get("access-ltp-id"));
180
181                 // change resources
182                 String resourceName = (String) tpInfoMap.get("resourceName");
183                 for(Object curResource : resources) {
184                         Map<String, Object> resource = (Map<String, Object>)curResource;
185                         String curResourceName = (String) resource.get("resourceName");
186                         curResourceName = curResourceName.replaceAll(" ", "");
187                         if(resourceName.equalsIgnoreCase(curResourceName)) {
188                                 putResourceRequestInputs(resource, accessTPInfo);
189                                 break;
190                         }
191                 }
192
193                 return true;
194         }
195
196         @SuppressWarnings("unchecked")
197         private Map<String, Object> getTPforVPNAttachment(Map<String, Object> serviceRequestInputs) {
198                 Object location = null;
199                 Object clientSignal = null;
200                 String vpnAttachmentResourceName = null;
201
202                 // support R2 uuiReq and R1 uuiReq
203                 // logic for R2 uuiRequest params in service level
204                 for (Entry<String, Object> entry : serviceRequestInputs.entrySet()) {
205                         String key = entry.getKey();
206                         if (key.toLowerCase().contains("site_address")) {
207                                 location = entry.getValue();
208                         }
209                         if (key.toLowerCase().contains("sotncondition_clientsignal")) {
210                                 clientSignal = entry.getValue();
211                                 vpnAttachmentResourceName = key.substring(0, key.indexOf("_"));
212                         }
213                 }
214
215                 Map<String, Object> tpInfoMap =  new HashMap<String, Object>();
216
217                 // Site resource has location param and SOTNAttachment resource has clientSignal param
218                 if(location == null || clientSignal == null ) {
219                         return tpInfoMap;
220                 }
221
222                 // Query terminal points from InventoryOSS system by location.
223                 String locationAddress = (String) location;
224                 List<Object> locationTPList = queryAccessTPbyLocationFromInventoryOSS(locationAddress);
225                 if(locationTPList != null && !locationTPList.isEmpty()) {
226                     for(Object tp: locationTPList) {
227                         Map<String, Object> tpJson = (Map<String, Object>) tp;
228                         String loc =  (String)tpJson.get ("location");
229                         if(StringUtils.equalsIgnoreCase (locationAddress, loc)) {
230                             tpInfoMap = tpJson;
231                             // add resourceName
232                             tpInfoMap.put("resourceName", vpnAttachmentResourceName);
233                             break;
234                         }
235                     }
236                         logger.debug("Get Terminal TP from InventoryOSS");
237                         return tpInfoMap;
238                 }
239
240                 return tpInfoMap;
241         }
242
243         @SuppressWarnings("unchecked")
244         private List<Object> queryAccessTPbyLocationFromInventoryOSS(String locationAddress) {
245                 String url = getInventoryOSSEndPoint();
246                 url += "/oss/inventory?location=" +  UriUtils.encode(locationAddress,"UTF-8");
247                 String responseContent = sendRequest(url, "GET", "");
248                 List<Object> accessTPs = new ArrayList<>();
249                 if (null != responseContent) {
250                         accessTPs = getJsonObject(responseContent, List.class);
251                 }
252                 return accessTPs;
253         }
254
255         @SuppressWarnings("unchecked")
256         private void putResourceRequestInputs(Map<String, Object> resource, Map<String, Object> resourceInputs) {
257                 Map<String, Object> resourceParametersObject = new HashMap<>();
258                 Map<String, Object> resourceRequestInputs = new HashMap<>();
259                 resourceRequestInputs.put("requestInputs", resourceInputs);
260                 resourceParametersObject.put("parameters", resourceRequestInputs);
261
262                 if(resource.containsKey("parameters")) {
263                         Map<String, Object> resParametersObject = (Map<String, Object>) resource.get("parameters");
264                         if(resParametersObject.containsKey("requestInputs")) {
265                                 Map<String, Object> resRequestInputs = (Map<String, Object>) resourceRequestInputs.get("requestInputs");
266                                 Map<String, Object> oldRequestInputs = (Map<String, Object>) resParametersObject.get("requestInputs");
267                                 if(oldRequestInputs != null) {
268                                         oldRequestInputs.putAll(resRequestInputs);
269                                 }
270                                 else {
271                                         resParametersObject.put("requestInputs", resRequestInputs);
272                                 }
273                         }
274                         else {
275                                 resParametersObject.putAll(resourceRequestInputs);
276                         }
277                 }
278                 else {
279                         resource.putAll(resourceParametersObject);
280                 }
281
282                 return;
283         }
284
285
286
287         @SuppressWarnings("unchecked")
288         public String doTPResourcesAllocation(DelegateExecution execution, String uuiRequest) {
289       Map<String, Object> uuiObject = getJsonObject(uuiRequest, Map.class);
290       if (uuiObject == null) {
291           return uuiRequest;
292       }
293       Map<String, Object> serviceObject = (Map<String, Object>) uuiObject
294           .getOrDefault("service", Collections.emptyMap());
295       Map<String, Object> serviceParametersObject = (Map<String, Object>) serviceObject
296           .getOrDefault("parameters", Collections.emptyMap());
297       Map<String, Object> serviceRequestInputs = (Map<String, Object>) serviceParametersObject
298           .getOrDefault("requestInputs", Collections.emptyMap());
299
300       if (!isNeedAllocateCrossTPResources(serviceRequestInputs)) {
301           return uuiRequest;
302       }
303
304       allocateCrossTPResources(execution, serviceRequestInputs);
305       return getJsonString(uuiObject);
306   }
307
308         @SuppressWarnings("unchecked")
309         private boolean isNeedAllocateCrossTPResources(Map<String, Object> serviceRequestInputs) {
310                 if(serviceRequestInputs.containsKey("CallSource"))
311                 {
312                         String callSource = (String) serviceRequestInputs.get("CallSource");
313                         if("ExternalAPI".equalsIgnoreCase(callSource)) {
314                                 return false;
315                         }
316                 }
317                 for (String input : serviceRequestInputs.keySet())
318                 {
319                         if(input.toLowerCase().contains("sotnconnectivity")) {
320                                 return true;
321                         }
322                 }
323                 return false;
324         }
325
326         @SuppressWarnings("unchecked")
327         private void allocateCrossTPResources(DelegateExecution execution, Map<String, Object> serviceRequestInputs) {
328
329                 Map<String, Object> crossTPs = this.getTPsfromAAI();
330
331                 if(crossTPs == null || crossTPs.isEmpty()) {
332                         serviceRequestInputs.put("local-access-provider-id", "");
333                         serviceRequestInputs.put("local-access-client-id", "");
334                         serviceRequestInputs.put("local-access-topology-id", "");
335                         serviceRequestInputs.put("local-access-node-id", "");
336                         serviceRequestInputs.put("local-access-ltp-id", "");
337                         serviceRequestInputs.put("remote-access-provider-id", "");
338                         serviceRequestInputs.put("remote-access-client-id", "");
339                         serviceRequestInputs.put("remote-access-topology-id", "");
340                         serviceRequestInputs.put("remote-access-node-id", "");
341                         serviceRequestInputs.put("remote-access-ltp-id", "");
342                 }
343                 else {
344                         serviceRequestInputs.put("local-access-provider-id", crossTPs.get("local-access-provider-id"));
345                         serviceRequestInputs.put("local-access-client-id", crossTPs.get("local-access-client-id"));
346                         serviceRequestInputs.put("local-access-topology-id", crossTPs.get("local-access-topology-id"));
347                         serviceRequestInputs.put("local-access-node-id", crossTPs.get("local-access-node-id"));
348                         serviceRequestInputs.put("local-access-ltp-id", crossTPs.get("local-access-ltp-id"));
349                         serviceRequestInputs.put("remote-access-provider-id", crossTPs.get("remote-access-provider-id"));
350                         serviceRequestInputs.put("remote-access-client-id", crossTPs.get("remote-client-id"));
351                         serviceRequestInputs.put("remote-access-topology-id", crossTPs.get("remote-topology-id"));
352                         serviceRequestInputs.put("remote-access-node-id", crossTPs.get("remote-node-id"));
353                         serviceRequestInputs.put("remote-access-ltp-id", crossTPs.get("remote-ltp-id"));
354                 }
355
356                 return;
357         }
358
359         // This method returns Local and remote TPs information from AAI
360         public Map getTPsfromAAI() {
361                 Map<String, Object> tpInfo = new HashMap<>();
362
363                 AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.LOGICAL_LINK);
364                 AAIResourcesClient client = new AAIResourcesClient();
365                 Optional<LogicalLinks> result = client.get(LogicalLinks.class, uri);
366
367                 if (result.isPresent()) {
368                         LogicalLinks links = result.get();
369                         boolean isRemoteLink = false;
370
371                         links.getLogicalLink();
372
373                         for (LogicalLink link : links.getLogicalLink()) {
374                                 AAIResultWrapper wrapper = new AAIResultWrapper(link);
375                                 Optional<Relationships> optRelationships = wrapper.getRelationships();
376                                 List<AAIResourceUri> pInterfaces = new ArrayList<>();
377                                 if (optRelationships.isPresent()) {
378                                         Relationships relationships = optRelationships.get();
379                                         if (!relationships.getRelatedAAIUris(AAIObjectType.EXT_AAI_NETWORK).isEmpty()) {
380                                                 isRemoteLink = true;
381                                         }
382                                         pInterfaces.addAll(relationships.getRelatedAAIUris(AAIObjectType.P_INTERFACE));
383                                 }
384
385                                 if (isRemoteLink) {
386                                         // find remote p interface
387                                         AAIResourceUri localTP = null;
388                                         AAIResourceUri remoteTP = null;
389
390                                         AAIResourceUri pInterface0 = pInterfaces.get(0);
391
392                                         if (isRemotePInterface(client, pInterface0)) {
393                                                 remoteTP = pInterfaces.get(0);
394                                                 localTP = pInterfaces.get(1);
395                                         } else {
396                                                 localTP = pInterfaces.get(0);
397                                                 remoteTP = pInterfaces.get(1);
398                                         }
399
400                                         if (localTP != null && remoteTP != null) {
401                                                 // give local tp
402                                                 String tpUrl = localTP.build().toString();
403                                                 PInterface intfLocal = client.get(PInterface.class, localTP).get();
404                                                 tpInfo.put("local-access-node-id", tpUrl.split("/")[6]);
405
406                                                 String[] networkRef = intfLocal.getNetworkRef().split("/");
407                                                 if (networkRef.length == 6) {
408                                                         tpInfo.put("local-access-provider-id", networkRef[1]);
409                                                         tpInfo.put("local-access-client-id", networkRef[3]);
410                                                         tpInfo.put("local-access-topology-id", networkRef[5]);
411                                                 }
412                                                 String ltpIdStr = tpUrl.substring(tpUrl.lastIndexOf("/") + 1);
413                                                 if (ltpIdStr.contains("-")) {
414                                                         tpInfo.put("local-access-ltp-id", ltpIdStr.substring(ltpIdStr.lastIndexOf("-") + 1));
415                                                 }
416
417                                                 // give remote tp
418                                                 tpUrl = remoteTP.build().toString();
419                                                 PInterface intfRemote = client.get(PInterface.class, remoteTP).get();
420                                                 tpInfo.put("remote-access-node-id", tpUrl.split("/")[6]);
421
422                                                 String[] networkRefRemote = intfRemote.getNetworkRef().split("/");
423
424                                                 if (networkRefRemote.length == 6) {
425                                                         tpInfo.put("remote-access-provider-id", networkRefRemote[1]);
426                                                         tpInfo.put("remote-access-client-id", networkRefRemote[3]);
427                                                         tpInfo.put("remote-access-topology-id", networkRefRemote[5]);
428                                                 }
429                                                 String ltpIdStrR = tpUrl.substring(tpUrl.lastIndexOf("/") + 1);
430                                                 if (ltpIdStrR.contains("-")) {
431                                                         tpInfo.put("remote-access-ltp-id", ltpIdStrR.substring(ltpIdStr.lastIndexOf("-") + 1));
432                                                 }
433                                                 return tpInfo;
434                                         }
435                                 }
436                         }
437                 }
438                 return tpInfo;
439         }
440
441         // this method check if pInterface is remote
442         private boolean isRemotePInterface(AAIResourcesClient client, AAIResourceUri uri) {
443
444                 String uriString = uri.build().toString();
445
446                 if (uriString != null) {
447                         // get the pnfname
448                         String[] token = uriString.split("/");
449                         AAIResourceUri parent = AAIUriFactory.createResourceUri(AAIObjectType.PNF, token[4]);
450
451                         AAIResultWrapper wrapper = client.get(parent);
452                         Optional<Relationships> optRelationships = wrapper.getRelationships();
453                         if (optRelationships.isPresent()) {
454                                 Relationships relationships = optRelationships.get();
455
456                                 return !relationships.getRelatedAAIUris(AAIObjectType.EXT_AAI_NETWORK).isEmpty();
457                         }
458                 }
459
460                 return false;
461         }
462
463         public String preProcessService(ServiceDecomposition serviceDecomposition, String uuiRequest) {
464
465                 // now only for sotn
466                 if (isSOTN(serviceDecomposition, uuiRequest)) {
467                         // We Need to query the terminalpoint of the VPN by site location
468                         // info
469                         return preProcessSOTNService(serviceDecomposition, uuiRequest);
470                 }
471                 return uuiRequest;
472         }
473
474         public String doServiceHoming(ServiceDecomposition serviceDecomposition, String uuiRequest) {
475                 // now only for sotn
476                 if (isSOTN(serviceDecomposition, uuiRequest)) {
477                         return doSOTNServiceHoming(serviceDecomposition, uuiRequest);
478                 }
479                 return uuiRequest;
480         }
481
482         private boolean isSOTN(ServiceDecomposition serviceDecomposition, String uuiRequest) {
483                 // there should be a register platform , we check it very simple here.
484                 return uuiRequest.contains("clientSignal") && uuiRequest.contains("vpnType");
485         }
486
487         @SuppressWarnings("unchecked")
488         private String preProcessSOTNService(ServiceDecomposition serviceDecomposition, String uuiRequest) {
489                 Map<String, Object> uuiObject = getJsonObject(uuiRequest, Map.class);
490       if (uuiObject == null) {
491           return uuiRequest;
492       }
493       Map<String, Object> serviceObject = (Map<String, Object>) uuiObject
494           .getOrDefault("service", Collections.emptyMap());
495       Map<String, Object> serviceParametersObject = (Map<String, Object>) serviceObject
496           .getOrDefault("parameters", Collections.emptyMap());
497       Map<String, Object> serviceRequestInputs = (Map<String, Object>) serviceParametersObject
498           .getOrDefault("requestInputs", Collections.emptyMap());
499       List<Object> resources = (List<Object>) serviceParametersObject.getOrDefault("resources", Collections.emptyList());
500                 // This is a logic for demo , it could not be finalized to community.
501                 String srcLocation = "";
502                 String dstLocation = "";
503                 String srcClientSignal = "";
504                 String dstClientSignal = "";
505                 // support R2 uuiReq and R1 uuiReq
506                 // logic for R2 uuiRequest params in service level
507                 for (Entry<String, Object> entry : serviceRequestInputs.entrySet()) {
508                         if (entry.getKey().toLowerCase().contains("location")) {
509                                 if ("".equals(srcLocation)) {
510                                         srcLocation = (String) entry.getValue();
511                                 } else if ("".equals(dstLocation)) {
512                                         dstLocation = (String) entry.getValue();
513                                 }
514                         }
515                         if (entry.getKey().toLowerCase().contains("clientsignal")) {
516                                 if ("".equals(srcClientSignal)) {
517                                         srcClientSignal = (String) entry.getValue();
518                                 } else if ("".equals(dstClientSignal)) {
519                                         dstClientSignal = (String) entry.getValue();
520                                 }
521                         }
522                 }
523
524                 // logic for R1 uuiRequest, params in resource level
525                 for (Object resource : resources) {
526                         Map<String, Object> resourceObject = (Map<String, Object>) resource;
527                         Map<String, Object> resourceParametersObject = (Map<String, Object>) resourceObject.get("parameters");
528                         Map<String, Object> resourceRequestInputs = (Map<String, Object>) resourceParametersObject.get("requestInputs");
529                         for (Entry<String, Object> entry : resourceRequestInputs.entrySet()) {
530                                 if (entry.getKey().toLowerCase().contains("location")) {
531                                         if ("".equals(srcLocation)) {
532                                                 srcLocation = (String) entry.getValue();
533                                         } else if ("".equals(dstLocation)) {
534                                                 dstLocation = (String) entry.getValue();
535                                         }
536                                 }
537                                 if (entry.getKey().toLowerCase().contains("clientsignal")) {
538                                         if ("".equals(srcClientSignal)) {
539                                                 srcClientSignal = (String) entry.getValue();
540                                         } else if ("".equals(dstClientSignal)) {
541                                                 dstClientSignal = (String) entry.getValue();
542                                         }
543                                 }
544                         }
545                 }
546
547                 Map<String, Object> vpnRequestInputs = getVPNResourceRequestInputs(resources);
548                 // here we put client signal to vpn resource inputs
549                 if(null!=vpnRequestInputs) {
550                         vpnRequestInputs.put("src-client-signal", srcClientSignal);
551                         vpnRequestInputs.put("dst-client-signal", dstClientSignal);
552                 }
553
554
555                 // Now we need to query terminal points from SP resourcemgr system.
556                 List<Object> locationTerminalPointList = queryTerminalPointsFromServiceProviderSystem(srcLocation, dstLocation);
557                 Map<String, Object> tpInfoMap = (Map<String, Object>) locationTerminalPointList.get(0);
558
559                 serviceRequestInputs.put("inner-src-access-provider-id", tpInfoMap.get("access-provider-id"));
560                 serviceRequestInputs.put("inner-src-access-client-id", tpInfoMap.get("access-client-id"));
561                 serviceRequestInputs.put("inner-src-access-topology-id", tpInfoMap.get("access-topology-id"));
562                 serviceRequestInputs.put("inner-src-access-node-id", tpInfoMap.get("access-node-id"));
563                 serviceRequestInputs.put("inner-src-access-ltp-id", tpInfoMap.get("access-ltp-id"));
564                 tpInfoMap = (Map<String, Object>) locationTerminalPointList.get(1);
565
566                 serviceRequestInputs.put("inner-dst-access-provider-id", tpInfoMap.get("access-provider-id"));
567                 serviceRequestInputs.put("inner-dst-access-client-id", tpInfoMap.get("access-client-id"));
568                 serviceRequestInputs.put("inner-dst-access-topology-id", tpInfoMap.get("access-topology-id"));
569                 serviceRequestInputs.put("inner-dst-access-node-id", tpInfoMap.get("access-node-id"));
570                 serviceRequestInputs.put("inner-dst-access-ltp-id", tpInfoMap.get("access-ltp-id"));
571
572                 String newRequest = getJsonString(uuiObject);
573                 return newRequest;
574         }
575
576         private List<Object> queryTerminalPointsFromServiceProviderSystem(String srcLocation, String dstLocation) {
577                 Map<String, String> locationSrc = new HashMap<>();
578                 locationSrc.put("location", srcLocation);
579                 Map<String, String> locationDst = new HashMap<>();
580                 locationDst.put("location", dstLocation);
581                 List<Map<String, String>> locations = new ArrayList<>();
582                 locations.add(locationSrc);
583                 locations.add(locationDst);
584                 List<Object> returnList = new ArrayList<>();
585                 String reqContent = getJsonString(locations);
586                 String url = getThirdSPEndPoint();
587                 String responseContent = sendRequest(url, "POST", reqContent);
588                 if (null != responseContent) {
589                         returnList = getJsonObject(responseContent, List.class);
590                 }
591                 return returnList;
592         }
593
594         @SuppressWarnings("unchecked")
595         private Map<String, Object> getVPNResourceRequestInputs(List<Object> resources) {
596                 for (Object resource : resources) {
597                         Map<String, Object> resourceObject = (Map<String, Object>) resource;
598                         Map<String, Object> resourceParametersObject = (Map<String, Object>) resourceObject.get("parameters");
599                         Map<String, Object> resourceRequestInputs = (Map<String, Object>) resourceParametersObject.get("requestInputs");
600                         for (Entry<String, Object> entry : resourceRequestInputs.entrySet()) {
601                                 if (entry.getKey().toLowerCase().contains("vpntype")) {
602                                         return resourceRequestInputs;
603                                 }
604                         }
605                 }
606                 return null;
607         }
608
609         public static void main(String args[]){
610                 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/";
611
612                 int index1 = str.indexOf("/network/");
613                 int index2 = str.indexOf("/network-data");
614
615                 String str1 = str.substring(index1 + "/network/".length(), index2);
616                 System.out.println(str1);
617
618         }
619
620     @SuppressWarnings("unchecked")
621     private String doSOTNServiceHoming(ServiceDecomposition serviceDecomposition, String uuiRequest) {
622         // query the route for the service.
623         Map<String, Object> uuiObject = getJsonObject(uuiRequest, Map.class);
624         if (uuiObject == null) {
625             return uuiRequest;
626         }
627         Map<String, Object> serviceObject = (Map<String, Object>) uuiObject
628             .getOrDefault("service", Collections.emptyMap());
629         Map<String, Object> serviceParametersObject = (Map<String, Object>) serviceObject
630             .getOrDefault("parameters", Collections.emptyMap());
631         Map<String, Object> serviceRequestInputs = (Map<String, Object>) serviceParametersObject
632             .getOrDefault("requestInputs", Collections.emptyMap());
633         Map<String, Object> oofQueryObject = new HashMap<>();
634         List<Object> resources = (List<Object>) serviceParametersObject
635             .getOrDefault("resources", Collections.emptyList());
636         oofQueryObject.put("src-access-provider-id", serviceRequestInputs.get("inner-src-access-provider-id"));
637         oofQueryObject.put("src-access-client-id", serviceRequestInputs.get("inner-src-access-client-id"));
638         oofQueryObject.put("src-access-topology-id", serviceRequestInputs.get("inner-src-access-topology-id"));
639         oofQueryObject.put("src-access-node-id", serviceRequestInputs.get("inner-src-access-node-id"));
640         oofQueryObject.put("src-access-ltp-id", serviceRequestInputs.get("inner-src-access-ltp-id"));
641         oofQueryObject.put("dst-access-provider-id", serviceRequestInputs.get("inner-dst-access-provider-id"));
642         oofQueryObject.put("dst-access-client-id", serviceRequestInputs.get("inner-dst-access-client-id"));
643         oofQueryObject.put("dst-access-topology-id", serviceRequestInputs.get("inner-dst-access-topology-id"));
644         oofQueryObject.put("dst-access-node-id", serviceRequestInputs.get("inner-dst-access-node-id"));
645         oofQueryObject.put("dst-access-ltp-id", serviceRequestInputs.get("inner-dst-access-ltp-id"));
646         String oofRequestReq = getJsonString(oofQueryObject);
647         String url = getOOFCalcEndPoint();
648         String responseContent = sendRequest(url, "POST", oofRequestReq);
649
650         List<Object> returnList = new ArrayList<>();
651         if (null != responseContent) {
652             returnList = getJsonObject(responseContent, List.class);
653         }
654         // in demo we have only one VPN. no cross VPNs, so get first item.
655         Map<String, Object> returnRoute = getReturnRoute(returnList);
656         Map<String, Object> vpnRequestInputs = getVPNResourceRequestInputs(resources);
657         if (null != vpnRequestInputs) {
658             vpnRequestInputs.putAll(returnRoute);
659         }
660         return getJsonString(uuiObject);
661     }
662
663         private Map<String, Object> getReturnRoute(List<Object> returnList){
664                 Map<String, Object> returnRoute = new HashMap<>();
665                 for(Object returnVpn :returnList){
666                         Map<String, Object> returnVpnInfo = (Map<String, Object>) returnVpn;
667                     String accessTopoId = (String)returnVpnInfo.get("access-topology-id");
668                         if("100".equals(accessTopoId)){
669                                 returnRoute.putAll(returnVpnInfo);
670                         }
671                         else if("101".equals(accessTopoId)){
672                                 for(String key : returnVpnInfo.keySet()){
673                                         returnRoute.put("domain1-" + key, returnVpnInfo.get(key));
674                                 }
675                         }
676                         else if("102".equals(accessTopoId)){
677                                 for(String key : returnVpnInfo.keySet()){
678                                         returnRoute.put("domain2-" + key, returnVpnInfo.get(key));
679                                 }
680                         }
681                         else{
682                                 for(String key : returnVpnInfo.keySet()){
683                                         returnRoute.put("domain" + accessTopoId +"-" + key, returnVpnInfo.get(key));
684                                 }
685                         }
686                 }
687                 return returnRoute;
688         }
689
690         private Map<String, Object> getResourceParams(Execution execution, String resourceCustomizationUuid,
691                         String serviceParameters) {
692                 List<String> resourceList = jsonUtil.StringArrayToList(execution,
693                                 JsonUtils.getJsonValue(serviceParameters, "resources"));
694                 // Get the right location str for resource. default is an empty array.
695                 String resourceInputsFromUui = "";
696                 for (String resource : resourceList) {
697                         String resCusUuid = JsonUtils.getJsonValue(resource, "resourceCustomizationUuid");
698                         if (resourceCustomizationUuid.equals(resCusUuid)) {
699                                 String resourceParameters = JsonUtils.getJsonValue(resource, "parameters");
700                                 resourceInputsFromUui = JsonUtils.getJsonValue(resourceParameters, "requestInputs");
701                         }
702                 }
703                 Map<String, Object> resourceInputsFromUuiMap = getJsonObject(resourceInputsFromUui, Map.class);
704                 return resourceInputsFromUuiMap;
705         }
706
707         private static <T> T getJsonObject(String jsonstr, Class<T> type) {
708                 ObjectMapper mapper = new ObjectMapper();
709                 mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
710                 try {
711                         return mapper.readValue(jsonstr, type);
712                 } catch (IOException e) {
713                         logger.error("{} {} fail to unMarshal json", MessageEnum.RA_NS_EXC.toString(),
714                                 ErrorCode.BusinessProcesssError.getValue(), e);
715                 }
716                 return null;
717         }
718
719         public static String getJsonString(Object srcObj) {
720                 ObjectMapper mapper = new ObjectMapper();
721                 mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
722                 String jsonStr = null;
723                 try {
724                         jsonStr = mapper.writeValueAsString(srcObj);
725                 } catch (JsonProcessingException e) {
726                         logger.debug("SdcToscaParserException", e);
727                 }
728                 return jsonStr;
729         }
730
731         private static String sendRequest(String url, String methodType, String content) {
732
733                 String msbUrl = url;
734                 HttpRequestBase method = null;
735                 HttpResponse httpResponse = null;
736
737                 try {
738                         int timeout = DEFAULT_TIME_OUT;
739
740                         RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout)
741                                         .setConnectionRequestTimeout(timeout).build();
742
743                         HttpClient client = HttpClientBuilder.create().build();
744
745                         if ("POST".equals(methodType.toUpperCase())) {
746                                 HttpPost httpPost = new HttpPost(msbUrl);
747                                 httpPost.setConfig(requestConfig);
748                                 httpPost.setEntity(new StringEntity(content, ContentType.APPLICATION_JSON));
749                                 method = httpPost;
750                         } else if ("PUT".equals(methodType.toUpperCase())) {
751                                 HttpPut httpPut = new HttpPut(msbUrl);
752                                 httpPut.setConfig(requestConfig);
753                                 httpPut.setEntity(new StringEntity(content, ContentType.APPLICATION_JSON));
754                                 method = httpPut;
755                         } else if ("GET".equals(methodType.toUpperCase())) {
756                                 HttpGet httpGet = new HttpGet(msbUrl);
757                                 httpGet.setConfig(requestConfig);
758                                 httpGet.addHeader("X-FromAppId", "MSO");
759                                 httpGet.addHeader("Accept","application/json");
760                                 method = httpGet;
761                         } else if ("DELETE".equals(methodType.toUpperCase())) {
762                                 HttpDelete httpDelete = new HttpDelete(msbUrl);
763                                 httpDelete.setConfig(requestConfig);
764                                 method = httpDelete;
765                         }
766
767                         httpResponse = client.execute(method);
768                         String responseContent = null;
769                         if (null != httpResponse && httpResponse.getEntity() != null) {
770                                 try {
771                                         responseContent = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
772                                 } catch (ParseException e) {
773                                         logger.debug("ParseException in sendrequest", e);
774                                 } catch (IOException e) {
775                                         logger.debug("IOException in sendrequest", e);
776                                 }
777                         }
778                         if (null != method) {
779                                 method.reset();
780                         }
781                         method = null;
782                         return responseContent;
783
784                 } catch (SocketTimeoutException | ConnectTimeoutException e) {
785                         return null;
786
787                 } catch (Exception e) {
788                         return null;
789
790                 } finally {
791                         if (httpResponse != null) {
792                                 try {
793                                         EntityUtils.consume(httpResponse.getEntity());
794                                 } catch (Exception e) {
795                                 }
796                         }
797                         if (method != null) {
798                                 try {
799                                         method.reset();
800                                 } catch (Exception e) {
801
802                                 }
803                         }
804                 }
805         }
806 }