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

fix for #127

parent a31ee4ee
Loading
Loading
Loading
Loading
Loading
+7 −1
Changes for src/main/java/org/etsi/osl/tmf/ri639/api/ResourceApiRouteBuilder.java: 7 added lines, 1 removed line.
Original line number Original line Diff line number Diff line
@@ -137,7 +137,13 @@ public class ResourceApiRouteBuilder extends RouteBuilder {
		.log(LoggingLevel.DEBUG, log, CATALOG_GET_RESOURCES_BY_FILTER + " message received!")
		.log(LoggingLevel.DEBUG, log, CATALOG_GET_RESOURCES_BY_FILTER + " message received!")
		.to("log:DEBUG?showBody=true&showHeaders=true")
		.to("log:DEBUG?showBody=true&showHeaders=true")
		.convertBodyTo( String.class )
		.convertBodyTo( String.class )
		.bean( resourceRepoService, "findResourcesByFilter(${body})");
		.doTry()
			.bean( resourceRepoService, "findResourcesByFilter(${body})")
		.doCatch( Exception.class )
			.setHeader("error", constant("true"))
			.setHeader("errorMessage", simple("${exception.message}"))
			.setBody(simple("{\"error\":true}"))
		.end();
	}
	}
	
	


+26
Changes for src/main/java/org/etsi/osl/tmf/ri639/reposervices/ResourceFilter.java: 26 added lines, 0 removed lines.
Original line number Original line Diff line number Diff line
@@ -21,6 +21,32 @@ public class ResourceFilter {
    private String category;
    private String category;
    private int page = 0;
    private int page = 0;
    private int pageSize = 20;
    private int pageSize = 20;
    /** "summary" (default) or "full" (complete TMF639 Resource objects) */
    private String detail;
    /** Optional characteristic filter */
    private CharacteristicFilter characteristic;

    @JsonIgnoreProperties(ignoreUnknown = true)
    public static class CharacteristicFilter {
        private String name;
        /** If set, characteristic value must equal this */
        private String value;
        /** If true, characteristic must exist with a non-empty value */
        private Boolean exists;

        public String getName() { return name; }
        public void setName(String name) { this.name = name; }
        public String getValue() { return value; }
        public void setValue(String value) { this.value = value; }
        public Boolean getExists() { return exists; }
        public void setExists(Boolean exists) { this.exists = exists; }
    }

    public String getDetail() { return detail; }
    public void setDetail(String detail) { this.detail = detail; }

    public CharacteristicFilter getCharacteristic() { return characteristic; }
    public void setCharacteristic(CharacteristicFilter characteristic) { this.characteristic = characteristic; }


    public String getCategory() { return category; }
    public String getCategory() { return category; }
    public void setCategory(String category) { this.category = category; }
    public void setCategory(String category) { this.category = category; }
+10
Changes for src/main/java/org/etsi/osl/tmf/ri639/reposervices/ResourceQueryException.java: 10 added lines, 0 removed lines.
Original line number Original line Diff line number Diff line
package org.etsi.osl.tmf.ri639.reposervices;

/** Thrown when a resource filter query cannot be parsed or executed. */
public class ResourceQueryException extends RuntimeException {
    private static final long serialVersionUID = 1L;

    public ResourceQueryException(String message, Throwable cause) {
        super(message, cause);
    }
}
+46 −6
Changes for src/main/java/org/etsi/osl/tmf/ri639/reposervices/ResourceRepoService.java: 46 added lines, 6 removed lines.
Original line number Original line Diff line number Diff line
@@ -696,13 +696,17 @@ public class ResourceRepoService {
      filter = objectMapper.readValue(filterJson, ResourceFilter.class);
      filter = objectMapper.readValue(filterJson, ResourceFilter.class);
    } catch (Exception e) {
    } catch (Exception e) {
      logger.error("Cannot parse ResourceFilter JSON: " + filterJson, e);
      logger.error("Cannot parse ResourceFilter JSON: " + filterJson, e);
      return emptyBrowseResult();
      throw new ResourceQueryException("Cannot parse ResourceFilter JSON: " + e.getMessage(), e);
    }
    }


    Session session = sessionFactory.openSession();
    Session session = sessionFactory.openSession();
    Transaction tx = session.beginTransaction();
    Transaction tx = session.beginTransaction();
    try {
    try {
      boolean joinVendorChar = filter.getVendor() != null;
      boolean joinVendorChar = filter.getVendor() != null;
      ResourceFilter.CharacteristicFilter cf = filter.getCharacteristic();
      boolean joinCharFilter = cf != null && cf.getName() != null
          && (cf.getValue() != null || Boolean.TRUE.equals(cf.getExists()));
      boolean fullDetail = "full".equalsIgnoreCase(filter.getDetail());


      List<String> conditions = new ArrayList<>();
      List<String> conditions = new ArrayList<>();
      Map<String, Object> params = new HashMap<>();
      Map<String, Object> params = new HashMap<>();
@@ -719,6 +723,21 @@ public class ResourceRepoService {
        conditions.add("vendorChar.name = 'vendor' AND vendorChar.value.value = :vendor");
        conditions.add("vendorChar.name = 'vendor' AND vendorChar.value.value = :vendor");
        params.put("vendor", filter.getVendor());
        params.put("vendor", filter.getVendor());
      }
      }
      if (joinCharFilter) {
        // value.value is @Lob: cast to String; EXISTS keeps one row per resource (no join duplication)
        String valueCond = cf.getValue() != null
            ? "CAST(c.value.value AS String) = :cfValue"
            : "CAST(c.value.value AS String) IS NOT NULL AND CAST(c.value.value AS String) <> ''";
        // `x.value` on a collection-element alias is parsed as the HQL VALUE() path in Hibernate 6,
        // so the Lob test is done on a root RICharacteristic and matched by id
        conditions.add("EXISTS (SELECT 1 FROM RIResource cfr JOIN cfr.resourceCharacteristic cfc "
            + "WHERE cfr = srv AND cfc.id IN (SELECT c.id FROM RICharacteristic c "
            + "WHERE c.name = :cfName AND " + valueCond + "))");
        params.put("cfName", cf.getName());
        if (cf.getValue() != null) {
          params.put("cfValue", cf.getValue());
        }
      }
      if (filter.getLocation() != null) {
      if (filter.getLocation() != null) {
        conditions.add("srv.place.name LIKE :location");
        conditions.add("srv.place.name LIKE :location");
        params.put("location", "%" + filter.getLocation() + "%");
        params.put("location", "%" + filter.getLocation() + "%");
@@ -747,7 +766,7 @@ public class ResourceRepoService {
      long totalCount = countQuery.uniqueResult();
      long totalCount = countQuery.uniqueResult();


      // Data query with pagination
      // Data query with pagination
      String dataHql = "SELECT DISTINCT srv FROM RIResource srv " + joinClause + whereClause + "ORDER BY srv.name ASC";
      String dataHql = "SELECT DISTINCT srv FROM RIResource srv " + joinClause + whereClause + "ORDER BY srv.name ASC, srv.uuid ASC";
      org.hibernate.query.Query<Resource> query = session.createQuery(dataHql, Resource.class);
      org.hibernate.query.Query<Resource> query = session.createQuery(dataHql, Resource.class);
      params.forEach(query::setParameter);
      params.forEach(query::setParameter);


@@ -758,8 +777,19 @@ public class ResourceRepoService {


      List<Resource> resources = query.list();
      List<Resource> resources = query.list();


      List<Map<String, Object>> resourceList = new ArrayList<>();
      List<Object> resourceList = new ArrayList<>();
      for (Resource r : resources) {
      for (Resource r : resources) {
        if (fullDetail) {
          Hibernate.initialize(r.getRelatedParty());
          Hibernate.initialize(r.getNote());
          Hibernate.initialize(r.getResourceCharacteristic());
          Hibernate.initialize(r.getResourceSpecification());
          Hibernate.initialize(r.getResourceRelationship());
          Hibernate.initialize(r.getAttachment());
          Hibernate.initialize(r.getActivationFeature());
          resourceList.add(fullResourceMapper().valueToTree(r));
          continue;
        }
        Hibernate.initialize(r.getResourceCharacteristic());
        Hibernate.initialize(r.getResourceCharacteristic());
        Hibernate.initialize(r.getResourceSpecification());
        Hibernate.initialize(r.getResourceSpecification());
        Map<String, Object> entry = new LinkedHashMap<>();
        Map<String, Object> entry = new LinkedHashMap<>();
@@ -789,8 +819,12 @@ public class ResourceRepoService {
      return objectMapper.writeValueAsString(browseResult);
      return objectMapper.writeValueAsString(browseResult);
    } catch (Exception e) {
    } catch (Exception e) {
      logger.error("Error querying resources by filter", e);
      logger.error("Error querying resources by filter", e);
      try {
        tx.rollback();
        tx.rollback();
      return emptyBrowseResult();
      } catch (Exception re) {
        logger.warn("Rollback failed", re);
      }
      throw new ResourceQueryException("Error querying resources by filter: " + e.getMessage(), e);
    } finally {
    } finally {
      session.close();
      session.close();
    }
    }
@@ -827,8 +861,14 @@ public class ResourceRepoService {
    return result;
    return result;
  }
  }


  private String emptyBrowseResult() {
  private ObjectMapper fullMapper;
    return "{\"resources\":[],\"totalCount\":0,\"continuationToken\":null}";

  private synchronized ObjectMapper fullResourceMapper() {
    if (fullMapper == null) {
      fullMapper = new ObjectMapper();
      fullMapper.registerModule(new Hibernate5JakartaModule());
    }
    return fullMapper;
  }
  }


}
}
+108
Changes for src/test/java/org/etsi/osl/services/api/ri639/ResourceFilterFullDetailTest.java: 108 added lines, 0 removed lines.
Original line number Original line Diff line number Diff line
package org.etsi.osl.services.api.ri639;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.HashSet;
import java.util.Set;
import org.etsi.osl.services.api.BaseIT;
import org.etsi.osl.tmf.common.model.Any;
import org.etsi.osl.tmf.ri639.model.Characteristic;
import org.etsi.osl.tmf.ri639.model.ResourceCreate;
import org.etsi.osl.tmf.ri639.reposervices.ResourceQueryException;
import org.etsi.osl.tmf.ri639.reposervices.ResourceRepoService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/** Tests for findResourcesByFilter: detail=full, stable ordering, characteristic filter, errors. */
@Transactional(propagation = Propagation.NOT_SUPPORTED)
public class ResourceFilterFullDetailTest extends BaseIT {

  private static final ObjectMapper MAPPER = new ObjectMapper();

  @Autowired
  private ResourceRepoService resourceRepoService;

  private String createResources(int n, String category) {
    for (int i = 0; i < n; i++) {
      ResourceCreate rc = new ResourceCreate();
      rc.setName("res-" + i);
      rc.setCategory(category);
      rc.setResourceVersion("v1");
      org.etsi.osl.tmf.rcm634.model.ResourceSpecificationRef specRef =
          new org.etsi.osl.tmf.rcm634.model.ResourceSpecificationRef();
      specRef.setId("test-spec-id");
      specRef.setName("test-spec");
      rc.setResourceSpecification(specRef);
      Characteristic c = new Characteristic();
      c.setName("Kind");
      c.setValueType("TEXT");
      c.setValue(new Any(i % 2 == 0 ? "even" : "", ""));
      rc.addResourceCharacteristicItem(c);
      resourceRepoService.addResource(rc);
    }
    return category;
  }

  private JsonNode query(String json) throws Exception {
    return MAPPER.readTree(resourceRepoService.findResourcesByFilter(json));
  }

  @Test
  public void testFullDetailReturnsCharacteristicsAndStates() throws Exception {
    String cat = createResources(2, "FullCat-" + System.nanoTime());
    JsonNode res = query("{\"category\":\"" + cat + "\",\"detail\":\"full\"}");
    assertThat(res.get("totalCount").asInt()).isEqualTo(2);
    JsonNode first = res.get("resources").get(0);
    assertThat(first.has("resourceCharacteristic")).isTrue();
    assertThat(first.get("resourceCharacteristic").size()).isEqualTo(1);
    assertThat(first.has("administrativeState")).isTrue();
    assertThat(first.has("operationalState")).isTrue();
    assertThat(first.has("usageState")).isTrue();
  }

  @Test
  public void testPagingIsStableAndComplete() throws Exception {
    String cat = createResources(5, "PageCat-" + System.nanoTime());
    Set<String> ids = new HashSet<>();
    int page = 0;
    String lastKey = "";
    while (true) {
      JsonNode res = query("{\"category\":\"" + cat + "\",\"pageSize\":2,\"page\":" + page + "}");
      for (JsonNode r : res.get("resources")) {
        String id = r.get("id").asText();
        assertThat(ids.add(id)).isTrue();
        // ordered by name, then uuid
        String key = r.get("name").asText() + "\u0000" + id;
        assertThat(key.compareTo(lastKey)).isGreaterThan(0);
        lastKey = key;
      }
      if (res.get("continuationToken").isNull()) {
        break;
      }
      page = res.get("continuationToken").asInt();
    }
    assertThat(ids).hasSize(5);
  }

  @Test
  public void testCharacteristicFilter() throws Exception {
    String cat = createResources(4, "CharCat-" + System.nanoTime());
    JsonNode byValue = query("{\"category\":\"" + cat
        + "\",\"characteristic\":{\"name\":\"Kind\",\"value\":\"even\"}}");
    assertThat(byValue.get("totalCount").asInt()).isEqualTo(2);
    JsonNode exists = query("{\"category\":\"" + cat
        + "\",\"characteristic\":{\"name\":\"Kind\",\"exists\":true}}");
    assertThat(exists.get("totalCount").asInt()).isEqualTo(2);
  }

  @Test
  public void testMalformedFilterThrows() {
    assertThatThrownBy(() -> resourceRepoService.findResourcesByFilter("not json"))
        .isInstanceOf(ResourceQueryException.class);
  }
}
Loading