Project

General

Profile

Download (10.2 KB) Statistics
| Branch: | Tag: | Revision:
1
// $Id$
2
/**
3
* Copyright (C) 2017 EDIT
4
* European Distributed Institute of Taxonomy
5
* http://www.e-taxonomy.eu
6
*
7
* The contents of this file are subject to the Mozilla Public License Version 1.1
8
* See LICENSE.TXT at the top of this package for the full license terms.
9
*/
10
package eu.etaxonomy.cdm.vaadin.util;
11

    
12
import java.util.ArrayList;
13
import java.util.Arrays;
14
import java.util.HashMap;
15
import java.util.HashSet;
16
import java.util.List;
17
import java.util.Map;
18
import java.util.Set;
19
import java.util.UUID;
20

    
21
import org.springframework.transaction.TransactionStatus;
22
import org.vaadin.addons.lazyquerycontainer.LazyQueryContainer;
23
import org.vaadin.addons.lazyquerycontainer.Query;
24
import org.vaadin.addons.lazyquerycontainer.QueryDefinition;
25

    
26
import com.vaadin.data.Item;
27
import com.vaadin.data.util.ObjectProperty;
28
import com.vaadin.data.util.PropertysetItem;
29

    
30
import eu.etaxonomy.cdm.api.application.CdmRepository;
31
import eu.etaxonomy.cdm.model.description.DescriptionBase;
32
import eu.etaxonomy.cdm.model.description.Distribution;
33
import eu.etaxonomy.cdm.model.description.Feature;
34
import eu.etaxonomy.cdm.model.description.PresenceAbsenceTerm;
35
import eu.etaxonomy.cdm.model.description.TaxonDescription;
36
import eu.etaxonomy.cdm.model.location.NamedArea;
37
import eu.etaxonomy.cdm.model.taxon.Taxon;
38
import eu.etaxonomy.cdm.model.taxon.TaxonNode;
39

    
40
/**
41
 * A {@link Query} for populating a {@link LazyQueryContainer} with distribution status data.
42
 * Currently unused.
43
 *
44
 * @author freimeier
45
 * @since 16.11.2017
46
 */
