Commit 7214aa27 authored by Christos Tranoris's avatar Christos Tranoris
Browse files

Merge branch...

Merge branch '82-implement-the-notifications-of-tmf620-v4-product-catalog-management' into 83-implement-the-listener-api-for-product-catalog-620-with-just-stub-code
parents 9937a3f7 4f5ab1c8
Loading
Loading
Loading
Loading
Loading
+50 −1
Original line number Diff line number Diff line
@@ -22,21 +22,38 @@ package org.etsi.osl.tmf.pcm620.api;
import java.util.Optional;

import com.fasterxml.jackson.databind.ObjectMapper;

import org.etsi.osl.tmf.pcm620.model.EventSubscription;
import org.etsi.osl.tmf.pcm620.model.EventSubscriptionInput;
import org.etsi.osl.tmf.pcm620.reposervices.EventSubscriptionRepoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import io.swagger.v3.oas.annotations.Parameter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
@jakarta.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2019-10-19T00:15:57.249+03:00")

@Controller("HubApiController620")
@RequestMapping("/productCatalogManagement/v4/")
public class HubApiController implements HubApi {

    private static final Logger log = LoggerFactory.getLogger(HubApiController.class);

    private final ObjectMapper objectMapper;

    private final HttpServletRequest request;

    @Autowired
    EventSubscriptionRepoService eventSubscriptionRepoService;

