Commit 1007bf17 authored by Christos Tranoris's avatar Christos Tranoris Committed by Kostis Trantzas
Browse files

adding product spec notifications and events

parent cb018645
Loading
Loading
Loading
Loading
+13 −1
Original line number Diff line number Diff line
@@ -37,6 +37,8 @@ import org.etsi.osl.tmf.pcm620.model.CatalogCreateNotification;
import org.etsi.osl.tmf.pcm620.model.CatalogDeleteNotification;
import org.etsi.osl.tmf.pcm620.model.CategoryCreateNotification;
import org.etsi.osl.tmf.pcm620.model.CategoryDeleteNotification;
import org.etsi.osl.tmf.pcm620.model.ProductSpecificationCreateNotification;
import org.etsi.osl.tmf.pcm620.model.ProductSpecificationDeleteNotification;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
@@ -61,6 +63,12 @@ public class ProductCatalogApiRouteBuilderEvents extends RouteBuilder {
	@Value("${EVENT_PRODUCT_CATEGORY_DELETE}")
	private String EVENT_CATEGORY_DELETE = "direct:EVENT_CATEGORY_DELETE";
	
	@Value("${EVENT_PRODUCT_SPECIFICATION_CREATE}")
	private String EVENT_PRODUCT_SPECIFICATION_CREATE = "direct:EVENT_PRODUCT_SPECIFICATION_CREATE";
	
	@Value("${EVENT_PRODUCT_SPECIFICATION_DELETE}")
	private String EVENT_PRODUCT_SPECIFICATION_DELETE = "direct:EVENT_PRODUCT_SPECIFICATION_DELETE";

	@Value("${spring.application.name}")
	private String compname;
	
@@ -95,6 +103,10 @@ public class ProductCatalogApiRouteBuilderEvents extends RouteBuilder {
				 msgtopic = EVENT_CATEGORY_CREATE;
			} else if (n instanceof CategoryDeleteNotification) {
				 msgtopic = EVENT_CATEGORY_DELETE;
			} else if (n instanceof ProductSpecificationCreateNotification) {
				 msgtopic = EVENT_PRODUCT_SPECIFICATION_CREATE;
			} else if (n instanceof ProductSpecificationDeleteNotification) {
				 msgtopic = EVENT_PRODUCT_SPECIFICATION_DELETE;				
			}
			
			Map<String, Object> map = new HashMap<>();
+158 −0
Original line number Diff line number Diff line
/*-
 * ========================LICENSE_START=================================
 * org.etsi.osl.tmf.api
 * %%
 * Copyright (C) 2019 - 2021 openslice.io
 * %%
 * 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.etsi.osl.tmf.pcm620.reposervices;

import java.util.List;

import org.etsi.osl.tmf.pcm620.model.ProductSpecificationCreateEvent;
import org.etsi.osl.tmf.pcm620.model.ProductSpecificationDeleteEvent;
import org.etsi.osl.tmf.pcm620.model.EventSubscription;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class ProductSpecificationCallbackService {

    private static final Logger logger = LoggerFactory.getLogger(ProductSpecificationCallbackService.class);

    @Autowired
    private EventSubscriptionRepoService eventSubscriptionRepoService;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * Send product specification create event to all registered callback URLs
     * @param productSpecificationCreateEvent The product specification create event to send
     */
    public void sendProductSpecificationCreateCallback(ProductSpecificationCreateEvent productSpecificationCreateEvent) {
        List<EventSubscription> subscriptions = eventSubscriptionRepoService.findAll();
        
        for (EventSubscription subscription : subscriptions) {
            if (shouldNotifySubscription(subscription, "productSpecificationCreateEvent")) {
                sendProductSpecificationCreateEventToCallback(subscription.getCallback(), productSpecificationCreateEvent);
            }
        }
    }

    /**
     * Send product specification delete event to all registered callback URLs
     * @param productSpecificationDeleteEvent The product specification delete event to send
     */
    public void sendProductSpecificationDeleteCallback(ProductSpecificationDeleteEvent productSpecificationDeleteEvent) {
        List<EventSubscription> subscriptions = eventSubscriptionRepoService.findAll();
        
        for (EventSubscription subscription : subscriptions) {
            if (shouldNotifySubscription(subscription, "productSpecificationDeleteEvent")) {
                sendProductSpecificationDeleteEventToCallback(subscription.getCallback(), productSpecificationDeleteEvent);
            }
        }
    }

    /**
     * Send product specification create event to a specific callback URL
     * @param callbackUrl The callback URL to send to
     * @param event The product specification create event
     */
    private void sendProductSpecificationCreateEventToCallback(String callbackUrl, ProductSpecificationCreateEvent event) {
        try {
            String url = buildCallbackUrl(callbackUrl, "/listener/productSpecificationCreateEvent");
            
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<ProductSpecificationCreateEvent> entity = new HttpEntity<>(event, headers);
            
            ResponseEntity<String> response = restTemplate.exchange(
                url, HttpMethod.POST, entity, String.class);
            
            logger.info("Successfully sent product specification create event to callback URL: {} - Response: {}", 
                url, response.getStatusCode());
            
        } catch (Exception e) {
            logger.error("Failed to send product specification create event to callback URL: {}", callbackUrl, e);
        }
    }

    /**
     * Send product specification delete event to a specific callback URL
     * @param callbackUrl The callback URL to send to
     * @param event The product specification delete event
     */
    private void sendProductSpecificationDeleteEventToCallback(String callbackUrl, ProductSpecificationDeleteEvent event) {
        try {
            String url = buildCallbackUrl(callbackUrl, "/listener/productSpecificationDeleteEvent");
            
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<ProductSpecificationDeleteEvent> entity = new HttpEntity<>(event, headers);
            
            ResponseEntity<String> response = restTemplate.exchange(
                url, HttpMethod.POST, entity, String.class);
            
            logger.info("Successfully sent product specification delete event to callback URL: {} - Response: {}", 
                url, response.getStatusCode());
            
        } catch (Exception e) {
            logger.error("Failed to send product specification delete event to callback URL: {}", callbackUrl, e);
        }
    }

    /**
     * Build the full callback URL with the listener endpoint
     * @param baseUrl The base callback URL
     * @param listenerPath The listener path to append
     * @return The complete callback URL
     */
    private String buildCallbackUrl(String baseUrl, String listenerPath) {
        if (baseUrl.endsWith("/")) {
            return baseUrl.substring(0, baseUrl.length() - 1) + listenerPath;
        } else {
            return baseUrl + listenerPath;
        }
    }

    /**
     * Check if a subscription should be notified for a specific event type
     * @param subscription The event subscription
     * @param eventType The event type to check
     * @return true if the subscription should be notified
     */
    private boolean shouldNotifySubscription(EventSubscription subscription, String eventType) {
        // If no query is specified, notify all events
        if (subscription.getQuery() == null || subscription.getQuery().trim().isEmpty()) {
            return true;
        }
        
        // Check if the query contains the event type
        String query = subscription.getQuery().toLowerCase();
        return query.contains("productspecification") || 
               query.contains(eventType.toLowerCase()) ||
               query.contains("productspecification.create") ||
               query.contains("productspecification.delete");
    }
}
 No newline at end of file
