Resolve "Product orders submitted over JMS fail with LazyInitializationException"

Closes #110 (closed)

Merge request reports

Loading
+3 −2
Changes for src/main/java/org/etsi/osl/tmf/pcm620/reposervices/ProductSpecificationRepoService.java: 3 added lines, 2 removed lines.
Original line number Diff line number Diff line
@@ -208,8 +208,9 @@ public class ProductSpecificationRepoService {

	}

//	 @Transactional(propagation=Propagation.REQUIRED , readOnly=true,
//	 noRollbackFor=Exception.class)
	// The lazy collections below are initialized here, so a session must be open
	// even when the caller (e.g. a Camel JMS consumer thread) has none.
	@Transactional(readOnly = true)
	public ProductSpecification findByUuid(String id) {
		Optional<ProductSpecification> optionalCat = this.prodsOfferingRepo.findByUuid(id);
		if ( optionalCat.isPresent() ) {
+17
Changes for src/main/java/org/etsi/osl/tmf/po622/api/ProductOrderApiRouteBuilder.java: 17 added lines, 0 removed lines.
Original line number Diff line number Diff line
package org.etsi.osl.tmf.po622.api;

import java.util.LinkedHashMap;
import java.util.Map;
import org.apache.camel.Exchange;
import org.apache.camel.LoggingLevel;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
@@ -15,6 +17,7 @@ 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 com.fasterxml.jackson.databind.ObjectMapper;

@Configuration
//@RefreshScope
@@ -60,6 +63,20 @@ public class ProductOrderApiRouteBuilder extends RouteBuilder {
  
  @Override
  public void configure() throws Exception {

    // Without this, an exception in any request/reply route below produces no reply at all,
    // so the requester only learns about the failure when its requestTimeout expires.
    onException(Exception.class)
        .handled(true)
        .process(exchange -> {
          Exception ex = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class);
          logger.error("Product order route " + exchange.getFromRouteId() + " failed", ex);
          Map<String, String> error = new LinkedHashMap<>();
          error.put("error", ex.getClass().getSimpleName());
          error.put("message", ex.getMessage());
          exchange.getMessage().setBody(new ObjectMapper().writeValueAsString(error));
        });

    from(CATALOG_GET_PRODUCTORDERS).log(LoggingLevel.INFO, log, CATALOG_GET_PRODUCTORDERS + " message received!")
    .to("log:DEBUG?showBody=true&showHeaders=true")
    .bean(productOrderRepoService, "findAllParamsJsonOrderIDs").convertBodyTo(String.class);
+28 −12
Changes for src/main/java/org/etsi/osl/tmf/po622/reposervices/ProductOrderRepoService.java: 28 added lines, 12 removed lines.
Original line number Diff line number Diff line
@@ -77,6 +77,7 @@ import org.hibernate.query.Query;
import org.hibernate.transform.ResultTransformer;
import org.mapstruct.factory.Mappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import jakarta.persistence.EntityManager;
@@ -98,6 +99,15 @@ public class ProductOrderRepoService {
  @Autowired
  ProductOrderRepository productOrderRepo;

  /**
   * Proxied reference to this bean. Internal calls that need their own transaction
   * (e.g. addProductOrder from addProductOrderReturnEager) must go through it, since
   * a plain this.method() call bypasses the Spring proxy and its @Transactional.
   */
  @Autowired
  @Lazy
  private ProductOrderRepoService self;


  @Autowired
  ProductSpecificationRepoService  productSpecificationRepoService;
@@ -178,18 +188,18 @@ public class ProductOrderRepoService {
    return res;
  }
  
  public String addProductOrderReturnEager(@Valid ProductOrderCreate pOrderCreate) {
    try {
      ProductOrder so = this.addProductOrder(pOrderCreate);
        return this.getProductOrderEagerAsString( so.getUuid());
    } catch (JsonProcessingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
  /**
   * Entry point for the CATALOG_ADD_PRODUCTORDER JMS route.
   * <p>
   * Deliberately not @Transactional: addProductOrder must commit in its own transaction
   * (through the proxy) before getProductOrderEager re-reads the order in a separate
   * Hibernate session, which cannot see uncommitted rows.
   * Exceptions are propagated so the route's error handler can reply to the caller.
   */
  public String addProductOrderReturnEager(@Valid ProductOrderCreate pOrderCreate)
      throws NotFoundException, JsonProcessingException {
    ProductOrder so = self.addProductOrder(pOrderCreate); // transaction commits here
    return self.getProductOrderEagerAsString(so.getUuid()); // separate session can now see the order
  }
  
  /**
@@ -332,8 +342,14 @@ public class ProductOrderRepoService {
      }
      
      ProductOffering pOffer = productOfferingRepoService.findByUuid( pOfferf.getId() );
      if (pOffer == null) {
        throw new NotFoundException(400, "There is no Product Offering with Id: " + pOfferf.getId());
      }
      @Valid
      ProductSpecificationRef prodSpec = pOffer.getProductSpecification();
      if (prodSpec == null) {
        throw new NotFoundException(400, "Product Offering with Id: " + pOfferf.getId() + " has no Product Specification");
      }
      String prodSpecificationId = prodSpec.getId();

        ProductSpecification prodSpecification = productSpecificationRepoService.findByUuid(prodSpecificationId);
+162
Changes for src/test/java/org/etsi/osl/services/api/po622/ProductOrderJmsRouteIntegrationTest.java: 162 added lines, 0 removed lines.
Original line number Diff line number Diff line
package org.etsi.osl.services.api.po622;

import static org.assertj.core.api.Assertions.assertThat;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.camel.ProducerTemplate;
import org.apache.commons.io.IOUtils;
import org.etsi.osl.services.api.BaseIT;
import org.etsi.osl.tmf.JsonUtils;
import org.etsi.osl.tmf.pcm620.model.ProductOffering;
import org.etsi.osl.tmf.pcm620.model.ProductOfferingCreate;
import org.etsi.osl.tmf.pcm620.model.ProductOfferingRef;
import org.etsi.osl.tmf.pcm620.model.ProductSpecification;
import org.etsi.osl.tmf.pcm620.model.ProductSpecificationCreate;
import org.etsi.osl.tmf.pcm620.model.ProductSpecificationRef;
import org.etsi.osl.tmf.pcm620.reposervices.ProductOfferingRepoService;
import org.etsi.osl.tmf.pcm620.reposervices.ProductSpecificationRepoService;
import org.etsi.osl.tmf.po622.model.OrderItemActionType;
import org.etsi.osl.tmf.po622.model.ProductOrder;
import org.etsi.osl.tmf.po622.model.ProductOrderCreate;
import org.etsi.osl.tmf.po622.model.ProductOrderItem;
import org.etsi.osl.tmf.po622.reposervices.ProductOrderRepoService;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * Regression tests for #110: ProductOrderCreate sent over the CATALOG_ADD_PRODUCTORDER JMS queue.
 * <p>
 * The tests run without the class-level test transaction from {@link BaseIT}: the route is consumed
 * on a Camel JMS thread, which can only see committed data, and the bug only shows up when that
 * thread has no transaction or session of its own. Created rows are removed in {@link #cleanUp()}.
 */
@Transactional(propagation = Propagation.NOT_SUPPORTED)
public class ProductOrderJmsRouteIntegrationTest extends BaseIT {

  @Autowired
  private ProducerTemplate template;

  @Autowired
  ProductOrderRepoService productOrderRepoService;

  @Autowired
  ProductOfferingRepoService productOfferingRepoService;

  @Autowired
  ProductSpecificationRepoService productSpecificationRepoService;

  @Autowired
  TransactionTemplate txTemplate;

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

  private final List<String> createdOrders = new ArrayList<>();
  private final List<String> createdOfferings = new ArrayList<>();
  private final List<String> createdSpecs = new ArrayList<>();

  @AfterEach
  public void cleanUp() {
    txTemplate.executeWithoutResult(status -> {
      createdOrders.forEach(productOrderRepoService::deleteByUuid);
      createdOfferings.forEach(productOfferingRepoService::deleteByUuid);
      createdSpecs.forEach(productSpecificationRepoService::deleteByUuid);
    });
    createdOrders.clear();
    createdOfferings.clear();
    createdSpecs.clear();
  }

  @Test
  public void testAddProductOrderOverJms() throws Exception {
    ProductOfferingRef offeringRef = createProductOffering();

    long start = System.currentTimeMillis();
    Object response = template.requestBody(CATALOG_ADD_PRODUCTORDER,
        JsonUtils.toJsonString(productOrderCreate(offeringRef)));
    long elapsed = System.currentTimeMillis() - start;

    assertThat(response).isInstanceOf(String.class);
    ProductOrder po = JsonUtils.toJsonObj((String) response, ProductOrder.class);
    assertThat(po).isNotNull();
    assertThat(po.getId()).isNotNull();
    createdOrders.add(po.getId());

    assertThat(po.getDescription()).isEqualTo("A JMS Product Order");
    assertThat(po.getProductOrderItem()).hasSize(1);
    assertThat(po.getProductOrderItem().iterator().next().getProductOffering().getId())
        .isEqualTo(offeringRef.getId());
    assertThat(productOrderRepoService.getProductOrderEager(po.getId())).isNotNull();
    assertThat(elapsed).isLessThan(10_000);
  }

  @Test
  public void testAddProductOrderOverJmsWithUnknownOfferingRepliesWithError() throws Exception {
    ProductOfferingRef unknown = new ProductOfferingRef();
    unknown.setId("non-existent-offering-id");

    long start = System.currentTimeMillis();
    Object response = template.requestBody(CATALOG_ADD_PRODUCTORDER,
        JsonUtils.toJsonString(productOrderCreate(unknown)));
    long elapsed = System.currentTimeMillis() - start;

    // An error reply instead of no reply at all (which made the requester wait for its 20 s timeout)
    assertThat(elapsed).isLessThan(10_000);
    assertThat(response).isInstanceOf(String.class);
    Map<?, ?> error = JsonUtils.toJsonObj((String) response, Map.class);
    assertThat(error.get("error")).isEqualTo("NotFoundException");
    assertThat((String) error.get("message")).contains("non-existent-offering-id");
  }

  private ProductOrderCreate productOrderCreate(ProductOfferingRef offeringRef) {
    ProductOrderCreate productOrder = new ProductOrderCreate();
    productOrder.setCategory("Test Category");
    productOrder.setDescription("A JMS Product Order");
    productOrder.setRequestedStartDate(OffsetDateTime.now(ZoneOffset.UTC).toString());
    productOrder.setRequestedCompletionDate(OffsetDateTime.now(ZoneOffset.UTC).toString());

    ProductOrderItem poi = new ProductOrderItem();
    poi.action(OrderItemActionType.ADD).productOffering(offeringRef);
    productOrder.getProductOrderItem().add(poi);
    return productOrder;
  }

  /** Creates and commits a product specification (with characteristics) and an offering for it. */
  private ProductOfferingRef createProductOffering() throws Exception {
    File sspec = new File("src/test/resources/testProductSpec.json");
    String sspectext;
    try (InputStream in = new FileInputStream(sspec)) {
      sspectext = IOUtils.toString(in, "UTF-8");
    }
    ProductSpecificationCreate psc = JsonUtils.toJsonObj(sspectext, ProductSpecificationCreate.class);
    psc.setVersion("1.1");

    ProductOffering pOffer = txTemplate.execute(status -> {
      ProductSpecification spec = productSpecificationRepoService.addProductSpecification(psc);
      createdSpecs.add(spec.getId());

      ProductSpecificationRef prodSpecRef = new ProductSpecificationRef();
      prodSpecRef.setId(spec.getId());
      ProductOfferingCreate pefCre = new ProductOfferingCreate();
      pefCre.productSpecification(prodSpecRef);
      ProductOffering offering = productOfferingRepoService.addProductOffering(pefCre);
      createdOfferings.add(offering.getId());
      return offering;
    });

    ProductOfferingRef prodOffRef = new ProductOfferingRef();
    prodOffRef.setId(pOffer.getId());
    return prodOffRef;
  }
}
Loading