    @org.springframework.beans.factory.annotation.Autowired
    public HubApiController(ObjectMapper objectMapper, HttpServletRequest request) {
        this.objectMapper = objectMapper;
@@ -53,4 +70,36 @@ public class HubApiController implements HubApi {
        return Optional.ofNullable(request);
    }

    @Override
    @PreAuthorize("hasAnyAuthority('ROLE_ADMIN', 'ROLE_USER')")
    public ResponseEntity<EventSubscription> registerListener(@Parameter(description = "Data containing the callback endpoint to deliver the information", required = true) @Valid @RequestBody EventSubscriptionInput data) {
        try {
            EventSubscription eventSubscription = eventSubscriptionRepoService.addEventSubscription(data);
            return new ResponseEntity<>(eventSubscription, HttpStatus.CREATED);
        } catch (IllegalArgumentException e) {
            log.error("Invalid input for listener registration: {}", e.getMessage());
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        } catch (Exception e) {
            log.error("Error registering listener", e);
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @Override
    @PreAuthorize("hasAnyAuthority('ROLE_ADMIN', 'ROLE_USER')")
    public ResponseEntity<Void> unregisterListener(@Parameter(description = "The id of the registered listener", required = true) @PathVariable("id") String id) {
        try {
            EventSubscription existing = eventSubscriptionRepoService.findById(id);
            if (existing == null) {
                return new ResponseEntity<>(HttpStatus.NOT_FOUND);
            }
            
            eventSubscriptionRepoService.deleteById(id);
            return new ResponseEntity<>(HttpStatus.NO_CONTENT);
        } catch (Exception e) {
            log.error("Error unregistering listener with id: " + id, e);
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

}
+186 −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.pcm620.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 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.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.etsi.osl.tmf.pcm620.model.ProductSpecificationCreateNotification;
import org.etsi.osl.tmf.pcm620.model.ProductSpecificationDeleteNotification;
import org.etsi.osl.tmf.pcm620.model.ProductOfferingCreateNotification;
import org.etsi.osl.tmf.pcm620.model.ProductOfferingDeleteNotification;
import org.etsi.osl.tmf.pcm620.model.ProductOfferingAttributeValueChangeNotification;
import org.etsi.osl.tmf.pcm620.model.ProductOfferingStateChangeNotification;
import org.etsi.osl.tmf.pcm620.model.ProductOfferingPriceCreateNotification;
import org.etsi.osl.tmf.pcm620.model.ProductOfferingPriceDeleteNotification;
import org.etsi.osl.tmf.pcm620.model.ProductOfferingPriceAttributeValueChangeNotification;
import org.etsi.osl.tmf.pcm620.model.ProductOfferingPriceStateChangeNotification;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Configuration
@Component
public class ProductCatalogApiRouteBuilderEvents extends RouteBuilder {

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

	@Value("${EVENT_PRODUCT_CATALOG_CREATE}")
	private String EVENT_CATALOG_CREATE = "";
	
	@Value("${EVENT_PRODUCT_CATALOG_DELETE}")
	private String EVENT_CATALOG_DELETE = "";
	
	@Value("${EVENT_PRODUCT_CATEGORY_CREATE}")
	private String EVENT_CATEGORY_CREATE = "";
	
	@Value("${EVENT_PRODUCT_CATEGORY_DELETE}")
	private String EVENT_CATEGORY_DELETE = "";
	
	@Value("${EVENT_PRODUCT_SPECIFICATION_CREATE}")
	private String EVENT_PRODUCT_SPECIFICATION_CREATE = "";
	
	@Value("${EVENT_PRODUCT_SPECIFICATION_DELETE}")
	private String EVENT_PRODUCT_SPECIFICATION_DELETE  = "";
	
	@Value("${EVENT_PRODUCT_OFFERING_CREATE}")
	private String EVENT_PRODUCT_OFFERING_CREATE = "";
	
	@Value("${EVENT_PRODUCT_OFFERING_DELETE}")
	private String EVENT_PRODUCT_OFFERING_DELETE = "";
	
	@Value("${EVENT_PRODUCT_OFFERING_ATTRIBUTE_VALUE_CHANGE}")
	private String EVENT_PRODUCT_OFFERING_ATTRIBUTE_VALUE_CHANGE = "";
	
	@Value("${EVENT_PRODUCT_OFFERING_STATE_CHANGE}")
	private String EVENT_PRODUCT_OFFERING_STATE_CHANGE = "";
	
	@Value("${EVENT_PRODUCT_OFFERING_PRICE_CREATE}")
	private String EVENT_PRODUCT_OFFERING_PRICE_CREATE = "";
	
	@Value("${EVENT_PRODUCT_OFFERING_PRICE_DELETE}")
	private String EVENT_PRODUCT_OFFERING_PRICE_DELETE = "";
	
	@Value("${EVENT_PRODUCT_OFFERING_PRICE_ATTRIBUTE_VALUE_CHANGE}")
	private String EVENT_PRODUCT_OFFERING_PRICE_ATTRIBUTE_VALUE_CHANGE = "";
	
	@Value("${EVENT_PRODUCT_OFFERING_PRICE_STATE_CHANGE}")
	private String EVENT_PRODUCT_OFFERING_PRICE_STATE_CHANGE = "";

	@Value("${spring.application.name}")
	private String compname;
	
	@Autowired
	private ProducerTemplate template;

	@Autowired
	private CentralLogger centralLogger;

	@Override
	public void configure() throws Exception {
		// Configure routes for catalog events
	}

	/**
	 * Publish notification events for catalog operations
	 * @param n The notification to publish
	 * @param objId The catalog object ID
	 */
    @Transactional
	public void publishEvent(final Notification n, final String objId) {
		n.setEventType(n.getClass().getName());
		logger.info("will send Event for type " + n.getEventType());
		try {
			String msgtopic = "";
			
			if (n instanceof CatalogCreateNotification) {
				 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;
			} else if (n instanceof ProductSpecificationCreateNotification) {
				 msgtopic = EVENT_PRODUCT_SPECIFICATION_CREATE;
			} else if (n instanceof ProductSpecificationDeleteNotification) {
				 msgtopic = EVENT_PRODUCT_SPECIFICATION_DELETE;
			} else if (n instanceof ProductOfferingCreateNotification) {
				 msgtopic = EVENT_PRODUCT_OFFERING_CREATE;
			} else if (n instanceof ProductOfferingDeleteNotification) {
				 msgtopic = EVENT_PRODUCT_OFFERING_DELETE;
			} else if (n instanceof ProductOfferingAttributeValueChangeNotification) {
				 msgtopic = EVENT_PRODUCT_OFFERING_ATTRIBUTE_VALUE_CHANGE;
			} else if (n instanceof ProductOfferingStateChangeNotification) {
				 msgtopic = EVENT_PRODUCT_OFFERING_STATE_CHANGE;
			} else if (n instanceof ProductOfferingPriceCreateNotification) {
				 msgtopic = EVENT_PRODUCT_OFFERING_PRICE_CREATE;
			} else if (n instanceof ProductOfferingPriceDeleteNotification) {
				 msgtopic = EVENT_PRODUCT_OFFERING_PRICE_DELETE;
			} else if (n instanceof ProductOfferingPriceAttributeValueChangeNotification) {
				 msgtopic = EVENT_PRODUCT_OFFERING_PRICE_ATTRIBUTE_VALUE_CHANGE;
			} else if (n instanceof ProductOfferingPriceStateChangeNotification) {
				 msgtopic = EVENT_PRODUCT_OFFERING_PRICE_STATE_CHANGE;
			}
			
			Map<String, Object> map = new HashMap<>();
			map.put("eventid", n.getEventId());
			map.put("objId", objId);
			
			String apayload = toJsonString(n);
			template.sendBodyAndHeaders(msgtopic, apayload, map);
			
			centralLogger.log(CLevel.INFO, apayload, 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.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.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        return mapper.readValue(content, valueType);
    }
}
 No newline at end of file
+39 −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.configuration;

import java.time.Duration;

import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        return builder
                .setConnectTimeout(Duration.ofSeconds(10))
                .setReadTimeout(Duration.ofSeconds(30))
                .build();
    }
}
 No newline at end of file
+32 −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.repo;

import java.util.Optional;
import org.etsi.osl.tmf.pcm620.model.EventSubscription;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface EventSubscriptionRepository extends CrudRepository<EventSubscription, String>, PagingAndSortingRepository<EventSubscription, String> {

    Optional<EventSubscription> findById(String id);
}
 No newline at end of file
+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.CatalogCreateEvent;
import org.etsi.osl.tmf.pcm620.model.CatalogDeleteEvent;
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 CatalogCallbackService {

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

    @Autowired
    private EventSubscriptionRepoService eventSubscriptionRepoService;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * Send catalog create event to all registered callback URLs
     * @param catalogCreateEvent The catalog create event to send
     */
    public void sendCatalogCreateCallback(CatalogCreateEvent catalogCreateEvent) {
        List<EventSubscription> subscriptions = eventSubscriptionRepoService.findAll();
        
        for (EventSubscription subscription : subscriptions) {
            if (shouldNotifySubscription(subscription, "catalogCreateEvent")) {
                sendCatalogCreateEventToCallback(subscription.getCallback(), catalogCreateEvent);
            }
        }
    }

    /**
     * Send catalog delete event to all registered callback URLs
     * @param catalogDeleteEvent The catalog delete event to send
     */
    public void sendCatalogDeleteCallback(CatalogDeleteEvent catalogDeleteEvent) {
        List<EventSubscription> subscriptions = eventSubscriptionRepoService.findAll();
        
        for (EventSubscription subscription : subscriptions) {
            if (shouldNotifySubscription(subscription, "catalogDeleteEvent")) {
                sendCatalogDeleteEventToCallback(subscription.getCallback(), catalogDeleteEvent);
            }
        }
    }

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

    /**
     * Send catalog delete event to a specific callback URL
     * @param callbackUrl The callback URL to send to
     * @param event The catalog delete event
     */
    private void sendCatalogDeleteEventToCallback(String callbackUrl, CatalogDeleteEvent event) {
        try {
            String url = buildCallbackUrl(callbackUrl, "/listener/catalogDeleteEvent");
            
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<CatalogDeleteEvent> entity = new HttpEntity<>(event, headers);
            
            ResponseEntity<String> response = restTemplate.exchange(
                url, HttpMethod.POST, entity, String.class);
            
            logger.info("Successfully sent catalog delete event to callback URL: {} - Response: {}", 
                url, response.getStatusCode());
            
        } catch (Exception e) {
            logger.error("Failed to send catalog 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("catalog") || 
               query.contains(eventType.toLowerCase()) ||
               query.contains("catalog.create") ||
               query.contains("catalog.delete");
    }
}
 No newline at end of file
Loading