Commit 0807e128 authored by Christos Tranoris's avatar Christos Tranoris
Browse files

fix for #84

parent 68e920d5
Loading
Loading
Loading
Loading
Loading
+164 −0
Original line number Diff line number Diff line
/*-
 * ========================LICENSE_START=================================
 * org.etsi.osl.tmf.api
 * %%
 * Copyright (C) 2019 - 2020 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.scm633.api;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;

import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.etsi.osl.centrallog.client.CLevel;
import org.etsi.osl.centrallog.client.CentralLogger;
import org.etsi.osl.tmf.scm633.model.ServiceCatalogCreateNotification;
import org.etsi.osl.tmf.scm633.model.ServiceCatalogDeleteNotification;
import org.etsi.osl.tmf.scm633.model.ServiceCategoryCreateNotification;
import org.etsi.osl.tmf.scm633.model.ServiceCategoryDeleteNotification;
import org.etsi.osl.tmf.scm633.model.ServiceSpecificationCreateNotification;
import org.etsi.osl.tmf.scm633.model.ServiceSpecificationDeleteNotification;
import org.etsi.osl.tmf.scm633.model.ServiceSpecificationChangeNotification;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

@Component
public class ServiceCatalogApiRouteBuilderEvents extends RouteBuilder {

	private static final transient Log logger = LogFactory.getLog(ServiceCatalogApiRouteBuilderEvents.class.getName());

	@Value("${EVENT_SERVICE_CATALOG_CREATE}")
	private String EVENT_SERVICE_CATALOG_CREATE = "direct:EVENT_SERVICE_CATALOG_CREATE";
	
	@Value("${EVENT_SERVICE_CATALOG_DELETE}")
	private String EVENT_SERVICE_CATALOG_DELETE = "direct:EVENT_SERVICE_CATALOG_DELETE";

	@Value("${EVENT_SERVICE_CATEGORY_CREATE}")
	private String EVENT_SERVICE_CATEGORY_CREATE = "direct:EVENT_SERVICE_CATEGORY_CREATE";
	
	@Value("${EVENT_SERVICE_CATEGORY_DELETE}")
	private String EVENT_SERVICE_CATEGORY_DELETE = "direct:EVENT_SERVICE_CATEGORY_DELETE";

	@Value("${EVENT_SERVICE_SPECIFICATION_CREATE}")
	private String EVENT_SERVICE_SPECIFICATION_CREATE = "direct:EVENT_SERVICE_SPECIFICATION_CREATE";
	
	@Value("${EVENT_SERVICE_SPECIFICATION_DELETE}")
	private String EVENT_SERVICE_SPECIFICATION_DELETE = "direct:EVENT_SERVICE_SPECIFICATION_DELETE";

	@Value("${EVENT_SERVICE_SPECIFICATION_CHANGE}")
	private String EVENT_SERVICE_SPECIFICATION_CHANGE = "direct:EVENT_SERVICE_SPECIFICATION_CHANGE";

	@Autowired
	private ApplicationContext context;

	@Autowired
	private ProducerTemplate template;


    @Autowired
    private CentralLogger centralLogger;
    
	@Override
	public void configure() throws Exception {
		
	}

	public void publishEvent(Object notification, String objId) {

		try {
			String msgtopic = "";
			
			if (notification instanceof ServiceCatalogCreateNotification) {
				 msgtopic = EVENT_SERVICE_CATALOG_CREATE;
			} else if (notification instanceof ServiceCatalogDeleteNotification) {
				 msgtopic = EVENT_SERVICE_CATALOG_DELETE;
			} else if (notification instanceof ServiceCategoryCreateNotification) {
				 msgtopic = EVENT_SERVICE_CATEGORY_CREATE;
			} else if (notification instanceof ServiceCategoryDeleteNotification) {
				 msgtopic = EVENT_SERVICE_CATEGORY_DELETE;
			} else if (notification instanceof ServiceSpecificationCreateNotification) {
				 msgtopic = EVENT_SERVICE_SPECIFICATION_CREATE;
			} else if (notification instanceof ServiceSpecificationDeleteNotification) {
				 msgtopic = EVENT_SERVICE_SPECIFICATION_DELETE;
			} else if (notification instanceof ServiceSpecificationChangeNotification) {
				 msgtopic = EVENT_SERVICE_SPECIFICATION_CHANGE;
			}
			
			Map<String, Object> map = new HashMap<>();
			String eventId = null;
			
			if (notification instanceof ServiceCatalogCreateNotification) {
				eventId = ((ServiceCatalogCreateNotification) notification).getEventId();
			} else if (notification instanceof ServiceCatalogDeleteNotification) {
				eventId = ((ServiceCatalogDeleteNotification) notification).getEventId();
			} else if (notification instanceof ServiceCategoryCreateNotification) {
				eventId = ((ServiceCategoryCreateNotification) notification).getEventId();
			} else if (notification instanceof ServiceCategoryDeleteNotification) {
				eventId = ((ServiceCategoryDeleteNotification) notification).getEventId();
			} else if (notification instanceof ServiceSpecificationCreateNotification) {
				eventId = ((ServiceSpecificationCreateNotification) notification).getEventId();
			} else if (notification instanceof ServiceSpecificationDeleteNotification) {
				eventId = ((ServiceSpecificationDeleteNotification) notification).getEventId();
			} else if (notification instanceof ServiceSpecificationChangeNotification) {
				eventId = ((ServiceSpecificationChangeNotification) notification).getEventId();
			}
			
			map.put("eventid", eventId);
			map.put("objId", objId);
			
			String apayload = toJsonString(notification);
			map.put("event", apayload);
			
			template.sendBodyAndHeaders(msgtopic, apayload, map);

			String msgtxt = "EVENT " + notification.getClass().getName() + " sent";
			logger.info(msgtxt);
			centralLogger.log(CLevel.INFO, msgtxt, compname());

		} catch (Exception e) {
			e.printStackTrace();
			logger.error("Cannot send Event . " + e.getMessage());
		}
	}

	static String toJsonString(Object object) throws IOException {
		ObjectMapper mapper = new ObjectMapper();
		mapper.registerModule(new JavaTimeModule());
		mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
		return mapper.writeValueAsString(object);
	}

	static <T> T toJsonObj(String content, Class<T> valueType) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(new JavaTimeModule());
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        return mapper.readValue(content, valueType);
    }
	
	private String compname() {
		return "ServiceCatalogApiRouteBuilderEvents";
	}
}
 No newline at end of file
+14 −6
Original line number Diff line number Diff line
@@ -61,10 +61,13 @@ public class CatalogRepoService {
	@Autowired
	ServiceSpecificationRepoService specRepoService;	    

	@Autowired
	ServiceCatalogNotificationService serviceCatalogNotificationService;

	public ServiceCatalog addCatalog(ServiceCatalog c) {

		return this.catalogRepo.save(c);
		ServiceCatalog savedCatalog = this.catalogRepo.save(c);
		serviceCatalogNotificationService.publishServiceCatalogCreateNotification(savedCatalog);
		return savedCatalog;
	}

	public ServiceCatalog addCatalog(@Valid ServiceCatalogCreate serviceCat) {
@@ -72,7 +75,9 @@ public class CatalogRepoService {
		ServiceCatalog sc = new ServiceCatalog();

		sc = updateCatalogDataFromAPICall(sc, serviceCat);
		return this.catalogRepo.save(sc);
		ServiceCatalog savedCatalog = this.catalogRepo.save(sc);
		serviceCatalogNotificationService.publishServiceCatalogCreateNotification(savedCatalog);
		return savedCatalog;
	}

	public String findAllEager() {
@@ -157,9 +162,12 @@ public class CatalogRepoService {

	public Void deleteById(String id) {
		Optional<ServiceCatalog> optionalCat = this.catalogRepo.findByUuid(id);
		this.catalogRepo.delete(optionalCat.get());
		if (optionalCat.isPresent()) {
			ServiceCatalog catalogToDelete = optionalCat.get();
			serviceCatalogNotificationService.publishServiceCatalogDeleteNotification(catalogToDelete);
			this.catalogRepo.delete(catalogToDelete);
		}
		return null;

	}

	public ServiceCatalog updateCatalog(String id, ServiceCatalogUpdate serviceCatalog) {
+23 −9
Original line number Diff line number Diff line
@@ -56,6 +56,9 @@ public class CategoryRepoService {
	
	private final CandidateRepository candidateRepo;
	
	@Autowired
	private ServiceCategoryNotificationService serviceCategoryNotificationService;

	
    @Autowired
    public CategoryRepoService(CategoriesRepository categsRepo, CandidateRepository candidateRepo) {
@@ -64,8 +67,9 @@ public class CategoryRepoService {
    }
	
	public ServiceCategory addCategory(ServiceCategory c) {

		return this.getCategsRepo().save( c );
		ServiceCategory savedCategory = this.getCategsRepo().save(c);
		serviceCategoryNotificationService.publishServiceCategoryCreateNotification(savedCategory);
		return savedCategory;
	}

	public ServiceCategory addCategory(@Valid ServiceCategoryCreate serviceCategory) {	
@@ -73,7 +77,9 @@ public class CategoryRepoService {
		
		ServiceCategory sc = new ServiceCategory() ;
		sc = updateCategoryDataFromAPICall(sc, serviceCategory);
		return this.getCategsRepo().save( sc );
		ServiceCategory savedCategory = this.getCategsRepo().save(sc);
		serviceCategoryNotificationService.publishServiceCategoryCreateNotification(savedCategory);
		return savedCategory;
		
	}

@@ -159,17 +165,25 @@ public class CategoryRepoService {

	public boolean deleteById(String id) {
		Optional<ServiceCategory> optionalCat = this.getCategsRepo().findByUuid( id );
		if ( optionalCat.get().getCategoryObj().size()>0 ) {
		
		// Check if category exists
		if (!optionalCat.isPresent()) {
			return false; // Category not found
		}
		
		ServiceCategory category = optionalCat.get();
		
		if ( category.getCategoryObj().size()>0 ) {
			return false; //has children
		}
		
		
		if ( optionalCat.get().getParentId() != null ) {
			ServiceCategory parentCat = (this.getCategsRepo().findByUuid( optionalCat.get().getParentId() )).get();
		if ( category.getParentId() != null ) {
			ServiceCategory parentCat = (this.getCategsRepo().findByUuid( category.getParentId() )).get();
			
			//remove from parent category
			for (ServiceCategory ss : parentCat.getCategoryObj()) {
				if  ( ss.getId()  == optionalCat.get().getId() ) {
				if  ( ss.getId()  == category.getId() ) {
					 parentCat.getCategoryObj().remove(ss);
					 break;
				}
@@ -177,8 +191,8 @@ public class CategoryRepoService {
			parentCat = this.getCategsRepo().save(parentCat);
		}
		
		
		this.getCategsRepo().delete( optionalCat.get());
		serviceCategoryNotificationService.publishServiceCategoryDeleteNotification(category);
		this.getCategsRepo().delete(category);
		return true;
		
	}
+362 −0

File added.

Preview size limit exceeded, changes collapsed.

+129 −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.scm633.reposervices;

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

import org.etsi.osl.tmf.scm633.api.ServiceCatalogApiRouteBuilderEvents;
import org.etsi.osl.tmf.scm633.model.ServiceCatalog;
import org.etsi.osl.tmf.scm633.model.ServiceCatalogCreateEvent;
import org.etsi.osl.tmf.scm633.model.ServiceCatalogCreateNotification;
import org.etsi.osl.tmf.scm633.model.ServiceCatalogDeleteEvent;
import org.etsi.osl.tmf.scm633.model.ServiceCatalogDeleteNotification;
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 ServiceCatalogNotificationService {

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

    @Autowired
    private ServiceCatalogApiRouteBuilderEvents eventPublisher;

    @Autowired
    private ServiceCatalogCallbackService serviceCatalogCallbackService;

    /**
     * Publish a service catalog create notification
     * @param serviceCatalog The created service catalog
     */
    public void publishServiceCatalogCreateNotification(ServiceCatalog serviceCatalog) {
        try {
            ServiceCatalogCreateNotification notification = createServiceCatalogCreateNotification(serviceCatalog);
            eventPublisher.publishEvent(notification, serviceCatalog.getUuid());
            
            // Send callbacks to registered subscribers
            serviceCatalogCallbackService.sendServiceCatalogCreateCallback(notification.getEvent());
            
            logger.info("Published service catalog create notification for service catalog ID: {}", serviceCatalog.getUuid());
        } catch (Exception e) {
            logger.error("Error publishing service catalog create notification for service catalog ID: {}", serviceCatalog.getUuid(), e);
        }
    }

    /**
     * Publish a service catalog delete notification
     * @param serviceCatalog The deleted service catalog
     */
    public void publishServiceCatalogDeleteNotification(ServiceCatalog serviceCatalog) {
        try {
            ServiceCatalogDeleteNotification notification = createServiceCatalogDeleteNotification(serviceCatalog);
            eventPublisher.publishEvent(notification, serviceCatalog.getUuid());
            
            // Send callbacks to registered subscribers
            serviceCatalogCallbackService.sendServiceCatalogDeleteCallback(notification.getEvent());
            
            logger.info("Published service catalog delete notification for service catalog ID: {}", serviceCatalog.getUuid());
        } catch (Exception e) {
            logger.error("Error publishing service catalog delete notification for service catalog ID: {}", serviceCatalog.getUuid(), e);
        }
    }

    /**
     * Create a service catalog create notification
     * @param serviceCatalog The created service catalog
     * @return ServiceCatalogCreateNotification
     */
    private ServiceCatalogCreateNotification createServiceCatalogCreateNotification(ServiceCatalog serviceCatalog) {
        ServiceCatalogCreateNotification notification = new ServiceCatalogCreateNotification();
        
        // Set common notification properties
        notification.setEventId(UUID.randomUUID().toString());
        notification.setEventTime(OffsetDateTime.now(ZoneOffset.UTC));
        notification.setEventType(ServiceCatalogCreateNotification.class.getName());
        notification.setResourcePath("/serviceCatalogManagement/v4/serviceCatalog/" + serviceCatalog.getUuid());

        // Create event
        ServiceCatalogCreateEvent event = new ServiceCatalogCreateEvent();
        event.setServiceCatalog(serviceCatalog);

        notification.setEvent(event);
        return notification;
    }

    /**
     * Create a service catalog delete notification
     * @param serviceCatalog The deleted service catalog
     * @return ServiceCatalogDeleteNotification
     */
    private ServiceCatalogDeleteNotification createServiceCatalogDeleteNotification(ServiceCatalog serviceCatalog) {
        ServiceCatalogDeleteNotification notification = new ServiceCatalogDeleteNotification();
        
        // Set common notification properties
        notification.setEventId(UUID.randomUUID().toString());
        notification.setEventTime(OffsetDateTime.now(ZoneOffset.UTC));
        notification.setEventType(ServiceCatalogDeleteNotification.class.getName());
        notification.setResourcePath("/serviceCatalogManagement/v4/serviceCatalog/" + serviceCatalog.getUuid());

        // Create event
        ServiceCatalogDeleteEvent event = new ServiceCatalogDeleteEvent();
        event.setServiceCatalog(serviceCatalog);

        notification.setEvent(event);
        return notification;
    }
}
 No newline at end of file
Loading