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