ref #9541 DTOs for referencing objects and server side initialization
authorAndreas Müller <a.mueller@bgbm.org>
Wed, 31 Mar 2021 19:58:54 +0000 (21:58 +0200)
committerAndreas Müller <a.mueller@bgbm.org>
Wed, 31 Mar 2021 19:58:54 +0000 (21:58 +0200)
cdmlib-model/src/main/java/eu/etaxonomy/cdm/format/DescriptionElementFormatter.java [new file with mode: 0644]
cdmlib-model/src/main/java/eu/etaxonomy/cdm/format/ReferencingObjectFormatter.java [new file with mode: 0644]
cdmlib-persistence/src/main/java/eu/etaxonomy/cdm/persistence/dao/common/ICdmGenericDao.java
cdmlib-persistence/src/main/java/eu/etaxonomy/cdm/persistence/dao/hibernate/common/CdmGenericDaoImpl.java
cdmlib-persistence/src/main/java/eu/etaxonomy/cdm/persistence/dto/ReferencingObjectDto.java [new file with mode: 0644]
cdmlib-persistence/src/test/java/eu/etaxonomy/cdm/persistence/dao/hibernate/common/CdmGenericDaoImplTest.java
cdmlib-services/src/main/java/eu/etaxonomy/cdm/api/service/CommonServiceImpl.java
cdmlib-services/src/main/java/eu/etaxonomy/cdm/api/service/ICommonService.java

