revert small changes
[cdmlib.git] / cdmlib-services / src / main / java / eu / etaxonomy / cdm / api / service / TaxonNodeServiceImpl.java
index 234145f67703be1a3f31a1535e09c0f4411be3b8..9fdf1cd3fdd2ed3f70ad746547626d792b0b11d4 100644 (file)
@@ -17,6 +17,7 @@ import java.util.Comparator;
 import java.util.HashSet;
 import java.util.Iterator;
 import java.util.List;
+import java.util.Map;
 import java.util.Map.Entry;
 import java.util.Set;
 import java.util.UUID;
@@ -35,7 +36,9 @@ import eu.etaxonomy.cdm.api.service.config.SecundumForSubtreeConfigurator;
 import eu.etaxonomy.cdm.api.service.config.TaxonDeletionConfigurator;
 import eu.etaxonomy.cdm.api.service.config.TaxonNodeDeletionConfigurator;
 import eu.etaxonomy.cdm.api.service.dto.CdmEntityIdentifier;
+import eu.etaxonomy.cdm.api.service.dto.CreateTaxonDTO;
 import eu.etaxonomy.cdm.api.service.dto.TaxonDistributionDTO;
+import eu.etaxonomy.cdm.api.service.dto.TaxonDistributionDTOComparator;
 import eu.etaxonomy.cdm.api.service.pager.Pager;
 import eu.etaxonomy.cdm.api.service.pager.PagerUtils;
 import eu.etaxonomy.cdm.api.service.pager.impl.AbstractPagerImpl;
@@ -76,10 +79,11 @@ import eu.etaxonomy.cdm.persistence.dao.common.Restriction;
 import eu.etaxonomy.cdm.persistence.dao.initializer.IBeanInitializer;
 import eu.etaxonomy.cdm.persistence.dao.taxon.ITaxonNodeDao;
 import eu.etaxonomy.cdm.persistence.dao.taxon.ITaxonNodeFilterDao;
+import eu.etaxonomy.cdm.persistence.dto.MergeResult;
 import eu.etaxonomy.cdm.persistence.dto.TaxonNodeDto;
-import eu.etaxonomy.cdm.persistence.dto.UuidAndTitleCache;
 import eu.etaxonomy.cdm.persistence.hibernate.permission.ICdmPermissionEvaluator;
 import eu.etaxonomy.cdm.persistence.query.OrderHint;
+import eu.etaxonomy.cdm.strategy.parser.NonViralNameParserImpl;
 
 /**
  * @author n.hoffmann
@@ -158,9 +162,6 @@ public class TaxonNodeServiceImpl
         return dao.listChildrenOf(node, pageSize, pageIndex, recursive, includeUnpublished, propertyPaths);
     }
 
-    /**
-     * {@inheritDoc}
-     */
     @Override
     public TaxonNodeDto getParentUuidAndTitleCache(ITaxonTreeNode child) {
         UUID uuid = child.getUuid();
@@ -169,9 +170,6 @@ public class TaxonNodeServiceImpl
         return getParentUuidAndTitleCache(uuidAndTitleCache);
     }
 
-    /**
-     * {@inheritDoc}
-     */
     @Override
     public TaxonNodeDto getParentUuidAndTitleCache(TaxonNodeDto child) {
         return dao.getParentUuidAndTitleCache(child);
@@ -182,25 +180,30 @@ public class TaxonNodeServiceImpl
         return dao.listChildNodesAsTaxonNodeDto(parent);
     }
 
-
-
     @Override
