Commit af13ba21 authored by Kostis Trantzas's avatar Kostis Trantzas
Browse files

Check for a not null Service Specification, when appending a new Service Order...

Check for a not null Service Specification, when appending a new Service Order Item (match Service Order create) + unit tests
parent 9f32c4b9
Loading
Loading
Loading
Loading
Loading
+5
Changes for src/main/java/org/etsi/osl/tmf/so641/api/ServiceOrderApiController.java: 5 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -218,9 +218,14 @@ public class ServiceOrderApiController implements ServiceOrderApi {
			Principal principal,			
			@Parameter(description = "Identifier of the ServiceOrder", required = true) @PathVariable("id") String id,
			@Parameter(description = "The ServiceOrder to be updated", required = true) @Valid @RequestBody ServiceOrderUpdate serviceOrder) {
		try {
			ServiceOrder c = serviceOrderRepoService.updateServiceOrder(id, serviceOrder);

			return new ResponseEntity<ServiceOrder>(c, HttpStatus.OK);
		} catch (NotFoundException e) {
			log.error("Couldn't update Service Order. ", e);
			return new ResponseEntity<ServiceOrder>(HttpStatus.BAD_REQUEST);
		}
	}

	@PreAuthorize("hasAnyAuthority('ROLE_USER')" )
