2  * ============LICENSE_START=======================================================
 
   4  * ================================================================================
 
   5  * Copyright (C) 2017 Huawei Technologies Co., Ltd. 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
 
  11  *      http://www.apache.org/licenses/LICENSE-2.0
 
  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=========================================================
 
  21 package org.onap.so.bpmn.infrastructure.scripts;
 
  23 import static org.apache.commons.lang3.StringUtils.*;
 
  25 import org.apache.commons.lang3.*
 
  26 import org.camunda.bpm.engine.delegate.BpmnError 
 
  27 import org.camunda.bpm.engine.delegate.DelegateExecution
 
  28 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor 
 
  29 import org.onap.so.bpmn.common.scripts.ExceptionUtil 
 
  30 import org.onap.so.bpmn.common.scripts.MsoUtils
 
  31 import org.onap.so.bpmn.core.json.JsonUtils 
 
  32 import org.onap.so.logger.MessageEnum
 
  33 import org.onap.so.logger.MsoLogger
 
  34 import org.onap.so.rest.APIResponse
 
  35 import org.onap.so.rest.RESTClient 
 
  36 import org.onap.so.rest.RESTConfig
 
  41  * This groovy class supports the <class>DoCreateVFCNetworkServiceInstance.bpmn</class> process.
 
  42  * flow for VFC Network Service Create
 
  44 public class CreateVFCNSResource extends AbstractServiceTaskProcessor {
 
  45         private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, CreateVFCNSResource.class);
 
  48     String vfcUrl = "/vfc/rest/v1/vfcadapter"
 
  50     String host = "http://mso.mso.testlab.openecomp.org:8080"
 
  52     ExceptionUtil exceptionUtil = new ExceptionUtil()
 
  54     JsonUtils jsonUtil = new JsonUtils()
 
  58      * Pre Process the BPMN Flow Request
 
  60      * generate the nsOperationKey
 
  61      * generate the nsParameters
 
  63     public void preProcessRequest (DelegateExecution execution) {
 
  64         JsonUtils jsonUtil = new JsonUtils()
 
  67        msoLogger.trace("preProcessRequest() ")
 
  69            //deal with nsName and Description
 
  70            String resourceInput = execution.getVariable("resourceInput")
 
  72            String resourceParameters = jsonUtil.getJsonValue(resourceInput, "resourceParameters")
 
  74            String resourceName = jsonUtil.getJsonValue(resourceInput, "resourceInstanceName")
 
  75            execution.setVariable("nsServiceName", resourceName)
 
  77            String nsServiceDescription = execution.getVariable("nsServiceDescription")
 
  78            msoLogger.info("nsServiceName:" + resourceName + " nsServiceDescription:" + nsServiceDescription)
 
  79            //deal with operation key
 
  80            String globalSubscriberId = jsonUtil.getJsonValue(resourceInput, "globalSubscriberId")
 
  81            msoLogger.info("globalSubscriberId:" + globalSubscriberId)
 
  82            //set local globalSubscriberId variable
 
  83            execution.setVariable("globalSubscriberId", globalSubscriberId);
 
  84            String serviceType = execution.getVariable("serviceType")
 
  85            msoLogger.info("serviceType:" + serviceType)
 
  87            String serviceId = execution.getVariable("serviceInstanceId")
 
  88            msoLogger.info("serviceId:" + serviceId)
 
  90            String operationId = jsonUtil.getJsonValue(resourceInput, "operationId")
 
  91            msoLogger.info("serviceType:" + serviceType)
 
  93            String nodeTemplateUUID = jsonUtil.getJsonValue(resourceInput, "resourceModelInfo.modelCustomizationUuid")
 
  94            String nsServiceModelUUID = jsonUtil.getJsonValue(resourceParameters, "requestInputs.nsd0_providing_service_uuid")
 
  95            msoLogger.info("nodeTemplateUUID:" + nodeTemplateUUID)
 
  97             * segmentInformation needed as a object of segment
 
 100             *     "nodeTemplateName":"",
 
 103             *       //this is the nsParameters sent to VF-C
 
 107            String nsParameters = jsonUtil.getJsonValue(resourceInput, "resourceParameters")
 
 108            msoLogger.info("nsParameters:" + nsParameters)
 
 109            String nsOperationKey = """{
 
 110                    "globalSubscriberId":"${globalSubscriberId}",
 
 111                    "serviceType":"${serviceType}",
 
 112                    "serviceId":"${serviceId}",
 
 113                    "operationId":"${operationId}",
 
 114                    "nodeTemplateUUID":"${nodeTemplateUUID}"
 
 116            execution.setVariable("nsOperationKey", nsOperationKey);
 
 117            execution.setVariable("nsParameters", nsParameters)
 
 118            execution.setVariable("nsServiceModelUUID", nsServiceModelUUID);
 
 121        } catch (BpmnError e) {
 
 123        } catch (Exception ex){
 
 124            msg = "Exception in preProcessRequest " + ex.getMessage()
 
 126            exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
 
 128        msoLogger.trace("Exit preProcessRequest ")
 
 134     public void createNetworkService(DelegateExecution execution) {
 
 135         msoLogger.trace("createNetworkService ")
 
 136         String nsOperationKey = execution.getVariable("nsOperationKey");
 
 137         String nsServiceModelUUID = execution.getVariable("nsServiceModelUUID");
 
 138         String nsParameters = execution.getVariable("nsParameters");
 
 139         String nsServiceName = execution.getVariable("nsServiceName")
 
 140         String nsServiceDescription = execution.getVariable("nsServiceDescription")
 
 141         String locationConstraints = jsonUtil.getJsonValue(nsParameters, "locationConstraints")
 
 142         String requestInputs = jsonUtil.getJsonValue(nsParameters, "requestInputs")
 
 144                 "nsServiceName":"${nsServiceName}",
 
 145                 "nsServiceDescription":"${nsServiceDescription}",
 
 146                 "nsServiceModelUUID":"${nsServiceModelUUID}",
 
 147                 "nsOperationKey":${nsOperationKey},
 
 149                      "locationConstraints":${locationConstraints},
 
 150                      "additionalParamForNs":${requestInputs}
 
 153         APIResponse apiResponse = postRequest(execution, host + vfcUrl + "/ns", reqBody)
 
 154         String returnCode = apiResponse.getStatusCode()
 
 155         String aaiResponseAsString = apiResponse.getResponseBodyAsString()
 
 156         String nsInstanceId = "";
 
 157         if(returnCode== "200" || returnCode == "201"){
 
 158             nsInstanceId =  jsonUtil.getJsonValue(aaiResponseAsString, "nsInstanceId")
 
 160         execution.setVariable("nsInstanceId", nsInstanceId)
 
 161         msoLogger.info(" *****Exit  createNetworkService *****")
 
 165      * instantiate NS task
 
 167     public void instantiateNetworkService(DelegateExecution execution) {
 
 168         msoLogger.trace("instantiateNetworkService ")
 
 169         String nsOperationKey = execution.getVariable("nsOperationKey");
 
 170         String nsParameters = execution.getVariable("nsParameters");
 
 171         String nsServiceName = execution.getVariable("nsServiceName")
 
 172         String nsServiceDescription = execution.getVariable("nsServiceDescription")
 
 174         "nsServiceName":"${nsServiceName}",
 
 175         "nsServiceDescription":"${nsServiceDescription}",
 
 176         "nsOperationKey":${nsOperationKey},
 
 177         "nsParameters":${nsParameters}
 
 179         String nsInstanceId = execution.getVariable("nsInstanceId")
 
 180         String url = host + vfcUrl + "/ns/" +nsInstanceId + "/instantiate"
 
 181         APIResponse apiResponse = postRequest(execution, url, reqBody)
 
 182         String returnCode = apiResponse.getStatusCode()
 
 183         String aaiResponseAsString = apiResponse.getResponseBodyAsString()
 
 185         if(returnCode== "200"|| returnCode == "201"){
 
 186             jobId =  jsonUtil.getJsonValue(aaiResponseAsString, "jobId")
 
 188         execution.setVariable("jobId", jobId)
 
 189         msoLogger.info(" *****Exit  instantiateNetworkService *****")
 
 195     public void queryNSProgress(DelegateExecution execution) {
 
 196         msoLogger.trace("queryNSProgress ")
 
 197         String jobId = execution.getVariable("jobId")
 
 198         String nsOperationKey = execution.getVariable("nsOperationKey");
 
 199         String url = host + vfcUrl + "/jobs/" + jobId
 
 200         APIResponse apiResponse = postRequest(execution, url, nsOperationKey)
 
 201         String returnCode = apiResponse.getStatusCode()
 
 202         String aaiResponseAsString = apiResponse.getResponseBodyAsString()
 
 203         String operationStatus = "error"
 
 204         if(returnCode== "200"|| returnCode == "201"){
 
 205             operationStatus = jsonUtil.getJsonValue(aaiResponseAsString, "responseDescriptor.status")
 
 207         execution.setVariable("operationStatus", operationStatus)
 
 208         msoLogger.info(" *****Exit  queryNSProgress *****")
 
 214     public void timeDelay(DelegateExecution execution) {
 
 217         } catch(InterruptedException e) {           
 
 218             msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Time Delay exception" + e , "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
 
 225     public void addNSRelationship(DelegateExecution execution) {
 
 226         msoLogger.trace("addNSRelationship ")
 
 227         String nsInstanceId = execution.getVariable("nsInstanceId")
 
 228         if(nsInstanceId == null || nsInstanceId == ""){
 
 229             msoLogger.info(" create NS failed, so do not need to add relationship")
 
 232         String globalSubscriberId = execution.getVariable("globalSubscriberId")
 
 233         String serviceType = execution.getVariable("serviceType")
 
 234         String serviceId = execution.getVariable("serviceInstanceId")
 
 235         String addRelationPayload = """<relationship xmlns="http://org.openecomp.aai.inventory/v11">
 
 236                                             <related-to>service-instance</related-to>
 
 237                                             <related-link>/aai/v11/business/customers/customer/${globalSubscriberId}/service-subscriptions/service-subscription/${serviceType}/service-instances/service-instance/${nsInstanceId}</related-link>
 
 239                                                 <relationship-key>customer.global-customer-id</relationship-key>
 
 240                                                 <relationship-value>${MsoUtils.xmlEscape(globalSubscriberId)}</relationship-value>
 
 243                                                 <relationship-key>service-subscription.service-type</relationship-key>
 
 244                                                 <relationship-value>${MsoUtils.xmlEscape(serviceType)}</relationship-value>
 
 247                                                 <relationship-key>service-instance.service-instance-id</relationship-key>
 
 248                                                 <relationship-value>${MsoUtils.xmlEscape(nsInstanceId)}</relationship-value>
 
 251         String endpoint = execution.getVariable("URN_aai_endpoint")  
 
 252         msoLogger.info("Add Relationship req:\n" + addRelationPayload)
 
 253         String url = endpoint + "/aai/v11/business/customers/customer/" + globalSubscriberId + "/service-subscriptions/service-subscription/" + serviceType + "/service-instances/service-instance/" + serviceId + "/relationship-list/relationship"
 
 254         APIResponse aaiRsp = executeAAIPutCall(execution, url, addRelationPayload)
 
 255         msoLogger.info("aai response status code:" + aaiRsp.getStatusCode())
 
 256         msoLogger.info("aai response content:" + aaiRsp.getResponseBodyAsString())
 
 257         msoLogger.info(" *****Exit addNSRelationship *****")
 
 260     public APIResponse executeAAIPutCall(DelegateExecution execution, String url, String payload){
 
 261         msoLogger.trace("Started Execute AAI Put Process ") 
 
 262         APIResponse apiResponse = null
 
 264             String uuid = utils.getRequestID()
 
 265             msoLogger.info("Generated uuid is: " + uuid) 
 
 266             msoLogger.info("URL to be used is: " + url) 
 
 267             String userName = execution.getVariable("URN_aai_auth")
 
 268             String password = execution.getVariable("URN_mso_msoKey")
 
 269             String basicAuthCred = utils.getBasicAuth(userName,password)
 
 270             RESTConfig config = new RESTConfig(url);
 
 271             RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Content-Type", "application/xml").addHeader("Accept","application/xml");
 
 272             if (basicAuthCred != null && !"".equals(basicAuthCred)) {
 
 273                 client.addAuthorizationHeader(basicAuthCred)
 
 275             apiResponse = client.httpPut(payload)
 
 276             msoLogger.trace("Completed Execute AAI Put Process ") 
 
 278             msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while executing AAI Put Call.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e); 
 
 279             throw new BpmnError("MSOWorkflowException")
 
 286      * url: the url of the request
 
 287      * requestBody: the body of the request
 
 289     private APIResponse postRequest(DelegateExecution execution, String url, String requestBody){
 
 290         msoLogger.trace("Started Execute VFC adapter Post Process ")
 
 291         msoLogger.info("url:"+url +"\nrequestBody:"+ requestBody)
 
 292         APIResponse apiResponse = null
 
 294             RESTConfig config = new RESTConfig(url);
 
 295             RESTClient client = new RESTClient(config).addHeader("Content-Type", "application/json").addHeader("Accept","application/json").addHeader("Authorization","Basic QlBFTENsaWVudDpwYXNzd29yZDEk");
 
 296             apiResponse = client.httpPost(requestBody)
 
 297             msoLogger.info("response code:"+ apiResponse.getStatusCode() +"\nresponse body:"+ apiResponse.getResponseBodyAsString())    
 
 298             msoLogger.trace("Completed Execute VF-C adapter Post Process ")
 
 300             msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while executing AAI Post Call.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e);
 
 301             throw new BpmnError("MSOWorkflowException")
 
 306         public void sendSyncResponse (DelegateExecution execution) {
 
 307                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
 
 308                 utils.log("DEBUG", " *** sendSyncResponse *** ", isDebugEnabled)
 
 311                         String operationStatus = execution.getVariable("operationStatus")
 
 312                         // RESTResponse for main flow
 
 313                         String resourceOperationResp = """{"operationStatus":"${operationStatus}"}""".trim()
 
 314                         utils.log("DEBUG", " sendSyncResponse to APIH:" + "\n" + resourceOperationResp, isDebugEnabled)
 
 315                         sendWorkflowResponse(execution, 202, resourceOperationResp)
 
 316                         execution.setVariable("sentSyncResponse", true)
 
 318                 } catch (Exception ex) {
 
 319                         String msg = "Exceptuion in sendSyncResponse:" + ex.getMessage()
 
 320                         utils.log("DEBUG", msg, isDebugEnabled)
 
 321                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
 
 323                 utils.log("DEBUG"," ***** Exit sendSyncResopnse *****",  isDebugEnabled)