Commit dd74cd65 authored by Christos Tranoris's avatar Christos Tranoris
Browse files

fix for 115

parent 246c5604
Loading
Loading
Loading
Loading
Loading
+43
Changes for src/main/java/org/etsi/osl/tmf/sim638/api/ServiceApiController.java: 43 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -88,6 +88,20 @@ public class ServiceApiController implements ServiceApi {
				service.setRelatedParty(AddUserAsOwnerToRelatedParties.addUser(principal.getName(), principal.getName(),
						UserPartRoleType.REQUESTER, "", service.getRelatedParty()));

				// Create a temporary service object to check consistency
				Service tempService = new Service();
				tempService.setServiceSpecificationRef(service.getServiceSpecificationRef());
				if (service.getServiceCharacteristic() != null) {
					tempService.getServiceCharacteristic().addAll(service.getServiceCharacteristic());
				}

				// Check consistency before creating the service
				String consistencyReason = serviceRepoService.checkConsistencyReason(tempService);
				if (consistencyReason != null) {
					log.warn("Service consistency check failed: " + consistencyReason);
					return new ResponseEntity<Service>(HttpStatus.BAD_REQUEST);
				}

				Service c = serviceRepoService.addService(service);

				return new ResponseEntity<Service>(c, HttpStatus.OK);
@@ -135,6 +149,35 @@ public class ServiceApiController implements ServiceApi {
	@PreAuthorize("hasAnyAuthority('ROLE_USER')" )
	@Override
	public ResponseEntity<Service> patchService(Principal principal, String id, @Valid ServiceUpdate service) {
		// Check consistency if service characteristics or specification are being updated
		if (service.getServiceCharacteristic() != null ) {
			// Create a temporary service object to check consistency
			Service tempService = new Service();

			// Get the existing service to check against
			Service existingService = serviceRepoService.findByUuid(id);
			if (existingService == null) {
				log.warn("Service not found with id: " + id);
				return new ResponseEntity<Service>(HttpStatus.NOT_FOUND);
			}

			tempService.setServiceSpecificationRef(existingService.getServiceSpecificationRef());
			
			// Use the updated characteristics if provided, otherwise use the existing ones
			if (service.getServiceCharacteristic() != null) {
				tempService.getServiceCharacteristic().addAll(service.getServiceCharacteristic());
			} else {
				tempService.getServiceCharacteristic().addAll(existingService.getServiceCharacteristic());
			}

			// Check consistency before updating the service
			String consistencyReason = serviceRepoService.checkConsistencyReason(tempService);
			if (consistencyReason != null) {
				log.warn("Service consistency check failed during patch: " + consistencyReason);
				return new ResponseEntity<Service>(HttpStatus.BAD_REQUEST);
			}
		}

		Service c = serviceRepoService.updateService(id, service, true, null, null);

		return new ResponseEntity<Service>(c, HttpStatus.OK);
+108 −10
Changes for src/main/java/org/etsi/osl/tmf/sim638/service/ServiceRepoService.java: 108 added lines, 10 removed lines.
Original line number Diff line number Diff line
@@ -22,24 +22,19 @@ package org.etsi.osl.tmf.sim638.service;
import java.io.UnsupportedEncodingException;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.datatype.hibernate5.jakarta.Hibernate5JakartaModule;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.etsi.osl.model.nfv.DeploymentDescriptor;
import org.etsi.osl.model.nfv.DeploymentDescriptorVxFInstanceInfo;
import org.etsi.osl.tmf.common.model.Any;
import org.etsi.osl.tmf.common.model.UserPartRoleType;
import org.etsi.osl.tmf.common.model.service.Characteristic;
@@ -80,8 +75,11 @@ import org.hibernate.transform.ResultTransformer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.etsi.osl.model.nfv.DeploymentDescriptor;
import org.etsi.osl.model.nfv.DeploymentDescriptorVxFInstanceInfo;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.datatype.hibernate5.jakarta.Hibernate5JakartaModule;
import jakarta.persistence.EntityManagerFactory;
import jakarta.validation.Valid;

@@ -1365,6 +1363,106 @@ public class ServiceRepoService {

    }

    /**
     * Checks the consistency between a Service and its ServiceSpecification and returns the reason if inconsistent.
     *
     * @param service The Service to check
     * @return null if consistent, otherwise a string describing the inconsistency reason
     */
    @Transactional
    public String checkConsistencyReason(Service service) {
        if (service == null) {
            return "Service is null";
        }

        if (service.getServiceSpecificationRef() == null) {
            return "Service has no ServiceSpecificationRef";
        }

        String specId = service.getServiceSpecificationRef().getId();
        if (specId == null || specId.isEmpty()) {
            return "ServiceSpecificationRef has no id";
        }

        // Retrieve the ServiceSpecification using the id from ServiceSpecificationRef
        org.etsi.osl.tmf.scm633.model.ServiceSpecification serviceSpec = serviceSpecRepoService.findByUuidEager(specId);

        if (serviceSpec == null) {
            return "ServiceSpecification not found with id " + specId;
        }

        // Get the service characteristics from both entities
        Set<Characteristic> serviceCharacteristics = service.getServiceCharacteristic();
        Set<org.etsi.osl.tmf.scm633.model.ServiceSpecCharacteristic> specCharacteristics = serviceSpec.getServiceSpecCharacteristic();

        // Create maps for easier lookup and validation
        Set<String> serviceCharNames = new HashSet<>();
        for (Characteristic serviceChar : serviceCharacteristics) {
            if (serviceChar.getName() != null) {
                serviceCharNames.add(serviceChar.getName());
            }
        }

        // Create a map of spec characteristic names to their configurable status
        Map<String, org.etsi.osl.tmf.scm633.model.ServiceSpecCharacteristic> specCharMap = new HashMap<>();
        for (org.etsi.osl.tmf.scm633.model.ServiceSpecCharacteristic specChar : specCharacteristics) {
            if (specChar.getName() != null) {
                specCharMap.put(specChar.getName(), specChar);
            }
        }

        // Validate each spec characteristic
        // Configurable characteristics MAY exist in service (optional)
        // Non-configurable characteristics must NOT exist in service
        for (org.etsi.osl.tmf.scm633.model.ServiceSpecCharacteristic specChar : specCharacteristics) {
            if (specChar.getName() == null) {
                continue;
            }

            boolean isConfigurable = specChar.isConfigurable() != null && specChar.isConfigurable();
            boolean existsInService = serviceCharNames.contains(specChar.getName());

            if (!isConfigurable && existsInService) {
                // Non-configurable characteristics must NOT exist in the service
                return "Service has non-configurable characteristic '" + specChar.getName() +
                       "' which should not exist in the service (non-configurable characteristics should not be instantiated)";
            }
        }

        // Check that all service characteristics are defined in the spec
        for (Characteristic serviceChar : serviceCharacteristics) {
            if (serviceChar.getName() == null) {
                return "Service has a characteristic with null name";
            }

            if (!specCharMap.containsKey(serviceChar.getName())) {
                return "Service has characteristic '" + serviceChar.getName() +
                       "' which is not defined in ServiceSpecification " + specId;
            }
        }

        return null; // Consistent
    }

    /**
     * Checks the consistency between a Service and its ServiceSpecification.
     * Compares the ServiceCharacteristics of the Service with the ServiceSpecCharacteristics
     * from the ServiceSpecification to ensure they have the same names and count.
     *
     * @param service The Service to check
     * @return true if the service characteristics are consistent with the specification, false otherwise
     */
    @Transactional
    public boolean checkConsistency(Service service) {
        String reason = checkConsistencyReason(service);
        if (reason != null) {
            logger.warn("checkConsistency: " + reason);
            return false;
        }
        logger.debug("checkConsistency: Service " + (service != null ? service.getId() : "null") + " is consistent with its ServiceSpecification");
        return true;
    }

    /**
     * This function will try to identify if the resource contains
     * a characteristic called "org.etsi.osl.serviceId" and will check if there is a related service.
+6 −13
Changes for src/test/java/org/etsi/osl/services/api/sim638/ServiceApiControllerTest.java: 6 added lines, 13 removed lines.
Original line number Diff line number Diff line
@@ -210,29 +210,22 @@ public class ServiceApiControllerTest extends BaseIT {
        sspeccr.setName("Spec1");
        ServiceSpecification responsesSpec = createServiceSpec( sspeccr);

        ServiceOrderCreate serviceOrder = new ServiceOrderCreate();
        serviceOrder.setCategory("Test Category");
        serviceOrder.setDescription("A Test Service");
        serviceOrder.setRequestedStartDate(OffsetDateTime.now(ZoneOffset.UTC).toString());
        serviceOrder.setRequestedCompletionDate(OffsetDateTime.now(ZoneOffset.UTC).toString());
        ServiceCreate aService = new ServiceCreate();
        aService.setCategory("Test Category");
        aService.setDescription("A Test Service");

        ServiceOrderItem soi = new ServiceOrderItem();
        serviceOrder.getOrderItem().add(soi);
        soi.setState(ServiceOrderStateType.ACKNOWLEDGED);

        ServiceRestriction serviceRestriction = new ServiceRestriction();
        ServiceSpecificationRef aServiceSpecificationRef = new ServiceSpecificationRef();
        aServiceSpecificationRef.setId(responsesSpec.getId() );
        aServiceSpecificationRef.setName(responsesSpec.getName());

        serviceRestriction.setServiceSpecification(aServiceSpecificationRef);
        serviceRestriction.setName("aServiceRestriction");
        soi.setService(serviceRestriction);
        aService.setServiceSpecificationRef(aServiceSpecificationRef );
        //Service has no ServiceSpecificationRef
        
        String response = mvc
                .perform(MockMvcRequestBuilders.post("/serviceInventory/v4/service")
                        .with( SecurityMockMvcRequestPostProcessors.csrf())
                        .contentType(MediaType.APPLICATION_JSON).content(JsonUtils.toJson(serviceOrder)))
                        .contentType(MediaType.APPLICATION_JSON).content(JsonUtils.toJson(aService)))
                .andExpect(status().isOk()).andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk()).andReturn().getResponse().getContentAsString();