74c9a4991190a4f24d8ee2d3a8335d7607f966a0
[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 com.fasterxml.jackson.databind.ObjectMapper
24 import groovy.json.JsonSlurper
25 import org.json.JSONObject
26 import org.camunda.bpm.engine.delegate.DelegateExecution
27 import org.onap.so.beans.nsmf.JobStatusRequest
28 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
29 import org.onap.so.bpmn.common.scripts.ExceptionUtil
30 import org.onap.so.bpmn.core.json.JsonUtils
31 import org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames
32 import org.slf4j.Logger
33 import org.slf4j.LoggerFactory
34 import org.onap.so.bpmn.core.UrnPropertiesReader
35
36 public class QueryJobStatus extends AbstractServiceTaskProcessor{
37     private static final Logger logger = LoggerFactory.getLogger(QueryJobStatus.class)
38
39     ExceptionUtil exceptionUtil = new ExceptionUtil()
40     JsonUtils jsonUtil = new JsonUtils()
41     
42     public void preProcessRequest(DelegateExecution execution) {
43         logger.debug("Start preProcessRequest")
44         
45         try{
46             String requestId = execution.getVariable("msoRequestId")
47             logger.debug("RequestId :" + requestId)
48             String jobId = execution.getVariable("jobId")
49             def jsonSlurper = new JsonSlurper()
50             
51             HashMap<String,?> esrInfo = jsonSlurper.parseText(execution.getVariable("esrInfo"))
52             logger.debug("esrInfo" + esrInfo.toString())
53             
54             HashMap<String,?> serviceInfo = jsonSlurper.parseText(execution.getVariable("serviceInfo"))
55             logger.debug("serviceInfo" + serviceInfo.toString())
56
57             execution.setVariable("esrInfo", esrInfo)
58             execution.setVariable("serviceInfo", serviceInfo)
59             
60             String nssmfEndpoint = UrnPropertiesReader.getVariable("mso.adapters.nssmf.endpoint",execution)          
61             String endPoint = String.format("/api/rest/provMns/v1/NSS/jobs/%s", jobId)          
62             String url = nssmfEndpoint + endPoint 
63             execution.setVariable("NSSMF_AdapterEndpoint", url)
64
65             String payload = """
66                 {
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 e){
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}",
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}",
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 }