-    public List<UuidAndTitleCache<TaxonNode>> getUuidAndTitleCache(Integer limit, String pattern, UUID classificationUuid) {
+    public List<TaxonNodeDto> getUuidAndTitleCache(Integer limit, String pattern, UUID classificationUuid) {
         return dao.getUuidAndTitleCache(limit, pattern, classificationUuid);
     }
 
     @Override
     public List<TaxonNodeDto> listChildNodesAsTaxonNodeDto(ITaxonTreeNode parent) {
+        List<String> propertyPaths = new ArrayList<>();
+        propertyPaths.add("parent");
+        parent = dao.load(parent.getId(), propertyPaths);
         TaxonNodeDto uuidAndTitleCache = new TaxonNodeDto(parent);
         return listChildNodesAsTaxonNodeDto(uuidAndTitleCache);
     }
 
-
     @Override
-    public TaxonNodeDto taxonNodeDtoParentRank(Classification classification, Rank rank, TaxonName name) {
+    public List<TaxonNodeDto> taxonNodeDtoParentRank(Classification classification, Rank rank, TaxonName name) {
        return dao.getParentTaxonNodeDtoForRank(classification, rank, name);
     }
 
+    @Override
+    public List<TaxonNodeDto> taxonNodeDtoParentRank(Classification classification, Rank rank, TaxonBase<?> taxonBase) {
+        return dao.getParentTaxonNodeDtoForRank(classification, rank, taxonBase);
+    }
+
     @Override
     public Pager<TaxonNodeDto> pageChildNodesDTOs(UUID taxonNodeUuid, boolean recursive,  boolean includeUnpublished,
             boolean doSynonyms, NodeSortMode sortMode,
@@ -243,6 +246,9 @@ public class TaxonNodeServiceImpl
 
     @Override
     public TaxonNodeDto parentDto(UUID taxonNodeUuid) {
+        if (taxonNodeUuid == null){
+            return null;
+        }
         TaxonNode taxonNode = dao.load(taxonNodeUuid);
         if(taxonNode.getParent() != null) {
             return new TaxonNodeDto(taxonNode.getParent());
@@ -252,8 +258,11 @@ public class TaxonNodeServiceImpl
 
     @Override
     public TaxonNodeDto dto(UUID taxonNodeUuid) {
+        if (taxonNodeUuid == null){
+            return null;
+        }
         TaxonNode taxonNode = dao.load(taxonNodeUuid);
-        if(taxonNode.getParent() != null) {
+        if (taxonNode != null){
             return new TaxonNodeDto(taxonNode);
         }
         return null;
@@ -478,11 +487,11 @@ public class TaxonNodeServiceImpl
                if (treeNode != null){
 
                        TaxonNode taxonNode;
-                   taxonNode = HibernateProxyHelper.deproxy(treeNode, TaxonNode.class);
+                   taxonNode = CdmBase.deproxy(treeNode);
                    TaxonNode parent = taxonNode.getParent();
                        //check whether the node has children or the children are already deleted
                    if(taxonNode.hasChildNodes()) {
-                       List<TaxonNode> children = new ArrayList<TaxonNode> ();
+                       List<TaxonNode> children = new ArrayList<> ();
                        List<TaxonNode> childNodesList = taxonNode.getChildNodes();
                                children.addAll(childNodesList);
                                //To avoid NPE when child is also in list of taxonNodes, remove it from the list
@@ -552,7 +561,7 @@ public class TaxonNodeServiceImpl
                    } else {
                        //classification = null;
                        Taxon taxon = taxonNode.getTaxon();
-                       taxon = HibernateProxyHelper.deproxy(taxon, Taxon.class);
+                       taxon = CdmBase.deproxy(taxon);
                        if (taxon != null){
                                taxon.removeTaxonNode(taxonNode);
                                if (config.getTaxonNodeConfig().isDeleteTaxon()){
@@ -606,7 +615,7 @@ public class TaxonNodeServiceImpl
     @Transactional(readOnly = false)
     public DeleteResult deleteTaxonNode(UUID nodeUUID, TaxonDeletionConfigurator config) {
 
-       TaxonNode node = HibernateProxyHelper.deproxy(dao.load(nodeUUID), TaxonNode.class);
+       TaxonNode node = CdmBase.deproxy(dao.load(nodeUUID));
        return deleteTaxonNode(node, config);
     }
 
@@ -804,13 +813,23 @@ public class TaxonNodeServiceImpl
 
     @Override
     @Transactional
-    public UpdateResult createNewTaxonNode(UUID parentNodeUuid, Taxon newTaxon, Reference ref, String microref){
+    public UpdateResult createNewTaxonNode(UUID parentNodeUuid, CreateTaxonDTO taxonDto, UUID refUuid, String microref, boolean unplaced, boolean doubtful, boolean excluded, Map<Language,LanguageString> excludedNote){
         UpdateResult result = new UpdateResult();
-        if (newTaxon.getName().getId() != 0){
-            TaxonName name = nameService.load(newTaxon.getName().getUuid());
-            newTaxon.setName(name);
+        TaxonName name = null;
+        if (taxonDto.getNameUuid() != null){
+            name = nameService.load(taxonDto.getNameUuid());
+
         }else{
-            for (HybridRelationship rel : newTaxon.getName().getHybridChildRelations()){
+            NonViralNameParserImpl nonViralNameParser = NonViralNameParserImpl.NewInstance();
+            name = (TaxonName) nonViralNameParser.parseFullName(taxonDto.getTaxonNameString());
+        }
+        Reference sec = null;
+        if (taxonDto.getSecUuid() != null ){
+            sec = referenceService.load(taxonDto.getSecUuid());
+
+        }
+        if (!name.isPersited()){
+            for (HybridRelationship rel : name.getHybridChildRelations()){
                 if (!rel.getHybridName().isPersited()) {
                     nameService.save(rel.getHybridName());
                 }
@@ -819,13 +838,25 @@ public class TaxonNodeServiceImpl
                 }
             }
         }
-        UUID taxonUUID = taxonService.saveOrUpdate(newTaxon);
-        newTaxon = (Taxon) taxonService.load(taxonUUID);
 
-        TaxonNode parent = dao.load(parentNodeUuid);
-        TaxonNode child = null;
-        try{
-            child = parent.addChildTaxon(newTaxon,ref, microref);
+       Taxon newTaxon = Taxon.NewInstance(name, sec);
+//       UUID taxonUuid = taxonService.saveOrUpdate(newTaxon);
+//       newTaxon = (Taxon) taxonService.load(taxonUuid);
+
+       TaxonNode parent = dao.load(parentNodeUuid);
+       TaxonNode child = null;
+       Reference ref = null;
+       if (refUuid != null){
+           ref = referenceService.load(refUuid);
+       }
+
+       try{
+           child = parent.addChildTaxon(newTaxon, ref, microref);
+           child.setDoubtful(doubtful);
+           child.setExcluded(excluded);
+           child.setUnplaced(unplaced);
+           child.getExcludedNote().putAll(excludedNote);
+
         }catch(Exception e){
             result.addException(e);
             result.setError();
@@ -838,10 +869,8 @@ public class TaxonNodeServiceImpl
             result.setCdmEntity(child);
         }
         return result;
-
     }
 
-
     @Override
     @Transactional
     public UpdateResult saveNewTaxonNode(TaxonNode newTaxonNode){
@@ -849,14 +878,14 @@ public class TaxonNodeServiceImpl
         UUID parentUuid = newTaxonNode.getParent().getUuid();
         Taxon taxon = null;
 
-        if (newTaxonNode.getTaxon().getId() != 0){
+        if (newTaxonNode.getTaxon().isPersited()){
             taxon = (Taxon)taxonService.load(newTaxonNode.getTaxon().getUuid());
-            //newTaxonNode.setTaxon(taxon);
-        }else if (newTaxonNode.getTaxon().getName().getId() != 0){
+        }else if (newTaxonNode.getTaxon().getName().isPersited()){
             TaxonName name = nameService.load(newTaxonNode.getTaxon().getName().getUuid());
             taxon = newTaxonNode.getTaxon();
             taxon.setName(name);
         }else{
+            //taxon and name is not persisted, persist possible related names
             for (HybridRelationship rel : newTaxonNode.getTaxon().getName().getHybridChildRelations()){
                 if (!rel.getHybridName().isPersited()) {
                     nameService.save(rel.getHybridName());
@@ -875,24 +904,23 @@ public class TaxonNodeServiceImpl
             Reference sec = referenceService.load(taxon.getSec().getUuid());
             taxon.setSec(sec);
         }
-        if (taxon.getId() == 0){
-            UUID taxonUUID = taxonService.saveOrUpdate(taxon);
-            taxon = (Taxon) taxonService.load(taxonUUID);
+        if (!taxon.isPersited()){
+            MergeResult<TaxonBase> mergeResult = taxonService.merge(taxon, true);
+            taxon = (Taxon) mergeResult.getMergedEntity();
 
         }
 
-
         TaxonNode parent = dao.load(parentUuid);
         TaxonNode child = null;
         try{
             child = parent.addChildTaxon(taxon, newTaxonNode.getReference(), newTaxonNode.getMicroReference());
-
         }catch(Exception e){
             result.addException(e);
             result.setError();
             return result;
         }
 
+        //TODO can't we work with clone method here?
         child.setUnplaced(newTaxonNode.isUnplaced());
         child.setExcluded(newTaxonNode.isExcluded());
         child.setDoubtful(newTaxonNode.isDoubtful());
@@ -904,22 +932,16 @@ public class TaxonNodeServiceImpl
         }
 
         newTaxonNode = null;
-        dao.saveOrUpdate(child);
-
+        MergeResult<TaxonNode> mergeNode = dao.merge(child,true);
+        child = mergeNode.getMergedEntity();
         result.addUpdatedObject(child.getParent());
-        if (child != null){
-            result.setCdmEntity(child);
-        }
+        result.setCdmEntity(child);
         return result;
-
-
     }
 
-
-
     @Override
     @Transactional
-    public UpdateResult createNewTaxonNode(UUID parentNodeUuid, UUID taxonUuid, Reference ref, String microref){
+    public UpdateResult createNewTaxonNode(UUID parentNodeUuid, UUID taxonUuid, UUID refUuid, String microref){
         UpdateResult result = new UpdateResult();
         TaxonNode parent = dao.load(parentNodeUuid);
         Taxon taxon = (Taxon) taxonService.load(taxonUuid);
@@ -939,7 +961,6 @@ public class TaxonNodeServiceImpl
             result.setCdmEntity(child);
         }
         return result;
-
     }
 
     @Override
@@ -1011,7 +1032,6 @@ public class TaxonNodeServiceImpl
         return result;
     }
 
-
     @Override
     @Transactional(readOnly=false)
     public UpdateResult setPublishForSubtree(PublishForSubtreeConfigurator config){
@@ -1051,11 +1071,13 @@ public class TaxonNodeServiceImpl
 
         if (includeAcceptedTaxa){
             monitor.subTask("Update Accepted Taxa");
+            @SuppressWarnings("rawtypes")
             Set<TaxonBase> updatedTaxa = dao.setPublishForSubtreeAcceptedTaxa(subTreeIndex, publish, includeSharedTaxa, includeHybrids, monitor);
             result.addUpdatedObjects(updatedTaxa);
         }
         if (includeSynonyms){
             monitor.subTask("Update Synonyms");
+            @SuppressWarnings("rawtypes")
             Set<TaxonBase> updatedSynonyms = dao.setPublishForSubtreeSynonyms(subTreeIndex, publish, includeSharedTaxa, includeHybrids, monitor);
             result.addUpdatedObjects(updatedSynonyms);
         }
@@ -1068,6 +1090,7 @@ public class TaxonNodeServiceImpl
             if (config.isIncludeProParteSynonyms()){
                 relationTypes.addAll(TaxonRelationshipType.proParteOrPartialSynonymUuids());
             }
+            @SuppressWarnings("rawtypes")
             Set<TaxonBase> updatedTaxa = dao.setPublishForSubtreeRelatedTaxa(subTreeIndex, publish,
                     relationTypes, includeSharedTaxa, includeHybrids, monitor);
             result.addUpdatedObjects(updatedTaxa);
@@ -1077,8 +1100,6 @@ public class TaxonNodeServiceImpl
         return result;
     }
 
-
-
     @Override
     public long count(TaxonNodeFilter filter){
         return nodeFilterDao.count(filter);
@@ -1138,12 +1159,17 @@ public class TaxonNodeServiceImpl
         return commonParent;
     }
 
-
-
     @Override
-    public List<TaxonDistributionDTO> getTaxonDistributionDTOForSubtree(UUID parentNodeUuid, List<String> propertyPaths, Authentication authentication){
-        List<TaxonNode> nodes = listChildrenOf(load(parentNodeUuid), null, null,
-               true, true, propertyPaths);
+    public List<TaxonDistributionDTO> getTaxonDistributionDTO(List<UUID> nodeUuids, List<String> propertyPaths, Authentication authentication, boolean openChildren){
+        Set<TaxonNode> nodes = new HashSet<>();
+        if (openChildren){
+            List<TaxonNode> parentNodes = load(nodeUuids, propertyPaths);
+            for (TaxonNode node: parentNodes){
+                nodes.addAll(listChildrenOf(node, null, null, true, true, propertyPaths));
+            }
+            nodes.addAll(parentNodes);
+
+        }
         List<TaxonDistributionDTO> result = new ArrayList<>();
         boolean hasPermission = false;
         //TaxonDescription instance = TaxonDescription.NewInstance();
@@ -1151,7 +1177,7 @@ public class TaxonNodeServiceImpl
         for(TaxonNode node:nodes){
             if (authentication != null ) {
                 hasPermission = permissionEvaluator.hasPermission(authentication, node, Operation.UPDATE);
-            }else if (authentication == null){
+            }else {
                 hasPermission = true;
             }
             if (node.getTaxon() != null && hasPermission){
@@ -1159,13 +1185,11 @@ public class TaxonNodeServiceImpl
                     TaxonDistributionDTO dto = new TaxonDistributionDTO(node.getTaxon());
                     result.add(dto);
                 }catch(Exception e){
-                    System.err.println(node.getTaxon().getTitleCache());
+                    logger.error(e.getMessage(), e);
                 }
-
             }
-
         }
-
+        result.sort(new TaxonDistributionDTOComparator());
         return result;
     }
 
@@ -1190,29 +1214,15 @@ public class TaxonNodeServiceImpl
         return pager;
     }
 
-    @Override
-    public List<TaxonDistributionDTO> getTaxonDistributionDTOForSubtree(UUID parentNodeUuid,
-            List<String> propertyPaths) {
-        return getTaxonDistributionDTOForSubtree(parentNodeUuid, propertyPaths, null);
-    }
+//    @Override
+//    public List<TaxonDistributionDTO> getTaxonDistributionDTOForSubtree(UUID parentNodeUuid,
+//            List<String> propertyPaths, boolean openChildren) {
+//        return getTaxonDistributionDTOForSubtree(parentNodeUuid, propertyPaths, null, openChildren);
+//    }
 
     @Override
-    public List<TaxonNodeDto> getTaxonNodeDto(Integer limit, String pattern, UUID classificationUuid) {
-        return dao.getTaxonNodeDto(limit, pattern, classificationUuid);
+    public List<TaxonDistributionDTO> getTaxonDistributionDTO(List<UUID> nodeUuids,
+            List<String> propertyPaths, boolean openChildren) {
+        return getTaxonDistributionDTO(nodeUuids, propertyPaths, null, openChildren);
     }
-
-    @Override
-    public List<UuidAndTitleCache<TaxonNode>> listChildNodesAsUuidAndTitleCache(ITaxonTreeNode parent) {
-        UUID uuid = parent.getUuid();
-        int id = parent.getId();
-        UuidAndTitleCache<TaxonNode> uuidAndTitleCache = new UuidAndTitleCache<>(uuid, id, null);
-        return listChildNodesAsUuidAndTitleCache(uuidAndTitleCache);
-    }
-
-    @Override
-    public List<UuidAndTitleCache<TaxonNode>> listChildNodesAsUuidAndTitleCache(UuidAndTitleCache<TaxonNode> parent) {
-        return dao.listChildNodesAsUuidAndTitleCache(parent);
-    }
-
-
 }