diff --git a/cdmlib-model/src/main/java/eu/etaxonomy/cdm/format/DescriptionElementFormatter.java b/cdmlib-model/src/main/java/eu/etaxonomy/cdm/format/DescriptionElementFormatter.java
new file mode 100644 (file)
index 0000000..6130b4b
--- /dev/null
@@ -0,0 +1,110 @@
+/**
+* Copyright (C) 2021 EDIT
+* European Distributed Institute of Taxonomy
+* http://www.e-taxonomy.eu
+*
+* The contents of this file are subject to the Mozilla Public License Version 1.1
+* See LICENSE.TXT at the top of this package for the full license terms.
+*/
+package eu.etaxonomy.cdm.format;
+
+import org.apache.commons.lang3.StringUtils;
+
+import eu.etaxonomy.cdm.common.CdmUtils;
+import eu.etaxonomy.cdm.model.common.CdmBase;
+import eu.etaxonomy.cdm.model.common.Language;
+import eu.etaxonomy.cdm.model.description.CommonTaxonName;
+import eu.etaxonomy.cdm.model.description.DescriptionBase;
+import eu.etaxonomy.cdm.model.description.DescriptionElementBase;
+import eu.etaxonomy.cdm.model.description.Distribution;
+import eu.etaxonomy.cdm.model.description.PresenceAbsenceTerm;
+import eu.etaxonomy.cdm.model.description.SpecimenDescription;
+import eu.etaxonomy.cdm.model.description.TaxonDescription;
+import eu.etaxonomy.cdm.model.description.TaxonInteraction;
+import eu.etaxonomy.cdm.model.description.TaxonNameDescription;
+import eu.etaxonomy.cdm.model.description.TextData;
+import eu.etaxonomy.cdm.model.location.NamedArea;
+import eu.etaxonomy.cdm.model.name.TaxonName;
+import eu.etaxonomy.cdm.model.occurrence.SpecimenOrObservationBase;
+import eu.etaxonomy.cdm.model.taxon.Taxon;
+
+/**
+ * This formatting has been copied from TaxEditor to allow serverside formatting
+ * for referencing objects.<BR>
+ * Maybe in future it will become a common formatting class for {@link DescriptionElementBase}
+ * instances or it will be moved back to TaxEditor and replaced by a general formatter
+ * for {@link DescriptionElementBase}.
+ *
+ * @author a.mueller
+ * @since 31.03.2021
+ */
+public class DescriptionElementFormatter {
+
+    public static String format(DescriptionElementBase element, Language defaultLanguage){
+
+        String mainElementLabel= null;
+        DescriptionBase<?> descr = element.getInDescription();
+        descr = CdmBase.deproxy(descr);
+
+        if (descr != null){
+            if (descr.isInstanceOf(TaxonDescription.class)){
+                Taxon taxon = CdmBase.deproxy(descr, TaxonDescription.class).getTaxon();
+                if (taxon != null){
+                    mainElementLabel = taxon.getTitleCache();
+                }
+            }else if (descr.isInstanceOf(SpecimenDescription.class)){
+                SpecimenOrObservationBase<?> specimen = CdmBase.deproxy(descr, SpecimenDescription.class).getDescribedSpecimenOrObservation();
+                if (specimen != null){
+                    mainElementLabel = specimen.getTitleCache();
+                }
+            }else if (descr.isInstanceOf(TaxonNameDescription.class)){
+                TaxonName name = CdmBase.deproxy(descr, TaxonNameDescription.class).getTaxonName();
+                if (name != null){
+                    mainElementLabel = name.getTitleCache();
+                }
+            }
+        }
+
+        String cache = null;
+        if (element instanceof TextData) {
+            //cache = ((TextData) element).getText(language);
+            cache = "Text Data";
+        }
+        if (element instanceof CommonTaxonName) {
+            cache = ((CommonTaxonName) element).getName();
+        }
+        if (element instanceof TaxonInteraction) {
+            Taxon taxon2 = ((TaxonInteraction) element).getTaxon2();
+            if(taxon2 != null && taxon2.getName() != null){
+                cache = taxon2.getName().getTitleCache();
+            }else{
+                cache = "No taxon chosen";
+            }
+        }
+        if (element instanceof Distribution) {
+            Distribution distribution = (Distribution) element;
+
+            NamedArea area = distribution.getArea();
+            if(area != null){
+                cache =  area.getLabel();
+
+                PresenceAbsenceTerm status = distribution.getStatus();
+                if (status == null){
+                    cache += ", no status";
+                }else {
+                    cache += ", " + status.getLabel();
+                }
+            }
+        }
+        String result = cache == null ? "" : cache;
+        if (isNotBlank(mainElementLabel)){
+            result = CdmUtils.concat(" ", result, "(" + mainElementLabel + ")");
+        }
+        return result;
+
+    }
+
+    private static boolean isNotBlank(String str) {
+        return StringUtils.isNotBlank(str);
+    }
+}
diff --git a/cdmlib-model/src/main/java/eu/etaxonomy/cdm/format/ReferencingObjectFormatter.java b/cdmlib-model/src/main/java/eu/etaxonomy/cdm/format/ReferencingObjectFormatter.java
new file mode 100644 (file)
index 0000000..53d6887
--- /dev/null
@@ -0,0 +1,487 @@
+/**
+* Copyright (C) 2021 EDIT
+* European Distributed Institute of Taxonomy
+* http://www.e-taxonomy.eu
+*
+* The contents of this file are subject to the Mozilla Public License Version 1.1
+* See LICENSE.TXT at the top of this package for the full license terms.
+*/
+package eu.etaxonomy.cdm.format;
+
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.Set;
+
+import org.apache.commons.lang3.StringUtils;
+
+import eu.etaxonomy.cdm.common.CdmUtils;
+import eu.etaxonomy.cdm.format.occurrences.DistanceStringFormatter;
+import eu.etaxonomy.cdm.model.agent.AgentBase;
+import eu.etaxonomy.cdm.model.common.CdmBase;
+import eu.etaxonomy.cdm.model.common.IdentifiableEntity;
+import eu.etaxonomy.cdm.model.common.Language;
+import eu.etaxonomy.cdm.model.common.LanguageString;
+import eu.etaxonomy.cdm.model.common.LanguageStringBase;
+import eu.etaxonomy.cdm.model.common.Marker;
+import eu.etaxonomy.cdm.model.common.MarkerType;
+import eu.etaxonomy.cdm.model.common.RelationshipBase;
+import eu.etaxonomy.cdm.model.common.RelationshipTermBase;
+import eu.etaxonomy.cdm.model.common.TimePeriod;
+import eu.etaxonomy.cdm.model.description.CommonTaxonName;
+import eu.etaxonomy.cdm.model.description.DescriptionBase;
+import eu.etaxonomy.cdm.model.description.DescriptionElementBase;
+import eu.etaxonomy.cdm.model.description.DescriptionElementSource;
+import eu.etaxonomy.cdm.model.description.Distribution;
+import eu.etaxonomy.cdm.model.description.IDescribable;
+import eu.etaxonomy.cdm.model.description.KeyStatement;
+import eu.etaxonomy.cdm.model.description.PresenceAbsenceTerm;
+import eu.etaxonomy.cdm.model.description.SpecimenDescription;
+import eu.etaxonomy.cdm.model.description.TaxonDescription;
+import eu.etaxonomy.cdm.model.description.TaxonInteraction;
+import eu.etaxonomy.cdm.model.description.TaxonNameDescription;
+import eu.etaxonomy.cdm.model.description.TextData;
+import eu.etaxonomy.cdm.model.location.NamedArea;
+import eu.etaxonomy.cdm.model.name.HomotypicalGroup;
+import eu.etaxonomy.cdm.model.name.HybridRelationship;
+import eu.etaxonomy.cdm.model.name.NameRelationship;
+import eu.etaxonomy.cdm.model.name.NameTypeDesignation;
+import eu.etaxonomy.cdm.model.name.NomenclaturalSource;
+import eu.etaxonomy.cdm.model.name.NomenclaturalStatus;
+import eu.etaxonomy.cdm.model.name.SpecimenTypeDesignation;
+import eu.etaxonomy.cdm.model.name.TaxonName;
+import eu.etaxonomy.cdm.model.name.TextualTypeDesignation;
+import eu.etaxonomy.cdm.model.name.TypeDesignationBase;
+import eu.etaxonomy.cdm.model.name.TypeDesignationStatusBase;
+import eu.etaxonomy.cdm.model.occurrence.DeterminationEvent;
+import eu.etaxonomy.cdm.model.occurrence.GatheringEvent;
+import eu.etaxonomy.cdm.model.occurrence.SpecimenOrObservationBase;
+import eu.etaxonomy.cdm.model.permission.Group;
+import eu.etaxonomy.cdm.model.permission.User;
+import eu.etaxonomy.cdm.model.reference.OriginalSourceBase;
+import eu.etaxonomy.cdm.model.taxon.Classification;
+import eu.etaxonomy.cdm.model.taxon.SecundumSource;
+import eu.etaxonomy.cdm.model.taxon.Taxon;
+import eu.etaxonomy.cdm.model.taxon.TaxonBase;
+import eu.etaxonomy.cdm.model.taxon.TaxonNode;
+import eu.etaxonomy.cdm.model.taxon.TaxonRelationship;
+import eu.etaxonomy.cdm.model.term.Representation;
+
+/**
+ * @author a.mueller
+ * @date 19.03.2021
+ */
+public class ReferencingObjectFormatter {
+
+    public static String format(CdmBase element, Language defaultLanguage) {
+
+        String resultString = null;
+        if (element == null){
+            return null;
+        }else if (element instanceof IdentifiableEntity) {
+            resultString = ((IdentifiableEntity<?>) element).getTitleCache();
+        }else if (element instanceof OriginalSourceBase) {
+            OriginalSourceBase originalSource = (OriginalSourceBase) element;
+//              ISourceable sourcedObject = originalSource.getSourcedObj();
+            //due to #5743 the bidirectionality for sourced object had to be removed
+
+            String sourceObjectTitle = "sourced object data not available (#5743)";
+
+            //it is now possible for NomenclaturalSource as they link to the sourced name
+            if (originalSource instanceof NomenclaturalSource){
+                TaxonName sourcedName = ((NomenclaturalSource)originalSource).getSourcedName();
+                sourceObjectTitle = sourcedName == null ? "Source orphaned, not attached to a name" :
+                    "Source for " + sourcedName.getTitleCache();
+            }else if (originalSource instanceof SecundumSource){
+                TaxonBase<?> sourcedTaxon = ((SecundumSource)originalSource).getSourcedTaxon();
+                sourceObjectTitle = sourcedTaxon == null ? "Source orphaned, not attached to a taxon" :
+                    "Source for " + sourcedTaxon.getTitleCache();
+            }else if (originalSource instanceof DescriptionElementSource){
+                sourceObjectTitle = getCache((DescriptionElementSource)originalSource, defaultLanguage);
+            }
+            resultString = CdmUtils.concat("; ", new String[]{originalSource.getIdNamespace(), originalSource.getIdInSource(), sourceObjectTitle});
+        }else if (element instanceof LanguageStringBase) {
+            resultString = ((LanguageStringBase) element).getText();
+        }else if (element instanceof DescriptionElementBase) {
+            resultString = getCache((DescriptionElementBase) element, defaultLanguage);
+        }else if (element instanceof RelationshipBase<?, ?, ?>) {
+            resultString = getCache((RelationshipBase<?, ?, ?>) element, defaultLanguage);
+        }else if (element instanceof TypeDesignationBase<?>) {
+            resultString = getCache((TypeDesignationBase<?>) element, defaultLanguage);
+        }else if (element instanceof HomotypicalGroup) {
+            resultString = getCache((HomotypicalGroup) element);
+        }else if (element instanceof TaxonNode) {
+            resultString = getCache((TaxonNode) element);
+        }else if (element instanceof DeterminationEvent) {
+            resultString = getCache((DeterminationEvent) element);
+        }else if (element instanceof NomenclaturalStatus) {
+            resultString = getCache((NomenclaturalStatus) element);
+        }else if (element instanceof GatheringEvent){
+            resultString = getCache((GatheringEvent) element);
+        }else if (element instanceof Marker) {
+            Marker marker = (Marker) element;
+            MarkerType type = marker.getMarkerType();
+            resultString = (type == null ? "- no marker type -" : marker.getMarkerType().getLabel()) + " (" + marker.getFlag() + ")";
+        }else if (element instanceof User) {
+            User user = (User) element;
+            resultString = user.getUsername();
+        }else if (element instanceof Group) {
+            Group group = (Group) element;
+            resultString = group.getName();
+        }else if (element instanceof KeyStatement) {
+            KeyStatement keyStatement = (KeyStatement) element;
+            resultString = getCache(keyStatement);
+        }else{
+            // TODO write return texts for HomotypicalGroup, etc.
+            resultString = element.toString();
+        }
+
+        if (resultString == null){
+            resultString = element.toString();
+        }
+        return resultString;
+    }
+
+    private static String getCache(DescriptionElementSource source, Language defaultLanguage) {
+        DescriptionElementBase sourcedElement = source.getSourcedElement();
+
+        if (sourcedElement == null){
+            return "Source orphaned, not attached to a fact";
+        }
+        String superLabel = getDescribedObjectLabel(sourcedElement.getInDescription());
+        String result = CdmUtils.concat(": ", DescriptionElementFormatter.format(sourcedElement, defaultLanguage), superLabel);
+        return result;
+    }
+
+    private static String getDescribedObjectLabel(DescriptionBase<?> inDescription) {
+        IDescribable<?> entity = inDescription.describedEntity();
+        if (entity != null){
+            return entity.getTitleCache();
+        }else{
+            return inDescription.getTitleCache();
+        }
+    }
+
+    private static String getCache(RelationshipBase<?, ?, ?> rel, Language defaultLanguage) {
+        rel = CdmBase.deproxy(rel);
+        RelationshipTermBase<?> type = rel.getType();
+        IdentifiableEntity<?> from;
+        IdentifiableEntity<?> to;
+        if (rel.isInstanceOf(NameRelationship.class)){
+            from = ((NameRelationship)rel).getFromName();
+            to = ((NameRelationship)rel).getToName();
+        }else if (rel.isInstanceOf(HybridRelationship.class)){
+            from = ((HybridRelationship)rel).getParentName();
+            to = ((HybridRelationship)rel).getHybridName();
+        }else if (rel.isInstanceOf(TaxonRelationship.class)){
+            from = ((TaxonRelationship)rel).getFromTaxon();
+            to = ((TaxonRelationship)rel).getToTaxon();
+        }else{
+            try {
+                Method fromMethod = rel.getClass().getMethod("getRelatedFrom");
+                Method toMethod = rel.getClass().getMethod("getRelatedFrom");
+                fromMethod.setAccessible(true);
+                toMethod.setAccessible(true);
+                from = (IdentifiableEntity<?>)fromMethod.invoke(rel);
+                to = (IdentifiableEntity<?>)toMethod.invoke(rel);
+            } catch (NoSuchMethodException | SecurityException | IllegalAccessException
+                | IllegalArgumentException | InvocationTargetException e) {
+                throw new RuntimeException(e);
+            }
+        }
+        String typeLabel = null;
+        if (type != null){
+            Representation typeRepr = type.getPreferredRepresentation(defaultLanguage);
+            if (typeRepr != null){
+                typeLabel = typeRepr.getAbbreviatedLabel();
+            }
+            if (isBlank(typeLabel) && typeRepr != null){
+                typeLabel = typeRepr.getLabel();
+            }
+            if (isBlank(typeLabel) ){
+                typeLabel = type.getSymbol();
+            }
+            if (isBlank(typeLabel)){
+                typeLabel = type.getTitleCache();
+            }
+        }
+        if (isBlank(typeLabel)){
+            typeLabel = "->";
+        }
+        String result = CdmUtils.concat(" ", new String[]{from == null ? null : from.getTitleCache(),
+                typeLabel, to == null? null : to.getTitleCache()});
+        return result;
+    }
+
+    private static String getCache(GatheringEvent gatheringEvent){
+        String ALTITUDE_PREFIX = "alt. ";
+        final String METER = "m";
+
+        String result = "";
+
+        //collector
+        AgentBase<?> collector = CdmBase.deproxy(gatheringEvent.getCollector());
+        String collectorStr = collector == null? null : collector.getTitleCache();
+        result = CdmUtils.concat(", ", result, collectorStr);
+
+        //gathering period
+        TimePeriod gatheringPeriod = gatheringEvent.getTimeperiod();
+        result = CdmUtils.concat(", ", result, (gatheringPeriod == null? null : gatheringPeriod.toString()));
+
+        //country
+        String strCountry = null;
+        NamedArea country = gatheringEvent.getCountry();
+        Representation repCountry = country == null ? null : country.getRepresentation(Language.DEFAULT());
+        strCountry = repCountry == null ? null: repCountry.getLabel();
+        result = CdmUtils.concat(", ", result, strCountry);
+
+        //locality
+        LanguageString locality = gatheringEvent.getLocality();
+        if (locality != null) {
+            result = CdmUtils.concat(", ", result, locality.getText());
+        }
+
+        //elevation
+        String elevationStr;
+        if (isNotBlank(gatheringEvent.getAbsoluteElevationText())){
+            elevationStr = gatheringEvent.getAbsoluteElevationText();
+        }else{
+            String text = gatheringEvent.getAbsoluteElevationText();
+            Integer min = gatheringEvent.getAbsoluteElevation();
+            Integer max = gatheringEvent.getAbsoluteElevationMax();
+            elevationStr = DistanceStringFormatter.distanceString(min, max, text, METER);
+        }
+        if (isNotBlank(elevationStr)){
+            result = CdmUtils.concat(", " , result, ALTITUDE_PREFIX);
+            result += elevationStr;
+        }
+
+        //exact locality
+        if (gatheringEvent.getExactLocation() != null){
+            String exactLocation = gatheringEvent.getExactLocation().toSexagesimalString(false, false);
+            result = CdmUtils.concat(", ", result, exactLocation);
+        }
+
+        return result;
+    }
+
+    private static String getCache(DeterminationEvent detEvent) {
+        //taxon
+        String taxonStr = null;
+        TaxonName taxonName = detEvent.getTaxonName();
+        TaxonBase<?> taxon = detEvent.getTaxon();
+        if (taxonName != null){
+            taxonStr = taxonName.getTitleCache();
+        }
+        if (isBlank(taxonStr) && taxon != null){
+            taxonStr = taxon.getTitleCache();
+        }
+        if (isBlank(taxonStr)){
+            taxonStr = "no or unlabled taxon";
+        }
+
+        //unit
+        SpecimenOrObservationBase<?> unit = detEvent.getIdentifiedUnit();
+        String unitStr;
+        if (unit != null){
+            unitStr = unit.getTitleCache();
+            if (isBlank(unitStr)){
+                unitStr = "Unlabled unit";
+            }
+        }else{
+            unitStr = "no unit";
+        }
+
+        String result = CdmUtils.concat(" determined as ", unitStr, taxonStr);
+
+        return result;
+    }
+
+    private static String getCache(TaxonNode taxonNode) {
+        String result = "";
+        Classification classification = taxonNode.getClassification();
+        if (classification != null){
+            String classificationStr = classification.getName() == null ? "" : classification.getName().getText();
+            result = CdmUtils.concat("" , result, classificationStr);
+            if (isBlank(result)){
+                result = classification.toString();
+            }
+        }
+        String parentStr;
+        TaxonNode parentNode = taxonNode.getParent();
+        if (parentNode == null){
+            parentStr = "no parent";
+        }else{
+            Taxon parentTaxon = parentNode.getTaxon();
+            if (parentTaxon == null){
+                parentStr = "no parent taxon";
+            }else{
+                TaxonName parentName = parentTaxon.getName();
+                if (parentName == null){
+                    parentStr = "child of " + parentTaxon.getTitleCache();
+                }else{
+                    parentStr = "child of " + parentName.getTitleCache();
+                }
+            }
+        }
+        result = CdmUtils.concat(": ", result, parentStr);
+
+        return result;
+    }
+
+    private static String getCache(TypeDesignationBase<?> designation, Language defaultLanguage) {
+        designation = CdmBase.deproxy(designation);
+        //from
+        String fromString = null;
+        Set<TaxonName> from = designation.getTypifiedNames();
+        if(from != null){
+            for (TaxonName name : from){
+                fromString = CdmUtils.concat(",", fromString, name.getTitleCache());
+            }
+        }
+        //to
+        IdentifiableEntity<?> to = null;
+        String toStr = "";
+        if (designation.isInstanceOf(SpecimenTypeDesignation.class)){
+            to = ((SpecimenTypeDesignation)designation).getTypeSpecimen();
+        }else if (designation.isInstanceOf(NameTypeDesignation.class)){
+            to = ((NameTypeDesignation)designation).getTypeName();
+        }else if (designation.isInstanceOf(TextualTypeDesignation.class)){
+            toStr = ((TextualTypeDesignation)designation).getPreferredText(defaultLanguage);
+        }else{
+            throw new RuntimeException("Type Designation class not supported: " +  designation.getClass().getName());
+        }
+        toStr = to == null? toStr : to.getTitleCache();
+        //status
+        String typeLabel = null;
+        TypeDesignationStatusBase<?> status = designation.getTypeStatus();
+        if (status != null){
+            Representation typeRepr = status.getPreferredRepresentation(defaultLanguage);
+            if (typeRepr != null){
+                typeLabel = typeRepr.getAbbreviatedLabel();
+            }
+            if (isBlank(typeLabel) && typeRepr != null){
+                typeLabel = typeRepr.getLabel();
+            }
+            if (isBlank(typeLabel) ){
+                typeLabel = status.getSymbol();
+            }
+            if (isBlank(typeLabel)){
+                typeLabel = status.getTitleCache();
+            }
+        }
+        if (isBlank(typeLabel)){
+            typeLabel = "->";
+        }
+        //concat
+        String result = CdmUtils.concat(" ", new String[]{fromString, typeLabel, toStr});
+        return result;
+    }
+
+    private static String getCache(HomotypicalGroup hg) {
+        String result = "";
+        for (TaxonName tnb : hg.getTypifiedNames()){
+            result = CdmUtils.concat(", ", result, tnb.getTitleCache());
+        }
+        if (isBlank(result)){
+            result = "No typified names";
+        }
+        return result;
+    }
+
+    private static String getCache(KeyStatement ks) {
+        String result = "";
+        LanguageString ls = ks.getPreferredLanguageString(Language.DEFAULT());
+        if (ls != null && CdmUtils.isNotBlank(ls.getText())){
+            result = ls.getText();
+        }else{
+            result = ks.toString();
+        }
+        return result;
+    }
+
+    private static String getCache(NomenclaturalStatus nomStatus) {
+        String result = nomStatus.getName().getTitleCache();
+        if (nomStatus.getType()!= null){
+            Representation rep = nomStatus.getType().getPreferredRepresentation(Language.DEFAULT());
+            if (rep != null){
+                result = CdmUtils.concat(": ", rep.getAbbreviatedLabel(), result);
+            }
+        }
+        return result;
+    }
+
+
+    private static boolean isNotBlank(String str){
+        return StringUtils.isNotBlank(str);
+    }
+
+    private static boolean isBlank(String str){
+        return StringUtils.isBlank(str);
+    }
+
+    //from taxeditor DescriptionHelper
+    public static String getCache(DescriptionElementBase element,
+            Language defaultLanguage) {
+
+        String mainElementLabel= null;
+        DescriptionBase<?> descr = element.getInDescription();
+        descr = CdmBase.deproxy(descr);
+
+        if (descr != null){
+            if (descr.isInstanceOf(TaxonDescription.class)){
+                Taxon taxon = CdmBase.deproxy(descr, TaxonDescription.class).getTaxon();
+                if (taxon != null){
+                    mainElementLabel = taxon.getTitleCache();
+                }
+            }else if (descr.isInstanceOf(SpecimenDescription.class)){
+                SpecimenOrObservationBase<?> specimen = CdmBase.deproxy(descr, SpecimenDescription.class).getDescribedSpecimenOrObservation();
+                if (specimen != null){
+                    mainElementLabel = specimen.getTitleCache();
+                }
+            }else if (descr.isInstanceOf(TaxonNameDescription.class)){
+                TaxonName name = CdmBase.deproxy(descr, TaxonNameDescription.class).getTaxonName();
+                if (name != null){
+                    mainElementLabel = name.getTitleCache();
+                }
+            }
+        }
+
+        String cache = null;
+        if (element instanceof TextData) {
+            //cache = ((TextData) element).getText(language);
+            cache = "Text Data";
+        }
+        if (element instanceof CommonTaxonName) {
+            cache = ((CommonTaxonName) element).getName();
+        }
+        if (element instanceof TaxonInteraction) {
+            Taxon taxon2 = ((TaxonInteraction) element).getTaxon2();
+            if(taxon2 != null && taxon2.getName() != null){
+                cache = taxon2.getName().getTitleCache();
+            }else{
+                cache = "No taxon chosen";
+            }
+        }
+        if (element instanceof Distribution) {
+            Distribution distribution = (Distribution) element;
+
+            NamedArea area = distribution.getArea();
+            if(area != null){
+                cache =  area.getLabel();
+
+                PresenceAbsenceTerm status = distribution.getStatus();
+                if (status == null){
+                    cache += ", no status";
+                }else {
+                    cache += ", " + status.getLabel();
+                }
+            }
+        }
+        String result = cache == null ? "" : cache;
+        if (isNotBlank(mainElementLabel)){
+            result = CdmUtils.concat(" ", result, "(" + mainElementLabel + ")");
+        }
+        return result;
+    }
+
+}
index 3959b4604cf160143fec0f82670b2af7b919750b..9c4cd038431280e68998d39180789d22e9cd4917 100644 (file)
@@ -19,6 +19,7 @@ import org.springframework.dao.DataAccessException;
 
 import eu.etaxonomy.cdm.model.common.CdmBase;
 import eu.etaxonomy.cdm.model.metadata.CdmMetaData;
