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

Adding product catalog API related routes

parent 5f3bb8cf
Loading
Loading
Loading
Loading
Loading
+132 −0
Original line number Original line Diff line number Diff line
/*-
 * ========================LICENSE_START=================================
 * org.etsi.osl.tmf.api
 * %%
 * Copyright (C) 2019 - 2020 openslice.io
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =========================LICENSE_END==================================
 */
package org.etsi.osl.tmf.pcm620.api;

import java.io.IOException;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;

import org.apache.camel.LoggingLevel;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.model.dataformat.JsonLibrary;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.etsi.osl.tmf.pcm620.reposervices.ProductCatalogRepoService;
import org.etsi.osl.tmf.pcm620.reposervices.ProductCategoryRepoService;
import org.etsi.osl.tmf.scm633.model.ServiceSpecification;
import org.etsi.osl.tmf.scm633.model.ServiceSpecificationCreate;
import org.etsi.osl.tmf.scm633.model.ServiceSpecificationUpdate;
import org.etsi.osl.tmf.scm633.reposervices.CatalogRepoService;
import org.etsi.osl.tmf.scm633.reposervices.CategoryRepoService;
import org.etsi.osl.tmf.scm633.reposervices.ServiceSpecificationRepoService;
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;

@Configuration
//@RefreshScope
@Component
public class ProductCatalogApiRouteBuilder extends RouteBuilder {

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

	

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

    @Value("${CATALOG_GET_PRODUCTCATALOG_BY_ID}")
    private String CATALOG_GET_PRODUCTCATALOG_BY_ID = "";
    
    @Value("${CATALOG_GET_PRODUCTCATALOG_BY_NAME}")
    private String CATALOG_GET_PRODUCTCATALOG_BY_NAME = "";
    
    @Value("${CATALOG_GET_PRODUCTCATEGORIES}")
    private String CATALOG_GET_PRODUCTCATEGORIES = "";
    
    @Value("${CATALOG_GET_PRODUCTCATEGORY_BY_ID}")
    private String CATALOG_GET_PRODUCTCATEGORY_BY_ID = "";
	

    @Value("${CATALOG_GET_PRODUCTOFFERINGS_BYCATEGORY_ID}")
    private String CATALOG_GET_PRODUCTOFFERINGS_BYCATEGORY_ID = "";
	
  
	@Autowired
	ProductCatalogRepoService catalogRepoService;
	

    @Autowired
    ProductCategoryRepoService categoryRepoService;
	
	
	@Override
	public void configure() throws Exception {
		
		from( CATALOG_GET_PRODUCTCATALOG_BY_ID )
		.log(LoggingLevel.INFO, log, CATALOG_GET_PRODUCTCATALOG_BY_ID + " message received!")
		.to("log:DEBUG?showBody=true&showHeaders=true")
		.bean( catalogRepoService, "findByUuidEager(${header.catalogId})");
		
		from( CATALOG_GET_PRODUCTCATALOGS )
		.log(LoggingLevel.INFO, log, CATALOG_GET_PRODUCTCATALOGS + " message received!")
		.to("log:DEBUG?showBody=true&showHeaders=true")	
		.bean( catalogRepoService, "findAllEager()");
		
	    from( CATALOG_GET_PRODUCTCATALOG_BY_NAME )
	    .log(LoggingLevel.INFO, log, CATALOG_GET_PRODUCTCATALOG_BY_NAME + " message received!")
	    .to("log:DEBUG?showBody=true&showHeaders=true")
        .bean( catalogRepoService, "findByNameEager(${header.catalogName})")
	    .marshal().json( JsonLibrary.Jackson, String.class)
	    .convertBodyTo( String.class );
	      
	    
        from( CATALOG_GET_PRODUCTCATEGORIES )
        .log(LoggingLevel.INFO, log, CATALOG_GET_PRODUCTCATEGORIES + " message received!")
        .to("log:DEBUG?showBody=true&showHeaders=true")
        .bean( catalogRepoService, "findAllCategoriesByCatalogName(${header.catalogName})");
          
        
        from( CATALOG_GET_PRODUCTCATEGORY_BY_ID )
        .log(LoggingLevel.INFO, log, CATALOG_GET_PRODUCTCATEGORY_BY_ID + " message received!")
        .to("log:DEBUG?showBody=true&showHeaders=true")
        .bean( categoryRepoService, "findByIdEager(${header.catalogId})");
        
        
        from( CATALOG_GET_PRODUCTOFFERINGS_BYCATEGORY_ID )
        .log(LoggingLevel.INFO, log, CATALOG_GET_PRODUCTOFFERINGS_BYCATEGORY_ID + " message received!")
        .to("log:DEBUG?showBody=true&showHeaders=true")
        .bean( categoryRepoService, "findAllProductOfferingsByCategId(${header.categoryId})");
	      
	}

	
	

	
	static <T> T toJsonObj(String content, Class<T> valueType)  throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        return mapper.readValue( content, valueType);
    }
	
}
+13 −0
Original line number Original line Diff line number Diff line
package org.etsi.osl.tmf.pcm620.api;
package org.etsi.osl.tmf.pcm620.api;


