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