22c4f95a6f9b8f94e2bdc8d72a1a662ff8dd3aa9
[so.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2018 Huawei Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Modifications Copyright (c) 2019 Samsung
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.so.bpmn.infrastructure.workflow.service;
24
25 import 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         if (locationTerminalPointList != null) {
557             Map<String, Object> tpInfoMap = (Map<String, Object>) locationTerminalPointList.get(0);
558
559             serviceRequestInputs.put("inner-src-access-provider-id", tpInfoMap.get("access-provider-id"));
560             serviceRequestInputs.put("inner-src-access-client-id", tpInfoMap.get("access-client-id"));
561             serviceRequestInputs.put("inner-src-access-topology-id", tpInfoMap.get("access-topology-id"));
562             serviceRequestInputs.put("inner-src-access-node-id", tpInfoMap.get("access-node-id"));
563             serviceRequestInputs.put("inner-src-access-ltp-id", tpInfoMap.get("access-ltp-id"));
564             tpInfoMap = (Map<String, Object>) locationTerminalPointList.get(1);
565
566             serviceRequestInputs.put("inner-dst-access-provider-id", tpInfoMap.get("access-provider-id"));
567             serviceRequestInputs.put("inner-dst-access-client-id", tpInfoMap.get("access-client-id"));
568             serviceRequestInputs.put("inner-dst-access-topology-id", tpInfoMap.get("access-topology-id"));
569             serviceRequestInputs.put("inner-dst-access-node-id", tpInfoMap.get("access-node-id"));
570             serviceRequestInputs.put("inner-dst-access-ltp-id", tpInfoMap.get("access-ltp-id"));
571         }
572         String newRequest = getJsonString(uuiObject);
573         return newRequest;
574     }
575
576     private List<Object> queryTerminalPointsFromServiceProviderSystem(String srcLocation, String dstLocation) {
577         Map<String, String> locationSrc = new HashMap<>();
578         locationSrc.put("location", srcLocation);
579         Map<String, String> locationDst = new HashMap<>();
580         locationDst.put("location", dstLocation);
581         List<Map<String, String>> locations = new ArrayList<>();
582         locations.add(locationSrc);
583         locations.add(locationDst);
584         List<Object> returnList = new ArrayList<>();
585         String reqContent = getJsonString(locations);
586         String url = getThirdSPEndPoint();
587         String responseContent = sendRequest(url, "POST", reqContent);
588         if (null != responseContent) {
589             returnList = getJsonObject(responseContent, List.class);
590         }
591         return returnList;
592     }
593
594     @SuppressWarnings("unchecked")
595     private Map<String, Object> getVPNResourceRequestInputs(List<Object> resources) {
596         for (Object resource : resources) {
597             Map<String, Object> resourceObject = (Map<String, Object>) resource;
598             Map<String, Object> resourceParametersObject = (Map<String, Object>) resourceObject.get("parameters");
599             Map<String, Object> resourceRequestInputs =
600                     (Map<String, Object>) resourceParametersObject.get("requestInputs");
601             for (Entry<String, Object> entry : resourceRequestInputs.entrySet()) {
602                 if (entry.getKey().toLowerCase().contains("vpntype")) {
603                     return resourceRequestInputs;
604                 }
605             }
606         }
607         return null;
608     }
609
610     public static void main(String args[]) {
611         String str =
612                 "restconf/config/GENERIC-RESOURCE-API:services/service/eca7e542-12ba-48de-8544-fac59303b14e/service-data/networks/network/aec07806-1671-4af2-b722-53c8e320a633/network-data/";
613
614         int index1 = str.indexOf("/network/");
615         int index2 = str.indexOf("/network-data");
616
617         String str1 = str.substring(index1 + "/network/".length(), index2);
618         System.out.println(str1);
619
620     }
621
622     @SuppressWarnings("unchecked")
623     private String doSOTNServiceHoming(ServiceDecomposition serviceDecomposition, String uuiRequest) {
624         // query the route for the service.
625         Map<String, Object> uuiObject = getJsonObject(uuiRequest, Map.class);
626         if (uuiObject == null) {
627             return uuiRequest;
628         }
629         Map<String, Object> serviceObject =
630                 (Map<String, Object>) uuiObject.getOrDefault("service", Collections.emptyMap());
631         Map<String, Object> serviceParametersObject =
632                 (Map<String, Object>) serviceObject.getOrDefault("parameters", Collections.emptyMap());
633         Map<String, Object> serviceRequestInputs =
634                 (Map<String, Object>) serviceParametersObject.getOrDefault("requestInputs", Collections.emptyMap());
635         Map<String, Object> oofQueryObject = new HashMap<>();
636         List<Object> resources =
637                 (List<Object>) serviceParametersObject.getOrDefault("resources", Collections.emptyList());
638         oofQueryObject.put("src-access-provider-id", serviceRequestInputs.get("inner-src-access-provider-id"));
639         oofQueryObject.put("src-access-client-id", serviceRequestInputs.get("inner-src-access-client-id"));
640         oofQueryObject.put("src-access-topology-id", serviceRequestInputs.get("inner-src-access-topology-id"));
641         oofQueryObject.put("src-access-node-id", serviceRequestInputs.get("inner-src-access-node-id"));
642         oofQueryObject.put("src-access-ltp-id", serviceRequestInputs.get("inner-src-access-ltp-id"));
643         oofQueryObject.put("dst-access-provider-id", serviceRequestInputs.get("inner-dst-access-provider-id"));
644         oofQueryObject.put("dst-access-client-id", serviceRequestInputs.get("inner-dst-access-client-id"));
645         oofQueryObject.put("dst-access-topology-id", serviceRequestInputs.get("inner-dst-access-topology-id"));
646         oofQueryObject.put("dst-access-node-id", serviceRequestInputs.get("inner-dst-access-node-id"));
647         oofQueryObject.put("dst-access-ltp-id", serviceRequestInputs.get("inner-dst-access-ltp-id"));
648         String oofRequestReq = getJsonString(oofQueryObject);
649         String url = getOOFCalcEndPoint();
650         String responseContent = sendRequest(url, "POST", oofRequestReq);
651
652         List<Object> returnList = new ArrayList<>();
653         if (null != responseContent) {
654             returnList = getJsonObject(responseContent, List.class);
655         }
656         // in demo we have only one VPN. no cross VPNs, so get first item.
657         Map<String, Object> returnRoute = getReturnRoute(returnList);
658         Map<String, Object> vpnRequestInputs = getVPNResourceRequestInputs(resources);
659         if (null != vpnRequestInputs) {
660             vpnRequestInputs.putAll(returnRoute);
661         }
662         return getJsonString(uuiObject);
663     }
664
665     private Map<String, Object> getReturnRoute(List<Object> returnList) {
666         Map<String, Object> returnRoute = new HashMap<>();
667         for (Object returnVpn : returnList) {
668             Map<String, Object> returnVpnInfo = (Map<String, Object>) returnVpn;
669             String accessTopoId = (String) returnVpnInfo.get("access-topology-id");
670             if ("100".equals(accessTopoId)) {
671                 returnRoute.putAll(returnVpnInfo);
672             } else if ("101".equals(accessTopoId)) {
673                 for (String key : returnVpnInfo.keySet()) {
674                     returnRoute.put("domain1-" + key, returnVpnInfo.get(key));
675                 }
676             } else if ("102".equals(accessTopoId)) {
677                 for (String key : returnVpnInfo.keySet()) {
678                     returnRoute.put("domain2-" + key, returnVpnInfo.get(key));
679                 }
680             } else {
681                 for (String key : returnVpnInfo.keySet()) {
682                     returnRoute.put("domain" + accessTopoId + "-" + key, returnVpnInfo.get(key));
683                 }
684             }
685         }
686         return returnRoute;
687     }
688
689     private Map<String, Object> getResourceParams(Execution execution, String resourceCustomizationUuid,
690             String serviceParameters) {
691         List<String> resourceList =
692                 jsonUtil.StringArrayToList(execution, JsonUtils.getJsonValue(serviceParameters, "resources"));
693         // Get the right location str for resource. default is an empty array.
694         String resourceInputsFromUui = "";
695         for (String resource : resourceList) {
696             String resCusUuid = JsonUtils.getJsonValue(resource, "resourceCustomizationUuid");
697             if (resourceCustomizationUuid.equals(resCusUuid)) {
698                 String resourceParameters = JsonUtils.getJsonValue(resource, "parameters");
699                 resourceInputsFromUui = JsonUtils.getJsonValue(resourceParameters, "requestInputs");
700             }
701         }
702         Map<String, Object> resourceInputsFromUuiMap = getJsonObject(resourceInputsFromUui, Map.class);
703         return resourceInputsFromUuiMap;
704     }
705
706     private static <T> T getJsonObject(String jsonstr, Class<T> type) {
707         ObjectMapper mapper = new ObjectMapper();
708         mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
709         try {
710             return mapper.readValue(jsonstr, type);
711         } catch (IOException e) {
712             logger.error("{} {} fail to unMarshal json", MessageEnum.RA_NS_EXC.toString(),
713                     ErrorCode.BusinessProcesssError.getValue(), e);
714         }
715         return null;
716     }
717
718     public static String getJsonString(Object srcObj) {
719         ObjectMapper mapper = new ObjectMapper();
720         mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
721         String jsonStr = null;
722         try {
723             jsonStr = mapper.writeValueAsString(srcObj);
724         } catch (JsonProcessingException e) {
725             logger.debug("SdcToscaParserException", e);
726         }
727         return jsonStr;
728     }
729
730     private static String sendRequest(String url, String methodType, String content) {
731
732         String msbUrl = url;
733         HttpRequestBase method = null;
734         HttpResponse httpResponse = null;
735
736         try {
737             int timeout = DEFAULT_TIME_OUT;
738
739             RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout)
740                     .setConnectionRequestTimeout(timeout).build();
741
742             HttpClient client = HttpClientBuilder.create().build();
743
744             if ("POST".equals(methodType.toUpperCase())) {
745                 HttpPost httpPost = new HttpPost(msbUrl);
746                 httpPost.setConfig(requestConfig);
747                 httpPost.setEntity(new StringEntity(content, ContentType.APPLICATION_JSON));
748                 method = httpPost;
749             } else if ("PUT".equals(methodType.toUpperCase())) {
750                 HttpPut httpPut = new HttpPut(msbUrl);
751                 httpPut.setConfig(requestConfig);
752                 httpPut.setEntity(new StringEntity(content, ContentType.APPLICATION_JSON));
753                 method = httpPut;
754             } else if ("GET".equals(methodType.toUpperCase())) {
755                 HttpGet httpGet = new HttpGet(msbUrl);
756                 httpGet.setConfig(requestConfig);
757                 httpGet.addHeader("X-FromAppId", "MSO");
758                 httpGet.addHeader("Accept", "application/json");
759                 method = httpGet;
760             } else if ("DELETE".equals(methodType.toUpperCase())) {
761                 HttpDelete httpDelete = new HttpDelete(msbUrl);
762                 httpDelete.setConfig(requestConfig);
763                 method = httpDelete;
764             }
765
766             httpResponse = client.execute(method);
767             String responseContent = null;
768             if (null != httpResponse && httpResponse.getEntity() != null) {
769                 try {
770                     responseContent = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
771                 } catch (ParseException e) {
772                     logger.debug("ParseException in sendrequest", e);
773                 } catch (IOException e) {
774                     logger.debug("IOException in sendrequest", e);
775                 }
776             }
777             if (null != method) {
778                 method.reset();
779             }
780             method = null;
781             return responseContent;
782
783         } catch (SocketTimeoutException | ConnectTimeoutException e) {
784             return null;
785
786         } catch (Exception e) {
787             return null;
788
789         } finally {
790             if (httpResponse != null) {
791                 try {
792                     EntityUtils.consume(httpResponse.getEntity());
793                 } catch (Exception e) {
794                 }
795             }
796             if (method != null) {
797                 try {
798                     method.reset();
799                 } catch (Exception e) {
800
801                 }
802             }
803         }
804     }
805 }