Resolve "Find currently-active Service Orders that have active Services"

Closes #104 (closed)

Merge request reports

Loading
+15 −8
Changes for src/main/java/org/etsi/osl/tmf/rcm634/api/ResourceSpecificationApiRouteBuilder.java: 15 added lines, 8 removed lines.
Original line number Original line Diff line number Diff line
@@ -6,10 +6,8 @@ import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.model.dataformat.JsonLibrary;
import org.apache.camel.model.dataformat.JsonLibrary;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.LogFactory;
import org.etsi.osl.tmf.rcm634.model.ResourceSpecification;
import org.etsi.osl.tmf.rcm634.model.ResourceSpecificationCreate;
import org.etsi.osl.tmf.rcm634.model.ResourceSpecificationUpdate;
import org.etsi.osl.tmf.rcm634.reposervices.ResourceSpecificationRepoService;
import org.etsi.osl.tmf.rcm634.reposervices.ResourceSpecificationRepoService;
import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Configuration;
@@ -47,27 +45,36 @@ public class ResourceSpecificationApiRouteBuilder extends RouteBuilder {
	@Override
	@Override
	public void configure() throws Exception {
	public void configure() throws Exception {


		/*
		 * These three routes unmarshal to JsonNode rather than binding straight to a specification class,
		 * because the concrete class depends on the body's own "@type" discriminator. Physical fields
		 * (model/part/sku/vendor) are declared only on PhysicalResourceSpecificationUpdate — a sibling of
		 * ResourceSpecificationCreate, not a supertype — so binding a physical payload to
		 * ResourceSpecificationCreate silently discards them. The repo service picks the payload class and
		 * the entity from that one string.
		 */

		from( CATALOG_ADD_RESOURCESPEC )
		from( CATALOG_ADD_RESOURCESPEC )
		.log(LoggingLevel.INFO, log, CATALOG_ADD_RESOURCESPEC + " message received!")
		.log(LoggingLevel.INFO, log, CATALOG_ADD_RESOURCESPEC + " message received!")
		.to("log:DEBUG?showBody=true&showHeaders=true")
		.to("log:DEBUG?showBody=true&showHeaders=true")
		.unmarshal()
		.unmarshal()
		.json( JsonLibrary.Jackson, ResourceSpecificationCreate .class, true)
		.json( JsonLibrary.Jackson, JsonNode.class )
		.bean( resourceSpecificationRepoService, "addResourceSpecification(${body})")
		.bean( resourceSpecificationRepoService, "addResourceSpecificationFromJson(${body})")
		.marshal().json( JsonLibrary.Jackson)
		.marshal().json( JsonLibrary.Jackson)
		.convertBodyTo( String.class );
		.convertBodyTo( String.class );


		from( CATALOG_UPD_RESOURCESPEC )
		from( CATALOG_UPD_RESOURCESPEC )
		.log(LoggingLevel.INFO, log, CATALOG_UPD_RESOURCESPEC + " message received!")
		.log(LoggingLevel.INFO, log, CATALOG_UPD_RESOURCESPEC + " message received!")
		.to("log:DEBUG?showBody=true&showHeaders=true")
		.to("log:DEBUG?showBody=true&showHeaders=true")
		.unmarshal().json( JsonLibrary.Jackson, ResourceSpecificationUpdate.class, true)
		.unmarshal().json( JsonLibrary.Jackson, JsonNode.class )
		.bean( resourceSpecificationRepoService, "updateResourceSpecification(${header.resourceSpecId},  ${body} )")
		.bean( resourceSpecificationRepoService, "updateResourceSpecificationFromJson(${header.resourceSpecId},  ${body} )")
		.marshal().json( JsonLibrary.Jackson)
		.marshal().json( JsonLibrary.Jackson)
		.convertBodyTo( String.class );
		.convertBodyTo( String.class );


		from( CATALOG_UPDADD_RESOURCESPEC )
		from( CATALOG_UPDADD_RESOURCESPEC )
		.log(LoggingLevel.INFO, log, CATALOG_UPDADD_RESOURCESPEC + " message received!")
		.log(LoggingLevel.INFO, log, CATALOG_UPDADD_RESOURCESPEC + " message received!")
		.to("log:DEBUG?showBody=true&showHeaders=true")
		.to("log:DEBUG?showBody=true&showHeaders=true")
		.unmarshal().json( JsonLibrary.Jackson, ResourceSpecificationCreate.class, true)
		.unmarshal().json( JsonLibrary.Jackson, JsonNode.class )
		.bean( resourceSpecificationRepoService, "addOrupdateResourceSpecificationByNameCategoryVersion(${header.aname}, ${header.acategory}, ${header.aversion},  ${body} )")
		.bean( resourceSpecificationRepoService, "addOrupdateResourceSpecificationByNameCategoryVersion(${header.aname}, ${header.acategory}, ${header.aversion},  ${body} )")
		.marshal().json( JsonLibrary.Jackson)
		.marshal().json( JsonLibrary.Jackson)
		.convertBodyTo( String.class );
		.convertBodyTo( String.class );
+122 −30
Changes for src/main/java/org/etsi/osl/tmf/rcm634/reposervices/ResourceSpecificationRepoService.java: 122 added lines, 30 removed lines.
Original line number Original line Diff line number Diff line
@@ -36,6 +36,7 @@ import java.util.Optional;
import java.util.UUID;
import java.util.UUID;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectMapper;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.Log;
@@ -115,16 +116,75 @@ public class ResourceSpecificationRepoService {
	
	
	@Transactional
	@Transactional
	public ResourceSpecification addResourceSpecification(@Valid ResourceSpecificationCreate resourceSpecification) {
	public ResourceSpecification addResourceSpecification(@Valid ResourceSpecificationCreate resourceSpecification) {
		return addResourceSpecificationGeneric( newEntityForType( resourceSpecification.getType() ), resourceSpecification);
	}


		ResourceSpecification reSpec ;
	/**
		if (resourceSpecification.getType() !=null && (  resourceSpecification.getType().equals( "PhysicalResourceSpecification" )  || 
	 * Creates a resource specification from the raw request body, choosing the payload class from the
				 resourceSpecification.getType().equals( "PhysicalResourceSpecificationCreate" )  )) {
	 * {@code @type} discriminator.
			reSpec = new PhysicalResourceSpecification(); 
	 *
		}else {
	 * <p>The JMS routes call this rather than binding straight to a class: physical fields
			reSpec = new LogicalResourceSpecification();			
	 * (model/part/sku/vendor) are declared only on {@link PhysicalResourceSpecificationUpdate}, so
	 * unmarshalling a physical payload into {@link ResourceSpecificationCreate} silently drops them
	 * before this service ever sees them. The entity and the payload are chosen from the same string, so
	 * they cannot disagree.
	 */
	@Transactional
	public ResourceSpecification addResourceSpecificationFromJson(JsonNode jsonNode) throws JsonProcessingException {
		ResourceSpecificationUpdate payload = toTypedCreatePayload( jsonNode );
		return addResourceSpecificationGeneric( newEntityForType( payload.getType() ), payload );
	}

	/** Updates a resource specification from the raw request body. @type selects the payload class. */
	@Transactional
	public ResourceSpecification updateResourceSpecificationFromJson(String id, JsonNode jsonNode)
			throws JsonProcessingException {
		return updateResourceSpecification( id, toTypedCreatePayload( jsonNode ) );
	}

	/**
	 * Binds a request body to the concrete payload class its {@code @type} names. Mirrors the dispatch in
	 * {@code ResourceSpecificationApiController.createResourceSpecification} — the two must agree, or the
	 * same JSON would mean different things over REST and over JMS.
	 *
	 * <p>Falls back to {@link ResourceSpecificationCreate} for an absent or unrecognised {@code @type},
	 * which is what every logical producer sends.
	 */
	private ResourceSpecificationUpdate toTypedCreatePayload(JsonNode jsonNode) throws JsonProcessingException {
		String atType = jsonNode.path("@type").asText(null);

		if ( isPhysicalType( atType ) ) {
			return objectMapper.treeToValue( jsonNode, PhysicalResourceSpecificationCreate.class );
		}
		if ( isResourceFunctionType( atType ) ) {
			return objectMapper.treeToValue( jsonNode, ResourceFunctionSpecificationCreate.class );
		}
		return objectMapper.treeToValue( jsonNode, ResourceSpecificationCreate.class );
	}

	/**
	 * The JPA entity a {@code @type} names. Kept beside {@link #toTypedCreatePayload} deliberately: these
	 * two must stay in step, since pairing an entity with a payload that cannot carry its fields is
	 * exactly the defect this replaced.
	 */
	private ResourceSpecification newEntityForType(String atType) {
		if ( isPhysicalType( atType ) ) {
			return new PhysicalResourceSpecification();
		}
		if ( isResourceFunctionType( atType ) ) {
			return new ResourceFunctionSpecification();
		}
		return new LogicalResourceSpecification();
	}
	}


		return addResourceSpecificationGeneric(reSpec, resourceSpecification);
	private static boolean isPhysicalType(String atType) {
		return "PhysicalResourceSpecification".equals( atType )
				|| "PhysicalResourceSpecificationCreate".equals( atType );
	}

	private static boolean isResourceFunctionType(String atType) {
		return "ResourceFunctionSpecification".equals( atType )
				|| "ResourceFunctionSpecificationCreate".equals( atType );
	}
	}


	public LogicalResourceSpecification addLogicalResourceSpecification(@Valid ResourceSpecificationCreate logicalResourceSpec) {
	public LogicalResourceSpecification addLogicalResourceSpecification(@Valid ResourceSpecificationCreate logicalResourceSpec) {
@@ -323,8 +383,21 @@ public class ResourceSpecificationRepoService {
	}
	}
	
	


	/**
	 * Upserts a resource specification identified by name+category+version, from the raw request body.
	 *
	 * <p>Takes the body as a {@link JsonNode} so the {@code @type} discriminator can pick the payload
	 * class: physical fields exist only on {@link PhysicalResourceSpecificationUpdate}, and binding a
	 * physical payload to {@link ResourceSpecificationCreate} would drop them before this method runs.
	 *
	 * <p>Note the update branch cannot re-type an existing specification — JPA has no way to change an
	 * entity's concrete class in place. One first registered as logical stays logical, and a later
	 * physical payload's fields are ignored with a warning.
	 */
	@Transactional
	@Transactional
	public ResourceSpecification addOrupdateResourceSpecificationByNameCategoryVersion(String aname, String acategory, String aversion, ResourceSpecificationCreate aesourceCreate) {
	public ResourceSpecification addOrupdateResourceSpecificationByNameCategoryVersion(String aname, String acategory, String aversion, JsonNode jsonNode) throws JsonProcessingException {

		ResourceSpecificationUpdate payload = toTypedCreatePayload( jsonNode );


		List<ResourceSpecification> rspecs = this.resourceSpecificationRepo.findByNameAndCategoryAndVersion(aname, acategory, aversion);
		List<ResourceSpecification> rspecs = this.resourceSpecificationRepo.findByNameAndCategoryAndVersion(aname, acategory, aversion);
		ResourceSpecification result = null;
		ResourceSpecification result = null;
@@ -333,14 +406,13 @@ public class ResourceSpecificationRepoService {
		if ( rspecs.size() >0 ) {
		if ( rspecs.size() >0 ) {
			//perform update to the first one
			//perform update to the first one
			String resID = rspecs.get(0).getUuid();
			String resID = rspecs.get(0).getUuid();
			result = this.updateResourceSpecification(resID, aesourceCreate);
			result = this.updateResourceSpecification(resID, payload);
		} else {
		} else {
			result =  this.addResourceSpecification(aesourceCreate);
			result = addResourceSpecificationGeneric( newEntityForType( payload.getType() ), payload );
		}
		}


		ObjectMapper mapper = new ObjectMapper();
		try {
		try {
			String originaServiceAsJson = mapper.writeValueAsString( result );
			String originaServiceAsJson = objectMapper.writeValueAsString( result );
			logger.debug(originaServiceAsJson);
			logger.debug(originaServiceAsJson);
		} catch (JsonProcessingException e) {
		} catch (JsonProcessingException e) {
			logger.error("cannot umarshall service: " + result.getName() );
			logger.error("cannot umarshall service: " + result.getName() );
@@ -403,18 +475,6 @@ public class ResourceSpecificationRepoService {
		
		
	}
	}
	
	
	public LogicalResourceSpecification updateLogicalResourceSpecSpecification(String id,
			@Valid ResourceSpecificationUpdate logicalResourceSpec) {
		return (LogicalResourceSpecification) this.updateResourceSpecification(id, logicalResourceSpec);
	}
	
	public PhysicalResourceSpecification updatePhysicalResourceSpecSpecification(String id,
			@Valid ResourceSpecificationUpdate physicalResourceSpec) {
		return (PhysicalResourceSpecification) this.updateResourceSpecification(id, physicalResourceSpec);
	}
	
	
	
	private ResourceSpecification updateResourceSpecDataFromAPIcall(
	private ResourceSpecification updateResourceSpecDataFromAPIcall(
			ResourceSpecification resourceSpec, 
			ResourceSpecification resourceSpec, 
			ResourceSpecificationUpdate resSpecUpd )
			ResourceSpecificationUpdate resSpecUpd )
@@ -435,12 +495,44 @@ public class ResourceSpecificationRepoService {
		
		
		resourceSpec.setLastUpdate( OffsetDateTime.now(ZoneOffset.UTC) );
		resourceSpec.setLastUpdate( OffsetDateTime.now(ZoneOffset.UTC) );
		
		
		if (resourceSpec instanceof PhysicalResourceSpecification){
		/*
			((PhysicalResourceSpecification) resourceSpec)
		 * Physical fields live only on PhysicalResourceSpecificationUpdate, which is a SIBLING of
				.model(( (PhysicalResourceSpecificationUpdate) resSpecUpd ).getModel() )
		 * ResourceSpecificationCreate (both extend ResourceSpecificationUpdate) — not a supertype. So the
				.part( ( (PhysicalResourceSpecificationUpdate) resSpecUpd ).getPart())
		 * payload must be checked as well as the entity: a physical entity paired with a plain
				.sku( ( (PhysicalResourceSpecificationUpdate) resSpecUpd ).getSku())
		 * ResourceSpecificationCreate is a normal, expected combination (that is what an @type-tagged
				.vendor(( (PhysicalResourceSpecificationUpdate) resSpecUpd ).getVendor() );
		 * message from a JMS producer looks like), and casting on the entity check alone threw
		 * ClassCastException on every such call.
		 *
		 * Each field is copied only when present, matching the name/description/category handling above:
		 * a PATCH that does not mention model must leave model alone, not null it.
		 */
		if ( resourceSpec instanceof PhysicalResourceSpecification
				&& resSpecUpd instanceof PhysicalResourceSpecificationUpdate ) {
			PhysicalResourceSpecification prs = (PhysicalResourceSpecification) resourceSpec;
			PhysicalResourceSpecificationUpdate pUpd = (PhysicalResourceSpecificationUpdate) resSpecUpd;

			if ( pUpd.getModel() != null ) {
				prs.setModel( pUpd.getModel() );
			}
			if ( pUpd.getPart() != null ) {
				prs.setPart( pUpd.getPart() );
			}
			if ( pUpd.getSku() != null ) {
				prs.setSku( pUpd.getSku() );
			}
			if ( pUpd.getVendor() != null ) {
				prs.setVendor( pUpd.getVendor() );
			}
		} else if ( isPhysicalType( resSpecUpd.getType() ) && !(resourceSpec instanceof PhysicalResourceSpecification) ) {
			/*
			 * The payload claims to be physical but the stored entity is not. JPA cannot re-type an entity in
			 * place, so the physical fields are dropped. Say so — a spec registered as logical first stays
			 * logical forever, and silence here makes that look like data loss with no cause.
			 */
			logger.warn("Resource specification '" + resourceSpec.getName() + "' (" + resourceSpec.getUuid()
					+ ") is stored as " + resourceSpec.getClass().getSimpleName()
					+ " but the payload declares @type=" + resSpecUpd.getType()
					+ ". Physical fields are ignored; an existing specification cannot be re-typed.");
		}
		}
		
		
		
		
+35
Changes for src/main/java/org/etsi/osl/tmf/so641/api/ServiceOrderApiRouteBuilder.java: 35 added lines, 0 removed lines.
Original line number Original line Diff line number Diff line
@@ -60,6 +60,12 @@ public class ServiceOrderApiRouteBuilder extends RouteBuilder {
	@Value("${CATALOG_GET_SERVICEORDER_IDS_BY_STATE}")
	@Value("${CATALOG_GET_SERVICEORDER_IDS_BY_STATE}")
	private String CATALOG_GET_SERVICEORDER_IDS_BY_STATE = "";
	private String CATALOG_GET_SERVICEORDER_IDS_BY_STATE = "";


	@Value("${CATALOG_GET_SERVICEORDERS_BY_STATE_AND_DATES}")
	private String CATALOG_GET_SERVICEORDERS_BY_STATE_AND_DATES = "";

	@Value("${CATALOG_GET_ACTIVE_SERVICEORDERS}")
	private String CATALOG_GET_ACTIVE_SERVICEORDERS = "";

	@Value("${CATALOG_UPD_SERVICEORDER_BY_ID}")
	@Value("${CATALOG_UPD_SERVICEORDER_BY_ID}")
	private String CATALOG_UPD_SERVICEORDER_BY_ID = "";
	private String CATALOG_UPD_SERVICEORDER_BY_ID = "";


@@ -107,6 +113,35 @@ public class ServiceOrderApiRouteBuilder extends RouteBuilder {
				.unmarshal().json(JsonLibrary.Jackson, Map.class, true)
				.unmarshal().json(JsonLibrary.Jackson, Map.class, true)
				.bean(serviceOrderRepoService, "findAllParamsJsonOrderIDs").convertBodyTo(String.class);
				.bean(serviceOrderRepoService, "findAllParamsJsonOrderIDs").convertBodyTo(String.class);


		/**
		 * Retrieves the service orders ordered between two dates and, optionally, in a
		 * specific state. Expected headers:
		 * <ul>
		 * <li>startDate: ISO-8601 date or date time, e.g. 2024-01-01 or 2024-01-01T00:00:00Z</li>
		 * <li>endDate: ISO-8601 date or date time</li>
		 * <li>orderstate: e.g. ACKNOWLEDGED. If absent, orders of any state are returned</li>
		 * </ul>
		 * Returns a JSON array of service order summaries
		 */
		from(CATALOG_GET_SERVICEORDERS_BY_STATE_AND_DATES)
				.log(LoggingLevel.INFO, log, CATALOG_GET_SERVICEORDERS_BY_STATE_AND_DATES + " message received!")
				.to("log:DEBUG?showBody=true&showHeaders=true")
				.bean(serviceOrderRepoService,
						"findAllByStateBetweenDatesAsString(${header.orderstate}, ${header.startDate}, ${header.endDate})")
				.convertBodyTo(String.class);

		/**
		 * Retrieves the service orders which are currently in force (COMPLETED, already started
		 * and not yet expected to be completed) and have at least one active service.
		 * No headers are expected. Returns a JSON array of service order summaries, each one
		 * carrying the ids of its active services
		 */
		from(CATALOG_GET_ACTIVE_SERVICEORDERS)
				.log(LoggingLevel.INFO, log, CATALOG_GET_ACTIVE_SERVICEORDERS + " message received!")
				.to("log:DEBUG?showBody=true&showHeaders=true")
				.bean(serviceOrderRepoService, "findActiveServiceOrdersWithActiveServicesAsString")
				.convertBodyTo(String.class);

		from(CATALOG_GET_SERVICEORDER_BY_ID)
		from(CATALOG_GET_SERVICEORDER_BY_ID)
				.log(LoggingLevel.INFO, log, CATALOG_GET_SERVICEORDER_BY_ID + " message received!")
				.log(LoggingLevel.INFO, log, CATALOG_GET_SERVICEORDER_BY_ID + " message received!")
				.to("log:DEBUG?showBody=true&showHeaders=true")
				.to("log:DEBUG?showBody=true&showHeaders=true")
+40
Changes for src/main/java/org/etsi/osl/tmf/so641/repo/ServiceOrderRepository.java: 40 added lines, 0 removed lines.
Original line number Original line Diff line number Diff line
@@ -23,6 +23,7 @@ import java.time.OffsetDateTime;
import java.util.List;
import java.util.List;
import java.util.Optional;
import java.util.Optional;
import org.etsi.osl.tmf.common.model.UserPartRoleType;
import org.etsi.osl.tmf.common.model.UserPartRoleType;
import org.etsi.osl.tmf.common.model.service.ServiceStateType;
import org.etsi.osl.tmf.so641.model.ServiceOrder;
import org.etsi.osl.tmf.so641.model.ServiceOrder;
import org.etsi.osl.tmf.so641.model.ServiceOrderStateType;
import org.etsi.osl.tmf.so641.model.ServiceOrderStateType;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaRepository;
@@ -53,6 +54,45 @@ public interface ServiceOrderRepository extends JpaRepository<ServiceOrder, Long
			+ "ORDER BY an.date ASC")
			+ "ORDER BY an.date ASC")
	Optional<ServiceOrder> findNotesOfServOrder(String id);
	Optional<ServiceOrder> findNotesOfServOrder(String id);


	@Query("SELECT sor.uuid, sor.type, sor.externalId, sor.category, sor.description, sor.state, "
			+ "sor.orderDate, sor.requestedStartDate, sor.requestedCompletionDate, "
			+ "sor.startDate, sor.expectedCompletionDate, sor.completionDate "
			+ "FROM ServiceOrder sor "
			+ "WHERE sor.orderDate >= :starttime AND sor.orderDate <= :endtime "
			+ "AND sor.state = :state "
			+ "ORDER BY sor.orderDate DESC")
	List<Object[]> findByStateBetweenDates(OffsetDateTime starttime, OffsetDateTime endtime, ServiceOrderStateType state);

	@Query("SELECT sor.uuid, sor.type, sor.externalId, sor.category, sor.description, sor.state, "
			+ "sor.orderDate, sor.requestedStartDate, sor.requestedCompletionDate, "
			+ "sor.startDate, sor.expectedCompletionDate, sor.completionDate "
			+ "FROM ServiceOrder sor "
			+ "WHERE sor.orderDate >= :starttime AND sor.orderDate <= :endtime "
			+ "ORDER BY sor.orderDate DESC")
	List<Object[]> findBetweenDates(OffsetDateTime starttime, OffsetDateTime endtime);

	/**
	 * Service orders that are currently in force, together with the uuid of each of their
	 * services that is in one of the given states. There is no mapped association between
	 * ServiceOrder and Service; they are linked through Service.serviceOrder refs, whose id
	 * holds the uuid of the order (same link as ServiceRepository.findServicesFromOrderID).
	 * A null startDate is considered as already started and a null expectedCompletionDate as
	 * open-ended.
	 */
	@Query("SELECT sor.uuid, sor.type, sor.externalId, sor.category, sor.description, sor.state, "
			+ "sor.orderDate, sor.requestedStartDate, sor.requestedCompletionDate, "
			+ "sor.startDate, sor.expectedCompletionDate, sor.completionDate, "
			+ "srv.uuid "
			+ "FROM ServiceOrder sor, Service srv JOIN srv.serviceOrder sref "
			+ "WHERE sref.id = sor.uuid "
			+ "AND sor.state = :orderState "
			+ "AND ( sor.startDate IS NULL OR sor.startDate < :now ) "
			+ "AND ( sor.expectedCompletionDate IS NULL OR sor.expectedCompletionDate > :now ) "
			+ "AND srv.state IN :serviceStates "
			+ "ORDER BY sor.orderDate DESC")
	List<Object[]> findActiveOrdersWithServicesInStates(OffsetDateTime now,
			ServiceOrderStateType orderState, List<ServiceStateType> serviceStates);



	// Methods for metrics
	// Methods for metrics


+151
Changes for src/main/java/org/etsi/osl/tmf/so641/reposervices/ServiceOrderRepoService.java: 151 added lines, 0 removed lines.
Original line number Original line Diff line number Diff line
@@ -22,14 +22,18 @@ package org.etsi.osl.tmf.so641.reposervices;
import java.io.UnsupportedEncodingException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.OffsetDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.*;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Collectors;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
//import com.fasterxml.jackson.datatype.hibernate5.Hibernate5Module;
//import com.fasterxml.jackson.datatype.hibernate5.Hibernate5Module;
import com.fasterxml.jackson.datatype.hibernate5.jakarta.Hibernate5JakartaModule;
import com.fasterxml.jackson.datatype.hibernate5.jakarta.Hibernate5JakartaModule;


@@ -73,6 +77,10 @@ public class ServiceOrderRepoService {


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


	/** the service states which are considered as an active service of an order */
	private static final List<ServiceStateType> ACTIVE_SERVICE_STATES =
			List.of(ServiceStateType.ACTIVE, ServiceStateType.RESERVED);

	@Autowired
	@Autowired
	ObjectMapper objectMapper;
	ObjectMapper objectMapper;


@@ -291,6 +299,149 @@ public class ServiceOrderRepoService {


	}
	}
	
	
	/**
	 * Retrieve the service orders which have an orderDate within the given period and
	 * (optionally) are in a specific state. A lean summary of each order is returned.
	 *
	 * @param state     a {@link ServiceOrderStateType} value, e.g. ACKNOWLEDGED. If null or
	 *                  empty, orders of any state are returned
	 * @param startDate the beginning of the period, ISO-8601 (e.g. 2024-01-01T00:00:00Z or
	 *                  2024-01-01). If null, no lower bound is applied
	 * @param endDate   the end of the period, ISO-8601. If null, no upper bound is applied
	 * @return a list of service order summaries
	 */
	@Transactional(readOnly = true)
	public List<Map<String, Object>> findAllByStateBetweenDates(String state, String startDate, String endDate) {

		OffsetDateTime starttime = toOffsetDateTime(startDate, OffsetDateTime.of(1970, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC));
		OffsetDateTime endtime = toOffsetDateTime(endDate, OffsetDateTime.now(ZoneOffset.UTC).plusYears(100));

		logger.info("findAllByStateBetweenDates state=" + state + " startDate=" + starttime + " endDate=" + endtime);

		List<Object[]> rows;
		if ((state != null) && (state.trim().length() > 0)) {
			ServiceOrderStateType stateType = ServiceOrderStateType.fromValue(state.trim().toUpperCase());
			if (stateType == null) {
				throw new IllegalArgumentException("There is no such Service Order state: " + state);
			}
			rows = serviceOrderRepo.findByStateBetweenDates(starttime, endtime, stateType);
		} else {
			rows = serviceOrderRepo.findBetweenDates(starttime, endtime);
		}

		List<Map<String, Object>> result = new ArrayList<>();
		for (Object[] row : rows) {
			result.add(toServiceOrderSummary(row));
		}

		return result;
	}

	/**
	 * Same as {@link #findAllByStateBetweenDates(String, String, String)} but the result is
	 * marshaled to a JSON array, so that it can be returned over the message bus.
	 */
	public String findAllByStateBetweenDatesAsString(String state, String startDate, String endDate)
			throws JsonProcessingException {
		return toJsonArray(findAllByStateBetweenDates(state, startDate, endDate));
	}

	/**
	 * Retrieve the service orders which are currently in force, that is they are COMPLETED,
	 * they have already started and they are not expected to be completed yet, and which are
	 * backed by at least one active service (a service in ACTIVE or RESERVED state).
	 *
	 * A null startDate is considered as already started and a null expectedCompletionDate as
	 * open-ended, so that orders created without requested dates are not silently dropped.
	 *
	 * @return a list of service order summaries, each one carrying under "activeServices" the
	 *         ids of its services which are active
	 */
	@Transactional(readOnly = true)
	public List<Map<String, Object>> findActiveServiceOrdersWithActiveServices() {

		OffsetDateTime now = OffsetDateTime.now(ZoneOffset.UTC);
		logger.info("findActiveServiceOrdersWithActiveServices now=" + now);

		List<Object[]> rows = serviceOrderRepo.findActiveOrdersWithServicesInStates(now,
				ServiceOrderStateType.COMPLETED, ACTIVE_SERVICE_STATES);

		// an order appears once per active service, so fold the rows per order.
		// A LinkedHashMap preserves the orderDate DESC ordering of the query
		Map<String, Map<String, Object>> ordersByUuid = new LinkedHashMap<>();
		for (Object[] row : rows) {
			String orderUuid = (String) row[0];
			Map<String, Object> so = ordersByUuid.get(orderUuid);
			if (so == null) {
				so = toServiceOrderSummary(row);
				so.put("activeServices", new ArrayList<String>());
				ordersByUuid.put(orderUuid, so);
			}
			@SuppressWarnings("unchecked")
			List<String> activeServices = (List<String>) so.get("activeServices");
			activeServices.add((String) row[12]);
		}

		return new ArrayList<>(ordersByUuid.values());
	}

	/**
	 * Same as {@link #findActiveServiceOrdersWithActiveServices()} but the result is marshaled
	 * to a JSON array, so that it can be returned over the message bus.
	 */
	public String findActiveServiceOrdersWithActiveServicesAsString() throws JsonProcessingException {
		return toJsonArray(findActiveServiceOrdersWithActiveServices());
	}

	/**
	 * Maps the first 12 columns of a service order scalar projection to a lean summary
	 */
	private Map<String, Object> toServiceOrderSummary(Object[] row) {
		Map<String, Object> so = new LinkedHashMap<>();
		so.put("id", row[0]);
		so.put("@type", row[1]);
		so.put("externalId", row[2]);
		so.put("category", row[3]);
		so.put("description", row[4]);
		so.put("state", row[5] != null ? row[5].toString() : null);
		so.put("orderDate", row[6]);
		so.put("requestedStartDate", row[7]);
		so.put("requestedCompletionDate", row[8]);
		so.put("startDate", row[9]);
		so.put("expectedCompletionDate", row[10]);
		so.put("completionDate", row[11]);
		return so;
	}

	private String toJsonArray(List<Map<String, Object>> summaries) throws JsonProcessingException {
		ObjectMapper mapper = new ObjectMapper();
		mapper.registerModule(new Hibernate5JakartaModule());
		mapper.registerModule(new JavaTimeModule());
		mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
		return mapper.writeValueAsString(summaries);
	}

	/**
	 * Accepts either a full ISO-8601 offset date time (2024-01-01T00:00:00Z) or a plain
	 * ISO date (2024-01-01), which is then considered as the start of that day in UTC.
	 */
	private OffsetDateTime toOffsetDateTime(String date, OffsetDateTime defaultValue) {
		if ((date == null) || (date.trim().length() == 0)) {
			return defaultValue;
		}
		String d = date.trim();
		try {
			return OffsetDateTime.parse(d);
		} catch (DateTimeParseException e) {
			try {
				return LocalDate.parse(d).atStartOfDay().atOffset(ZoneOffset.UTC);
			} catch (DateTimeParseException e2) {
				throw new IllegalArgumentException("Cannot parse date: " + date
						+ ". Expecting an ISO-8601 date (2024-01-01) or date time (2024-01-01T00:00:00Z)");
			}
		}
	}

	public String findAllParamsJsonOrderIDs(Map<String, String> allParams) throws JsonProcessingException {
	public String findAllParamsJsonOrderIDs(Map<String, String> allParams) throws JsonProcessingException {
		List<ServiceOrder> lso = findAllParams(allParams);
		List<ServiceOrder> lso = findAllParams(allParams);
		ArrayList<String> oids = new ArrayList<>();
		ArrayList<String> oids = new ArrayList<>();
Loading
Loading