Commit 7fbf9df2 authored by Christos Tranoris's avatar Christos Tranoris
Browse files

fix for #72

parent c6a2420c
Loading
Loading
Loading
Loading
Loading
+1 −1
Original line number Diff line number Diff line
@@ -305,7 +305,7 @@
		<dependency>
			<groupId>com.h2database</groupId>
			<artifactId>h2</artifactId>
			<scope>test</scope>
			<version>2.3.232</version>
		</dependency>
		<dependency>
			<groupId>org.apache.activemq</groupId>
+145 −0
Original line number 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.scm633.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.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.etsi.osl.tmf.sim638.model.ServiceCreate;
import org.etsi.osl.tmf.sim638.model.ServiceUpdate;
import org.etsi.osl.tmf.so641.api.ServiceOrderApiRouteBuilder;
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 ServiceCatalogApiRouteBuilder extends RouteBuilder {

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

	

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

    @Value("${CATALOG_GET_SERVICECATALOG_BY_ID}")
    private String CATALOG_GET_SERVICECATALOG_BY_ID = "";
    
    @Value("${CATALOG_GET_SERVICECATALOG_BY_NAME}")
    private String CATALOG_GET_SERVICECATALOG_BY_NAME = "";
    
    @Value("${CATALOG_GET_SERVICECATEGORIES}")
    private String CATALOG_GET_SERVICECATEGORIES = "";
    
    @Value("${CATALOG_GET_SERVICECATEGORY_BY_ID}")
    private String CATALOG_GET_SERVICECATEGORY_BY_ID = "";
	

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

	
  
	@Autowired
	CatalogRepoService catalogRepoService;
	

    @Autowired
    CategoryRepoService categoryRepoService;
	
	
	@Override
	public void configure() throws Exception {
		
		from( CATALOG_GET_SERVICECATALOG_BY_ID )
		.log(LoggingLevel.INFO, log, CATALOG_GET_SERVICECATALOG_BY_ID + " message received!")
		.to("log:DEBUG?showBody=true&showHeaders=true")
		.bean( catalogRepoService, "findByUuidEager(${header.catalogId})")
		.marshal().json( JsonLibrary.Jackson, String.class)
		.convertBodyTo( String.class );
		
		from( CATALOG_GET_SERVICECATALOGS )
		.log(LoggingLevel.INFO, log, CATALOG_GET_SERVICECATALOGS + " message received!")
		.to("log:DEBUG?showBody=true&showHeaders=true")	
		.bean( catalogRepoService, "findAllEager()")
		.marshal().json( JsonLibrary.Jackson, String.class)
		.convertBodyTo( String.class );
		
	    from( CATALOG_GET_SERVICECATALOG_BY_NAME )
	    .log(LoggingLevel.INFO, log, CATALOG_GET_SERVICECATALOG_BY_NAME + " message received!")
	    .to("log:DEBUG?showBody=true&showHeaders=true")
        .bean( catalogRepoService, "findByNameEager(${header.catalogId})")
	    .marshal().json( JsonLibrary.Jackson, String.class)
	    .convertBodyTo( String.class );
	      
	    
        from( CATALOG_GET_SERVICECATEGORIES )
        .log(LoggingLevel.INFO, log, CATALOG_GET_SERVICECATEGORIES + " message received!")
        .to("log:DEBUG?showBody=true&showHeaders=true")
        .bean( catalogRepoService, "findAllCategoriesByCatalogName(${header.catalogName})")
        .marshal().json( JsonLibrary.Jackson, String.class)
        .convertBodyTo( String.class );
          
        
        from( CATALOG_GET_SERVICECATEGORY_BY_ID )
        .log(LoggingLevel.INFO, log, CATALOG_GET_SERVICECATEGORY_BY_ID + " message received!")
        .to("log:DEBUG?showBody=true&showHeaders=true")
        .bean( categoryRepoService, "findByIdEager(${header.catalogId})")
        .marshal().json( JsonLibrary.Jackson, String.class)
        .convertBodyTo( String.class );
        
        
        from( CATALOG_GET_SERVICESPECREFS_BYCATEGORY_ID )
        .log(LoggingLevel.INFO, log, CATALOG_GET_SERVICESPECREFS_BYCATEGORY_ID + " message received!")
        .to("log:DEBUG?showBody=true&showHeaders=true")
        .bean( categoryRepoService, "findAllServiceSpecRefsByCategId(${header.categoryId})")
        .marshal().json( JsonLibrary.Jackson, String.class)
        .convertBodyTo( String.class );
	      
	}

	
	

	
	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);
    }
	
}
+19 −1
Original line number Diff line number Diff line
@@ -68,6 +68,13 @@ public class ServiceSpecificationApiRouteBuilder extends RouteBuilder {
	@Value("${CATALOG_UPD_EXTERNAL_SERVICESPEC}")
	private String CATALOG_UPD_EXTERNAL_SERVICESPEC = "";


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


	    
	    
	@Autowired
	ServiceSpecificationRepoService serviceSpecificationRepoService;
	
@@ -114,6 +121,17 @@ public class ServiceSpecificationApiRouteBuilder extends RouteBuilder {
		.bean( serviceSpecificationRepoService, "updateOrAddServiceSpecification(${header.serviceSpecId}, ${header.forceId}, ${body} )")
		.marshal().json( JsonLibrary.Jackson)
		.convertBodyTo( String.class );
		


        from( CATALOG_SEARCH_SERVICESPECREFS )
        .log(LoggingLevel.INFO, log, CATALOG_SEARCH_SERVICESPECREFS + " message received!")
        .to("log:DEBUG?showBody=true&showHeaders=true")
        .bean( serviceSpecificationRepoService, "searchServiceSpecRefs(${header.searchText})")
        .marshal().json( JsonLibrary.Jackson, String.class)
        .convertBodyTo( String.class );
        
        
	}

	
+157 −0
Original line number Diff line number Diff line
@@ -21,8 +21,12 @@ package org.etsi.osl.tmf.scm633.reposervices;

import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;
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.TimePeriod;
import org.etsi.osl.tmf.scm633.model.ServiceCatalog;
@@ -30,9 +34,16 @@ import org.etsi.osl.tmf.scm633.model.ServiceCatalogCreate;
import org.etsi.osl.tmf.scm633.model.ServiceCatalogUpdate;
import org.etsi.osl.tmf.scm633.model.ServiceCategory;
import org.etsi.osl.tmf.scm633.model.ServiceCategoryRef;
import org.etsi.osl.tmf.scm633.model.ServiceSpecCharacteristic;
import org.etsi.osl.tmf.scm633.model.ServiceSpecification;
import org.etsi.osl.tmf.scm633.repo.CatalogRepository;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import jakarta.persistence.EntityManagerFactory;
import jakarta.validation.Valid;

@Service
@@ -51,6 +62,18 @@ public class CatalogRepoService {
	@Autowired
	CandidateRepoService candidateRepoService;
	

    private SessionFactory sessionFactory;
    
    @Autowired
    public CatalogRepoService(EntityManagerFactory factory) {
        if (factory.unwrap(SessionFactory.class) == null) {
            throw new NullPointerException("factory is not a hibernate factory");
        }
        this.sessionFactory = factory.unwrap(SessionFactory.class);
    }
    

	public ServiceCatalog addCatalog(ServiceCatalog c) {

		return this.catalogRepo.save(c);
@@ -64,10 +87,86 @@ public class CatalogRepoService {
		return this.catalogRepo.save(sc);
	}

	public String findAllEager() {
	  
	  List<ServiceCatalog> oids = (List<ServiceCatalog>) 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 List<ServiceCatalog> findAll() {
		return (List<ServiceCatalog>) this.catalogRepo.findByOrderByName();
	}

	
	 public ServiceCatalog findByUuidEager(String id) {
       

       Session session = sessionFactory.openSession();
       Transaction tx = session.beginTransaction(); // instead of begin transaction, is it possible to continue?
       try {
           ServiceCatalog dd = null;
           try {
               dd = session.get(ServiceCatalog.class, id);
               if (dd == null) {
                   return this.findById(id);// last resort
               }
               Hibernate.initialize(dd.getCategoryRefs() );
               Hibernate.initialize(dd.getRelatedParty() );
               Hibernate.initialize(dd.getCategoryObj() );

               tx.commit();
           } finally {
               session.close();
           }
           return dd;
           
       } catch (Exception e) {
           e.printStackTrace();
       }

       session.close();
       return null;
       
	 }
	 
	 
	 
	public String findByNameEager(String aname) {
	  ServiceCatalog 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 ServiceCatalog findById(String id) {
		Optional<ServiceCatalog> optionalCat = this.catalogRepo.findByUuid(id);
		return optionalCat.orElse(null);
@@ -138,6 +237,64 @@ public class CatalogRepoService {
	}
	
	
	/**
	 * return recursively all categories in catalog
	 * @param catalogName
	 */
	public String findAllCategoriesByCatalogName(String catalogName) {
	  String res="{}";

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


	  List<ServiceCategory> 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 "{}";
      }
      
      
      return res;
      
	}
	
	
	  private List<ServiceCategory> getCategories( @Valid List<ServiceCategoryRef> list) {
	    List<ServiceCategory> categories = new ArrayList<ServiceCategory>();
	    
	    for (ServiceCategoryRef c : list ) {	      
	     ServiceCategory category = this.categRepoService.findByUuid( c.getId());
	     categories.add(category);
	     
	     if (category.getCategoryRefs()!=null && category.getCategoryRefs().size()>0) {
	         List<ServiceCategory> subcategories = this.getCategories( category.getCategoryRefs() );
	         categories.addAll(subcategories );//add children
	     }
	      
	    }
	    
	    return categories;
	  }

	


	
+36 −1
Original line number Diff line number Diff line
@@ -27,8 +27,13 @@ import java.util.Iterator;
import java.util.List;
import java.util.Map;
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.TimePeriod;
import org.etsi.osl.tmf.common.model.service.ServiceSpecificationRef;
import org.etsi.osl.tmf.scm633.model.ServiceCandidate;
import org.etsi.osl.tmf.scm633.model.ServiceCandidateRef;
import org.etsi.osl.tmf.scm633.model.ServiceCategory;
@@ -146,6 +151,36 @@ public class CategoryRepoService {
	


    public String findAllServiceSpecRefsByCategId(String categoryId) {
      
      List<ServiceSpecificationRef> serviceSpecificationRefList = new ArrayList<>();
      ServiceCategory category = this.findByUuid(categoryId);      
      Set<ServiceCandidate> serviceCands = category.getServiceCandidateObj();
      
      for (ServiceCandidate serviceCandidate : serviceCands) {
        @Valid
        ServiceSpecificationRef specRef = serviceCandidate.getServiceSpecificationRef();
        serviceSpecificationRefList.add(specRef);
      }
      

      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( serviceSpecificationRefList );
      } catch (JsonProcessingException e) {
        e.printStackTrace();
      }
      
      
      return res;
      
    }
	

	public boolean deleteById(String id) {
		Optional<ServiceCategory> optionalCat = this.categsRepo.findByUuid( id );
Loading