+31 −9
Changes for src/main/java/org/etsi/osl/tmf/so641/reposervices/ServiceOrderRepoService.java: 31 added lines, 9 removed lines.
Original line number Diff line number Diff line
@@ -462,14 +462,7 @@ public class ServiceOrderRepoService {
		// Ensure that all Services Specifications exist
		List <ServiceOrderItem> serviceOrderItemList = serviceOrderCreate.getOrderItem();
		for (ServiceOrderItem serviceOrderItem: serviceOrderItemList) {
			ServiceRestriction serviceRestriction = serviceOrderItem.getService();
			ServiceSpecificationRef serviceSpecificationRef = serviceRestriction.getServiceSpecification();
			String serviceSpecificationId = serviceSpecificationRef.getId();

			ServiceSpecification serviceSpecification = serviceSpecRepoService.findByUuid(serviceSpecificationId);

			if (serviceSpecification == null)
				throw new NotFoundException(400, "There is no Service Specification with Id: " + serviceSpecificationId);
			checkServiceSpecificationExists(serviceOrderItem);
		}

		ServiceOrder so = new ServiceOrder();
@@ -701,12 +694,41 @@ public class ServiceOrderRepoService {
		
	}

	/**
	 * Ensures that the order item references an existing Service Specification
	 *
	 * @param soi
	 * @throws NotFoundException (400) if the item has no service specification or it does not exist
	 */
	private void checkServiceSpecificationExists(ServiceOrderItem soi) throws NotFoundException {
		ServiceSpecificationRef serviceSpecificationRef = ( soi.getService() != null ) ? soi.getService().getServiceSpecification() : null;
		String serviceSpecificationId = ( serviceSpecificationRef != null ) ? serviceSpecificationRef.getId() : null;

		if ( ( serviceSpecificationId == null ) || ( serviceSpecRepoService.findByUuid(serviceSpecificationId) == null ) ) {
			throw new NotFoundException(400, "There is no Service Specification with Id: " + serviceSpecificationId);
		}
	}

	@Transactional
	public ServiceOrder updateServiceOrder(String id, @Valid ServiceOrderUpdate serviceOrderUpd) {
	public ServiceOrder updateServiceOrder(String id, @Valid ServiceOrderUpdate serviceOrderUpd) throws NotFoundException {

		logger.info("Will updateServiceOrder:" + id);

		ServiceOrder so = this.findByUuid(id);

		/**
		 * Order items to be appended are validated before anything is changed: the order is managed,
		 * and a checked exception does not roll the transaction back, so a later throw would still
		 * commit the part of the update applied until then
		 */
		if ( serviceOrderUpd.getOrderItem() != null ) {
			for (ServiceOrderItem soiUpd :  serviceOrderUpd.getOrderItem()) {
				if ( so.findOrderItemById( soiUpd.getId() ) == null ) {
					checkServiceSpecificationExists( soiUpd );
				}
			}
		}

		boolean stateChanged = false;
		boolean expectedCompletionDateChanged = false;

+152
Changes for src/test/java/org/etsi/osl/services/api/so641/ServiceOrderRepoServiceTest.java: 152 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -19,6 +19,8 @@ import org.apache.commons.io.IOUtils;
import org.etsi.osl.services.api.BaseIT;
import org.etsi.osl.tmf.JsonUtils;
import java.util.stream.Collectors;
import org.etsi.osl.tmf.common.model.Any;
import org.etsi.osl.tmf.common.model.service.Characteristic;
import org.etsi.osl.tmf.common.model.service.Note;
import org.etsi.osl.tmf.common.model.service.ServiceSpecificationRef;
import org.etsi.osl.tmf.common.model.service.ServiceStateType;
@@ -29,6 +31,7 @@ import org.etsi.osl.tmf.so641.repo.ServiceOrderRepository;
import org.etsi.osl.tmf.scm633.model.ServiceSpecification;
import org.etsi.osl.tmf.scm633.model.ServiceSpecificationCreate;
import org.etsi.osl.tmf.so641.model.ServiceOrder;
import org.etsi.osl.tmf.so641.model.ServiceOrderActionType;
import org.etsi.osl.tmf.so641.model.ServiceOrderCreate;
import org.etsi.osl.tmf.so641.model.ServiceOrderItem;
import org.etsi.osl.tmf.so641.model.ServiceOrderRelationship;
@@ -342,6 +345,155 @@ public class ServiceOrderRepoServiceTest extends BaseIT {
    }


    /**
     * An existing order is amended with one new order item via PATCH (#105).
     * Before the fix, an item the order did not carry was silently dropped.
     */
    @WithMockUser(username="osadmin", roles = {"ADMIN","USER"})
    @Test
    public void testUpdateServiceOrderAppendsNewOrderItem() throws Exception {

        ServiceOrder createdServiceOrder = JsonUtils.toJsonObj(createServiceOrder(), ServiceOrder.class);
        String soId = createdServiceOrder.getId();
        ServiceOrderItem originalItem = createdServiceOrder.getOrderItem().iterator().next();
        String specId = originalItem.getService().getServiceSpecification().getId();

        ServiceOrderUpdate servOrderUpd = new ServiceOrderUpdate();
        servOrderUpd.addOrderItemItem(newOrderItem(specId, "addedRestriction", "addedValue"));
        patchServiceOrder(soId, servOrderUpd);

        ServiceOrder updatedServiceOrder = JsonUtils.toJsonObj(
                serviceOrderRepoService.getServiceOrderEagerAsString(soId), ServiceOrder.class);

        assertThat(updatedServiceOrder.getOrderItem()).hasSize(2);
        assertThat(updatedServiceOrder.findOrderItemById(originalItem.getId())).isNotNull();

        ServiceOrderItem addedItem = updatedServiceOrder.getOrderItem().stream()
                .filter(soi -> !soi.getId().equals(originalItem.getId())).findFirst().orElseThrow();
        assertThat(addedItem.getId()).isNotNull();
        assertThat(addedItem.getAction()).isEqualTo(ServiceOrderActionType.ADD);
        assertThat(addedItem.getService().getName()).isEqualTo("addedRestriction");
        assertThat(addedItem.getService().getServiceSpecification().getId()).isEqualTo(specId);
        assertThat(addedItem.getService().findCharacteristicByName("addedChar").getValue().getValue())
                .isEqualTo("addedValue");
    }


    /**
     * An existing order is amended with two new order items in the same PATCH (#105).
     * The first appended item is still transient (no uuid) while the second one is looked up,
     * which threw a NullPointerException in ServiceOrder.findOrderItemById before model.tmf #39.
     */
    @WithMockUser(username="osadmin", roles = {"ADMIN","USER"})
    @Test
    public void testUpdateServiceOrderAppendsTwoNewOrderItems() throws Exception {

        ServiceOrder createdServiceOrder = JsonUtils.toJsonObj(createServiceOrder(), ServiceOrder.class);
        String soId = createdServiceOrder.getId();
        ServiceOrderItem originalItem = createdServiceOrder.getOrderItem().iterator().next();
        String specId = originalItem.getService().getServiceSpecification().getId();

        ServiceOrderUpdate servOrderUpd = new ServiceOrderUpdate();
        servOrderUpd.addOrderItemItem(newOrderItem(specId, "firstAddedRestriction", "firstValue"));
        servOrderUpd.addOrderItemItem(newOrderItem(specId, "secondAddedRestriction", "secondValue"));
        patchServiceOrder(soId, servOrderUpd);

        ServiceOrder updatedServiceOrder = JsonUtils.toJsonObj(
                serviceOrderRepoService.getServiceOrderEagerAsString(soId), ServiceOrder.class);

        assertThat(updatedServiceOrder.getOrderItem()).hasSize(3);
        assertThat(updatedServiceOrder.findOrderItemById(originalItem.getId())).isNotNull();
        assertThat(updatedServiceOrder.getOrderItem().stream().map(ServiceOrderItem::getId).distinct().count())
                .isEqualTo(3);

        List<ServiceOrderItem> addedItems = updatedServiceOrder.getOrderItem().stream()
                .filter(soi -> !soi.getId().equals(originalItem.getId())).collect(Collectors.toList());
        assertThat(addedItems).extracting(soi -> soi.getService().getName())
                .containsExactlyInAnyOrder("firstAddedRestriction", "secondAddedRestriction");
        assertThat(addedItems).extracting(soi -> soi.getService().findCharacteristicByName("addedChar").getValue().getValue())
                .containsExactlyInAnyOrder("firstValue", "secondValue");
    }


    /**
     * A new order item must reference an existing Service Specification, as on order creation.
     * The PATCH is rejected with 400 and none of it is applied, not even the other attributes it carries.
     */
    @WithMockUser(username="osadmin", roles = {"ADMIN","USER"})
    @Test
    public void testUpdateServiceOrderRejectsNewOrderItemWithUnknownSpec() throws Exception {

        ServiceOrder createdServiceOrder = JsonUtils.toJsonObj(createServiceOrder(), ServiceOrder.class);
        String soId = createdServiceOrder.getId();

        // a service specification that does not exist
        ServiceOrderUpdate servOrderUpd = new ServiceOrderUpdate();
        servOrderUpd.setDescription("Should not be applied");
        servOrderUpd.addOrderItemItem(newOrderItem("no-such-spec", "rejectedRestriction", "rejectedValue"));
        patchServiceOrderExpectingBadRequest(soId, servOrderUpd);

        // no service specification at all
        ServiceOrderUpdate servOrderUpdNoSpec = new ServiceOrderUpdate();
        servOrderUpdNoSpec.setDescription("Should not be applied");
        ServiceOrderItem noSpecItem = new ServiceOrderItem();
        noSpecItem.setService(new ServiceRestriction());
        servOrderUpdNoSpec.addOrderItemItem(noSpecItem);
        patchServiceOrderExpectingBadRequest(soId, servOrderUpdNoSpec);

        ServiceOrder unchangedServiceOrder = JsonUtils.toJsonObj(
                serviceOrderRepoService.getServiceOrderEagerAsString(soId), ServiceOrder.class);
        assertThat(unchangedServiceOrder.getOrderItem()).hasSize(1);
        assertThat(unchangedServiceOrder.getDescription()).isEqualTo("A Test Service Order");
    }


    private void patchServiceOrderExpectingBadRequest(String soId, ServiceOrderUpdate servOrderUpd) throws Exception {

        mvc.perform(MockMvcRequestBuilders.patch("/serviceOrdering/v4/serviceOrder/" + soId)
                        .with( SecurityMockMvcRequestPostProcessors.csrf())
                        .contentType(MediaType.APPLICATION_JSON)
                        .content( JsonUtils.toJson( servOrderUpd ) ))
                .andExpect(status().isBadRequest() );
    }


    /**
     * A new order item as a client would send it: no uuid, so the order does not carry it yet
     */
    private ServiceOrderItem newOrderItem(String specId, String restrictionName, String charValue) {

        ServiceOrderItem soi = new ServiceOrderItem();
        soi.setAction(ServiceOrderActionType.ADD);
        soi.setState(ServiceOrderStateType.ACKNOWLEDGED);

        ServiceSpecificationRef aServiceSpecificationRef = new ServiceSpecificationRef();
        aServiceSpecificationRef.setId(specId);

        ServiceRestriction serviceRestriction = new ServiceRestriction();
        serviceRestriction.setServiceSpecification(aServiceSpecificationRef);
        serviceRestriction.setName(restrictionName);

        Characteristic aCharacteristic = new Characteristic();
        aCharacteristic.setName("addedChar");
        aCharacteristic.setValue(new Any(charValue, charValue));
        serviceRestriction.addServiceCharacteristicItem(aCharacteristic);

        soi.setService(serviceRestriction);
        return soi;
    }


    private void patchServiceOrder(String soId, ServiceOrderUpdate servOrderUpd) throws Exception {

        mvc.perform(MockMvcRequestBuilders.patch("/serviceOrdering/v4/serviceOrder/" + soId)
                        .with( SecurityMockMvcRequestPostProcessors.csrf())
                        .contentType(MediaType.APPLICATION_JSON)
                        .content( JsonUtils.toJson( servOrderUpd ) ))
                .andExpect(status().isOk() )
                .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON));
    }


    @WithMockUser(username="osadmin", roles = {"ADMIN","USER"})
    @Test
    public void testGetServiceOrderEagerAsString() throws Exception {