import java.util.ArrayList;
import org.apache.camel.LoggingLevel;
import org.apache.camel.LoggingLevel;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.model.dataformat.JsonLibrary;
import org.apache.camel.model.dataformat.JsonLibrary;
@@ -40,6 +41,10 @@ public class ProductSpecificationApiRouteBuilder extends RouteBuilder {
  private String CATALOG_GET_PRODUCTOFFERING_BY_ID = "";
  private String CATALOG_GET_PRODUCTOFFERING_BY_ID = "";




  @Value("${CATALOG_SEARCH_PRODUCTOFFERINGS}")
  private String CATALOG_SEARCH_PRODUCTOFFERINGS = "";
  
  
  
  
  @Autowired
  @Autowired
  ProductSpecificationRepoService productSpecificationRepoService;
  ProductSpecificationRepoService productSpecificationRepoService;
@@ -91,5 +96,13 @@ public class ProductSpecificationApiRouteBuilder extends RouteBuilder {
    .convertBodyTo( String.class );
    .convertBodyTo( String.class );
    
    



    from( CATALOG_SEARCH_PRODUCTOFFERINGS )
    .log(LoggingLevel.INFO, log, CATALOG_SEARCH_PRODUCTOFFERINGS + " message received!")
    .to("log:DEBUG?showBody=true&showHeaders=true")
    .unmarshal().json( JsonLibrary.Jackson, ArrayList.class, true)
    .bean( productOfferingRepoService, "searchProductOfferings( ${body} )");
    
    
  }
  }
}
}
+127 −0
Original line number Original line Diff line number Diff line
@@ -21,8 +21,12 @@ package org.etsi.osl.tmf.pcm620.reposervices;


import java.time.OffsetDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;
import java.util.List;
import java.util.Optional;
import java.util.Optional;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.hibernate5.jakarta.Hibernate5JakartaModule;
import org.etsi.osl.tmf.common.model.ELifecycle;
import org.etsi.osl.tmf.common.model.ELifecycle;
import org.etsi.osl.tmf.common.model.TimePeriod;
import org.etsi.osl.tmf.common.model.TimePeriod;
import org.etsi.osl.tmf.pcm620.model.Catalog;
import org.etsi.osl.tmf.pcm620.model.Catalog;
@@ -31,11 +35,16 @@ import org.etsi.osl.tmf.pcm620.model.CatalogUpdate;
import org.etsi.osl.tmf.pcm620.model.Category;
import org.etsi.osl.tmf.pcm620.model.Category;
import org.etsi.osl.tmf.pcm620.model.CategoryRef;
import org.etsi.osl.tmf.pcm620.model.CategoryRef;
import org.etsi.osl.tmf.pcm620.repo.ProductCatalogRepository;
import org.etsi.osl.tmf.pcm620.repo.ProductCatalogRepository;
import org.etsi.osl.tmf.scm633.model.ServiceCatalog;
import org.etsi.osl.tmf.scm633.model.ServiceCategory;
import org.etsi.osl.tmf.scm633.model.ServiceCategoryRef;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import jakarta.validation.Valid;
import jakarta.validation.Valid;