47
public class DistributionStatusQuery implements Query{
48
    public static final String DTYPE_COLUMN = "DTYPE";
49
    public static final String ID_COLUMN = "ID";
50
    public static final String UUID_COLUMN = "UUID";
51
    public static final String CLASSIFICATION_COLUMN = "CLASSIFICATION";
52
    public static final String RANK_COLUMN = "RANK";
53
    public static final String TAXON_COLUMN = "TAXON";
54

    
55
    private CdmRepository repo;
56
    private QueryDefinition definition;
57
    private List<UUID> nodeUuids;
58
    private List<NamedArea> namedAreas;
59

    
60
    /**
61
     * Creates a new DistributionStatusQuery which will return distribution status information
62
     * found in the specified {@link CdmRepository} for the {@link TaxonNode}s given by {@code nodeUuids} and the specified {@link NamedArea}s.
63
     * @param repo The repo to search for information.
64
     * @param nodeUuids The {@link UUID}s of {@link TaxonNode}s to search information for.
65
     * @param namedAreas The list of {@link NamedArea}s the distribution information should be related to.
66
     * @param definition The query definition to be used.
67
     */
68
    public DistributionStatusQuery(CdmRepository repo, List<UUID> nodeUuids, List<NamedArea> namedAreas, QueryDefinition definition) {
69
        this.repo = repo;
70
        this.nodeUuids = nodeUuids;
71
        this.namedAreas = namedAreas;
72
        this.definition = definition;
73
    }
74

    
75
    /**
76
     *
77
     * {@inheritDoc}
78
     */
79
    @Override
80
    public Item constructItem() {
81
        return null;
82
    }
83

    
84
   /**
85
    *
86
    * {@inheritDoc}
87
    */
88
    @Override
89
    public boolean deleteAllItems() {
90
        return false;
91
    }
92

    
93
	/**
94
	 *
95
	 * {@inheritDoc}
96
	 */
97
    @Override
98
    public List<Item> loadItems(int startIndex, int count) {
99
        List<Item> items = new ArrayList<>();
100
        for(int i=startIndex; i<startIndex+count; i++) {
101
            if(i<this.size()) {
102
                UUID nodeUuid = this.nodeUuids.get(i);
103
                TaxonNode taxonNode = CdmSpringContextHelper.getTaxonNodeService().load(nodeUuid, Arrays.asList("taxon"));
104
                Taxon taxon = taxonNode.getTaxon();
105
                Item item = new PropertysetItem();
106
                item.addItemProperty(UUID_COLUMN, new ObjectProperty<>(taxon.getUuid(), UUID.class));
107
                item.addItemProperty(TAXON_COLUMN, new ObjectProperty<>(taxon.getTitleCache(), String.class));
108
                Map<NamedArea,PresenceAbsenceTerm> distributionStatusMap = this.getAreaToDistributionStatusMap(taxon);
109
                for(NamedArea namedArea : this.namedAreas) {
110
                    PresenceAbsenceTerm distributionStatus = distributionStatusMap.get(namedArea);
111
                    UUID distributionStatusUuid = (distributionStatus != null) ? distributionStatus.getUuid() : null;
112
                    item.addItemProperty(namedArea.getUuid(), new ObjectProperty<>(distributionStatusUuid, UUID.class));
113
                }
114
                if(definition.getFilters().parallelStream().allMatch(f -> f.passesFilter(taxon.getUuid(), item))) {
115
                    items.add(item);
116
                }
117
            }
118
        }
119
        return items;
120
    }
121

    
122
    /**
123
     *
124
     * {@inheritDoc}
125
     */
126
    @Override
127
    public void saveItems(List<Item> addedItems, List<Item> modifiedItems, List<Item> removedItems) {
128
        System.out.println("Save requested!");
129
        for(Item item : modifiedItems) {
130
            final UUID taxonUuid = (UUID) item.getItemProperty(UUID_COLUMN).getValue();
131
            final Taxon taxon = (Taxon) CdmSpringContextHelper.getTaxonService().find(taxonUuid);
132
            Map<NamedArea, UUID> areaToDistributionStatusUuidMap = new HashMap<>();
133
            for(NamedArea namedArea : this.namedAreas) {
134
                areaToDistributionStatusUuidMap.put(namedArea, (UUID) item.getItemProperty(namedArea.getUuid()).getValue());
135
            }
136
            this.updateDistributionStatus(taxon, areaToDistributionStatusUuidMap);
137
        }
138
    }
139

    
140
    /**
141
     *
142
     * {@inheritDoc}
143
     */
144
    @Override
145
    public int size() {
146
        return this.nodeUuids.size();
147
    }
148

    
149
    /**
150
     * Returns a map which maps {@link NamedArea}s to the related distribution status for the given {@code taxon}.
151
     * @param taxon The taxon the map should contain information for.
152
     * @return Map of {@link NamedArea}s and the related distribution status for the given {@code taxon}.
153
     */
154
    private Map<NamedArea, PresenceAbsenceTerm> getAreaToDistributionStatusMap(Taxon taxon) {
155
        Map<NamedArea, PresenceAbsenceTerm> distributionStatusMap = new HashMap<>();
156

    
157
        List<Distribution> distributions = this.getDistributions(taxon);
158
        for(Distribution dist : distributions){
159
            if(dist.getArea()!=null){
160
                distributionStatusMap.put(dist.getArea(), dist.getStatus());
161
            }
162
        }
163

    
164
        return distributionStatusMap;
165
    }
166

    
167
    /**
168
     * Updates the given taxon with the distribution information contained in {@code areaToDistributionStatusUuidMap}.
169
     * @param taxon The taxon to be updated.
170
     * @param areaToDistributionStatusUuidMap The information to update the taxon with.
171
     */
172
    private void updateDistributionStatus(Taxon taxon,  Map<NamedArea, UUID> areaToDistributionStatusUuidMap) {
173
        CdmRepository repo = this.repo;
174
        TransactionStatus tx = repo.startTransaction();
175
        taxon = (Taxon)repo.getTaxonService().find(taxon.getUuid());
176

    
177
        List<Distribution> distributions = this.getDistributions(taxon);
178

    
179
        for(NamedArea namedArea : areaToDistributionStatusUuidMap.keySet()) {
180
            Distribution distribution = null;
181
            for(Distribution dist : distributions){
182
                if(dist.getArea()!= null && dist.getArea().equals(namedArea)){
183
                    distribution = dist;
184
                    break;
185
                }
186
            }
187

    
188
            PresenceAbsenceTerm distributionStatus = null;
189
            try {
190
                distributionStatus = (PresenceAbsenceTerm) CdmSpringContextHelper.getTermService().load(areaToDistributionStatusUuidMap.get(namedArea));
191
            } catch (IllegalArgumentException iae) {
192
                distributionStatus = null;
193
            }
194

    
195
            if(distribution==null){
196
                //create new distribution
197
                distribution = Distribution.NewInstance(namedArea, distributionStatus);
198
                Set<TaxonDescription> descriptions = taxon.getDescriptions();
199
                if (descriptions != null && !descriptions.isEmpty()) {
200
                    for (TaxonDescription desc : descriptions) {
201
                        // add to first taxon description
202
                        desc.addElement(distribution);
203
                    }
204
                } else {// there are no TaxonDescription yet.
205
                    TaxonDescription taxonDescription = TaxonDescription.NewInstance(taxon);
206
                    taxonDescription.addElement(distribution);
207
                }
208
            }
209
            else if(distributionStatus == null){
210
                //delete descriptionElementBase
211
                DescriptionBase<?> desc = distribution.getInDescription();
212
                desc.removeElement(distribution);
213
            }
214
            else if(!distributionStatus.equals(distribution.getStatus())){
215
               //update distribution
216
               distribution.setStatus(distributionStatus);
217
               repo.getCommonService().saveOrUpdate(distribution);
218
            }
219
        }
220
        repo.commitTransaction(tx);
221
    }
222

    
223
    /**
224
     * Returns the distribution information of the given {@code taxon}.
225
     * @param taxon The taxon to get the distribution information of.
226
     * @return The distribution information of the given {@code taxon}.
227
     */
228
    private List<Distribution> getDistributions(Taxon taxon) {
229
        Set<Feature> setFeature = new HashSet<>(Arrays.asList(Feature.DISTRIBUTION()));
230
        List<Distribution> listTaxonDescription = CdmSpringContextHelper.getDescriptionService()
231
                .listDescriptionElementsForTaxon(taxon, setFeature, null, null, null, DESCRIPTION_INIT_STRATEGY);
232
        return listTaxonDescription;
233
    }
234

    
235
    private static final List<String> DESCRIPTION_INIT_STRATEGY = Arrays.asList(new String []{
236
            "$",
237
            "elements.*",
238
            "elements.sources.citation.authorship.$",
239
            "elements.sources.nameUsedInSource.originalNameString",
240
            "elements.area.level",
241
            "elements.modifyingText",
242
            "elements.states.*",
243
            "elements.media",
244
            "elements.multilanguageText",
245
            "multilanguageText",
246
            "stateData.$",
247
            "annotations",
248
            "markers",
249
            "sources.citation.authorship",
250
            "sources.nameUsedInSource",
251
            "multilanguageText",
252
            "media",
253
            "name.$",
254
            "name.rank.representations",
255
            "name.status.type.representations",
256
            "taxon2.name",
257
    });
258
}
(11-11/16)