Commit 114e4922 authored by Christos Tranoris's avatar Christos Tranoris
Browse files

adding category create and delete events

parent 2355c086
Loading
Loading
Loading
Loading
Loading
+13 −1
Original line number Diff line number Diff line
@@ -35,6 +35,8 @@ import org.etsi.osl.centrallog.client.CentralLogger;
import org.etsi.osl.tmf.common.model.Notification;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
@@ -53,6 +55,12 @@ public class ProductCatalogApiRouteBuilderEvents extends RouteBuilder {
	@Value("${EVENT_PRODUCT_CATALOG_DELETE}")
	private String EVENT_CATALOG_DELETE = "direct:EVENT_CATALOG_DELETE";
	
	@Value("${EVENT_PRODUCT_CATEGORY_CREATE}")
	private String EVENT_CATEGORY_CREATE = "direct:EVENT_CATEGORY_CREATE";
	
	@Value("${EVENT_PRODUCT_CATEGORY_DELETE}")
	private String EVENT_CATEGORY_DELETE = "direct:EVENT_CATEGORY_DELETE";

	@Value("${spring.application.name}")
	private String compname;
	
@@ -83,6 +91,10 @@ public class ProductCatalogApiRouteBuilderEvents extends RouteBuilder {
				 msgtopic = EVENT_CATALOG_CREATE;
			} else if (n instanceof CatalogDeleteNotification) {
				 msgtopic = EVENT_CATALOG_DELETE;
			} else if (n instanceof CategoryCreateNotification) {
				 msgtopic = EVENT_CATEGORY_CREATE;
			} else if (n instanceof CategoryDeleteNotification) {
				 msgtopic = EVENT_CATEGORY_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.CategoryCreateEvent;
import org.etsi.osl.tmf.pcm620.model.CategoryDeleteEvent;
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 CategoryCallbackService {

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

    @Autowired
    private EventSubscriptionRepoService eventSubscriptionRepoService;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * Send category create event to all registered callback URLs
     * @param categoryCreateEvent The category create event to send
     */
    public void sendCategoryCreateCallback(CategoryCreateEvent categoryCreateEvent) {
        List<EventSubscription> subscriptions = eventSubscriptionRepoService.findAll();
        
        for (EventSubscription subscription : subscriptions) {
            if (shouldNotifySubscription(subscription, "categoryCreateEvent")) {
                sendCategoryCreateEventToCallback(subscription.getCallback(), categoryCreateEvent);
            }
        }
    }

    /**
     * Send category delete event to all registered callback URLs
     * @param categoryDeleteEvent The category delete event to send
     */
    public void sendCategoryDeleteCallback(CategoryDeleteEvent categoryDeleteEvent) {
        List<EventSubscription> subscriptions = eventSubscriptionRepoService.findAll();
        
        for (EventSubscription subscription : subscriptions) {
            if (shouldNotifySubscription(subscription, "categoryDeleteEvent")) {
                sendCategoryDeleteEventToCallback(subscription.getCallback(), categoryDeleteEvent);
            }
        }
    }

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

    /**
     * Send category delete event to a specific callback URL
     * @param callbackUrl The callback URL to send to
     * @param event The category delete event
     */
    private void sendCategoryDeleteEventToCallback(String callbackUrl, CategoryDeleteEvent event) {
        try {
            String url = buildCallbackUrl(callbackUrl, "/listener/categoryDeleteEvent");
            
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<CategoryDeleteEvent> entity = new HttpEntity<>(event, headers);
            
            ResponseEntity<String> response = restTemplate.exchange(
                url, HttpMethod.POST, entity, String.class);
            
            logger.info("Successfully sent category delete event to callback URL: {} - Response: {}", 
                url, response.getStatusCode());
            
        } catch (Exception e) {
            logger.error("Failed to send category 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("category") || 
               query.contains(eventType.toLowerCase()) ||
               query.contains("category.create") ||
               query.contains("category.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.Category;
import org.etsi.osl.tmf.pcm620.model.CategoryCreateEvent;
import org.etsi.osl.tmf.pcm620.model.CategoryCreateEventPayload;
import org.etsi.osl.tmf.pcm620.model.CategoryCreateNotification;
import org.etsi.osl.tmf.pcm620.model.CategoryDeleteEvent;
import org.etsi.osl.tmf.pcm620.model.CategoryDeleteEventPayload;
import org.etsi.osl.tmf.pcm620.model.CategoryDeleteNotification;
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 CategoryNotificationService {

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

    @Autowired
    private ProductCatalogApiRouteBuilderEvents eventPublisher;

    @Autowired
    private CategoryCallbackService categoryCallbackService;

    /**
     * Publish a category create notification
     * @param category The created category
     */
    public void publishCategoryCreateNotification(Category category) {
        try {
            CategoryCreateNotification notification = createCategoryCreateNotification(category);
            eventPublisher.publishEvent(notification, category.getUuid());
            
            // Send callbacks to registered subscribers
            categoryCallbackService.sendCategoryCreateCallback(notification.getEvent());
            
            logger.info("Published category create notification for category ID: {}", category.getUuid());
        } catch (Exception e) {
            logger.error("Error publishing category create notification for category ID: {}", category.getUuid(), e);
        }
    }

    /**
     * Publish a category delete notification
     * @param category The deleted category
     */
    public void publishCategoryDeleteNotification(Category category) {
        try {
            CategoryDeleteNotification notification = createCategoryDeleteNotification(category);
            eventPublisher.publishEvent(notification, category.getUuid());
            
            // Send callbacks to registered subscribers
            categoryCallbackService.sendCategoryDeleteCallback(notification.getEvent());
            
            logger.info("Published category delete notification for category ID: {}", category.getUuid());
        } catch (Exception e) {
            logger.error("Error publishing category delete notification for category ID: {}", category.getUuid(), e);
        }
    }

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

        // Create event
        CategoryCreateEvent event = new CategoryCreateEvent();
        event.setEventId(notification.getEventId());
        event.setEventTime(notification.getEventTime());
        event.setEventType("CategoryCreateEvent");
        event.setTitle("Category Create Event");
        event.setDescription("A category has been created");
        event.setTimeOcurred(notification.getEventTime());

        // Create event payload
        CategoryCreateEventPayload payload = new CategoryCreateEventPayload();
        payload.setCategory(category);
        event.setEvent(payload);

        notification.setEvent(event);
        return notification;
    }

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

        // Create event
        CategoryDeleteEvent event = new CategoryDeleteEvent();
        event.setEventId(notification.getEventId());
        event.setEventTime(notification.getEventTime());
        event.setEventType("CategoryDeleteEvent");
        event.setTitle("Category Delete Event");
        event.setDescription("A category has been deleted");
        event.setTimeOcurred(notification.getEventTime());

        // Create event payload
        CategoryDeleteEventPayload payload = new CategoryDeleteEventPayload();
        payload.setCategory(category);
        event.setEvent(payload);

        notification.setEvent(event);
        return notification;
    }
}
 No newline at end of file
+29 −7
Original line number Diff line number Diff line
@@ -62,6 +62,9 @@ public class ProductCategoryRepoService {
	
	private final ProductOfferingRepository prodsOfferingRepo;
	
	@Autowired
	private CategoryNotificationService categoryNotificationService;

	/**
	 * from
	 * https://stackoverflow.com/questions/25063995/spring-boot-handle-to-hibernate-sessionfactory
@@ -78,8 +81,14 @@ public class ProductCategoryRepoService {
	
	
	public Category addCategory(Category c) {
		Category savedCategory = this.categsRepo.save( c );
		
		return this.categsRepo.save( c );
		// Publish category create notification
		if (categoryNotificationService != null) {
			categoryNotificationService.publishCategoryCreateNotification(savedCategory);
		}
		
		return savedCategory;
	}

	public Category addCategory(@Valid CategoryCreate Category) {	
@@ -87,7 +96,14 @@ public class ProductCategoryRepoService {
		
		Category sc = new Category() ;
		sc = updateCategoryDataFromAPICall(sc, Category);
		return this.categsRepo.save( sc );
		Category savedCategory = this.categsRepo.save( sc );
		
		// Publish category create notification
		if (categoryNotificationService != null) {
			categoryNotificationService.publishCategoryCreateNotification(savedCategory);
		}
		
		return savedCategory;
		
	}

@@ -138,13 +154,14 @@ public class ProductCategoryRepoService {
			return false; //has children
		}
		
		Category categoryToDelete = optionalCat.get();
		
		if ( optionalCat.get().getParentId() != null ) {
			Category parentCat = (this.categsRepo.findByUuid( optionalCat.get().getParentId() )).get();
		if ( categoryToDelete.getParentId() != null ) {
			Category parentCat = (this.categsRepo.findByUuid( categoryToDelete.getParentId() )).get();
			
			//remove from parent category
			for (Category ss : parentCat.getCategoryObj()) {
				if  ( ss.getId()  == optionalCat.get().getId() ) {
				if  ( ss.getId()  == categoryToDelete.getId() ) {
					 parentCat.getCategoryObj().remove(ss);
					 break;
				}
@@ -152,8 +169,13 @@ public class ProductCategoryRepoService {
			parentCat = this.categsRepo.save(parentCat);
		}
		
		this.categsRepo.delete( categoryToDelete);
		
		// Publish category delete notification
		if (categoryNotificationService != null) {
			categoryNotificationService.publishCategoryDeleteNotification(categoryToDelete);
		}
		
		this.categsRepo.delete( optionalCat.get());
		return true;
		
	}
+5 −0
Original line number Diff line number Diff line
@@ -185,6 +185,11 @@ EVENT_PRODUCT_ORDER_STATE_CHANGED: "jms:topic:EVENT.PRODUCTORDER.STATECHANGED"
EVENT_PRODUCT_ORDER_DELETE: "jms:topic:EVENT.PRODUCTORDER.DELETE"
EVENT_PRODUCT_ORDER_ATTRIBUTE_VALUE_CHANGED: "jms:topic:EVENT.PRODUCTORDER.ATTRCHANGED"

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"

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

Loading