@Service
@Service
@Transactional
public class ProductCatalogRepoService {
public class ProductCatalogRepoService {




@@ -81,6 +90,65 @@ public class ProductCatalogRepoService {


	}
	}
	
	
    public String findByUuidEager(String id) {
      
      Catalog sc = this.findById(id);

      ObjectMapper mapper = new ObjectMapper();
      // Registering Hibernate4Module to support lazy objects
      // this will fetch all lazy objects before marshaling
      mapper.registerModule(new Hibernate5JakartaModule());
      String res;
      try {
        res = mapper.writeValueAsString( sc );
      } catch (JsonProcessingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return "{}";
      }
      
      return res;
    }  
    
    public String findAllEager() {
      
      List<Catalog> oids = (List<Catalog>) this.catalogRepo.findByOrderByName();
      ObjectMapper mapper = new ObjectMapper();
      // Registering Hibernate4Module to support lazy objects
      // this will fetch all lazy objects before marshaling
      mapper.registerModule(new Hibernate5JakartaModule());
      String res;
      try {
        res = mapper.writeValueAsString( oids );
      } catch (JsonProcessingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return "{}";
      }
      
      return res;
    }
    
    public String findByNameEager(String aname) {
      Catalog sc = this.findByName(aname);

      ObjectMapper mapper = new ObjectMapper();
      // Registering Hibernate4Module to support lazy objects
      // this will fetch all lazy objects before marshaling
      mapper.registerModule(new Hibernate5JakartaModule());
      String res;
      try {
        res = mapper.writeValueAsString( sc );
      } catch (JsonProcessingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return "{}";
      }
      
      return res;
           
    }

	public Catalog updateCatalog(String id, CatalogUpdate Catalog) {
	public Catalog updateCatalog(String id, CatalogUpdate Catalog) {


		Optional<Catalog> optSC = catalogRepo.findByUuid(id);
		Optional<Catalog> optSC = catalogRepo.findByUuid(id);
@@ -132,4 +200,63 @@ public class ProductCatalogRepoService {
		return this.catalogRepo.save(scatalog);
		return this.catalogRepo.save(scatalog);
	}
	}
	
	
	   /**
     * return recursively all categories in catalog
     * @param catalogName
     */
    @Transactional
    public String findAllCategoriesByCatalogName(String catalogName) {
      String res="[]";

      Optional<Catalog> scopt = this.catalogRepo.findByName(catalogName);
      
      if (scopt.isEmpty() ) {
          return res;       
      }
      
      Catalog sc = scopt.get();
      
      sc.getCategoryRefs();


      List<Category> allcategories = this.getCategories( sc.getCategoryRefs());
      
      ObjectMapper mapper = new ObjectMapper();
      // Registering Hibernate4Module to support lazy objects
      // this will fetch all lazy objects before marshaling
      mapper.registerModule(new Hibernate5JakartaModule());     
      
      
      try {
        res = mapper.writeValueAsString( allcategories );
      } catch (JsonProcessingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      
      
      return res;
      
    }
    
    
    @Transactional
    private List<Category> getCategories( @Valid List<CategoryRef> list) {
      List<Category> categories = new ArrayList<Category>();
      
      for (CategoryRef c : list ) {          
        Category category = this.categRepoService.findByUuid( c.getId());
       categories.add(category);
       
       if (category.getCategoryRefs()!=null && category.getCategoryRefs().size()>0) {
           List<Category> subcategories = this.getCategories( category.getCategoryRefs() );
           categories.addAll(subcategories );//add children
       }
        
      }
      
      return categories;
    }


}
}
+72 −36
Original line number Original line Diff line number Diff line
@@ -26,39 +26,41 @@ import java.util.HashMap;
import java.util.List;
import java.util.List;
import java.util.Map;
import java.util.Map;
import java.util.Optional;
import java.util.Optional;
import java.util.Set;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.hibernate5.jakarta.Hibernate5JakartaModule;
import org.etsi.osl.tmf.common.model.ELifecycle;
import org.etsi.osl.tmf.common.model.ELifecycle;
import org.etsi.osl.tmf.common.model.TimePeriod;
import org.etsi.osl.tmf.common.model.TimePeriod;
import org.etsi.osl.tmf.common.model.service.ServiceSpecificationRef;
import org.etsi.osl.tmf.pcm620.model.Category;
import org.etsi.osl.tmf.pcm620.model.Category;
import org.etsi.osl.tmf.pcm620.model.CategoryCreate;
import org.etsi.osl.tmf.pcm620.model.CategoryCreate;
import org.etsi.osl.tmf.pcm620.model.CategoryRef;
import org.etsi.osl.tmf.pcm620.model.CategoryRef;
import org.etsi.osl.tmf.pcm620.model.CategoryUpdate;
import org.etsi.osl.tmf.pcm620.model.CategoryUpdate;
import org.etsi.osl.tmf.pcm620.model.ProductOffering;
import org.etsi.osl.tmf.pcm620.model.ProductOffering;
import org.etsi.osl.tmf.pcm620.model.ProductOfferingRef;
import org.etsi.osl.tmf.pcm620.model.ProductOfferingRef;
import org.etsi.osl.tmf.pcm620.model.ProductSpecificationRef;
import org.etsi.osl.tmf.pcm620.repo.ProductCatalogRepository;
import org.etsi.osl.tmf.pcm620.repo.ProductCatalogRepository;
import org.etsi.osl.tmf.pcm620.repo.ProductCategoriesRepository;
import org.etsi.osl.tmf.pcm620.repo.ProductCategoriesRepository;
import org.etsi.osl.tmf.pcm620.repo.ProductOfferingRepository;
import org.etsi.osl.tmf.pcm620.repo.ProductOfferingRepository;
import org.etsi.osl.tmf.scm633.model.ServiceCandidate;
import org.etsi.osl.tmf.scm633.model.ServiceCategory;
import org.hibernate.Hibernate;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.EntityManagerFactory;
import jakarta.validation.Valid;
import jakarta.validation.Valid;


@Service
@Service
public class ProductCategoryRepoService {
public class ProductCategoryRepoService {