+151 −0
Original line number Diff line number Diff line
/*-
 * ========================LICENSE_START=================================
 * org.etsi.osl.tmf.api
 * %%
 * Copyright (C) 2019 - 2021 openslice.io
 * %%
 * 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.etsi.osl.tmf.pcm620.reposervices;

import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.UUID;

import org.etsi.osl.tmf.pcm620.api.ProductCatalogApiRouteBuilderEvents;
import org.etsi.osl.tmf.pcm620.model.ProductSpecification;
import org.etsi.osl.tmf.pcm620.model.ProductSpecificationCreateEvent;
import org.etsi.osl.tmf.pcm620.model.ProductSpecificationCreateEventPayload;
import org.etsi.osl.tmf.pcm620.model.ProductSpecificationCreateNotification;
import org.etsi.osl.tmf.pcm620.model.ProductSpecificationDeleteEvent;
import org.etsi.osl.tmf.pcm620.model.ProductSpecificationDeleteEventPayload;
import org.etsi.osl.tmf.pcm620.model.ProductSpecificationDeleteNotification;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class ProductSpecificationNotificationService {

    private static final Logger logger = LoggerFactory.getLogger(ProductSpecificationNotificationService.class);

    @Autowired
    private ProductCatalogApiRouteBuilderEvents eventPublisher;

    @Autowired
    private ProductSpecificationCallbackService productSpecificationCallbackService;

    /**
     * Publish a product specification create notification
     * @param productSpecification The created product specification
     */
    public void publishProductSpecificationCreateNotification(ProductSpecification productSpecification) {
        try {
            ProductSpecificationCreateNotification notification = createProductSpecificationCreateNotification(productSpecification);
            eventPublisher.publishEvent(notification, productSpecification.getUuid());
            
            // Send callbacks to registered subscribers
            productSpecificationCallbackService.sendProductSpecificationCreateCallback(notification.getEvent());
            
            logger.info("Published product specification create notification for product spec ID: {}", productSpecification.getUuid());
        } catch (Exception e) {
            logger.error("Error publishing product specification create notification for product spec ID: {}", productSpecification.getUuid(), e);
        }
    }

    /**
     * Publish a product specification delete notification
     * @param productSpecification The deleted product specification
     */
    public void publishProductSpecificationDeleteNotification(ProductSpecification productSpecification) {
        try {
            ProductSpecificationDeleteNotification notification = createProductSpecificationDeleteNotification(productSpecification);
            eventPublisher.publishEvent(notification, productSpecification.getUuid());
            
            // Send callbacks to registered subscribers
            productSpecificationCallbackService.sendProductSpecificationDeleteCallback(notification.getEvent());
            
            logger.info("Published product specification delete notification for product spec ID: {}", productSpecification.getUuid());
        } catch (Exception e) {
            logger.error("Error publishing product specification delete notification for product spec ID: {}", productSpecification.getUuid(), e);
        }
    }

    /**
     * Create a product specification create notification
     * @param productSpecification The created product specification
     * @return ProductSpecificationCreateNotification
     */
    private ProductSpecificationCreateNotification createProductSpecificationCreateNotification(ProductSpecification productSpecification) {
        ProductSpecificationCreateNotification notification = new ProductSpecificationCreateNotification();
        
        // Set common notification properties
        notification.setEventId(UUID.randomUUID().toString());
        notification.setEventTime(OffsetDateTime.now(ZoneOffset.UTC));
        notification.setEventType(ProductSpecificationCreateNotification.class.getName());
        notification.setResourcePath("/productCatalogManagement/v4/productSpecification/" + productSpecification.getUuid());

        // Create event
        ProductSpecificationCreateEvent event = new ProductSpecificationCreateEvent();
        event.setEventId(notification.getEventId());
        event.setEventTime(notification.getEventTime());
        event.setEventType("ProductSpecificationCreateEvent");
        event.setTitle("Product Specification Create Event");
        event.setDescription("A product specification has been created");
        event.setTimeOcurred(notification.getEventTime());

        // Create event payload
        ProductSpecificationCreateEventPayload payload = new ProductSpecificationCreateEventPayload();
        payload.setProductSpecification(productSpecification);
        event.setEvent(payload);

        notification.setEvent(event);
        return notification;
    }

    /**
     * Create a product specification delete notification
     * @param productSpecification The deleted product specification
     * @return ProductSpecificationDeleteNotification
     */
    private ProductSpecificationDeleteNotification createProductSpecificationDeleteNotification(ProductSpecification productSpecification) {
        ProductSpecificationDeleteNotification notification = new ProductSpecificationDeleteNotification();
        
        // Set common notification properties
        notification.setEventId(UUID.randomUUID().toString());
        notification.setEventTime(OffsetDateTime.now(ZoneOffset.UTC));
        notification.setEventType(ProductSpecificationDeleteNotification.class.getName());
        notification.setResourcePath("/productCatalogManagement/v4/productSpecification/" + productSpecification.getUuid());

        // Create event
        ProductSpecificationDeleteEvent event = new ProductSpecificationDeleteEvent();
        event.setEventId(notification.getEventId());
        event.setEventTime(notification.getEventTime());
        event.setEventType("ProductSpecificationDeleteEvent");
        event.setTitle("Product Specification Delete Event");
        event.setDescription("A product specification has been deleted");
        event.setTimeOcurred(notification.getEventTime());

        // Create event payload
        ProductSpecificationDeleteEventPayload payload = new ProductSpecificationDeleteEventPayload();
        payload.setProductSpecification(productSpecification);
        event.setEvent(payload);

        notification.setEvent(event);
        return notification;
    }
}
 No newline at end of file
