Merge "Bpmn to cnf adapter implementation testing bpmn"
[so.git] / bpmn / MSOCommonBPMN / src / main / groovy / org / onap / so / bpmn / common / scripts / OofUtils.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2018 Intel Corp. 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.common.scripts
24
25 import org.onap.so.beans.nsmf.oof.NsiReqBody
26 import org.onap.so.beans.nsmf.oof.NssiReqBody
27 import org.onap.so.beans.nsmf.oof.RequestInfo
28 import org.onap.so.beans.nsmf.oof.SubnetCapability
29 import org.onap.so.beans.nsmf.oof.TemplateInfo
30
31 import static org.onap.so.bpmn.common.scripts.GenericUtils.*
32
33 import javax.ws.rs.core.UriBuilder
34
35 import org.camunda.bpm.engine.delegate.DelegateExecution
36 import org.onap.so.bpmn.common.util.OofInfraUtils
37 import org.onap.so.bpmn.core.UrnPropertiesReader
38 import org.onap.so.bpmn.core.domain.AllottedResource
39 import org.onap.so.bpmn.core.domain.HomingSolution
40 import org.onap.so.bpmn.core.domain.ModelInfo
41 import org.onap.so.bpmn.core.domain.Resource
42 import org.onap.so.bpmn.core.domain.ServiceDecomposition
43 import org.onap.so.bpmn.core.domain.ServiceInstance
44 import org.onap.so.bpmn.core.domain.Subscriber
45 import org.onap.so.bpmn.core.domain.VnfResource
46 import org.onap.so.bpmn.core.json.JsonUtils
47 import org.onap.so.db.catalog.beans.CloudSite
48 import org.onap.so.db.catalog.beans.HomingInstance
49 import org.slf4j.Logger
50 import org.slf4j.LoggerFactory
51 import com.google.gson.JsonObject
52
53 import com.fasterxml.jackson.databind.ObjectMapper
54
55 class OofUtils {
56     private static final Logger logger = LoggerFactory.getLogger( OofUtils.class);
57
58     ExceptionUtil exceptionUtil = new ExceptionUtil()
59     JsonUtils jsonUtil = new JsonUtils()
60     OofInfraUtils oofInfraUtils = new OofInfraUtils()
61
62     private AbstractServiceTaskProcessor utils
63
64     OofUtils(AbstractServiceTaskProcessor taskProcessor) {
65         this.utils = taskProcessor
66     }
67
68     /**
69      * This method builds the service-agnostic
70      * OOF json request to get a homing solution
71      * and license solution
72      *
73      * @param execution
74      * @param requestId
75      * @param decomposition - ServiceDecomposition object
76      * @param customerLocation -
77      * @param existingCandidates -
78      * @param excludedCandidates -
79      * @param requiredCandidates -
80      *
81      * @return request - OOF v1 payload - https://wiki.onap.org/pages/viewpage.action?pageId=25435066
82      */
83     String buildRequest(DelegateExecution execution,
84                         String requestId,
85                         ServiceDecomposition decomposition,
86                         Subscriber subscriber = null,
87                         Map customerLocation,
88                         ArrayList existingCandidates = null,
89                         ArrayList excludedCandidates = null,
90                         ArrayList requiredCandidates = null) {
91         logger.debug( "Started Building OOF Request")
92         String callbackEndpoint = UrnPropertiesReader.getVariable("mso.oof.callbackEndpoint", execution)
93         logger.debug( "mso.oof.callbackEndpoint is: " + callbackEndpoint)
94         try {
95             def callbackUrl = utils.createHomingCallbackURL(callbackEndpoint, "oofResponse", requestId)
96             logger.debug( "callbackUrl is: " + callbackUrl)
97
98
99             def transactionId = requestId
100             logger.debug( "transactionId is: " + transactionId)
101             //ServiceInstance Info
102             ServiceInstance serviceInstance = decomposition.getServiceInstance()
103             def serviceInstanceId = ""
104             def serviceName = ""
105
106             serviceInstanceId = execution.getVariable("serviceInstanceId")
107             logger.debug( "serviceInstanceId is: " + serviceInstanceId)
108             serviceName = execution.getVariable("subscriptionServiceType")
109             logger.debug( "serviceName is: " + serviceName)
110
111             if (serviceInstanceId == null || serviceInstanceId == "null") {
112                 logger.debug( "Unable to obtain Service Instance Id")
113                 exceptionUtil.buildAndThrowWorkflowException(execution, 400, "Internal Error - Unable to " +
114                         "obtain Service Instance Id, execution.getVariable(\"serviceInstanceId\") is null")
115             }
116             if (serviceName == null || serviceName == "null") {
117                 logger.debug( "Unable to obtain Service Name")
118                 exceptionUtil.buildAndThrowWorkflowException(execution, 400, "Internal Error - Unable to " +
119                         "obtain Service Name, execution.getVariable(\"subscriptionServiceType\") is null")
120             }
121             //Model Info
122             ModelInfo model = decomposition.getModelInfo()
123             logger.debug( "ModelInfo: " + model.toString())
124             String modelType = model.getModelType()
125             String modelInvariantId = model.getModelInvariantUuid()
126             String modelVersionId = model.getModelUuid()
127             String modelName = model.getModelName()
128             String modelVersion = model.getModelVersion()
129             //Subscriber Info
130             String subscriberId = ""
131             String subscriberName = ""
132             String commonSiteId = ""
133             if (subscriber != null) {
134                 subscriberId = subscriber.getGlobalId()
135                 subscriberName = subscriber.getName()
136                 commonSiteId = subscriber.getCommonSiteId()
137             }
138
139             //Determine RequestType
140             //TODO Figure out better way to determine this
141             String requestType = "create"
142             List<Resource> resources = decomposition.getServiceResources()
143             for (Resource r : resources) {
144                 HomingSolution currentSolution = (HomingSolution) r.getCurrentHomingSolution()
145                 if (currentSolution != null) {
146                     requestType = "speed changed"
147                 }
148             }
149
150             //Demands
151             String placementDemands = ""
152             StringBuilder sb = new StringBuilder()
153             List<AllottedResource> allottedResourceList = decomposition.getAllottedResources()
154             List<VnfResource> vnfResourceList = decomposition.getVnfResources()
155
156             if (allottedResourceList == null || allottedResourceList.isEmpty()) {
157                 logger.debug( "Allotted Resources List is empty - will try to get service VNFs instead.")
158             } else {
159                 for (AllottedResource resource : allottedResourceList) {
160                     logger.debug( "Allotted Resource: " + resource.toString())
161                     def serviceResourceId = resource.getResourceId()
162                     def toscaNodeType = resource.getToscaNodeType()
163                     def resourceModuleName = toscaNodeType.substring(toscaNodeType.lastIndexOf(".") + 1)
164                     def resourceModelInvariantId = resource.getModelInfo().getModelInvariantUuid()
165                     def resourceModelVersionId = resource.getModelInfo().getModelUuid()
166                     def resourceModelName = resource.getModelInfo().getModelName()
167                     def resourceModelVersion = resource.getModelInfo().getModelVersion()
168                     def resourceModelType = resource.getModelInfo().getModelType()
169                     def tenantId = execution.getVariable("tenantId")
170                     def requiredCandidatesJson = ""
171
172                     requiredCandidatesJson = createCandidateJson(
173                             existingCandidates,
174                             excludedCandidates,
175                             requiredCandidates)
176
177                     String demand =
178                             "      {\n" +
179                                     "      \"resourceModuleName\": \"${resourceModuleName}\",\n" +
180                                     "      \"serviceResourceId\": \"${serviceResourceId}\",\n" +
181                                     "      \"tenantId\": \"${tenantId}\",\n" +
182                                     "      \"resourceModelInfo\": {\n" +
183                                     "        \"modelInvariantId\": \"${resourceModelInvariantId}\",\n" +
184                                     "        \"modelVersionId\": \"${resourceModelVersionId}\",\n" +
185                                     "        \"modelName\": \"${resourceModelName}\",\n" +
186                                     "        \"modelType\": \"${resourceModelType}\",\n" +
187                                     "        \"modelVersion\": \"${resourceModelVersion}\",\n" +
188                                     "        \"modelCustomizationName\": \"\"\n" +
189                                     "        }" + requiredCandidatesJson + "\n" +
190                                     "      },"
191
192                     placementDemands = sb.append(demand)
193                 }
194             }
195
196             if (vnfResourceList == null || vnfResourceList.isEmpty()) {
197                 logger.debug( "VNF Resources List is empty")
198             } else {
199
200                 for (VnfResource vnfResource : vnfResourceList) {
201                     logger.debug( "VNF Resource: " + vnfResource.toString())
202                     ModelInfo vnfResourceModelInfo = vnfResource.getModelInfo()
203                     def toscaNodeType = vnfResource.getToscaNodeType()
204                     def resourceModuleName = toscaNodeType.substring(toscaNodeType.lastIndexOf(".") + 1)
205                     def serviceResourceId = vnfResource.getResourceId()
206                     def resourceModelInvariantId = vnfResourceModelInfo.getModelInvariantUuid()
207                     def resourceModelName = vnfResourceModelInfo.getModelName()
208                     def resourceModelVersion = vnfResourceModelInfo.getModelVersion()
209                     def resourceModelVersionId = vnfResourceModelInfo.getModelUuid()
210                     def resourceModelType = vnfResourceModelInfo.getModelType()
211                     def tenantId = execution.getVariable("tenantId")
212                     def requiredCandidatesJson = ""
213
214
215                     String placementDemand =
216                             "      {\n" +
217                                     "      \"resourceModuleName\": \"${resourceModuleName}\",\n" +
218                                     "      \"serviceResourceId\": \"${serviceResourceId}\",\n" +
219                                     "      \"tenantId\": \"${tenantId}\",\n" +
220                                     "      \"resourceModelInfo\": {\n" +
221                                     "        \"modelInvariantId\": \"${resourceModelInvariantId}\",\n" +
222                                     "        \"modelVersionId\": \"${resourceModelVersionId}\",\n" +
223                                     "        \"modelName\": \"${resourceModelName}\",\n" +
224                                     "        \"modelType\": \"${resourceModelType}\",\n" +
225                                     "        \"modelVersion\": \"${resourceModelVersion}\",\n" +
226                                     "        \"modelCustomizationName\": \"\"\n" +
227                                     "        }" + requiredCandidatesJson + "\n" +
228                                     "      },"
229
230                     placementDemands = sb.append(placementDemand)
231                 }
232                 placementDemands = placementDemands.substring(0, placementDemands.length() - 1)
233             }
234
235             /* Commenting Out Licensing as OOF doesn't support for Beijing
236         String licenseDemands = ""
237         sb = new StringBuilder()
238         if (vnfResourceList.isEmpty() || vnfResourceList == null) {
239             logger.debug( "Vnf Resources List is Empty")
240         } else {
241             for (VnfResource vnfResource : vnfResourceList) {
242                 ModelInfo vnfResourceModelInfo = vnfResource.getModelInfo()
243                 def resourceInstanceType = vnfResource.getResourceType()
244                 def serviceResourceId = vnfResource.getResourceId()
245                 def resourceModuleName = vnfResource.getResourceType()
246                 def resouceModelInvariantId = vnfResourceModelInfo.getModelInvariantUuid()
247                 def resouceModelName = vnfResourceModelInfo.getModelName()
248                 def resouceModelVersion = vnfResourceModelInfo.getModelVersion()
249                 def resouceModelVersionId = vnfResourceModelInfo.getModelUuid()
250                 def resouceModelType = vnfResourceModelInfo.getModelType()
251
252                 // TODO Add Existing Licenses to demand
253                 //"existingLicenses": {
254                 //"entitlementPoolUUID": ["87257b49-9602-4ca1-9817-094e52bc873b",
255                 // "43257b49-9602-4fe5-9337-094e52bc9435"],
256                 //"licenseKeyGroupUUID": ["87257b49-9602-4ca1-9817-094e52bc873b",
257                 // "43257b49-9602-4fe5-9337-094e52bc9435"]
258                 //}
259
260                     String licenseDemand =
261                         "{\n" +
262                         "\"resourceModuleName\": \"${resourceModuleName}\",\n" +
263                         "\"serviceResourceId\": \"${serviceResourceId}\",\n" +
264                         "\"resourceInstanceType\": \"${resourceInstanceType}\",\n" +
265                         "\"resourceModelInfo\": {\n" +
266                         "  \"modelInvariantId\": \"${resouceModelInvariantId}\",\n" +
267                         "  \"modelVersionId\": \"${resouceModelVersionId}\",\n" +
268                         "  \"modelName\": \"${resouceModelName}\",\n" +
269                         "  \"modelType\": \"${resouceModelType}\",\n" +
270                         "  \"modelVersion\": \"${resouceModelVersion}\",\n" +
271                         "  \"modelCustomizationName\": \"\"\n" +
272                         "  }\n"
273                         "},"
274
275                 licenseDemands = sb.append(licenseDemand)
276             }
277             licenseDemands = licenseDemands.substring(0, licenseDemands.length() - 1)
278         }*/
279
280             String request =
281                     "{\n" +
282                             "  \"requestInfo\": {\n" +
283                             "    \"transactionId\": \"${transactionId}\",\n" +
284                             "    \"requestId\": \"${requestId}\",\n" +
285                             "    \"callbackUrl\": \"${callbackUrl}\",\n" +
286                             "    \"sourceId\": \"so\",\n" +
287                             "    \"requestType\": \"${requestType}\"," +
288                             "    \"numSolutions\": 1,\n" +
289                             "    \"optimizers\": [\"placement\"],\n" +
290                             "    \"timeout\": 600\n" +
291                             "    },\n" +
292                             "  \"placementInfo\": {\n" +
293                             "    \"requestParameters\": {\n" +
294                             "      \"customerLatitude\": \"${customerLocation.customerLatitude}\",\n" +
295                             "      \"customerLongitude\": \"${customerLocation.customerLongitude}\",\n" +
296                             "      \"customerName\": \"${customerLocation.customerName}\"\n" +
297                             "    }," +
298                             "    \"subscriberInfo\": { \n" +
299                             "      \"globalSubscriberId\": \"${subscriberId}\",\n" +
300                             "      \"subscriberName\": \"${subscriberName}\",\n" +
301                             "      \"subscriberCommonSiteId\": \"${commonSiteId}\"\n" +
302                             "    },\n" +
303                             "    \"placementDemands\": [\n" +
304                             "      ${placementDemands}\n" +
305                             "      ]\n" +
306                             "    },\n" +
307                             "  \"serviceInfo\": {\n" +
308                             "    \"serviceInstanceId\": \"${serviceInstanceId}\",\n" +
309                             "    \"serviceName\": \"${serviceName}\",\n" +
310                             "    \"modelInfo\": {\n" +
311                             "      \"modelType\": \"${modelType}\",\n" +
312                             "      \"modelInvariantId\": \"${modelInvariantId}\",\n" +
313                             "      \"modelVersionId\": \"${modelVersionId}\",\n" +
314                             "      \"modelName\": \"${modelName}\",\n" +
315                             "      \"modelVersion\": \"${modelVersion}\",\n" +
316                             "      \"modelCustomizationName\": \"\"\n" +
317                             "    }\n" +
318                             "  }\n" +
319                             "}"
320
321
322             logger.debug( "Completed Building OOF Request")
323             return request
324         } catch (Exception ex) {
325              logger.debug( "buildRequest Exception: " + ex)
326         }
327     }
328
329     /**
330      * This method validates the callback response
331      * from OOF. If the response contains an
332      * exception the method will build and throw
333      * a workflow exception.
334      *
335      * @param execution
336      * @param response - the async callback response from oof
337      */
338     Void validateCallbackResponse(DelegateExecution execution, String response) {
339         String placements = ""
340         if (isBlank(response)) {
341             exceptionUtil.buildAndThrowWorkflowException(execution, 5000, "OOF Async Callback Response is Empty")
342         } else {
343             if (JsonUtils.jsonElementExist(response, "solutions.placementSolutions")) {
344                 placements = jsonUtil.getJsonValue(response, "solutions.placementSolutions")
345                 if (isBlank(placements) || placements.equalsIgnoreCase("[]")) {
346                     String statusMessage = jsonUtil.getJsonValue(response, "statusMessage")
347                     if (isBlank(statusMessage)) {
348                         logger.debug( "Error Occurred in Homing: OOF Async Callback Response does " +
349                                 "not contain placement solution.")
350                         exceptionUtil.buildAndThrowWorkflowException(execution, 400,
351                                 "OOF Async Callback Response does not contain placement solution.")
352                     } else {
353                         logger.debug( "Error Occurred in Homing: " + statusMessage)
354                         exceptionUtil.buildAndThrowWorkflowException(execution, 400, statusMessage)
355                     }
356                 } else {
357                     return
358                 }
359             } else if (response.contains("error") || response.contains("Error") ) {
360                 String errorMessage = ""
361                 if (response.contains("policyException")) {
362                     String text = jsonUtil.getJsonValue(response, "requestError.policyException.text")
363                     errorMessage = "OOF Async Callback Response contains a Request Error Policy Exception: " + text
364                 } else if (response.contains("Unable to find any candidate for demand")) {
365                     errorMessage = "OOF Async Callback Response contains error: Unable to find any candidate for " +
366                             "demand *** Response: " + response.toString()
367                 } else if (response.contains("serviceException")) {
368                     String text = jsonUtil.getJsonValue(response, "requestError.serviceException.text")
369                     errorMessage = "OOF Async Callback Response contains a Request Error Service Exception: " + text
370                 } else {
371                     errorMessage = "OOF Async Callback Response contains a Request Error. Unable to determine the Request Error Exception."
372                 }
373                 logger.debug( "Error Occurred in Homing: " + errorMessage)
374                 exceptionUtil.buildAndThrowWorkflowException(execution, 400, errorMessage)
375
376             } else {
377                 logger.debug( "Error Occurred in Homing: Received an Unknown Async Callback Response from OOF.")
378                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Received an Unknown Async Callback Response from OOF.")
379             }
380         }
381
382     }
383
384     /**
385      * This method creates candidates json for placement Demands.
386      *
387      * @param execution
388      * @param existingCandidates -
389      * @param excludedCandidates -
390      * @param requiredCandidates -
391      *
392      * @return candidatesJson - a JSON string with candidates
393      */
394     String createCandidateJson(ArrayList existingCandidates = null,
395                                ArrayList excludedCandidates = null,
396                                ArrayList requiredCandidates = null) {
397         def candidatesJson = ""
398         def type = ""
399         if (existingCandidates != null && existingCandidates != {}) {
400             sb = new StringBuilder()
401             sb.append(",\n" +
402                     "  \"existingCandidates\": [\n")
403             def existingCandidateJson = ""
404             existingCandidates.each { existingCandidate ->
405                 type = existingCandidate.get('identifierType')
406                 if (type == 'vimId') {
407                     def cloudOwner = existingCandidate.get('cloudOwner')
408                     def cloudRegionId = existingCandidate.get('identifiers')
409                     existingCandidateJson = "{\n" +
410                             "    \"identifierType\": \"vimId\",\n" +
411                             "    \"cloudOwner\": \"${cloudOwner}\",\n" +
412                             "    \"identifiers\": [\"${cloudRegionId}\"]\n" +
413                             "    },"
414                     sb.append(existingCandidateJson)
415                 }
416                 if (type == 'serviceInstanceId') {
417                     def serviceInstanceId = existingCandidate.get('identifiers')
418                     existingCandidateJson += "{\n" +
419                             "    \"identifierType\": \"serviceInstanceId\",\n" +
420                             "    \"identifiers\": [\"${serviceInstanceId}\"]\n" +
421                             "    },"
422                     sb.append(existingCandidateJson)
423                 }
424             }
425             if (existingCandidateJson != "") {
426                 sb.setLength(sb.length() - 1)
427                 candidatesJson = sb.append(",\n],")
428             }
429         }
430         if (excludedCandidates != null && excludedCandidates != {}) {
431             sb = new StringBuilder()
432             sb.append(",\n" +
433                     "  \"excludedCandidates\": [\n")
434             def excludedCandidateJson = ""
435             excludedCandidates.each { excludedCandidate ->
436                 type = excludedCandidate.get('identifierType')
437                 if (type == 'vimId') {
438                     def cloudOwner = excludedCandidate.get('cloudOwner')
439                     def cloudRegionId = excludedCandidate.get('identifiers')
440                     excludedCandidateJson = "{\n" +
441                             "    \"identifierType\": \"vimId\",\n" +
442                             "    \"cloudOwner\": \"${cloudOwner}\",\n" +
443                             "    \"identifiers\": [\"${cloudRegionId}\"]\n" +
444                             "    },"
445                     sb.append(excludedCandidateJson)
446                 }
447                 if (type == 'serviceInstanceId') {
448                     def serviceInstanceId = excludedCandidate.get('identifiers')
449                     excludedCandidateJson += "{\n" +
450                             "    \"identifierType\": \"serviceInstanceId\",\n" +
451                             "    \"identifiers\": [\"${serviceInstanceId}\"]\n" +
452                             "    },"
453                     sb.append(excludedCandidateJson)
454                 }
455             }
456             if (excludedCandidateJson != "") {
457                 sb.setLength(sb.length() - 1)
458                 candidatesJson = sb.append(",\n],")
459             }
460         }
461         if (requiredCandidates != null && requiredCandidates != {}) {
462             sb = new StringBuilder()
463             sb.append(",\n" +
464                     "  \"requiredCandidates\": [\n")
465             def requiredCandidatesJson = ""
466             requiredCandidates.each { requiredCandidate ->
467                 type = requiredCandidate.get('identifierType')
468                 if (type == 'vimId') {
469                     def cloudOwner = requiredCandidate.get('cloudOwner')
470                     def cloudRegionId = requiredCandidate.get('identifiers')
471                     requiredCandidatesJson = "{\n" +
472                             "    \"identifierType\": \"vimId\",\n" +
473                             "    \"cloudOwner\": \"${cloudOwner}\",\n" +
474                             "    \"identifiers\": [\"${cloudRegionId}\"]\n" +
475                             "    },"
476                     sb.append(requiredCandidatesJson)
477                 }
478                 if (type == 'serviceInstanceId') {
479                     def serviceInstanceId = requiredCandidate.get('identifiers')
480                     requiredCandidatesJson += "{\n" +
481                             "    \"identifierType\": \"serviceInstanceId\",\n" +
482                             "    \"identifiers\": [\"${serviceInstanceId}\"]\n" +
483                             "    },"
484                     sb.append(requiredCandidatesJson)
485                 }
486             }
487             if (requiredCandidatesJson != "") {
488                 sb.setLength(sb.length() - 1)
489                 candidatesJson = sb.append(",\n],")
490             }
491         }
492         if (candidatesJson != "") {candidatesJson = candidatesJson.substring(0, candidatesJson.length() - 1)}
493         return candidatesJson
494     }
495
496     /**
497      * This method creates a cloudsite in catalog database.
498      *
499      * @param CloudSite cloudSite
500      *
501      * @return void
502      */
503     Void createCloudSite(CloudSite cloudSite, DelegateExecution execution) {
504         oofInfraUtils.createCloudSite(cloudSite, execution)
505     }
506
507     /**
508      * This method creates a HomingInstance in catalog database.
509      *
510      * @param HomingInstance homingInstance
511      *
512      * @return void
513      */
514     Void createHomingInstance(HomingInstance homingInstance, DelegateExecution execution) {
515         oofInfraUtils.createHomingInstance(homingInstance, execution)
516     }
517
518     String getMsbHost(DelegateExecution execution) {
519         String msbHost = UrnPropertiesReader.getVariable("mso.msb.host", execution, "msb-iag.onap")
520
521         Integer msbPort = UrnPropertiesReader.getVariable("mso.msb.port", execution, "80").toInteger()
522
523         return UriBuilder.fromPath("").host(msbHost).port(msbPort).scheme("http").build().toString()
524     }
525
526     public String buildSelectNSTRequest(String requestId,String messageType, Map<String, Object> profileInfo) {
527         def transactionId = requestId
528         logger.debug( "transactionId is: " + transactionId)
529                 String correlator = requestId
530         String callbackUrl = UrnPropertiesReader.getVariable("mso.adapters.oof.callback.endpoint") + "/" + messageType + "/" + correlator
531         ObjectMapper objectMapper = new ObjectMapper()
532         String json = objectMapper.writeValueAsString(profileInfo)
533         StringBuilder response = new StringBuilder()
534         response.append(
535                 "{\n" +
536                         "  \"requestInfo\": {\n" +
537                         "    \"transactionId\": \"${transactionId}\",\n" +
538                         "    \"requestId\": \"${requestId}\",\n" +
539                         "    \"sourceId\": \"so\",\n" +
540                         "    \"timeout\": 600,\n" +
541                         "    \"callbackUrl\": \"${callbackUrl}\"\n" +
542                         "    },\n")
543         response.append(" \"serviceProfile\": {\n" +
544                 "   \"serviceProfileParameters\": ")
545         response.append(json);
546         response.append("\n }\n")
547         response.append("\n}\n")
548         return response.toString()
549     }
550
551     public String buildSelectNSIRequest(String requestId, String nstInfo,String messageType, Map<String, Object> profileInfo){
552
553         def transactionId = requestId
554         logger.debug( "transactionId is: " + transactionId)
555                 String correlator = requestId
556         String callbackUrl = UrnPropertiesReader.getVariable("mso.adapters.oof.callback.endpoint") + "/" + messageType + "/" + correlator
557         ObjectMapper objectMapper = new ObjectMapper();
558         String json = objectMapper.writeValueAsString(profileInfo);
559         StringBuilder response = new StringBuilder();
560         response.append(
561                 "{\n" +
562                         "  \"requestInfo\": {\n" +
563                         "    \"transactionId\": \"${transactionId}\",\n" +
564                         "    \"requestId\": \"${requestId}\",\n" +
565                         "    \"sourceId\": \"so\",\n" +
566                         "    \"timeout\": 600,\n" +
567                         "    \"callbackUrl\": \"${callbackUrl}\"\n" +
568                         "    },\n" +
569                         "  \"serviceInfo\": {\n" +
570                         "    \"serviceInstanceId\": \"\",\n" +
571                         "    \"serviceName\": \"\"\n" +
572                         "    },\n" +
573                         "  \"NSTInfoList\": [\n")
574         response.append(nstInfo);
575         response.append("\n  ],\n")
576         response.append("\n \"serviceProfile\": \n")
577         response.append(json);
578         response.append("\n  }\n")
579         return response.toString()
580     }
581 /**
582 * Method to create select NSSI request
583 * @param requestId - mso-request-id
584 * @param messageType - Message type for callback correlation
585 * @param UUID - UUID of NSST
586 * @param invariantUUID - Invariant UUID of NSST
587 * @param name - name of the NSST model
588 * @param profileInfo - A JSON object containing slice profile parameters
589 * @return
590 */
591 public String buildSelectNSSIRequest(String requestId, String messageType, String UUID,String invariantUUID,
592 String name, Map<String, Object> profileInfo){
593
594 def transactionId = requestId
595 logger.debug( "transactionId is: " + transactionId)
596 String correlator = requestId
597 String callbackUrl = UrnPropertiesReader.getVariable("mso.adapters.oof.callback.endpoint") + "/" + messageType + "/" + correlator
598 ObjectMapper objectMapper = new ObjectMapper();
599 String profileJson = objectMapper.writeValueAsString(profileInfo);
600
601 //Prepare requestInfo object
602 JsonObject requestInfo = new JsonObject()
603 requestInfo.addProperty("transactionId", transactionId)
604 requestInfo.addProperty("requestId", requestId)
605 requestInfo.addProperty("callbackUrl", callbackUrl)
606 requestInfo.addProperty("sourceId","SO" )
607 requestInfo.addProperty("timeout", 600)
608 requestInfo.addProperty("numSolutions", 1)
609
610 //Prepare serviceInfo object
611 JsonObject nsstInfo = new JsonObject()
612 nsstInfo.addProperty("UUID", UUID)
613 nsstInfo.addProperty("invariantUUID", invariantUUID)
614 nsstInfo.addProperty("name", name)
615
616 JsonObject json = new JsonObject()
617 json.add("requestInfo", requestInfo)
618 json.add("NSSTInfo", nsstInfo)
619 json.addProperty("sliceProfile", profileJson)
620 return json.toString()
621 }
622 /**
623 * Method to create NSI/NSSI termination request
624 * (OOF response will be synchronous in G-Release)
625 * @param requestId - mso-request-id
626 * @param nxlId        - NSI/NSSI Id to be terminated
627 * @param messageType - Message type for callback correlation
628 * @param serviceInstanceId - NSI/NSSI Id related to nxlId
629 * @return
630 */
631 public String buildTerminateNxiRequest(String requestId,String nxlId, String nxlType, String messageType, String serviceInstanceId) {
632 def transactionId = requestId
633 logger.debug( "transactionId is: " + transactionId)
634 String correlator = requestId
635 String callbackUrl = UrnPropertiesReader.getVariable("mso.adapters.oof.callback.endpoint") + "/" + messageType + "/" + correlator
636 //Prepare Terminate Nxl Json
637 JsonObject json = new JsonObject()
638 json.addProperty("type", nxlType)
639 json.addProperty("NxIId", nxlId)
640  
641 //Prepare requestInfo object
642 JsonObject requestInfo = new JsonObject()
643 requestInfo.addProperty("transactionId", transactionId)
644 requestInfo.addProperty("requestId", requestId)
645 requestInfo.addProperty("callbackUrl", callbackUrl)
646 requestInfo.addProperty("sourceId","SO" )
647 requestInfo.addProperty("timeout", 600)
648  
649 //Prepare addtnlArgs object
650 JsonObject addtnlArgs = new JsonObject()
651 addtnlArgs.addProperty("serviceInstanceId", serviceInstanceId)
652  
653 requestInfo.add("addtnlArgs", addtnlArgs)
654 json.add("requestInfo", requestInfo)
655  
656 return json.toString()
657  
658 }
659
660     public String buildSelectNSIRequest(String requestId, TemplateInfo nstInfo, List<TemplateInfo> nsstInfo,
661                                         String messageType, Map<String, Object> serviceProfile,
662                                         List<SubnetCapability> subnetCapabilities, Integer timeOut){
663
664         def transactionId = requestId
665         String correlator = requestId
666         logger.debug( "transactionId is: " + transactionId)
667
668         String callbackUrl = UrnPropertiesReader.getVariable("mso.adapters.oof.callback.endpoint") + "/" + messageType + "/" + correlator
669
670         NsiReqBody nsiReqBody = new NsiReqBody()
671
672         RequestInfo requestInfo = new RequestInfo()
673         requestInfo.setRequestId(requestId)
674         requestInfo.setTransactionId(transactionId)
675         requestInfo.setCallbackUrl(callbackUrl)
676         requestInfo.setSourceId("so")
677         requestInfo.setTimeout(timeOut)
678         //requestInfo.setNumSolutions()
679
680         nsiReqBody.setRequestInfo(requestInfo)
681         nsiReqBody.setNSTInfo(nstInfo)
682         nsiReqBody.setServiceProfile(serviceProfile)
683         nsiReqBody.setSubnetCapabilities(subnetCapabilities)
684         nsiReqBody.setNSSTInfo(nsstInfo)
685
686
687         ObjectMapper objectMapper = new ObjectMapper()
688
689         return objectMapper.writeValueAsString(nsiReqBody)
690     }
691
692     public <T> String buildSelectNSSIRequest(String requestId, TemplateInfo nsstInfo, String messageType,
693                                              T sliceProfile, Integer timeOut){
694
695         def transactionId = requestId
696         String correlator = requestId
697         logger.debug( "transactionId is: " + transactionId)
698
699         String callbackUrl = UrnPropertiesReader.getVariable("mso.adapters.oof.callback.endpoint") + "/" + messageType + "/" + correlator
700
701         NssiReqBody nssiReqBody = new NssiReqBody()
702
703         RequestInfo requestInfo = new RequestInfo()
704         requestInfo.setRequestId(requestId)
705         requestInfo.setTransactionId(transactionId)
706         requestInfo.setCallbackUrl(callbackUrl)
707         requestInfo.setSourceId("so")
708         requestInfo.setTimeout(timeOut)
709         //requestInfo.setNumSolutions()
710
711         nssiReqBody.setRequestInfo(requestInfo)
712         nssiReqBody.setSliceProfile(sliceProfile)
713         nssiReqBody.setNSSTInfo(nsstInfo)
714
715
716         ObjectMapper objectMapper = new ObjectMapper()
717
718         return objectMapper.writeValueAsString(nssiReqBody)
719     }
720 }