Catchup commits for Dublin
[so.git] / bpmn / MSOCommonBPMN / src / main / groovy / org / onap / so / bpmn / common / scripts / AllottedResourceUtils.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T 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.common.scripts
22
23 import org.onap.so.client.aai.entities.AAIResultWrapper
24
25 import static org.apache.commons.lang3.StringUtils.isBlank;
26
27 import javax.ws.rs.NotFoundException
28 import javax.ws.rs.core.UriBuilder
29
30 import org.apache.commons.lang.StringUtils
31 import org.camunda.bpm.engine.delegate.BpmnError
32 import org.camunda.bpm.engine.delegate.DelegateExecution
33 import org.onap.aai.domain.yang.AllottedResource
34 import org.onap.so.bpmn.core.WorkflowException
35 import org.onap.so.client.PreconditionFailedException
36 import org.onap.so.client.aai.AAIObjectType
37 import org.onap.so.client.aai.AAIResourcesClient
38 import org.onap.so.client.aai.entities.uri.AAIResourceUri
39 import org.onap.so.client.aai.entities.uri.AAIUriFactory
40 import org.onap.so.logger.MessageEnum
41 import org.onap.so.logger.MsoLogger
42
43
44
45 class AllottedResourceUtils {
46         private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, AllottedResourceUtils.class);
47
48
49         private AbstractServiceTaskProcessor taskProcessor
50         ExceptionUtil exceptionUtil = new ExceptionUtil()
51         MsoUtils utils;
52
53         public AllottedResourceUtils(AbstractServiceTaskProcessor taskProcessor) {
54                 this.taskProcessor = taskProcessor
55                 this.utils = taskProcessor.utils
56         }
57
58         /*Used on Create - called from DoCreate
59         * Using Consuming ServiceInstanceId get related Allotted Resources Orchestration status from AAI
60         * 1) get related AR links for CSI 2) get AR from AR links
61         * return: null -> AR Not found
62         * return: " " -> AR found with empty orchStatus
63         * return: orchStatus - > AR found with this orchStatus
64         * setsVariable aaiARGetResponse
65         */
66         public String getAROrchStatus (DelegateExecution execution) {
67
68                 msoLogger.trace("getAROrchStatus ")
69                 String msg = ""
70                 String serviceInstanceId = execution.getVariable("serviceInstanceId")
71                 String arType = execution.getVariable("allottedResourceType")
72                 String arRole = execution.getVariable("allottedResourceRole")
73                 String siXml = execution.getVariable("CSI_service")
74                 String orchStatus = null
75                 XmlParser xmlParser = new XmlParser()
76                 msoLogger.debug("getAROrchStatus siXml:" + siXml)
77                 try {
78                         if (!isBlank(siXml)) {
79                                 def groovy.util.Node siNode = xmlParser.parseText(siXml)
80                                 def groovy.util.Node relationshipList = utils.getChildNode(siNode, 'relationship-list')
81                                 if (relationshipList != null) {
82                                         def groovy.util.NodeList relationships = utils.getIdenticalChildren(relationshipList, 'relationship')
83                                         for (groovy.util.Node relationship in relationships) {
84                                                 def groovy.util.Node relatedTo = utils.getChildNode(relationship, 'related-to')
85                                                 if ((relatedTo != null) && (relatedTo.text().equals('allotted-resource'))) {
86                                                         msoLogger.debug("getARORchStatus AR found")
87                                                         def groovy.util.Node relatedLink = utils.getChildNode(relationship, 'related-link')
88                                                         if (relatedLink != null){
89                                                                 Optional<AllottedResource> ar = getARbyLink(execution, relatedLink.text(), arRole)
90                                                                 if (ar.isPresent()){
91                                                                         orchStatus = execution.getVariable("aaiAROrchStatus")
92                                                                         break
93                                                                 }
94                                                         }
95                                                 }
96                                         }
97                                 }
98                         }
99                 }catch(Exception e){
100                         msoLogger.debug(" Error encountered in getAROrchStatus" + e.getMessage())
101                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error in getAROrchStatus" + e.getMessage())
102                 }
103                 msoLogger.trace(" Exit getAROrchStatus - OrchStatus:" + orchStatus)
104                 return orchStatus
105         }
106
107         // get Allotted Resource by AllottedResourceId
108         // used on Delete - called from doDeleteAR
109         // setsVariable aaiARGetResponse
110         public boolean ifExistsAR(DelegateExecution execution, String allottedResourceId) {
111                 msoLogger.trace("ifExistsAR ")
112                 try {
113                         AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.ALLOTTED_RESOURCE, allottedResourceId)
114             AAIResultWrapper wrapper = getAAIClient().get(resourceUri)
115             Optional<AllottedResource> allottedResource = wrapper.asBean(AllottedResource.class)
116             if(allottedResource.isPresent()) {
117                 setExecutionVariables(execution , allottedResource.get(),resourceUri)
118                 return true
119             }else {
120                 return false
121             }
122                 }catch(Exception e){
123                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error in ifExistsAR" + e.getMessage())
124                 }
125         }
126
127         public String getPSIFmARLink(DelegateExecution execution, String arLink)
128         {
129                 // Path: /aai/{version}/business/customers/customer/{cust}/service-subscriptions/service-subscription/{subs}/service-instances/service-instance/{psiid}/allotted-resources/allotted-resource/{arid}
130                 msoLogger.trace(" getPSIFmARLink - path:" + arLink)
131                 String[] split = arLink.split("/service-instance/")
132                 String[] splitB =  split[1].split("/allotted-resources/")
133                 String siId = splitB[0]
134                 msoLogger.trace(" Exit getARLinkbyId - parentServiceInstanceId:" + siId )
135                 return siId
136         }
137         
138         // get Allotted resource using Link
139         // used on Create called from getARORchStatus
140         // used on Delete called from ifExistsAR
141         // setsVariable aaiARPath - used for Patch in create
142         
143         public Optional<AllottedResource> getARbyLink (DelegateExecution execution, String link, String role) {
144                 msoLogger.trace("getARbyLink ")
145                 Optional<AllottedResource> allottedResource = Optional.empty()
146                 try {
147                         msoLogger.debug("GET AR Aai Path is: \n" + link)
148                         AAIResourceUri uri = AAIUriFactory.createResourceFromExistingURI(AAIObjectType.ALLOTTED_RESOURCE, UriBuilder.fromPath(link).build())
149                         allottedResource = getAAIClient().get(AllottedResource.class,uri);
150                         if(allottedResource.isPresent()) {
151                                 if (!isBlank(role)) {
152                                         if (role == allottedResource.get().getRole()) {
153                                                 setExecutionVariables(execution,allottedResource.get(),uri)
154                                         } else {
155                                                 msoLogger.debug("AAI AR does not match input role:" + role)
156                                         }
157                                 } else {
158                                         setExecutionVariables(execution,allottedResource.get(),uri)
159                                 }
160                         }else{
161                                 msoLogger.debug("GET AR received a Not Found (404) Response")
162                         }
163                 }catch(Exception e){
164                         msoLogger.debug(" Error encountered within GetAaiAR" + e.getMessage())
165                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error in GetAaiAR" + e.getMessage())
166                 }
167                 return allottedResource
168         }
169
170         public void setExecutionVariables(DelegateExecution execution, AllottedResource ar, AAIResourceUri arUrl) {
171                 execution.setVariable("aaiARGetResponse", ar)
172                 execution.setVariable("aaiARPath", arUrl.build().toString())
173                 execution.setVariable("aaiARResourceVersion", ar.getResourceVersion())
174                 if (StringUtils.isNotEmpty(ar.getOrchestrationStatus())) {
175                         execution.setVariable("aaiAROrchStatus", ar.getOrchestrationStatus())
176                 }
177                 else
178                 {
179                         execution.setVariable("aaiAROrchStatus", " ")
180                 }
181         }
182
183         public void updateAROrchStatus(DelegateExecution execution, String status, String aaiARPath){
184                 msoLogger.trace("updaAROrchStatus ")
185                 try{
186
187                         AllottedResource allottedResource = new AllottedResource();
188                         allottedResource.setOrchestrationStatus(status)
189                         msoLogger.debug('AAI AR URI: ' + aaiARPath)
190
191                         AAIResourceUri uri = AAIUriFactory.createResourceFromExistingURI(AAIObjectType.ALLOTTED_RESOURCE, UriBuilder.fromPath(aaiARPath).build())
192                         getAAIClient().update(uri,allottedResource)
193                 }catch(Exception e){
194                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception in updateAR.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e.getMessage());
195                         exceptionUtil.buildAndThrowWorkflowException(execution, 500, 'Internal Error in updateAROrchStatus.' + e.getMessage())
196                 }
197                 msoLogger.trace("Exit updateAROrchStatus ")
198         }
199
200         //Sets Variable "wasDeleted"
201         public void deleteAR(DelegateExecution execution, String aaiARPath){
202                 msoLogger.trace(" deleteAR - aaiARPath:" + aaiARPath)
203                 try {
204
205                         AAIResourceUri uri = AAIUriFactory.createResourceFromExistingURI(AAIObjectType.ALLOTTED_RESOURCE, UriBuilder.fromPath(aaiARPath).build())
206                         getAAIClient().delete(uri);
207                 }catch(NotFoundException ex){
208                         msoLogger.debug("  Delete AR Received a Not Found (404) Response")
209                 }catch(PreconditionFailedException ex){
210                         msoLogger.debug("Delete AR Received a Resource Version Mismatch Error: \n")
211                         exceptionUtil.buildAndThrowWorkflowException(execution, 412, "DeleteAR Received a resource-version Mismatch Error Response from AAI")
212                 }catch(Exception e){
213                         msoLogger.debug(" Error encountered in deleteAR!" + e)
214                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured During Delete AR")
215                 }
216                 msoLogger.debug("  Delete AR Received a Good Response")
217                 execution.setVariable("wasDeleted", "true")
218                 msoLogger.trace("Exit deleteAR ")
219         }
220
221         public void buildAAIErrorResponse(DelegateExecution execution, String response, String errorMessage){
222                 msoLogger.trace("BuildAAIErrorResponse")
223
224                 if((response != null) && (response.contains("Fault") || response.contains("RESTFault"))){
225                         WorkflowException workflowException = exceptionUtil.MapAAIExceptionToWorkflowException(response, execution)
226                         execution.setVariable("WorkflowException", workflowException)
227                 }else{
228                         exceptionUtil.buildWorkflowException(execution, 500, errorMessage)
229                 }
230
231                 msoLogger.trace("Exit BuildAAIErrorResponse Process")
232                 throw new BpmnError("MSOWorkflowException")
233         }
234         
235         public  AAIResourcesClient getAAIClient(){
236                 return new AAIResourcesClient()
237         }
238
239 }