Merge "separate error status from progression status"
[so.git] / bpmn / MSOCommonBPMN / src / main / groovy / org / onap / so / bpmn / common / scripts / AaiUtil.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 import java.util.regex.Matcher
23 import java.util.regex.Pattern
24
25 import javax.ws.rs.core.MediaType
26 import javax.ws.rs.core.Response
27 import javax.ws.rs.core.UriBuilder
28
29 import org.camunda.bpm.engine.delegate.BpmnError
30 import org.camunda.bpm.engine.delegate.DelegateExecution
31 import org.onap.aai.domain.yang.GenericVnf
32 import org.onap.so.bpmn.core.UrnPropertiesReader;
33 import org.onap.so.client.HttpClient
34 import org.onap.so.client.aai.AAIVersion
35 import org.onap.so.client.aai.entities.uri.AAIUri
36 import org.onap.so.logger.MessageEnum
37 import org.onap.so.logger.MsoLogger
38 import org.onap.so.openpojo.rules.HasToStringRule
39 import org.onap.so.utils.TargetEntity
40
41 @Deprecated
42 class AaiUtil {
43         private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, AaiUtil.class);
44
45
46         public MsoUtils utils = new MsoUtils()
47         public static final String AAI_NAMESPACE_STRING_KEY = 'mso.workflow.global.default.aai.namespace'
48         public static final String DEFAULT_VERSION_KEY = 'mso.workflow.global.default.aai.version'
49
50         private String aaiNamespace = null;
51
52         private AbstractServiceTaskProcessor taskProcessor
53
54         public AaiUtil(AbstractServiceTaskProcessor taskProcessor) {
55                 this.taskProcessor = taskProcessor
56         }
57
58         public String createAaiUri(AAIUri uri) {
59                 return createAaiUri(AAIVersion.valueOf('V' + UrnPropertiesReader.getVariable(DEFAULT_VERSION_KEY)), uri)
60         }
61         public String createAaiUri(AAIVersion version, AAIUri uri) {
62                 String endpoint = UrnPropertiesReader.getVariable("aai.endpoint")
63                 String result = UriBuilder.fromUri(endpoint).path('aai').path(version.toString()).build().toString()
64                 return UriBuilder.fromUri(result + uri.build().toString()).build().toString()
65         }
66
67         public String getNamespace() {
68                 return getNamespace(AAIVersion.valueOf('V' + UrnPropertiesReader.getVariable(DEFAULT_VERSION_KEY)))
69         }
70
71         public String getNamespace(AAIVersion version) {
72                 String namespace = UrnPropertiesReader.getVariable(AAI_NAMESPACE_STRING_KEY)
73                 if (namespace == null) {
74                    throw new Exception('Internal Error: AAI Namespace has not been set yet. A getUri() method needs to be invoked first.')
75                 }
76
77                 return namespace + version
78         }
79
80         /* Utility to get the Cloud Region from AAI
81          * Returns String cloud region id, (ie, cloud-region-id)
82          * @param execution
83          * @param url  - url for AAI get cloud region
84          * @param backend - "PO" - real region, or "SDNC" - v2.5 (fake region).
85          */
86
87         public String getAAICloudReqion(DelegateExecution execution, String url, String backend, inputCloudRegion){
88                 String regionId = ""
89                 try{
90                         URL Url = new URL(url)
91                         HttpClient client = new HttpClient(Url, MediaType.APPLICATION_XML, TargetEntity.AAI)
92                         client.addBasicAuthHeader(UrnPropertiesReader.getVariable("aai.auth", execution), UrnPropertiesReader.getVariable("mso.msoKey", execution))
93                         client.addAdditionalHeader("X-FromAppId", "MSO")
94                         client.addAdditionalHeader("X-TransactionId", utils.getRequestID())
95                         client.addAdditionalHeader("Accept", MediaType.APPLICATION_XML)
96
97                         Response apiResponse = client.get()
98
99                         String returnCode = apiResponse.getStatus()
100                         String aaiResponseAsString = apiResponse.readEntity(String.class)
101                         msoLogger.debug("Call AAI Cloud Region Return code: " + returnCode)
102                         execution.setVariable(execution.getVariable("prefix")+"queryCloudRegionReturnCode", returnCode)
103
104                         if(returnCode == "200"){
105                                 msoLogger.debug("Call AAI Cloud Region is Successful.")
106
107                                 String regionVersion = taskProcessor.utils.getNodeText(aaiResponseAsString, "cloud-region-version")
108                                 msoLogger.debug("Cloud Region Version from AAI for " + backend + " is: " + regionVersion)
109                                 if (backend == "PO") {
110                                         regionId = taskProcessor.utils.getNodeText(aaiResponseAsString, "cloud-region-id")
111                                 } else { // backend not "PO"
112                                         if (regionVersion == "2.5" ) {
113                                                 regionId = "AAIAIC25"
114                                         } else {
115                                                 regionId = taskProcessor.utils.getNodeText(aaiResponseAsString, "cloud-region-id")
116                                         }
117                                 }
118                                 if(regionId == null){
119                                         throw new BpmnError("MSOWorkflowException")
120                                 }
121                                 msoLogger.debug("Cloud Region Id from AAI " + backend + " is: " + regionId)
122                         }else if (returnCode == "404"){ // not 200
123                                 if (backend == "PO") {
124                                         regionId = inputCloudRegion
125                                 }else{  // backend not "PO"
126                                         regionId = "AAIAIC25"
127                                 }
128                                 msoLogger.debug("Cloud Region value for code='404' of " + backend + " is: " + regionId)
129                         }else{
130                                 msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Call AAI Cloud Region is NOT Successful.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
131                                 throw new BpmnError("MSOWorkflowException")
132                         }
133                 }catch(Exception e) {
134                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while getting the Cloud Reqion.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e.getMessage());
135                         (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, e.getMessage())
136                 }
137                 return regionId
138         }
139
140         /**
141          * Get the lowest unused VF Module index from AAI response for a given module type. The criteria for
142          * determining module type is specified by "key" parameter (for example, "persona-model-id"),
143          * the value for filtering is specified in "value" parameter
144          *
145          * @param execution
146          * @param aaiVnfResponse
147          * @param key
148          * @param value
149          *
150          * @return moduleIndex
151          *
152          */
153         public int getLowestUnusedVfModuleIndexFromAAIVnfResponse(DelegateExecution execution, GenericVnf aaiVnfResponse, String key, String value) {
154                 if (aaiVnfResponse != null) {
155                         String vfModulesText = taskProcessor.utils.getNodeXml(aaiVnfResponse, "vf-modules")
156                         if (aaiVnfResponse.getVfModules() == null || aaiVnfResponse.getVfModules().getVfModule().isEmpty()) {
157                                 msoLogger.debug("There are no VF modules in this VNF yet")
158                                 return 0
159                         }
160                         else {
161                                 def xmlVfModules= new XmlSlurper().parseText(vfModulesText)
162                                 def vfModules = xmlVfModules.'**'.findAll {it.name() == "vf-module"}
163                                 int vfModulesSize = 0
164                                 if (vfModules != null) {
165                                         vfModulesSize = vfModules.size()
166                                 }
167                                 String matchingVfModules = "<vfModules>"
168                                 for (i in 0..vfModulesSize-1) {
169                                         def vfModuleXml = groovy.xml.XmlUtil.serialize(vfModules[i])
170                                         def keyFromAAI = taskProcessor.utils.getNodeText(vfModuleXml, key)
171                                         if (keyFromAAI != null && keyFromAAI.equals(value)) {
172                                                 matchingVfModules = matchingVfModules + taskProcessor.utils.removeXmlPreamble(vfModuleXml)
173                                         }
174                                 }
175                                 matchingVfModules = matchingVfModules + "</vfModules>"
176                                 msoLogger.debug("Matching VF Modules: " + matchingVfModules)
177                                 String lowestUnusedIndex = taskProcessor.utils.getLowestUnusedIndex(matchingVfModules)
178                                 return Integer.parseInt(lowestUnusedIndex)
179                         }
180                 }
181                 else {
182                         return 0
183                 }
184         }
185 }