	@Autowired
	private final ProductCategoriesRepository categsRepo;
	ProductCategoriesRepository categsRepo;

	@Autowired
	ProductCatalogRepository catalogRepo;
	
	@Autowired
	ProductOfferingRepository prodsOfferingRepo;
	
	
	private SessionFactory sessionFactory;
	private final ProductOfferingRepository prodsOfferingRepo;


	/**
	/**
	 * from
	 * from
@@ -67,11 +69,11 @@ public class ProductCategoryRepoService {
	 * @param factory
	 * @param factory
	 */
	 */
	@Autowired
	@Autowired
	public ProductCategoryRepoService(EntityManagerFactory factory) {
	public ProductCategoryRepoService( ProductCategoriesRepository categsRepo, 
		if (factory.unwrap(SessionFactory.class) == null) {
	    ProductOfferingRepository prodsOfferingRepo) {
			throw new NullPointerException("factory is not a hibernate factory");
	  
		}
	  this.categsRepo = categsRepo;
		this.sessionFactory = factory.unwrap(SessionFactory.class);
	  this.prodsOfferingRepo = prodsOfferingRepo;
	}
	}
	
	
	
	
@@ -100,27 +102,30 @@ public class ProductCategoryRepoService {
	}
	}
	
	


	public Category findByIdEager(String id) {
    @Transactional
//		Optional<Category> optionalCat = this.categsRepo.findByIdEager( id );
    public String findByIdEager(String id) {
//		return optionalCat
        Category sc = this.findByUuid( id );
//				.orElse(null);


		 Session session = sessionFactory.openSession();
        String res= "{}";
		    Transaction tx = session.beginTransaction();
        
		    Category dd = null;
        if ( sc == null ) {
		    try {
          return res;
		        dd = (Category) session.get(Category.class, id);
		        Hibernate.initialize( dd.getCategoryObj()  );
		        Hibernate.initialize( dd.getProductOfferingRefs() );
		        for (ProductOfferingRef sc : dd.getProductOfferingRefs()) {
			        Hibernate.initialize(sc );
        }
        }
          
          
		        tx.commit();
        
		    } finally {
        ObjectMapper mapper = new ObjectMapper();
		        session.close();
          // Registering Hibernate4Module to support lazy objects
          // this will fetch all lazy objects before marshaling
          mapper.registerModule(new Hibernate5JakartaModule());     
          
          try {
            res = mapper.writeValueAsString( sc );
          } catch (JsonProcessingException e) {
            e.printStackTrace();
          }
          }
		    return dd;
          
          
          return res;
    }
    }
	
	
	
	
@@ -321,4 +326,35 @@ public class ProductCategoryRepoService {
		return optionalCat
		return optionalCat
				.orElse(null);
				.orElse(null);
	}
	}
	