+import eu.etaxonomy.cdm.persistence.dto.ReferencingObjectDto;
 import eu.etaxonomy.cdm.persistence.query.OrderHint;
 import eu.etaxonomy.cdm.strategy.match.IMatchStrategy;
 import eu.etaxonomy.cdm.strategy.match.IMatchable;
@@ -61,6 +62,9 @@ public interface ICdmGenericDao {
        public List<CdmBase> getCdmBasesWithItemInCollection(Class<?> itemClass,
                Class<?> clazz, String propertyName, CdmBase item, Integer limit);
 
+       public List<ReferencingObjectDto> getCdmBasesWithItemInCollectionDto(Class<?> itemClass,
+            Class<? extends CdmBase> clazz, String propertyName, CdmBase item, Integer limit);
+
        /**
         * Returns all classes that are persisted via the persisting framework.
         * E.g. in hibernate these are all classes registered in the session factory
@@ -82,6 +86,8 @@ public interface ICdmGenericDao {
         */
        public Set<CdmBase> getReferencingObjects(CdmBase referencedCdmBase);
 
+       public Set<ReferencingObjectDto> getReferencingObjectsDto(CdmBase referencedCdmBase);
+
        /**
         * Merges cdmBase2 into cdmBase1 and rearranges all reference to cdmBase2 by letting them point to
         * cdmBase1. If the merge strategy is not defined (<code>null</code>) the default merge strategy is taken instead.
index 7aa353c6c56d561fc123775ac1d1c472853fdd79..cb6c82aa323ce5408a949694934eaf4586062478 100644 (file)
@@ -73,6 +73,7 @@ import eu.etaxonomy.cdm.model.common.CdmBase;
 import eu.etaxonomy.cdm.model.common.IdentifiableEntity;
 import eu.etaxonomy.cdm.model.metadata.CdmMetaData;
 import eu.etaxonomy.cdm.persistence.dao.common.ICdmGenericDao;
+import eu.etaxonomy.cdm.persistence.dto.ReferencingObjectDto;
 import eu.etaxonomy.cdm.strategy.match.CacheMatcher;
 import eu.etaxonomy.cdm.strategy.match.DefaultMatchStrategy;
 import eu.etaxonomy.cdm.strategy.match.FieldMatcher;
@@ -109,6 +110,23 @@ public class CdmGenericDaoImpl
                super(CdmBase.class);
        }
 
+//    @Override
+    private List<ReferencingObjectDto> getCdmBasesByFieldAndClassDto(Class<? extends CdmBase> clazz, String propertyName, CdmBase referencedCdmBase, Integer limit){
+
+        Query query = getSession().createQuery("SELECT new eu.etaxonomy.cdm.persistence.dto.ReferencingObjectDto(this.uuid, this.id) "
+                    + "FROM "+ clazz.getSimpleName() + " this "
+                    + "WHERE this." + propertyName +" = :referencedObject")
+                .setEntity("referencedObject", referencedCdmBase);
+
+        if (limit != null){
+            query.setMaxResults(limit);
+        }
+        @SuppressWarnings("unchecked")
+        List<ReferencingObjectDto> result = query.list();
+        result.forEach(dto->dto.setType((Class<CdmBase>)clazz));
+        return result;
+    }
+
        @Override
     public List<CdmBase> getCdmBasesByFieldAndClass(Class<? extends CdmBase> clazz, String propertyName, CdmBase referencedCdmBase, Integer limit){
         Session session = super.getSession();
@@ -135,16 +153,28 @@ public class CdmGenericDaoImpl
         return result;
     }
 
+    @Override
+    public List<ReferencingObjectDto> getCdmBasesWithItemInCollectionDto(Class<?> itemClass,
+            Class<? extends CdmBase> clazz, String propertyName, CdmBase item, Integer limit){
+
+        String queryStr = withItemInCollectionHql(itemClass, clazz, propertyName,
+                "new eu.etaxonomy.cdm.persistence.dto.ReferencingObjectDto(other.uuid, other.id)");
+        Query query = getSession().createQuery(queryStr).setEntity("referencedObject", item);
+        if (limit != null){
+            query.setMaxResults(limit);
+        }
+        @SuppressWarnings("unchecked")
+        List<ReferencingObjectDto> result = query.list();
+        result.forEach(dto->dto.setType((Class)clazz));
+        return result;
+    }
+
        @Override
        public List<CdmBase> getCdmBasesWithItemInCollection(Class<?> itemClass,
                Class<?> clazz, String propertyName, CdmBase item, Integer limit){
 
-           Session session = super.getSession();
-               String thisClassStr = itemClass.getSimpleName();
-               String otherClassStr = clazz.getSimpleName();
-               String queryStr = " SELECT other FROM "+ thisClassStr + " this, " + otherClassStr + " other " +
-                       " WHERE this = :referencedObject AND this member of other." + propertyName ;
-               Query query = session.createQuery(queryStr).setEntity("referencedObject", item);
+               String queryStr = withItemInCollectionHql(itemClass, clazz, propertyName, "other");
+               Query query = getSession().createQuery(queryStr).setEntity("referencedObject", item);
                if (limit != null){
                    query.setMaxResults(limit);
                }
@@ -153,16 +183,21 @@ public class CdmGenericDaoImpl
                return result;
        }
 
-       @Override
-    public long getCountWithItemInCollection(Class<?> itemClass, Class<?> clazz, String propertyName,
-            CdmBase item){
-        Session session = super.getSession();
+    private String withItemInCollectionHql(Class<?> itemClass, Class<?> clazz, String propertyName, String select) {
         String thisClassStr = itemClass.getSimpleName();
         String otherClassStr = clazz.getSimpleName();
-        String queryStr = " SELECT count(this) FROM "+ thisClassStr + " this, " + otherClassStr + " other " +
-            " WHERE this = :referencedObject AND this member of other."+propertyName ;
+        String result =  "SELECT "+select+" FROM "+ thisClassStr + " this, " + otherClassStr + " other " +
+                " WHERE this = :referencedObject AND this member of other." + propertyName ;
+        return result;
+    }
 
-        Query query = session.createQuery(queryStr).setEntity("referencedObject", item);
+    @Override
+    public long getCountWithItemInCollection(Class<?> itemClass, Class<?> clazz, String propertyName,
+            CdmBase item){
+
+        String queryStr = withItemInCollectionHql(itemClass, clazz, propertyName, "count(this)");
+
+        Query query = getSession().createQuery(queryStr).setEntity("referencedObject", item);
         long result =(Long)query.uniqueResult();
         return result;
     }
@@ -193,6 +228,28 @@ public class CdmGenericDaoImpl
                return result;
        }
 
+    @Override
+    public Set<ReferencingObjectDto> getReferencingObjectsDto(CdmBase referencedCdmBase){
+        Set<ReferencingObjectDto> result = new HashSet<>();
+        if (referencedCdmBase == null) {
+            return null;
+        }
+        try {
+
+            referencedCdmBase = HibernateProxyHelper.deproxy(referencedCdmBase);
+            Class<? extends CdmBase> referencedClass = referencedCdmBase.getClass();
+
+            Set<ReferenceHolder> holderSet = getOrMakeHolderSet(referencedClass);
+            for (ReferenceHolder refHolder: holderSet){
+                handleReferenceHolderDto(referencedCdmBase, result, refHolder, false);
+            }
+            return result;
+        } catch (Exception e) {
+            e.printStackTrace();
+            throw new RuntimeException(e);
+        }
+    }
+
        @Override
        public Set<CdmBase> getReferencingObjects(CdmBase referencedCdmBase){
                Set<CdmBase> result = new HashSet<>();
@@ -277,14 +334,27 @@ public class CdmGenericDaoImpl
                        e.printStackTrace();
                        throw new RuntimeException(e);
                }
-
        }
 
-       /**
-        * @param referencedCdmBase
-        * @param result
-        * @param refHolder
-        */
+    private void handleReferenceHolderDto(CdmBase referencedCdmBase,
+            Set<ReferencingObjectDto> result, ReferenceHolder refHolder, boolean limited) {
+
+        boolean isCollection = refHolder.isCollection();
+        if (isCollection){
+            if (limited){
+                result.addAll(getCdmBasesWithItemInCollectionDto(refHolder.itemClass, refHolder.otherClass, refHolder.propertyName, referencedCdmBase, 100));
+            }else{
+                result.addAll(getCdmBasesWithItemInCollectionDto(refHolder.itemClass, refHolder.otherClass, refHolder.propertyName, referencedCdmBase, null));
+            }
+        }else{
+            if (limited){
+                result.addAll(getCdmBasesByFieldAndClassDto(refHolder.otherClass, refHolder.propertyName, referencedCdmBase, 100));
+            }else{
+                result.addAll(getCdmBasesByFieldAndClassDto(refHolder.otherClass, refHolder.propertyName, referencedCdmBase, null));
+            }
+        }
+    }
+
        private void handleReferenceHolder(CdmBase referencedCdmBase,
                        Set<CdmBase> result, ReferenceHolder refHolder, boolean limited) {
 
diff --git a/cdmlib-persistence/src/main/java/eu/etaxonomy/cdm/persistence/dto/ReferencingObjectDto.java b/cdmlib-persistence/src/main/java/eu/etaxonomy/cdm/persistence/dto/ReferencingObjectDto.java
new file mode 100644 (file)
index 0000000..0b0d6b9
--- /dev/null
@@ -0,0 +1,117 @@
+/**
+* Copyright (C) 2021 EDIT
+* European Distributed Institute of Taxonomy
+* http://www.e-taxonomy.eu
+*
+* The contents of this file are subject to the Mozilla Public License Version 1.1
+* See LICENSE.TXT at the top of this package for the full license terms.
+*/
+package eu.etaxonomy.cdm.persistence.dto;
+
+import java.util.UUID;
+
+import eu.etaxonomy.cdm.common.CdmUtils;
+import eu.etaxonomy.cdm.model.common.CdmBase;
+
+/**
+ * @author a.mueller
+ * @since 31.03.2021
+ */
+public class ReferencingObjectDto extends UuidAndTitleCache<CdmBase> {
+
+    private static final long serialVersionUID = -6990153096653819574L;
+
+    private CdmBase referencedEntity;
+
+    private UuidAndTitleCache<CdmBase> openInTarget;
+
+//*************************** CONSTRUCTOR **************************/
+
+    public ReferencingObjectDto(){
+        super(null, null);
+    }
+
+    public ReferencingObjectDto(UUID uuid, Integer id) {
+        super(uuid, id, null);
+    }
+
+    @SuppressWarnings({ "unchecked", "rawtypes" })
+    public ReferencingObjectDto(Class type, UUID uuid, Integer id) {
+        super(type, uuid, id, null);
+    }
+
+    @SuppressWarnings({ "rawtypes", "unchecked" })
+    public ReferencingObjectDto(String typeStr, UUID uuid, Integer id) throws ClassNotFoundException {
+        super((Class)Class.forName(typeStr), uuid, id, null);
+    }
+
+    public ReferencingObjectDto(CdmBase referencedEntity) {
+        super((Class<CdmBase>)referencedEntity.getClass(), referencedEntity.getUuid(), referencedEntity.getId(), null);
+        this.referencedEntity = referencedEntity;
+    }
+
+//************************ GETTER / SETTER *****************************/
+
+    public CdmBase getReferencedEntity() {
+        return referencedEntity;
+    }
+    public void setReferencedEntity(CdmBase referencedEntity) {
+        this.referencedEntity = referencedEntity;
+    }
+
+    public UuidAndTitleCache<CdmBase> getOpenInTarget() {
+        return openInTarget;
+    }
+    public void setOpenInTarget(UuidAndTitleCache<CdmBase> openInTarget) {
+        this.openInTarget = openInTarget;
+    }
+
+// *********************** EQUALS *************************************/
+
+    //TODO move partly up to UuidAndTitleCache
+
+    @Override
+    public int hashCode() {
+        final int prime = 31;
+        int result = 1;
+        result = prime * result + ((getUuid() == null) ? 0 : getUuid().hashCode());
+        result = prime * result + ((getId() == null) ? 0 : getId().hashCode());
+        result = prime * result + ((getType() == null) ? 0 : getType().hashCode());
+        result = prime * result + ((getReferencedEntity() == null) ? 0 : getReferencedEntity().hashCode());
+        return result;
+    }
+
+    @Override
+    public boolean equals(Object obj) {
+        if (this == obj) {
+            return true;
+        }else if (obj == null || ! (obj instanceof ReferencingObjectDto)) {
+            return false;
+        }
+        ReferencingObjectDto other = (ReferencingObjectDto) obj;
+
+        if (!CdmUtils.nullSafeEqual(this.getType(), other.getType())){
+            return false;
+        }
+        if (!CdmUtils.nullSafeEqual(this.getId(), other.getId())){
+            return false;
+        }
+        if (!CdmUtils.nullSafeEqual(this.getUuid(), other.getUuid())){
+            return false;
+        }
+        //TODO allow only 1 side has entity
+        if (!CdmUtils.nullSafeEqual(this.getReferencedEntity(), other.getReferencedEntity())){
+            return false;
+        }
+
+        return true;
+    }
+// ********************** STRING ****************************************/
+
+    @Override
+    public String toString() {
+        return "RefObjDto[type=" + getType() + ":" + getId() + "]";
+    }
+
+
+}
\ No newline at end of file
index c8aa629df4fcb57507a208957c690d8d2ffb11f7..89dfe5ad7756be6dddb2639f5efc1384e1f64196 100644 (file)
@@ -158,6 +158,7 @@ import eu.etaxonomy.cdm.persistence.dao.name.ITaxonNameDao;
 import eu.etaxonomy.cdm.persistence.dao.occurrence.IOccurrenceDao;
 import eu.etaxonomy.cdm.persistence.dao.reference.IReferenceDao;
 import eu.etaxonomy.cdm.persistence.dao.taxon.ITaxonDao;
+import eu.etaxonomy.cdm.persistence.dto.ReferencingObjectDto;
 import eu.etaxonomy.cdm.strategy.match.DefaultMatchStrategy;
 import eu.etaxonomy.cdm.strategy.match.IMatchStrategyEqual;
 import eu.etaxonomy.cdm.strategy.match.MatchException;
@@ -421,6 +422,56 @@ public class CdmGenericDaoImplTest extends CdmTransactionalIntegrationTest {
                logger.info(debug);
        }
 
+
+       //similar to testGetReferencingObjectsCdmBase but with DTO
+       @Test
+    @DataSets({
+         @DataSet(loadStrategy=CleanSweepInsertLoadStrategy.class, value="/eu/etaxonomy/cdm/database/ClearDB_with_Terms_DataSet.xml"),
+         @DataSet("/eu/etaxonomy/cdm/database/TermsDataSet-with_auditing_info.xml")})
+    public void testGetReferencingObjectsDto() {
+
+           IBotanicalName name = TaxonNameFactory.NewBotanicalInstance(Rank.SPECIES());
+        name.setTitleCache("A name", true);
+        Reference ref1 = ReferenceFactory.newArticle();
+        Taxon taxon = Taxon.NewInstance(name, ref1);
+        Person author = Person.NewInstance();
+        author.setTitleCache("Author", true);
+        ref1.addAnnotation(Annotation.NewInstance("A1", Language.DEFAULT()));
+        ref1.setAuthorship(author);
+        name.setCombinationAuthorship(author);
+        name.setBasionymAuthorship(author);  //to test deduplication
+
+        name.setNomenclaturalReference(ref1);
+
+        taxonDao.save(taxon);
+//           UUID uuid = UUID.fromString("613980ac-9bd5-43b9-a374-d71e1794688f");
+//           Reference ref1 = referenceService.findByUuid(uuid);
+        commitAndStartNewTransaction(null);
+
+        int i = 1;
+        Set<ReferencingObjectDto> referencedObjects = cdmGenericDao.getReferencingObjectsDto(ref1);
+        String debug = "############## RESULT for ref1 ###################\n";
+        for (ReferencingObjectDto dto: referencedObjects){
+            debug += "Object"+ i++ +": " + dto.getType().getSimpleName() + " - " + dto + "\n";
+        }
+        //was 3 before bidirectionality was removed for supplemental data
+        assertEquals(2, referencedObjects.size());
+        debug += "############## END ###################\n";
+
+//           UUID uuidAuthor = UUID.fromString("4ce66544-a5a3-4601-ab0b-1f0a1338327b");
+//           AgentBase author = agentService.findByUuid(uuidAuthor);
+
+        referencedObjects = cdmGenericDao.getReferencingObjectsDto(author);
+        i = 1;
+        debug += "############## RESULT for author ###################\n";
+        for (ReferencingObjectDto dto: referencedObjects){
+            debug += "Object"+ i++ +": " + dto.getType().getSimpleName() + " - " + dto + "\n";
+        }
+        assertEquals("The both taxon names should be dedulicated", 2, referencedObjects.size());
+        debug += "############## END ###################\n";
+        logger.warn(debug);
+    }
+
        /**
         * 2nd test method for {@link eu.etaxonomy.cdm.persistence.dao.hibernate.common.CdmGenericDaoImpl#getReferencingObjects(CdmBase)}.
         */
index 51f45b266e351e38380090b7bd3b1a03a888b82c..0cbc73dc685da4f8db2778f9eb8832c698f8d3e3 100644 (file)
@@ -21,12 +21,20 @@ import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;\r
 import org.springframework.transaction.annotation.Transactional;\r
 \r
+import eu.etaxonomy.cdm.format.ReferencingObjectFormatter;\r
 import eu.etaxonomy.cdm.model.common.CdmBase;\r
+import eu.etaxonomy.cdm.model.common.Language;\r
+import eu.etaxonomy.cdm.model.description.DescriptionElementBase;\r
+import eu.etaxonomy.cdm.model.description.DescriptionElementSource;\r
 import eu.etaxonomy.cdm.model.metadata.CdmMetaData;\r
 import eu.etaxonomy.cdm.model.metadata.CdmMetaDataPropertyName;\r
+import eu.etaxonomy.cdm.model.name.NomenclaturalSource;\r
 import eu.etaxonomy.cdm.model.reference.ISourceable;\r
+import eu.etaxonomy.cdm.model.taxon.SecundumSource;\r
 import eu.etaxonomy.cdm.persistence.dao.common.ICdmGenericDao;\r
 import eu.etaxonomy.cdm.persistence.dao.reference.IOriginalSourceDao;\r
+import eu.etaxonomy.cdm.persistence.dto.ReferencingObjectDto;\r
+import eu.etaxonomy.cdm.persistence.dto.UuidAndTitleCache;\r
 import eu.etaxonomy.cdm.persistence.query.OrderHint;\r
 import eu.etaxonomy.cdm.strategy.match.DefaultMatchStrategy;\r
 import eu.etaxonomy.cdm.strategy.match.IMatchStrategy;\r
@@ -94,6 +102,11 @@ public class CommonServiceImpl
         }return result;\r
     }\r
 \r