+14 −1
Original line number Diff line number Diff line
@@ -71,6 +71,9 @@ public class ProductSpecificationRepoService {
    @Autowired
    ServiceSpecificationRepoService serviceSpecificationRepoService;
    
    @Autowired
    private ProductSpecificationNotificationService productSpecificationNotificationService;

	private SessionFactory sessionFactory;


@@ -94,8 +97,12 @@ public class ProductSpecificationRepoService {
		serviceSpec = this.updateProductSpecificationDataFromAPIcall(serviceSpec, serviceProductSpecification);
		serviceSpec = this.prodsOfferingRepo.save(serviceSpec);

		// Publish product specification create notification
		if (productSpecificationNotificationService != null) {
			productSpecificationNotificationService.publishProductSpecificationCreateNotification(serviceSpec);
		}
	
		return this.prodsOfferingRepo.save(serviceSpec);
		return serviceSpec;
	}

	public List<ProductSpecification> findAll() {
@@ -252,6 +259,12 @@ public class ProductSpecificationRepoService {
		 */

		this.prodsOfferingRepo.delete(s);
		
		// Publish product specification delete notification
		if (productSpecificationNotificationService != null) {
			productSpecificationNotificationService.publishProductSpecificationDeleteNotification(s);
		}
		
		return null;
	}
	
+2 −0
Original line number Diff line number Diff line
@@ -189,6 +189,8 @@ EVENT_PRODUCT_CATALOG_CREATE: "jms:topic:EVENT.PRODUCTCATALOG.CREATE"
EVENT_PRODUCT_CATALOG_DELETE: "jms:topic:EVENT.PRODUCTCATALOG.DELETE"
EVENT_PRODUCT_CATEGORY_CREATE: "jms:topic:EVENT.PRODUCTCATEGORY.CREATE"
EVENT_PRODUCT_CATEGORY_DELETE: "jms:topic:EVENT.PRODUCTCATEGORY.DELETE"
EVENT_PRODUCT_SPECIFICATION_CREATE: "jms:topic:EVENT.PRODUCTSPECIFICATION.CREATE"
EVENT_PRODUCT_SPECIFICATION_DELETE: "jms:topic:EVENT.PRODUCTSPECIFICATION.DELETE"

#QUEUE MESSSAGES WITH VNFNSD CATALOG
NFV_CATALOG_GET_NSD_BY_ID: "jms:queue:NFVCATALOG.GET.NSD_BY_ID"
Loading