	   @Transactional
	    public String findAllProductOfferingsByCategId(String categoryId) {
	      

	      String res="[]";
	      List<ProductSpecificationRef> productSpecificationRefList = new ArrayList<>();
	      Category category = this.findByUuid(categoryId);      
	      
	      if ( category == null ) {
	        return res;
	      }
	      
	      Set<ProductOffering> proffs = category.getProductOfferingObj();


	      ObjectMapper mapper = new ObjectMapper();
	      // Registering Hibernate4Module to support lazy objects
	      // this will fetch all lazy objects before marshaling
	      mapper.registerModule(new Hibernate5JakartaModule());     
	      
	      try {
	        res = mapper.writeValueAsString( proffs );
	      } catch (JsonProcessingException e) {
	        e.printStackTrace();
	      }
	      
	      
	      return res;
	      
	    }
}
}
+132 −14
Original line number Original line Diff line number Diff line
@@ -26,18 +26,20 @@ import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.List;
import java.util.Map;
import java.util.Map;
import java.util.Optional;
import java.util.Optional;
import org.etsi.osl.tmf.JsonUtils;
import java.util.StringJoiner;
import java.util.stream.Collectors;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.hibernate5.jakarta.Hibernate5JakartaModule;
import org.etsi.osl.tmf.am651.model.AgreementRef;
import org.etsi.osl.tmf.am651.model.AgreementRef;
import org.etsi.osl.tmf.common.model.Any;
import org.etsi.osl.tmf.common.model.Any;
import org.etsi.osl.tmf.common.model.AttachmentRefOrValue;
import org.etsi.osl.tmf.common.model.AttachmentRefOrValue;
import org.etsi.osl.tmf.common.model.ELifecycle;
import org.etsi.osl.tmf.common.model.ELifecycle;
import org.etsi.osl.tmf.common.model.TimePeriod;
import org.etsi.osl.tmf.common.model.TimePeriod;
import org.etsi.osl.tmf.common.model.service.ServiceSpecificationRef;
import org.etsi.osl.tmf.pcm620.model.BundledProductOffering;
import org.etsi.osl.tmf.pcm620.model.BundledProductOffering;
import org.etsi.osl.tmf.pcm620.model.ProductOffering;
import org.etsi.osl.tmf.pcm620.model.ProductOffering;
import org.etsi.osl.tmf.pcm620.model.ProductOfferingCreate;
import org.etsi.osl.tmf.pcm620.model.ProductOfferingCreate;
@@ -50,8 +52,6 @@ import org.etsi.osl.tmf.pcm620.model.ProductSpecificationCharacteristicValueUse;
import org.etsi.osl.tmf.pcm620.model.ProductSpecificationCreate;
import org.etsi.osl.tmf.pcm620.model.ProductSpecificationCreate;
import org.etsi.osl.tmf.pcm620.model.ProductSpecificationRef;
import org.etsi.osl.tmf.pcm620.model.ProductSpecificationRef;
import org.etsi.osl.tmf.pcm620.repo.ProductOfferingRepository;
import org.etsi.osl.tmf.pcm620.repo.ProductOfferingRepository;
import org.etsi.osl.tmf.pcm620.repo.ProductSpecificationRepository;
import org.etsi.osl.tmf.scm633.model.ServiceSpecCharacteristicValue;
import org.etsi.osl.tmf.scm633.model.ServiceSpecification;
import org.etsi.osl.tmf.scm633.model.ServiceSpecification;
import org.etsi.osl.tmf.scm633.reposervices.ServiceSpecificationRepoService;
import org.etsi.osl.tmf.scm633.reposervices.ServiceSpecificationRepoService;
import org.hibernate.Hibernate;
import org.hibernate.Hibernate;
@@ -143,12 +143,11 @@ public class ProductOfferingRepoService {
			}			
			}			
			sql += " FROM ProductOffering s";
			sql += " FROM ProductOffering s";
            if (allParams.size() > 0) {             
            if (allParams.size() > 0) {             
				sql += " WHERE ";
              String items = allParams.entrySet()
				for (String pname : allParams.keySet()) {
              .stream()
					sql += " " + pname + " LIKE ";
              .map(entry -> "s." + entry.getKey() + " LIKE '%" + URLDecoder.decode( entry.getValue(), StandardCharsets.UTF_8 )+ "%'" )
					String pval = URLDecoder.decode(allParams.get(pname), StandardCharsets.UTF_8.toString());
              .collect(Collectors.joining(" OR "));
					sql += "'" + pval + "'";
              sql += " WHERE " + items;
				}
              
              
          }
          }
			sql += " ORDER BY s.name";
			sql += " ORDER BY s.name";
