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