From 696b3aab041353afd74e26c0b9a569d0b1b9e254 Mon Sep 17 00:00:00 2001 From: Geora Barsky Date: Fri, 12 Oct 2018 11:46:52 -0400 Subject: Adding API Mapping infrastructure Issue-ID: LOG-391 Change-Id: I30d954bcdf1cf0748bb5249cbf10defb8dbc8ff6 Signed-off-by: Geora Barsky --- .../pomba/contextbuilder/sdnc/Application.java | 29 ++- .../contextbuilder/sdnc/SdncConfiguration.java | 69 ++++++- .../pomba/contextbuilder/sdnc/SpringXMLConfig.java | 28 +++ .../sdnc/handlers/GenericResourceApiHandler.java | 68 +++++++ .../sdnc/handlers/VnfApiHandler.java | 52 +++++ .../contextbuilder/sdnc/model/ServiceEntity.java | 73 +++++++ .../sdnc/service/SpringServiceImpl.java | 65 +++++-- .../pomba/contextbuilder/sdnc/util/RestUtil.java | 211 +++++++++++++++++++++ 8 files changed, 568 insertions(+), 27 deletions(-) create mode 100644 src/main/java/org/onap/pomba/contextbuilder/sdnc/SpringXMLConfig.java create mode 100644 src/main/java/org/onap/pomba/contextbuilder/sdnc/handlers/GenericResourceApiHandler.java create mode 100644 src/main/java/org/onap/pomba/contextbuilder/sdnc/handlers/VnfApiHandler.java create mode 100644 src/main/java/org/onap/pomba/contextbuilder/sdnc/model/ServiceEntity.java (limited to 'src/main/java/org') diff --git a/src/main/java/org/onap/pomba/contextbuilder/sdnc/Application.java b/src/main/java/org/onap/pomba/contextbuilder/sdnc/Application.java index e0ebfc8..93dd886 100644 --- a/src/main/java/org/onap/pomba/contextbuilder/sdnc/Application.java +++ b/src/main/java/org/onap/pomba/contextbuilder/sdnc/Application.java @@ -18,7 +18,13 @@ package org.onap.pomba.contextbuilder.sdnc; -import org.apache.velocity.app.VelocityEngine; +import org.kie.api.KieServices; +import org.kie.api.builder.KieBuilder; +import org.kie.api.builder.KieFileSystem; +import org.kie.api.builder.KieRepository; +import org.kie.api.io.Resource; +import org.kie.api.io.ResourceType; +import org.kie.api.runtime.KieContainer; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; @@ -30,8 +36,10 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.scheduling.annotation.EnableAsync; +import java.io.File; + @SpringBootApplication -@ComponentScan(basePackages = "org.onap.pomba.contextbuilder.sdnc") +@ComponentScan(basePackages = {"org.onap.pomba.contextbuilder.sdnc","org.kie.api"}) @EnableAsync @EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class }) public class Application extends SpringBootServletInitializer { @@ -45,9 +53,18 @@ public class Application extends SpringBootServletInitializer { } @Bean - public VelocityEngine velocityEngine() { - VelocityEngine velocityEngine = new VelocityEngine(); - velocityEngine.init(); - return velocityEngine; + public KieContainer kieContainer() { + + KieServices kServices = KieServices.Factory.get(); + KieFileSystem kfs = kServices.newKieFileSystem(); + KieRepository kr = kServices.getRepository(); + File file = new File("config/rules/api-mapping-rules.drl"); + Resource resource = kServices.getResources().newFileSystemResource(file).setResourceType(ResourceType.DRL); + kfs.write(resource); + + KieBuilder kb = kServices.newKieBuilder(kfs); + kb.buildAll(); + KieContainer kContainer = kServices.newKieContainer(kr.getDefaultReleaseId()); + return kContainer; } } \ No newline at end of file diff --git a/src/main/java/org/onap/pomba/contextbuilder/sdnc/SdncConfiguration.java b/src/main/java/org/onap/pomba/contextbuilder/sdnc/SdncConfiguration.java index ec5c8b3..71c3502 100644 --- a/src/main/java/org/onap/pomba/contextbuilder/sdnc/SdncConfiguration.java +++ b/src/main/java/org/onap/pomba/contextbuilder/sdnc/SdncConfiguration.java @@ -24,7 +24,7 @@ import org.eclipse.jetty.util.security.Password; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Component; - +import org.onap.aai.restclient.client.RestClient; @Component @ApplicationPath("/") @@ -70,5 +70,72 @@ public class SdncConfiguration { return ("Basic " + Base64.getEncoder().encodeToString(auth.getBytes())); } + /* AAI related interfaces */ + @Value("${aai.serviceName}") + private String aaiHost; + @Value("${aai.servicePort}") + private String aaiPort; + @Value("${aai.username}") + private String aaiUsername; + @Value("${aai.password}") + private String aaiPassword; + @Value("${aai.httpProtocol}") + private String aaiHttpProtocol; + @Value("${aai.connectionTimeout}") + private Integer aaiConnectionTimeout; + @Value("${aai.readTimeout}") + private Integer aaiReadTimeout; + + @Value("${aai.http.userId}") + private String aaiHttpUserId; + + @Value("${aai.http.password}") + private String aaiHttpPassword; + + @Value("${aai.searchNodeQuery}") + private String aaiSearchNodeQuery; + + @Value("${aai.customerQuery}") + private String aaiCustomerQuery; + + @Bean(name="aaiHttpBasicAuthorization") + public String getHttpBasicAuth() { + String auth = new String(this.aaiHttpUserId + ":" + Password.deobfuscate(this.aaiHttpPassword)); + + String encodedAuth = Base64.getEncoder().encodeToString(auth.getBytes()); + return ("Basic " + encodedAuth); + } + + @Bean(name="aaiBasicAuthorization") + public String getAAIBasicAuth() { + String auth = new String(this.aaiUsername + ":" + Password.deobfuscate(this.aaiPassword)); + String encodedAuth = Base64.getEncoder().encodeToString(auth.getBytes()); + return ("Basic " + encodedAuth); + } + + @Bean(name="aaiClient") + public RestClient restClient() { + RestClient restClient = new RestClient(); + restClient.validateServerHostname(false).validateServerCertChain(false).connectTimeoutMs(aaiConnectionTimeout).readTimeoutMs(aaiReadTimeout); + restClient.basicAuthUsername(aaiUsername); + restClient.basicAuthPassword(Password.deobfuscate(aaiPassword)); + return restClient; + } + + @Bean(name="aaiBaseUrl") + public String getAaiURL() { + return httpProtocol + "://" + aaiHost + ":" + aaiPort; + + } + + @Bean(name="aaiPathToSearchNodeQuery") + public String getAaiPathToSearchNodeQuery() { + return aaiSearchNodeQuery.trim(); + } + + @Bean(name="aaiPathToCustomerQuery") + public String getAaiPathToCustomerQuery() { + return aaiCustomerQuery.trim(); + } } diff --git a/src/main/java/org/onap/pomba/contextbuilder/sdnc/SpringXMLConfig.java b/src/main/java/org/onap/pomba/contextbuilder/sdnc/SpringXMLConfig.java new file mode 100644 index 0000000..db38754 --- /dev/null +++ b/src/main/java/org/onap/pomba/contextbuilder/sdnc/SpringXMLConfig.java @@ -0,0 +1,28 @@ +/** + * ============LICENSE_START=================================================== + * Copyright (c) 2018 Amdocs + * ============================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END===================================================== + */ +package org.onap.pomba.contextbuilder.sdnc; + +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.ImportResource; + +@Configuration +@ImportResource({"file:${service.xml.beans}"}) +public class SpringXMLConfig { + + +} \ No newline at end of file diff --git a/src/main/java/org/onap/pomba/contextbuilder/sdnc/handlers/GenericResourceApiHandler.java b/src/main/java/org/onap/pomba/contextbuilder/sdnc/handlers/GenericResourceApiHandler.java new file mode 100644 index 0000000..885c923 --- /dev/null +++ b/src/main/java/org/onap/pomba/contextbuilder/sdnc/handlers/GenericResourceApiHandler.java @@ -0,0 +1,68 @@ +/* + * ============LICENSE_START=================================================== + * Copyright (c) 2018 Amdocs + * ============================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END===================================================== + */ + +package org.onap.pomba.contextbuilder.sdnc.handlers; + +import org.apache.camel.Exchange; +import org.onap.pomba.common.datatypes.ModelContext; +import org.onap.pomba.contextbuilder.sdnc.exception.AuditException; +import org.onap.pomba.contextbuilder.sdnc.model.ServiceEntity; +import org.onap.pomba.contextbuilder.sdnc.util.RestUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import javax.ws.rs.client.Client; + +@Component +public class GenericResourceApiHandler { + + private static Logger log = LoggerFactory.getLogger(GenericResourceApiHandler.class); + @Autowired + private Client jerseyClient; + @Autowired + private String sdncBaseUrl; + @Autowired + private String sdncBasicAuthorization; + @Autowired + private String sdncGenericResourcePath; + + + + public ModelContext process(Exchange exchange) throws Exception { + + ModelContext context; + log.info("in GENERIC-RESOURCE-API HANDLER: "); + + ServiceEntity serviceEntity = (ServiceEntity)exchange.getIn().getBody(); + String serviceInstanceId = serviceEntity.getServiceInstanceId(); + + try { + String sdncResponse = RestUtil.getSdncGenericResource(jerseyClient, sdncBaseUrl, sdncBasicAuthorization, sdncGenericResourcePath, serviceInstanceId); + context = RestUtil.transform(sdncResponse); + } catch (AuditException ae) { + throw ae; + } catch (Exception e) { + throw new AuditException(e.getLocalizedMessage()); + } + + return context; + } + +} diff --git a/src/main/java/org/onap/pomba/contextbuilder/sdnc/handlers/VnfApiHandler.java b/src/main/java/org/onap/pomba/contextbuilder/sdnc/handlers/VnfApiHandler.java new file mode 100644 index 0000000..bfedf69 --- /dev/null +++ b/src/main/java/org/onap/pomba/contextbuilder/sdnc/handlers/VnfApiHandler.java @@ -0,0 +1,52 @@ +/* + * ============LICENSE_START=================================================== + * Copyright (c) 2018 Amdocs + * ============================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END===================================================== + */ + +package org.onap.pomba.contextbuilder.sdnc.handlers; + +import org.apache.camel.Exchange; +import org.onap.pomba.common.datatypes.ModelContext; +import org.onap.pomba.common.datatypes.Service; +import org.onap.pomba.contextbuilder.sdnc.model.ServiceEntity; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +@Component +public class VnfApiHandler { + + private static Logger log = LoggerFactory.getLogger(VnfApiHandler.class); + + public ModelContext process(Exchange exchange) throws Exception { + + log.info("in VNF-API HANDLER: "); + +// dummy population of the model context +// The following lines should be replaced with the logic of calling to SDN-C VNF-API +// and transforming the response into common model + ModelContext context = new ModelContext(); + Service service = new Service(); + ServiceEntity serviceEntity = (ServiceEntity)exchange.getIn().getBody(); + service.setName( serviceEntity.getServiceType() + " service instance"); + context.setService(service); +// end dummy code + + return context; + } + + +} diff --git a/src/main/java/org/onap/pomba/contextbuilder/sdnc/model/ServiceEntity.java b/src/main/java/org/onap/pomba/contextbuilder/sdnc/model/ServiceEntity.java new file mode 100644 index 0000000..2f08533 --- /dev/null +++ b/src/main/java/org/onap/pomba/contextbuilder/sdnc/model/ServiceEntity.java @@ -0,0 +1,73 @@ +/* + * ============LICENSE_START=================================================== + * Copyright (c) 2018 Amdocs + * ============================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END===================================================== + */ +package org.onap.pomba.contextbuilder.sdnc.model; + +public class ServiceEntity { + + private String customerType; + private String customerName; + private String serviceType; + private String apiName; + private String serviceInstanceId; + private String customerId; + + public String getCustomerId() { + return customerId; + } + + public void setCustomerId(String customerId) { + this.customerId = customerId; + } + + public String getServiceInstanceId() { return serviceInstanceId; } + + public void setServiceInstanceId(String serviceInstanceId) { this.serviceInstanceId = serviceInstanceId; } + + public String getCustomerType() { + return customerType; + } + + public void setCustomerType(String customerType) { + this.customerType = customerType; + } + + public String getCustomerName() { + return customerName; + } + + public void setCustomerName(String customerName) { + this.customerName = customerName; + } + + public String getServiceType() { + return serviceType; + } + + public void setServiceType(String serviceType) { + this.serviceType = serviceType; + } + + public String getApiName() { + return apiName; + } + + public void setApiName(String apiName) { + this.apiName = apiName; + } + +} diff --git a/src/main/java/org/onap/pomba/contextbuilder/sdnc/service/SpringServiceImpl.java b/src/main/java/org/onap/pomba/contextbuilder/sdnc/service/SpringServiceImpl.java index daf6bf8..b19c24c 100644 --- a/src/main/java/org/onap/pomba/contextbuilder/sdnc/service/SpringServiceImpl.java +++ b/src/main/java/org/onap/pomba/contextbuilder/sdnc/service/SpringServiceImpl.java @@ -18,57 +18,82 @@ package org.onap.pomba.contextbuilder.sdnc.service; -import javax.ws.rs.client.Client; +import org.apache.camel.ProducerTemplate; +import org.kie.api.runtime.KieContainer; +import org.kie.api.runtime.KieSession; import org.onap.pomba.common.datatypes.ModelContext; import org.onap.pomba.contextbuilder.sdnc.exception.AuditException; import org.onap.pomba.contextbuilder.sdnc.service.rs.RestService; -import org.onap.pomba.contextbuilder.sdnc.util.RestUtil; +import org.onap.pomba.contextbuilder.sdnc.model.ServiceEntity; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import org.onap.pomba.contextbuilder.sdnc.util.RestUtil; +import org.onap.aai.restclient.client.RestClient; @Service public class SpringServiceImpl implements SpringService { private static Logger log = LoggerFactory.getLogger(RestService.class); @Autowired - private Client jerseyClient; + private String sdncCtxBuilderBasicAuthorization; + private KieContainer kieContainer; @Autowired - private String sdncBaseUrl; + private ProducerTemplate producerTemplate; + + //AAI related @Autowired - private String sdncBasicAuthorization; + private String aaiBasicAuthorization; @Autowired - private String sdncGenericResourcePath; + private RestClient aaiClient; @Autowired - private String sdncCtxBuilderBasicAuthorization; + private String aaiBaseUrl; + @Autowired + private String aaiPathToSearchNodeQuery; + @Autowired + private String aaiPathToCustomerQuery; public SpringServiceImpl() { // needed for instantiation } + @Autowired + public SpringServiceImpl(KieContainer kieContainer) { + this.kieContainer = kieContainer; + + } @Override public ModelContext getContext(String serviceInstanceId, String transactionId) throws AuditException { ModelContext context = null; - String url = "serviceInstanceId=" + serviceInstanceId + " transactionId=" + transactionId; - log.info("URL Query the SDN-C model data with URL: " , url); - - // Retrieve the service instance information from SDNC and AAI - try { - String sdncResponse = RestUtil.getSdncGenericResource(jerseyClient, sdncBaseUrl, sdncBasicAuthorization, sdncGenericResourcePath, serviceInstanceId); - log.info("sdncResponse: ", sdncResponse); - context = RestUtil.transform(sdncResponse); - } catch (AuditException ae) { - throw ae; - } catch (Exception e) { - throw new AuditException(e.getLocalizedMessage()); - } + + // Call AAI system to populate ServiceData + ServiceEntity serviceEntity = RestUtil.getServiceEntity(aaiClient, aaiBaseUrl, aaiBasicAuthorization, aaiPathToSearchNodeQuery, aaiPathToCustomerQuery, serviceInstanceId, transactionId); + + processApiMappingRules(serviceEntity); + log.info("SDN-C determined API: " + serviceEntity.getApiName()); + + context = producerTemplate.requestBody("direct:startRoutingProcess", serviceEntity, ModelContext.class); + return context; } + private void processApiMappingRules(ServiceEntity serviceData){ + + KieSession kieSession = kieContainer.newKieSession(); + log.info ("KIE Session is created"); + kieSession.insert(serviceData); + kieSession.fireAllRules(); + log.info("Rules are fired"); + kieSession.getFactHandles().forEach(fh -> kieSession.delete(fh)); + kieSession.dispose(); + } + public String getSdncAuthoriztion() { return sdncCtxBuilderBasicAuthorization; } + + } diff --git a/src/main/java/org/onap/pomba/contextbuilder/sdnc/util/RestUtil.java b/src/main/java/org/onap/pomba/contextbuilder/sdnc/util/RestUtil.java index 806514c..8701c89 100644 --- a/src/main/java/org/onap/pomba/contextbuilder/sdnc/util/RestUtil.java +++ b/src/main/java/org/onap/pomba/contextbuilder/sdnc/util/RestUtil.java @@ -34,6 +34,16 @@ import org.onap.pomba.contextbuilder.sdnc.exception.AuditException; import org.onap.pomba.contextbuilder.sdnc.service.rs.RestService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.onap.aai.restclient.client.OperationResult; +import org.onap.aai.restclient.client.RestClient; +import javax.ws.rs.core.MediaType; +import com.sun.jersey.core.util.MultivaluedMapImpl; +import java.util.Map; +import java.util.Collections; +import javax.ws.rs.core.MultivaluedMap; +import org.json.JSONArray; +import org.json.JSONException; +import org.onap.pomba.contextbuilder.sdnc.model.ServiceEntity; public class RestUtil { @@ -46,6 +56,22 @@ public class RestUtil { public static final String FROM_APP_ID = "X-FromAppId"; public static final String AUTHORIZATION = "Authorization"; + // AAI related + private static final String APP_NAME = "sdncCtxBuilder"; + private static final String EMPTY_JSON_STRING = "{}"; + private static final String JSON_ATT_RESOURCE_TYPE = "resource-type"; + private static final String JSON_ATT_RESOURCE_LINK = "resource-link"; + private static final String RESULT_DATA = "result-data"; + private static final String CATALOG_SERVICE_INSTANCE = "service-instance"; + private static final String CUSTOMER_ID_STRING = "/customers/customer/"; + private static final String SERVICE_TYPE_STRING = "/service-subscriptions/service-subscription/"; + private static final String CUSTOMER = "customer"; + private static final String JSON_ATT_GLOBAL_CUSTOMER_ID = "global-customer-id"; + private static final String JSON_ATT_SUBSCRIBER_TYPE = "subscriber-type"; + private static final String JSON_ATT_SUBSCRIBER_NAME = "subscriber-name"; + + private static final String FORWARD_SLASH = "/"; + // Parameters for Query SDNC Model Data REST API URL private static final String SERVICE_INSTANCE_ID = "serviceInstanceId"; @@ -147,4 +173,189 @@ public class RestUtil { return MessageFormat.format(siPath, vfModuleLink); } + /** + * Get customer info from multiple AAI api + * @param aaiClient + * @param aaiBaseUrl + * @param aaiBasicAuthorization + * @param aaiPathToSearchNodeQuery + * @param aaiPathToCustomerQuery + * @param serviceInstaceId + * @param transactionId + * @return + * @throws AuditException + */ + public static ServiceEntity getServiceEntity(RestClient aaiClient, + String aaiBaseUrl, + String aaiBasicAuthorization, + String aaiPathToSearchNodeQuery, + String aaiPathToCustomerQuery, + String serviceInstanceId, + String transactionId)throws AuditException { + + String obtainResourceLink_url = generateUrl_ForResourceLink(aaiBaseUrl, aaiPathToSearchNodeQuery, serviceInstanceId); + String aaiResourceData = getAaiResource(aaiClient, obtainResourceLink_url, aaiBasicAuthorization, transactionId, MediaType.valueOf(MediaType.APPLICATION_JSON)); + + // Handle the case if the service instance is not found in AAI + if (isEmptyJson(aaiResourceData)) { + log.info(" Service Instance {} is not found from AAI", serviceInstanceId); + // Only return the empty Json on the root level. i.e service instance + return null; + } + + String resourceLink = extractResourceLinkBasedOnServiceInstance(aaiResourceData, CATALOG_SERVICE_INSTANCE); + + ServiceEntity serviceEntityObj = createServiceEntityObj (resourceLink); //customerId and serviceType are updated here. + if (serviceEntityObj != null) { + serviceEntityObj.setServiceInstanceId(serviceInstanceId); + String customerId = serviceEntityObj.getCustomerId(); + // Obtain customerType and customerName + String obtainCustomer_url = generateUrl_ForCustomer (aaiBaseUrl, aaiPathToCustomerQuery, customerId); + String aaiCustomerData = getAaiResource(aaiClient, obtainCustomer_url, aaiBasicAuthorization, transactionId, MediaType.valueOf(MediaType.APPLICATION_JSON)); + if (isEmptyJson(aaiCustomerData)) { + log.info(" Customer name {} is not found from AAI", customerId); + // Only return the empty Json on the root level. i.e service instance + throw new AuditException(INTERNAL_SERVER_ERROR + ": Customer ID cannot be found from AAI :" + customerId); + } + // Update customerType and customerName to the existing serviceEntityObj + updateServiceEntityObj ( aaiCustomerData , serviceEntityObj); + } + + return serviceEntityObj; + } + + private static boolean isEmptyJson(String serviceInstancePayload) { + return (serviceInstancePayload.equals(EMPTY_JSON_STRING)); + } + + private static String generateUrl_ForResourceLink (String aaiBaseURL, String aaiPathToSearchNodeQuery ,String serviceInstanceId) { + return aaiBaseURL + aaiPathToSearchNodeQuery + serviceInstanceId; + } + + private static String generateUrl_ForCustomer (String aaiBaseURL, String aaiPathToCustomerQuery ,String customerId) { + return aaiBaseURL + aaiPathToCustomerQuery + customerId; + } + + @SuppressWarnings("unchecked") + private static Map> buildHeaders(String aaiBasicAuthorization, String transactionId) { + MultivaluedMap headers = new MultivaluedMapImpl(); + headers.put(TRANSACTION_ID, Collections.singletonList(transactionId)); + headers.put(FROM_APP_ID, Collections.singletonList(APP_NAME)); + headers.put(AUTHORIZATION, Collections.singletonList(aaiBasicAuthorization)); + return headers; + } + + private static String getAaiResource(RestClient client, String url, String aaiBasicAuthorization, String transId, MediaType mediaType) + throws AuditException { + OperationResult result = client.get(url, buildHeaders(aaiBasicAuthorization, transId), MediaType.valueOf(MediaType.APPLICATION_JSON)); + + if (result.getResultCode() == 200) { + return result.getResult(); + } else if (result.getResultCode() == 404) { + // Resource not found, generate empty JSON format + log.info("Resource for {} is not found: {}", url, "return empty Json format"); + return new JSONObject().toString(); + + } else { + throw new AuditException(INTERNAL_SERVER_ERROR + " with " + result.getFailureCause()); + } + } + + /* + * Extract the resource-Link from Json payload. For example + * { + * "result-data": [ + * { + * "resource-type": "service-instance", + * "resource-link": "/aai/v11/business/customers/customer/DemoCust_651800ed-2a3c-45f5-b920-85c1ed155fc2/service-subscriptions/service-subscription/vFW/service-instances/service-instance/adc3cc2a-c73e-414f-8ddb-367de81300cb" + * } + * ] + * } + */ + private static String extractResourceLinkBasedOnServiceInstance(String payload, String catalog) throws AuditException { + String resourceLink = null; + log.info("Fetching the resource-link based on resource-type=" + catalog); + + try { + JSONArray result_data_list = new JSONObject(payload).getJSONArray(RESULT_DATA); + if (result_data_list != null) { + for (int i = 0; i < result_data_list.length(); i++) { + JSONObject obj = result_data_list.optJSONObject(i); + if (obj.has(JSON_ATT_RESOURCE_TYPE) && (obj.getString(JSON_ATT_RESOURCE_TYPE).equals(catalog) )) { + resourceLink = obj.getString(JSON_ATT_RESOURCE_LINK); + log.info(resourceLink); + return resourceLink; + } + } + } + } catch (JSONException e) { + log.error(e.getMessage()); + throw new AuditException("Json Reader Parse Error " + e.getMessage()); + } + + log.warn("resource-link CANNOT be found: ", payload ); + + return resourceLink; + } + + /* + * Extract the "subscriber-name" and "subscriber-type" from Json payload. For example + * { + * "global-customer-id": "OttoonMorph36", + * "subscriber-name": "OttoonMorph36", + * "subscriber-type": "CUST", + * "resource-version": "1526324315029" + * } + */ + private static void updateServiceEntityObj(String payload, ServiceEntity serviceEntityObj) throws AuditException { + if (serviceEntityObj == null ) { + throw new AuditException("null pointer serviceEntityObj"); + } + String customerId = serviceEntityObj.getCustomerId(); + log.info("Fetching the subscriber type based on customer-id = " + customerId); + + try { + JSONObject obj = new JSONObject (payload); + if (obj.has(JSON_ATT_GLOBAL_CUSTOMER_ID) && (obj.getString(JSON_ATT_GLOBAL_CUSTOMER_ID).equals(customerId) )) { + serviceEntityObj.setCustomerType(obj.getString(JSON_ATT_SUBSCRIBER_TYPE)); + serviceEntityObj.setCustomerName(obj.getString(JSON_ATT_SUBSCRIBER_NAME)); + return; + } + } catch (JSONException e) { + log.error(e.getMessage()); + throw new AuditException("Json Reader Parse Error " + e.getMessage()); + } + + log.warn("subscriberType (" + customerId + ") CANNOT be found: ", payload ); + + return; + } + + /* Look for "/customers/customer/" and "/service-subscriptions/service-subscription/" in resourceLink + * and find the customer id and service type. + * For example, + * "/aai/v11/business/customers/customer/DemoCust_651800ed-2a3c-45f5-b920-85c1ed155fc2/service-subscriptions/service-subscription/vFW/service-instances/service-instance/adc3cc2a-c73e-414f-8ddb-367de81300cb" + * customerId = DemoCust_651800ed-2a3c-45f5-b920-85c1ed155fc2 + * serviceType = vFW + * */ + + private static ServiceEntity createServiceEntityObj (String resourceLink) { + int customer_id_idx = resourceLink.indexOf(CUSTOMER_ID_STRING); + int service_type_idx = resourceLink.indexOf(SERVICE_TYPE_STRING); + + if (( customer_id_idx < 0 ) || ( service_type_idx < 0 )) { + return null; + } + + ServiceEntity serviceEntity = new ServiceEntity (); + serviceEntity.setCustomerId(abstractStrInfo(resourceLink, CUSTOMER_ID_STRING)); + serviceEntity.setServiceType(abstractStrInfo(resourceLink, SERVICE_TYPE_STRING)); + return serviceEntity; + } + + private static String abstractStrInfo (String origStr, String matchStr) { + String after = origStr.substring( origStr.indexOf(matchStr) + matchStr.length()); + + return after.substring(0, after.indexOf(FORWARD_SLASH)); + } } -- cgit 1.2.3-korg