@@ -633,4 +632,123 @@ public class ProductOfferingRepoService {
    return pOffer;
    return pOffer;
  }
  }
  
  
  
  @Transactional
  public String searchProductOfferings(List<String> searchText) {
    String res = "[]";

    try {
      
      List<String> specs= this.searchOfferingsInCategories( searchText);
      
      ObjectMapper mapper = new ObjectMapper();
      // Registering Hibernate4Module to support lazy objects
      // this will fetch all lazy objects before marshaling
      mapper.registerModule(new Hibernate5JakartaModule());   
      res = mapper.writeValueAsString( specs );  
      
      
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    } catch (JsonProcessingException e) {
      e.printStackTrace();
    }

    
    return res;
  }
  
  
  /**
   * 
   * This findAll is optimized on fields. 
   * @param fields
   * @param allParams
   * @return
   * @throws UnsupportedEncodingException
   */
  @Transactional
  public List searchOfferingsInCategories( List<String> searchList )
          throws UnsupportedEncodingException {

    if ( searchList == null || searchList.size() ==0) {
      return new ArrayList<>();
    }
    
      Session session = sessionFactory.openSession();
      Transaction tx = session.beginTransaction();
      
      try {
        String sql = "SELECT p.id as productOfferingId, p.name as productName, p.description as productDescription";
                     
          

          sql += " FROM ProductCategory as pcateg JOIN  pcateg.productOffObj as p  ";
          sql += " WHERE " ;
          
                    
          // Build the name LIKE clause
          StringJoiner nameJoiner = new StringJoiner(" AND ");
          for (String term : searchList) {
              nameJoiner.add("p.name LIKE '%" + term + "%'");
          }

          // Build the description LIKE clause
          StringJoiner descriptionJoiner = new StringJoiner(" AND ");
          for (String term : searchList) {
              descriptionJoiner.add("p.description LIKE '%" + term + "%'");
          }

          // Combine both clauses with OR
          sql += "(" + nameJoiner.toString() + ") OR (" + descriptionJoiner.toString() + ")";            
          
          sql += " ORDER BY p.name";
          
//          List<ServiceSpecification> specs = session
//              .createQuery( sql, ServiceSpecification.class)
//              .getResultList();
          
          
          List<Object> mapaEntity = session
                  .createQuery(sql )
                  .setResultTransformer( new ResultTransformer() {
                      
                      @Override
                      public Object transformTuple(Object[] tuple, String[] aliases) {
                          Map<String, Object> result = new LinkedHashMap<String, Object>(tuple.length);
                                  for (int i = 0; i < tuple.length; i++) {
                                      String alias = aliases[i];
                                      if (alias != null) {
                                        if (alias.equals("type")) {
                                            alias = "@type";
                                        }
                                          result.put(alias, tuple[i]);
                                      }
                                  }

                                  return result;
                      }
                      
                      @Override
                      public List transformList(List collection) {
                          return collection;
                      }
                  } )
                  .list();
          
//        //this will fetch the whole object fields
          
          
          return mapaEntity;
      
          
          
          
      } finally {
          tx.commit();
          session.close();
      }

  }
	
}
}
Loading