Fixed issues in AN NSSMF for allocate flow & added timeDelay in QueryJobStatus
[so.git] / bpmn / so-bpmn-infrastructure-common / src / main / groovy / org / onap / so / bpmn / infrastructure / scripts / QueryJobStatus.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2020 Wipro Limited.
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.scripts
22
23 import groovy.json.JsonSlurper
24 import org.json.JSONObject
25 import org.camunda.bpm.engine.delegate.DelegateExecution
26 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
27 import org.onap.so.bpmn.common.scripts.ExceptionUtil
28 import org.onap.so.bpmn.core.json.JsonUtils
29 import org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames
30 import org.slf4j.Logger
31 import org.slf4j.LoggerFactory
32 import org.onap.so.bpmn.core.UrnPropertiesReader
33
34 public class QueryJobStatus extends AbstractServiceTaskProcessor{
35     private static final Logger logger = LoggerFactory.getLogger(QueryJobStatus.class)
36
37     ExceptionUtil exceptionUtil = new ExceptionUtil()
38     JsonUtils jsonUtil = new JsonUtils()
39     
40     public void preProcessRequest(DelegateExecution execution) {
41         logger.debug("Start preProcessRequest")
42         
43         try{
44             String requestId = execution.getVariable("msoRequestId")
45             logger.debug("RequestId :" + requestId)
46             String responseId = execution.getVariable("responseId")
47             String jobId = execution.getVariable("jobId")   
48             def jsonSlurper = new JsonSlurper()
49             
50             HashMap<String,?> esrInfo = jsonSlurper.parseText(execution.getVariable("esrInfo"))
51             logger.debug("esrInfo" + esrInfo.toString())
52             
53             HashMap<String,?> serviceInfo = jsonSlurper.parseText(execution.getVariable("serviceInfo"))
54             logger.debug("serviceInfo" + serviceInfo.toString())
55             
56             execution.setVariable("esrInfo", esrInfo)
57             execution.setVariable("serviceInfo", serviceInfo)
58             
59             String nssmfEndpoint = UrnPropertiesReader.getVariable("mso.adapters.nssmf.endpoint",execution)          
60             String endPoint = String.format("/api/rest/provMns/v1/NSS/jobs/%s", jobId)          
61             String url = nssmfEndpoint + endPoint 
62             execution.setVariable("NSSMF_AdapterEndpoint", url)
63             
64             String payload = """
65                 {
66                   "responseId": "${responseId}",
67                   "esrInfo":  ${execution.getVariable("esrInfo") as JSONObject},
68                   "serviceInfo": ${execution.getVariable("serviceInfo") as JSONObject}
69                 }
70               """
71                
72             execution.setVariable("NSSMF_AdapterRequest", payload.replaceAll("\\s+", ""))   
73             execution.setVariable("startTime", System.currentTimeMillis())
74             logger.debug("Outgoing NSSMF_AdapterRequest: \n" + payload)
75         }catch(Exception ex){
76             String msg = "Exception in QueryJobStatus.preProcessRequest " + ex.getMessage()
77             logger.error(msg)
78             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
79         }
80         logger.debug("exit preProcessRequest")
81     }
82
83     public void checkJobStatus(DelegateExecution execution) {
84         logger.debug(" *** checkJobStatus *** ")
85         def NSSMF_ResponseCode = execution.getVariable("NSSMF_ResponseCode") as Integer
86         logger.debug("NSSMF_ResponseCode:" + NSSMF_ResponseCode)
87         def NSSMF_Response = execution.getVariable("NSSMF_Response") as String
88         def status = jsonUtil.getJsonValue(NSSMF_Response, "responseDescriptor.status")
89         logger.debug("NSSMF_Response" + NSSMF_Response)
90         
91         Long startTime = execution.getVariable("startTime") as Long
92         Long timeout = execution.getVariable("timeout") as Long
93         timeout = timeout == null ? 600000 : timeout * 60000
94         
95         if(NSSMF_Response != null) {                            
96             if (status.equalsIgnoreCase("processing") && (System.currentTimeMillis() - startTime) > timeout) {
97                 handleTimeOut(execution)
98             } 
99             else if(status.equalsIgnoreCase("finished") || status.equalsIgnoreCase("failed")) {
100                 execution.setVariable("JobStatusCompleted", "TRUE")
101             } else {
102                 execution.setVariable("JobStatusCompleted", "FALSE")
103             }
104             } else {
105                  Map<String, ?> responseDescriptorMap = new HashMap<>()
106                  responseDescriptorMap.put("status","failed")
107                  responseDescriptorMap.put("statusDescription","Exception while querying job status")
108                  String responseDescriptor = """
109                  {
110                   "responseDescriptor": "${responseDescriptorMap as JSONObject}"
111                  }
112                """
113                  execution.setVariable("JobStatusCompleted", "TRUE")
114                  execution.setVariable("NSSMF_Response",responseDescriptor.replaceAll("\\s+", ""))
115                 exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "Received a Bad Response from NSSMF.")
116             }
117         logger.debug("exit checkJobStatus")
118     }
119     
120     private handleTimeOut(DelegateExecution execution) {
121         Map<String, ?> responseDescriptorMap = new HashMap<>()
122         responseDescriptorMap.put("status","failed")
123         responseDescriptorMap.put("statusDescription","timeout")
124         String responseDescriptor = """
125                 {
126                   "responseDescriptor": ${responseDescriptorMap as JSONObject}
127                 }
128               """
129         execution.setVariable("JobStatusCompleted", "TRUE")
130         execution.setVariable("NSSMF_Response",responseDescriptor.replaceAll("\\s+", ""))
131     }
132     
133     public void updateJobStatusDetails(DelegateExecution execution)
134     {
135         logger.debug("**updateJobStatusDetails**")
136         def NSSMF_Response = execution.getVariable("NSSMF_Response") as String
137         def responseDescriptor = jsonUtil.getJsonValue(NSSMF_Response, "responseDescriptor")
138         execution.setVariable("responseDescriptor",responseDescriptor)
139         logger.debug("**exit updateJobStatusDetails")
140     }
141 }