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