+    @Override\r
+    public Set<ReferencingObjectDto> getReferencingObjectDtos(CdmBase referencedCdmBase){\r
+        return this.genericDao.getReferencingObjectsDto(referencedCdmBase);\r
+    }\r
+\r
     @Override\r
     public Set<CdmBase> getReferencingObjects(CdmBase referencedCdmBase){\r
         return this.genericDao.getReferencingObjects(referencedCdmBase);\r
@@ -108,124 +121,58 @@ public class CommonServiceImpl
     public Set<CdmBase> getReferencingObjectsForDeletion(CdmBase referencedCdmBase){\r
         return this.genericDao.getReferencingObjectsForDeletion(referencedCdmBase);\r
     }\r
-    //         try {\r
-    //                 Set<Class<? extends CdmBase>> allCdmClasses = genericDao.getAllCdmClasses(false); //findAllCdmClasses();\r
-    //\r
-    //                 referencedCdmBase = (CdmBase)HibernateProxyHelper.deproxy(referencedCdmBase);\r
-    //                 Class referencedClass = referencedCdmBase.getClass();\r
-    //                 Set<CdmBase> result = new HashSet<>();\r
-    //                 logger.debug("Referenced Class: " + referencedClass.getName());\r
-    //\r
-    //                 for (Class<? extends CdmBase> cdmClass : allCdmClasses){\r
-    //                         Set<Field> fields = getFields(cdmClass);\r
-    //                         for (Field field: fields){\r
-    //                                 Class<?> type = field.getType();\r
-    //                                 //class\r
-    //                                 if (! type.isInterface()){\r
-    //                                         if (referencedClass.isAssignableFrom(type)||\r
-    //                                                         type.isAssignableFrom(referencedClass) && CdmBase.class.isAssignableFrom(type)){\r
-    //                                                 handleSingleClass(referencedClass, type, field, cdmClass, result, referencedCdmBase, false);\r
-    //                                         }\r
-    //                                 //interface\r
-    //                                 }else if (type.isAssignableFrom(referencedClass)){\r
-    //                                                 handleSingleClass(referencedClass, type, field, cdmClass, result, referencedCdmBase, false);\r
-    //                                 }else if (Collection.class.isAssignableFrom(type)){\r
-    //\r
-    //                                         if (checkIsSetOfType(field, referencedClass, type) == true){\r
-    //                                                 handleSingleClass(referencedClass, type, field, cdmClass, result, referencedCdmBase, true);\r
-    //                                         }\r
-    //                                 }\r
-    ////                               Class[] interfaces = referencedClass.getInterfaces();\r
-    ////                               for (Class interfaze: interfaces){\r
-    ////                                       if (interfaze == type){\r
-    //////                                     if(interfaze.isAssignableFrom(returnType)){\r
-    ////                                               handleSingleClass(interfaze, type, field, cdmClass, result, referencedCdmBase);\r
-    ////                                       }\r
-    ////                               }\r
-    //                         }\r
-    //                 }\r
-    //                 return result;\r
-    //         } catch (Exception e) {\r
-    //                 e.printStackTrace();\r
-    //                 throw new RuntimeException(e);\r
-    //         }\r
-    //\r
-    // }\r
-    //\r
-    // private boolean checkIsSetOfType(Field field, Class referencedClass, Class<?> type){\r
-    //         Type genericType = (ParameterizedTypeImpl)field.getGenericType();\r
-    //         if (genericType instanceof ParameterizedTypeImpl){\r
-    //                 ParameterizedTypeImpl paraType = (ParameterizedTypeImpl)genericType;\r
-    //                 paraType.getRawType();\r
-    //                 Type[] arguments = paraType.getActualTypeArguments();\r
-    //                 //logger.debug(arguments.length);\r
-    //                 if (arguments.length == 1){\r
-    //                         Class collectionClass;\r
-    //                         try {\r
-    //                                 if (arguments[0] instanceof Class){\r
-    //                                         collectionClass = (Class)arguments[0];\r
-    //                                 }else if(arguments[0] instanceof TypeVariableImpl){\r
-    //                                         TypeVariableImpl typeVariable = (TypeVariableImpl)arguments[0];\r
-    //                                         GenericDeclaration genericDeclaration = typeVariable.getGenericDeclaration();\r
-    //                                         collectionClass = (Class)genericDeclaration;\r
-    //                                 }else{\r
-    //                                         logger.warn("Unknown Type");\r
-    //                                         return false;\r
-    //                                 }\r
-    //                                 if (CdmBase.class.isAssignableFrom(collectionClass) && collectionClass.isAssignableFrom(referencedClass)  ){\r
-    //                                         return true;\r
-    //                                 }\r
-    //                         } catch (Exception e) {\r
-    //                                 logger.warn(e.getMessage());\r
-    //                         }\r
-    //                 }else{\r
-    //                         logger.warn("Length of arguments <> 1");\r
-    //                 }\r
-    //         }else{\r
-    //                 logger.warn("Not a generic type of type ParameterizedTypeImpl");\r
-    //         }\r
-    //         return false;\r
-    // }\r
-    //\r
-    //\r
-    //\r
-    //\r
-    // private boolean handleSingleClass(Class itemClass, Class type, Field field, Class cdmClass, Set<CdmBase> result,CdmBase value, boolean isCollection){\r
-    //         if (! Modifier.isStatic(field.getModifiers())){\r
-    //                 String methodName = StringUtils.rightPad(field.getName(), 30);\r
-    //                 String className = StringUtils.rightPad(cdmClass.getSimpleName(), 30);\r
-    //                 String returnTypeName = StringUtils.rightPad(type.getSimpleName(), 30);\r
-    //\r
-    //                 logger.debug(methodName +   "\t\t" + className + "\t\t" + returnTypeName);\r
-    ////                       result_old.add(method);\r
-    //                 result.addAll(getCdmBasesByFieldAndClass(field, itemClass, cdmClass, value, isCollection));\r
-    //         }\r
-    //         return true;\r
-    // }\r
-    //\r
-    // private Set<Field> getFields(Class clazz){\r
-    //         Set<Field> result = new HashSet<>();\r
-    //         for (Field field: clazz.getDeclaredFields()){\r
-    //                 if (!Modifier.isStatic(field.getModifiers())){\r
-    //                         result.add(field);\r
-    //                 }\r
-    //         }\r
-    //         Class superclass = clazz.getSuperclass();\r
-    //         if (CdmBase.class.isAssignableFrom(superclass)){\r
-    //                 result.addAll(getFields(superclass));\r
-    //         }\r
-    //         return result;\r
-    // }\r
-    //\r
-    // private Set<CdmBase> getCdmBasesByFieldAndClass(Field field, Class itemClass, Class otherClazz, CdmBase item, boolean isCollection){\r
-    //         Set<CdmBase> result = new HashSet<>();\r
-    //         if (isCollection){\r
-    //                 result.addAll(genericDao.getCdmBasesWithItemInCollection(itemClass, otherClazz, field.getName(), item));\r
-    //         }else{\r
-    //                 result.addAll(genericDao.getCdmBasesByFieldAndClass(otherClazz, field.getName(), item));\r
-    //         }\r
-    //         return result;\r
-    // }\r
+\r
+\r
+    @Override\r
+    public Set<ReferencingObjectDto> initializeReferencingObjectDtos(Set<ReferencingObjectDto> dtos,\r
+            boolean doReferencingEntity, boolean doTargetEntity, boolean doDescription, Language language) {\r
+\r
+//        Set<ReferencingObjectDto> result = new HashSet<>();\r
+        for (ReferencingObjectDto dto : dtos){\r
+            //TODO or load()?\r
+            CdmBase entity = this.genericDao.find(dto.getType(), dto.getUuid());\r
+            if (doReferencingEntity){\r
+                dto.setReferencedEntity(entity);\r
+            }\r
+            if (doTargetEntity){\r
+                UuidAndTitleCache<CdmBase> target = getReferencingObjectTarget(entity);\r
+                dto.setOpenInTarget(target);\r
+            }\r
+            if (doDescription){\r
+                String description = getReferencingObjectDescription(entity, language);\r
+                dto.setTitleCache(description);\r
+            }\r
+        }\r
+        return dtos;\r
+    }\r
+\r
+    private UuidAndTitleCache<CdmBase> getReferencingObjectTarget(CdmBase entity) {\r
+        CdmBase targetEntity;\r
+        entity = CdmBase.deproxy(entity);\r
+        if (entity instanceof SecundumSource){\r
+            targetEntity = ((SecundumSource) entity).getSourcedTaxon();\r
+        }else if (entity instanceof NomenclaturalSource){\r
+            targetEntity = ((NomenclaturalSource) entity).getSourcedName();\r
+        }else if (entity instanceof DescriptionElementSource){\r
+            DescriptionElementBase element = ((DescriptionElementSource) entity).getSourcedElement();\r
+            targetEntity = getTarget(element);\r
+        }else if (entity instanceof DescriptionElementBase){\r
+           targetEntity = getTarget((DescriptionElementBase)entity);\r
+        }else{\r
+            targetEntity = entity;\r
+        }\r
+\r
+        UuidAndTitleCache<CdmBase> result = new UuidAndTitleCache<>(targetEntity.getClass(), targetEntity.getUuid(), targetEntity.getId(), null);\r
+        return result;\r
+    }\r
+\r
+    private CdmBase getTarget(DescriptionElementBase element) {\r
+        return (CdmBase)element.getInDescription().describedEntity();\r
+    }\r
+\r
+    private String getReferencingObjectDescription(CdmBase entity, Language language) {\r
+        return ReferencingObjectFormatter.format(entity, language);\r
+    }\r
 \r
     @Override\r
     public List getHqlResult(String hqlQuery){\r
@@ -428,4 +375,5 @@ public class CommonServiceImpl
     public UUID refresh(CdmBase persistentObject) {\r
         return genericDao.refresh(persistentObject);\r
     }\r
+\r
 }\r
index 81e7b4c6a3c9efb95967a6d8cf0ef7f5cbf7723f..55c3454779e907f08cd96e139fbeb940d06eb6c8 100644 (file)
@@ -18,10 +18,12 @@ import java.util.UUID;
 import org.hibernate.Session;
 
 import eu.etaxonomy.cdm.model.common.CdmBase;
+import eu.etaxonomy.cdm.model.common.Language;
 import eu.etaxonomy.cdm.model.metadata.CdmMetaData;
 import eu.etaxonomy.cdm.model.metadata.CdmMetaDataPropertyName;
 import eu.etaxonomy.cdm.model.reference.ISourceable;
 import eu.etaxonomy.cdm.persistence.dao.common.ICdmGenericDao;
+import eu.etaxonomy.cdm.persistence.dto.ReferencingObjectDto;
 import eu.etaxonomy.cdm.persistence.query.OrderHint;
 import eu.etaxonomy.cdm.strategy.match.IMatchStrategy;
 import eu.etaxonomy.cdm.strategy.match.IMatchable;
@@ -85,6 +87,14 @@ public interface ICommonService /*extends IService<OriginalSourceBase>*/{
         */
        public Set<CdmBase> getReferencingObjects(CdmBase referencedCdmBase);
 
+    /**
+     * @see #getReferencingObjects(CdmBase)
+     */
+    public Set<ReferencingObjectDto> getReferencingObjectDtos(CdmBase referencedCdmBase);
+
+
+    public Set<ReferencingObjectDto> initializeReferencingObjectDtos(Set<ReferencingObjectDto> dtos,
+            boolean doReferencingEntity, boolean doTargetEntity, boolean doDescription, Language language);
 
 
        /**