e753f79ebdb688d8aca32a3f0df63e443b6a23d5
[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  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.so.bpmn.infrastructure.workflow.service;
22
23 import java.io.IOException;
24 import java.io.UnsupportedEncodingException;
25 import java.net.SocketTimeoutException;
26 import java.util.ArrayList;
27 import java.util.HashMap;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.Map.Entry;
31 import java.util.Optional;
32
33 import org.apache.commons.lang3.StringUtils;
34 import org.apache.http.HttpResponse;
35 import org.apache.http.ParseException;
36 import org.apache.http.client.HttpClient;
37 import org.apache.http.client.config.RequestConfig;
38 import org.apache.http.client.methods.HttpDelete;
39 import org.apache.http.client.methods.HttpGet;
40 import org.apache.http.client.methods.HttpPost;
41 import org.apache.http.client.methods.HttpPut;
42 import org.apache.http.client.methods.HttpRequestBase;
43 import org.apache.http.conn.ConnectTimeoutException;
44 import org.apache.http.entity.ContentType;
45 import org.apache.http.entity.StringEntity;
46 import org.apache.http.impl.client.HttpClientBuilder;
47 import org.apache.http.util.EntityUtils;
48 import org.camunda.bpm.engine.delegate.DelegateExecution;
49 import org.camunda.bpm.engine.runtime.Execution;
50 import org.onap.aai.domain.yang.LogicalLink;
51 import org.onap.aai.domain.yang.LogicalLinks;
52 import org.onap.aai.domain.yang.PInterface;
53 import org.onap.so.bpmn.core.UrnPropertiesReader;
54 import org.onap.so.bpmn.core.domain.Resource;
55 import org.onap.so.bpmn.core.domain.ServiceDecomposition;
56 import org.onap.so.bpmn.core.json.JsonUtils;
57 import org.onap.so.client.aai.AAIObjectPlurals;
58 import org.onap.so.client.aai.AAIObjectType;
59 import org.onap.so.client.aai.AAIResourcesClient;
60 import org.onap.so.client.aai.entities.AAIResultWrapper;
61 import org.onap.so.client.aai.entities.Relationships;
62 import org.onap.so.client.aai.entities.uri.AAIResourceUri;
63 import org.onap.so.client.aai.entities.uri.AAIUriFactory;
64 import org.onap.so.logger.MessageEnum;
65 import org.onap.so.logger.MsoLogger;
66 import org.springframework.web.util.UriUtils;
67
68 import com.fasterxml.jackson.core.JsonProcessingException;
69 import com.fasterxml.jackson.databind.ObjectMapper;
70 import com.fasterxml.jackson.databind.SerializationFeature;
71
72 public class ServicePluginFactory {
73
74         // SOTN calculate route
75         public static final String OOF_DEFAULT_ENDPOINT = "http://192.168.1.223:8443/oof/sotncalc";
76
77         public static final String THIRD_SP_DEFAULT_ENDPOINT = "http://192.168.1.223:8443/sp/resourcemgr/querytps";
78         
79         public static final String INVENTORY_OSS_DEFAULT_ENDPOINT = "http://192.168.1.199:8443/oss/inventory";
80
81         private static final int DEFAULT_TIME_OUT = 60000;
82
83         static JsonUtils jsonUtil = new JsonUtils();
84
85         private static MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, ServicePluginFactory.class);
86
87         private static ServicePluginFactory instance;
88         
89
90         public static synchronized ServicePluginFactory getInstance() {
91                 if (null == instance) {
92                         instance = new ServicePluginFactory();
93                 }
94                 return instance;
95         }
96
97         private ServicePluginFactory() {
98
99         }
100         
101         private String getInventoryOSSEndPoint(){
102                 return UrnPropertiesReader.getVariable("mso.service-plugin.inventory-oss-endpoint", INVENTORY_OSS_DEFAULT_ENDPOINT);
103         }
104         
105         private String getThirdSPEndPoint(){
106                 return UrnPropertiesReader.getVariable("mso.service-plugin.third-sp-endpoint", THIRD_SP_DEFAULT_ENDPOINT);
107         }
108
109         private String getOOFCalcEndPoint(){
110                 return UrnPropertiesReader.getVariable("mso.service-plugin.oof-calc-endpoint", OOF_DEFAULT_ENDPOINT);
111         }
112
113         @SuppressWarnings("unchecked")
114         public String doProcessSiteLocation(ServiceDecomposition serviceDecomposition, String uuiRequest) {
115                 if(!isNeedProcessSite(uuiRequest)) {
116                         return uuiRequest;
117                 }
118         
119                 Map<String, Object> uuiObject = getJsonObject(uuiRequest, Map.class);
120                 Map<String, Object> serviceObject = (Map<String, Object>) uuiObject.get("service");
121                 Map<String, Object> serviceParametersObject = (Map<String, Object>) serviceObject.get("parameters");
122                 Map<String, Object> serviceRequestInputs = (Map<String, Object>) serviceParametersObject.get("requestInputs");
123                 List<Object> resources = (List<Object>) serviceParametersObject.get("resources");       
124
125                 if (isSiteLocationLocal(serviceRequestInputs, resources)) {
126                         // resources changed : added TP info 
127                         String newRequest = getJsonString(uuiObject);
128                         return newRequest;
129                 }
130
131                 List<Resource> addResourceList = new ArrayList<Resource>();
132                 addResourceList.addAll(serviceDecomposition.getServiceResources());
133                 
134                 serviceDecomposition.setVnfResources(null);
135                 serviceDecomposition.setAllottedResources(null);
136                 serviceDecomposition.setNetworkResources(null);
137                 serviceDecomposition.setConfigResources(null);
138                 for (Resource resource : addResourceList) {
139                         String resourcemodelName = resource.getModelInfo().getModelName();
140                         if (StringUtils.containsIgnoreCase(resourcemodelName, "sppartner")) {
141                                 // change serviceDecomposition
142                                 serviceDecomposition.addResource(resource);
143                                 break;
144                         }
145                 }
146
147                 return uuiRequest;
148         }
149
150         private boolean isNeedProcessSite(String uuiRequest) {
151                 return uuiRequest.toLowerCase().contains("site_address") && uuiRequest.toLowerCase().contains("sotncondition_clientsignal");
152         }
153
154         @SuppressWarnings("unchecked")
155         private boolean isSiteLocationLocal(Map<String, Object> serviceRequestInputs, List<Object> resources) {         
156         Map<String, Object> tpInfoMap = getTPforVPNAttachment(serviceRequestInputs);    
157                         
158                 if(tpInfoMap.isEmpty()) {
159                         return true;
160                 }
161                 String host = (String) tpInfoMap.get("host");
162                 // host is empty means TP is in local, not empty means TP is in remote ONAP
163                 if (!host.isEmpty()) {
164                         return false;
165                 }
166                 
167                 Map<String, Object> accessTPInfo = new HashMap<String, Object>();
168                 accessTPInfo.put("access-provider-id", tpInfoMap.get("access-provider-id"));
169                 accessTPInfo.put("access-client-id", tpInfoMap.get("access-client-id"));
170                 accessTPInfo.put("access-topology-id", tpInfoMap.get("access-topology-id"));
171                 accessTPInfo.put("access-node-id", tpInfoMap.get("access-node-id"));
172                 accessTPInfo.put("access-ltp-id", tpInfoMap.get("access-ltp-id"));
173
174                 // change resources
175                 String resourceName = (String) tpInfoMap.get("resourceName");
176                 for(Object curResource : resources) {
177                         Map<String, Object> resource = (Map<String, Object>)curResource;
178                         String curResourceName = (String) resource.get("resourceName");
179                         curResourceName = curResourceName.replaceAll(" ", "");
180                         if(resourceName.equalsIgnoreCase(curResourceName)) { 
181                                 putResourceRequestInputs(resource, accessTPInfo);
182                                 break;
183                         }
184                 }
185
186                 return true;
187         }
188         
189         @SuppressWarnings("unchecked")
190         private Map<String, Object> getTPforVPNAttachment(Map<String, Object> serviceRequestInputs) {
191                 Object location = null;
192                 Object clientSignal = null;
193                 String vpnAttachmentResourceName = null;
194
195                 // support R2 uuiReq and R1 uuiReq
196                 // logic for R2 uuiRequest params in service level
197                 for (Entry<String, Object> entry : serviceRequestInputs.entrySet()) {
198                         String key = entry.getKey();
199                         if (key.toLowerCase().contains("site_address")) {                               
200                                 location = entry.getValue();
201                         } 
202                         if (key.toLowerCase().contains("sotncondition_clientsignal")) {                         
203                                 clientSignal = entry.getValue();
204                                 vpnAttachmentResourceName = key.substring(0, key.indexOf("_"));
205                         }
206                 }
207
208                 Map<String, Object> tpInfoMap =  new HashMap<String, Object>();
209                 
210                 // Site resource has location param and SOTNAttachment resource has clientSignal param
211                 if(location == null || clientSignal == null ) {
212                         return tpInfoMap;
213                 }
214                 
215                 // Query terminal points from InventoryOSS system by location.          
216                 String locationAddress = (String) location;             
217                 List<Object> locationTPList = queryAccessTPbyLocationFromInventoryOSS(locationAddress);
218                 if(locationTPList != null && !locationTPList.isEmpty()) {
219                     for(Object tp: locationTPList) {
220                         Map<String, Object> tpJson = (Map<String, Object>) tp;
221                         String loc =  (String)tpJson.get ("location");
222                         if(StringUtils.equalsIgnoreCase (locationAddress, loc)) {
223                             tpInfoMap = tpJson;
224                             // add resourceName
225                             tpInfoMap.put("resourceName", vpnAttachmentResourceName);
226                             break;
227                         }
228                     }
229                         LOGGER.debug("Get Terminal TP from InventoryOSS");
230                         return tpInfoMap;
231                 }
232                 
233                 return tpInfoMap;
234         }
235         
236         @SuppressWarnings("unchecked")
237         private List<Object> queryAccessTPbyLocationFromInventoryOSS(String locationAddress) {
238                 String url = getInventoryOSSEndPoint();
239                 try {
240                         url += "/oss/inventory?location=" +  UriUtils.encode(locationAddress,"UTF-8");
241                 } catch (UnsupportedEncodingException e) {
242                         // TODO Auto-generated catch block
243                         e.printStackTrace();
244                 }
245                 String responseContent = sendRequest(url, "GET", "");
246                 List<Object> accessTPs = new ArrayList<Object>();
247                 if (null != responseContent) {
248                         accessTPs = getJsonObject(responseContent, List.class);
249                 }
250                 return accessTPs;
251         }
252         
253         @SuppressWarnings("unchecked")
254         private void putResourceRequestInputs(Map<String, Object> resource, Map<String, Object> resourceInputs) {
255                 Map<String, Object> resourceParametersObject = new HashMap<String, Object>();
256                 Map<String, Object> resourceRequestInputs = new HashMap<String, Object>();
257                 resourceRequestInputs.put("requestInputs", resourceInputs);
258                 resourceParametersObject.put("parameters", resourceRequestInputs);
259
260                 if(resource.containsKey("parameters")) {
261                         Map<String, Object> resParametersObject = (Map<String, Object>) resource.get("parameters");
262                         if(resParametersObject.containsKey("requestInputs")) {
263                                 Map<String, Object> resRequestInputs = (Map<String, Object>) resourceRequestInputs.get("requestInputs");
264                                 Map<String, Object> oldRequestInputs = (Map<String, Object>) resParametersObject.get("requestInputs");
265                                 if(oldRequestInputs != null) {                                  
266                                         oldRequestInputs.putAll(resRequestInputs);
267                                 }
268                                 else {
269                                         resParametersObject.put("requestInputs", resRequestInputs);
270                                 }
271                         }
272                         else {
273                                 resParametersObject.putAll(resourceRequestInputs);                              
274                         }
275                 }
276                 else {
277                         resource.putAll(resourceParametersObject);
278                 }
279
280                 return;
281         }
282         
283
284         
285         @SuppressWarnings("unchecked")
286         public String doTPResourcesAllocation(DelegateExecution execution, String uuiRequest) {         
287                 Map<String, Object> uuiObject = getJsonObject(uuiRequest, Map.class);
288                 Map<String, Object> serviceObject = (Map<String, Object>) uuiObject.get("service");
289                 Map<String, Object> serviceParametersObject = (Map<String, Object>) serviceObject.get("parameters");
290                 Map<String, Object> serviceRequestInputs = (Map<String, Object>) serviceParametersObject.get("requestInputs");
291                 
292                 if(!isNeedAllocateCrossTPResources(serviceRequestInputs)) {
293                         return uuiRequest;
294                 }
295                 
296                 allocateCrossTPResources(execution, serviceRequestInputs);
297                 String newRequest = getJsonString(uuiObject);
298                 return newRequest;
299         }
300
301         @SuppressWarnings("unchecked")
302         private boolean isNeedAllocateCrossTPResources(Map<String, Object> serviceRequestInputs) {
303                 if(serviceRequestInputs.containsKey("CallSource"))
304                 {
305                         String callSource = (String) serviceRequestInputs.get("CallSource");
306                         if("ExternalAPI".equalsIgnoreCase(callSource)) {
307                                 return false;
308                         }                                                       
309                 }
310                 for (String input : serviceRequestInputs.keySet())
311                 {
312                         if(input.toLowerCase().contains("sotnconnectivity")) {
313                                 return true;
314                         }
315                 }
316                 return false;
317         }
318         
319         @SuppressWarnings("unchecked")
320         private void allocateCrossTPResources(DelegateExecution execution, Map<String, Object> serviceRequestInputs) {
321
322                 Map<String, Object> crossTPs = this.getTPsfromAAI();
323                 
324                 if(crossTPs == null || crossTPs.isEmpty()) {
325                         serviceRequestInputs.put("local-access-provider-id", "");
326                         serviceRequestInputs.put("local-access-client-id", "");
327                         serviceRequestInputs.put("local-access-topology-id", "");
328                         serviceRequestInputs.put("local-access-node-id", "");
329                         serviceRequestInputs.put("local-access-ltp-id", "");
330                         serviceRequestInputs.put("remote-access-provider-id", "");
331                         serviceRequestInputs.put("remote-access-client-id", "");
332                         serviceRequestInputs.put("remote-access-topology-id", "");
333                         serviceRequestInputs.put("remote-access-node-id", "");
334                         serviceRequestInputs.put("remote-access-ltp-id", "");                   
335                 }
336                 else {
337                         serviceRequestInputs.put("local-access-provider-id", crossTPs.get("local-access-provider-id"));
338                         serviceRequestInputs.put("local-access-client-id", crossTPs.get("local-access-client-id"));
339                         serviceRequestInputs.put("local-access-topology-id", crossTPs.get("local-access-topology-id"));
340                         serviceRequestInputs.put("local-access-node-id", crossTPs.get("local-access-node-id"));
341                         serviceRequestInputs.put("local-access-ltp-id", crossTPs.get("local-access-ltp-id"));
342                         serviceRequestInputs.put("remote-access-provider-id", crossTPs.get("remote-access-provider-id"));
343                         serviceRequestInputs.put("remote-access-client-id", crossTPs.get("remote-client-id"));
344                         serviceRequestInputs.put("remote-access-topology-id", crossTPs.get("remote-topology-id"));
345                         serviceRequestInputs.put("remote-access-node-id", crossTPs.get("remote-node-id"));
346                         serviceRequestInputs.put("remote-access-ltp-id", crossTPs.get("remote-ltp-id"));
347                 }
348                 
349                 return;
350         }
351
352         // This method returns Local and remote TPs information from AAI        
353         public Map getTPsfromAAI() {
354                 Map<String, Object> tpInfo = new HashMap<>();
355                 
356                 AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.LOGICAL_LINK);
357                 AAIResourcesClient client = new AAIResourcesClient();
358                 Optional<LogicalLinks> result = client.get(LogicalLinks.class, uri);
359                 
360                 if (result.isPresent()) {
361                         LogicalLinks links = result.get();
362                         boolean isRemoteLink = false;
363                         
364                         links.getLogicalLink();
365                         
366                         for (LogicalLink link : links.getLogicalLink()) {
367                                 AAIResultWrapper wrapper = new AAIResultWrapper(link);
368                                 Optional<Relationships> optRelationships = wrapper.getRelationships();
369                                 List<AAIResourceUri> pInterfaces = new ArrayList<>();
370                                 if (optRelationships.isPresent()) {
371                                         Relationships relationships = optRelationships.get();
372                                         if (!relationships.getRelatedAAIUris(AAIObjectType.EXT_AAI_NETWORK).isEmpty()) {
373                                                 isRemoteLink = true;
374                                         }
375                                         pInterfaces.addAll(relationships.getRelatedAAIUris(AAIObjectType.P_INTERFACE));
376                                 }
377                                 
378                                 if (isRemoteLink) {
379                                         // find remote p interface
380                                         AAIResourceUri localTP = null;
381                                         AAIResourceUri remoteTP = null;
382
383                                         AAIResourceUri pInterface0 = pInterfaces.get(0);
384
385                                         if (isRemotePInterface(client, pInterface0)) {
386                                                 remoteTP = pInterfaces.get(0);
387                                                 localTP = pInterfaces.get(1);
388                                         } else {
389                                                 localTP = pInterfaces.get(0);
390                                                 remoteTP = pInterfaces.get(1);
391                                         }
392
393                                         if (localTP != null && remoteTP != null) {
394                                                 // give local tp
395                                                 String tpUrl = localTP.build().toString();
396                                                 PInterface intfLocal = client.get(PInterface.class, localTP).get();
397                                                 tpInfo.put("local-access-node-id", tpUrl.split("/")[6]);
398                                         
399                                                 String[] networkRef = intfLocal.getNetworkRef().split("/");
400                                                 if (networkRef.length == 6) {
401                                                         tpInfo.put("local-access-provider-id", networkRef[1]);
402                                                         tpInfo.put("local-access-client-id", networkRef[3]);
403                                                         tpInfo.put("local-access-topology-id", networkRef[5]);
404                                                 }
405                                                 String ltpIdStr = tpUrl.substring(tpUrl.lastIndexOf("/") + 1);
406                                                 if (ltpIdStr.contains("-")) {
407                                                         tpInfo.put("local-access-ltp-id", ltpIdStr.substring(ltpIdStr.lastIndexOf("-") + 1));
408                                                 }
409                                                 
410                                                 // give remote tp
411                                                 tpUrl = remoteTP.build().toString();
412                                                 PInterface intfRemote = client.get(PInterface.class, remoteTP).get();
413                                                 tpInfo.put("remote-access-node-id", tpUrl.split("/")[6]);
414
415                                                 String[] networkRefRemote = intfRemote.getNetworkRef().split("/");
416
417                                                 if (networkRefRemote.length == 6) {
418                                                         tpInfo.put("remote-access-provider-id", networkRefRemote[1]);
419                                                         tpInfo.put("remote-access-client-id", networkRefRemote[3]);
420                                                         tpInfo.put("remote-access-topology-id", networkRefRemote[5]);
421                                                 }
422                                                 String ltpIdStrR = tpUrl.substring(tpUrl.lastIndexOf("/") + 1);
423                                                 if (ltpIdStrR.contains("-")) {
424                                                         tpInfo.put("remote-access-ltp-id", ltpIdStrR.substring(ltpIdStr.lastIndexOf("-") + 1));
425                                                 }
426                                                 return tpInfo;
427                                         }
428                                 }
429                         }
430                 }
431                 return tpInfo;
432         }
433
434         // this method check if pInterface is remote
435         private boolean isRemotePInterface(AAIResourcesClient client, AAIResourceUri uri) {
436                 
437                 Map<String, String> keys = uri.getURIKeys();
438                 String uriString = uri.build().toString();
439                 AAIResourceUri parent = AAIUriFactory.createResourceUri(AAIObjectType.PNF, keys.get("pnf-name"));
440                 
441                 AAIResultWrapper wrapper = client.get(parent);
442                 Optional<Relationships> optRelationships = wrapper.getRelationships();
443                 if (optRelationships.isPresent()) {
444                         Relationships relationships = optRelationships.get();
445                         
446                         return !relationships.getRelatedAAIUris(AAIObjectType.EXT_AAI_NETWORK).isEmpty();
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<String, String>();
560                 locationSrc.put("location", srcLocation);
561                 Map<String, String> locationDst = new HashMap<String, String>();
562                 locationDst.put("location", dstLocation);
563                 List<Map<String, String>> locations = new ArrayList<Map<String, String>>();
564                 locations.add(locationSrc);
565                 locations.add(locationDst);
566                 List<Object> returnList = new ArrayList<Object>();
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<String, Object>();
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<Object>();
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                 vpnRequestInputs.putAll(returnRoute);
632                 String newRequest = getJsonString(uuiObject);
633                 return newRequest;
634         }
635         
636         private Map<String, Object> getReturnRoute(List<Object> returnList){
637                 Map<String, Object> returnRoute = new HashMap<String,Object>();
638                 for(Object returnVpn :returnList){
639                         Map<String, Object> returnVpnInfo = (Map<String, Object>) returnVpn;
640                     String accessTopoId = (String)returnVpnInfo.get("access-topology-id");
641                         if("100".equals(accessTopoId)){
642                                 returnRoute.putAll(returnVpnInfo);
643                         }
644                         else if("101".equals(accessTopoId)){
645                                 for(String key : returnVpnInfo.keySet()){
646                                         returnRoute.put("domain1-" + key, returnVpnInfo.get(key));
647                                 }
648                         }
649                         else if("102".equals(accessTopoId)){
650                                 for(String key : returnVpnInfo.keySet()){
651                                         returnRoute.put("domain2-" + key, returnVpnInfo.get(key));
652                                 }
653                         }
654                         else{
655                                 for(String key : returnVpnInfo.keySet()){
656                                         returnRoute.put("domain" + accessTopoId +"-" + key, returnVpnInfo.get(key));
657                                 }
658                         }
659                 }
660                 return returnRoute;
661         }
662
663         private Map<String, Object> getResourceParams(Execution execution, String resourceCustomizationUuid,
664                         String serviceParameters) {
665                 List<String> resourceList = jsonUtil.StringArrayToList(execution,
666                                 (String) JsonUtils.getJsonValue(serviceParameters, "resources"));
667                 // Get the right location str for resource. default is an empty array.
668                 String resourceInputsFromUui = "";
669                 for (String resource : resourceList) {
670                         String resCusUuid = (String) JsonUtils.getJsonValue(resource, "resourceCustomizationUuid");
671                         if (resourceCustomizationUuid.equals(resCusUuid)) {
672                                 String resourceParameters = JsonUtils.getJsonValue(resource, "parameters");
673                                 resourceInputsFromUui = JsonUtils.getJsonValue(resourceParameters, "requestInputs");
674                         }
675                 }
676                 Map<String, Object> resourceInputsFromUuiMap = getJsonObject(resourceInputsFromUui, Map.class);
677                 return resourceInputsFromUuiMap;
678         }
679
680         public static <T> T getJsonObject(String jsonstr, Class<T> type) {
681                 ObjectMapper mapper = new ObjectMapper();
682                 mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
683                 try {
684                         return mapper.readValue(jsonstr, type);
685                 } catch (IOException e) {
686                         LOGGER.error(MessageEnum.RA_NS_EXC, "", "", MsoLogger.ErrorCode.BusinessProcesssError,
687                                         "fail to unMarshal json", e);
688                 }
689                 return null;
690         }
691
692         public static String getJsonString(Object srcObj) {
693                 ObjectMapper mapper = new ObjectMapper();
694                 mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
695                 String jsonStr = null;
696                 try {
697                         jsonStr = mapper.writeValueAsString(srcObj);
698                 } catch (JsonProcessingException e) {
699                         LOGGER.debug("SdcToscaParserException", e);
700                 }
701                 return jsonStr;
702         }
703
704         private static String sendRequest(String url, String methodType, String content) {
705                 
706                 String msbUrl = url;
707                 HttpRequestBase method = null;
708                 HttpResponse httpResponse = null;
709
710                 try {
711                         int timeout = DEFAULT_TIME_OUT;
712
713                         RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout)
714                                         .setConnectionRequestTimeout(timeout).build();
715
716                         HttpClient client = HttpClientBuilder.create().build();
717
718                         if ("POST".equals(methodType.toUpperCase())) {
719                                 HttpPost httpPost = new HttpPost(msbUrl);
720                                 httpPost.setConfig(requestConfig);
721                                 httpPost.setEntity(new StringEntity(content, ContentType.APPLICATION_JSON));
722                                 method = httpPost;
723                         } else if ("PUT".equals(methodType.toUpperCase())) {
724                                 HttpPut httpPut = new HttpPut(msbUrl);
725                                 httpPut.setConfig(requestConfig);
726                                 httpPut.setEntity(new StringEntity(content, ContentType.APPLICATION_JSON));
727                                 method = httpPut;
728                         } else if ("GET".equals(methodType.toUpperCase())) {
729                                 HttpGet httpGet = new HttpGet(msbUrl);
730                                 httpGet.setConfig(requestConfig);
731                                 httpGet.addHeader("X-FromAppId", "MSO");
732                                 httpGet.addHeader("Accept","application/json");
733                                 method = httpGet;
734                         } else if ("DELETE".equals(methodType.toUpperCase())) {
735                                 HttpDelete httpDelete = new HttpDelete(msbUrl);
736                                 httpDelete.setConfig(requestConfig);
737                                 method = httpDelete;
738                         }
739
740                         // now have no auth
741                         // String userCredentials =
742                         // SDNCAdapterProperties.getEncryptedProperty(Constants.SDNC_AUTH_PROP,
743                         // Constants.DEFAULT_SDNC_AUTH, Constants.ENCRYPTION_KEY);
744                         // String authorization = "Basic " +
745                         // DatatypeConverter.printBase64Binary(userCredentials.getBytes());
746                         // method.setHeader("Authorization", authorization);
747
748                         httpResponse = client.execute(method);
749                         String responseContent = null;
750                         if (null != httpResponse && httpResponse.getEntity() != null) {
751                                 try {
752                                         responseContent = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
753                                 } catch (ParseException e) {
754                                         LOGGER.debug("ParseException in sendrequest", e);
755                                 } catch (IOException e) {
756                                         LOGGER.debug("IOException in sendrequest", e);
757                                 }
758                         }
759                         if (null != method) {
760                                 method.reset();
761                         }
762                         method = null;
763                         return responseContent;
764
765                 } catch (SocketTimeoutException | ConnectTimeoutException e) {
766                         return null;
767
768                 } catch (Exception e) {
769                         return null;
770
771                 } finally {
772                         if (httpResponse != null) {
773                                 try {
774                                         EntityUtils.consume(httpResponse.getEntity());
775                                 } catch (Exception e) {
776                                 }
777                         }
778                         if (method != null) {
779                                 try {
780                                         method.reset();
781                                 } catch (Exception e) {
782
783                                 }
784                         }
785                 }
786         }
787 }