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