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