Project

General

Profile

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

    
11
import java.sql.SQLException;
12
import java.util.ArrayList;
13
import java.util.Arrays;
14
import java.util.Collections;
15
import java.util.Comparator;
16
import java.util.HashMap;
17
import java.util.HashSet;
18
import java.util.List;
19
import java.util.Set;
20
import java.util.UUID;
21
import java.util.stream.Collectors;
22

    
23
import org.springframework.beans.factory.annotation.Autowired;
24
import org.springframework.beans.factory.annotation.Qualifier;
25
import org.springframework.transaction.TransactionStatus;
26
import org.vaadin.addons.lazyquerycontainer.LazyQueryContainer;
27
import org.vaadin.addons.lazyquerycontainer.QueryDefinition;
28
import org.vaadin.addons.lazyquerycontainer.QueryFactory;
29
import org.vaadin.spring.events.EventBus.ViewEventBus;
30

    
31
import com.vaadin.server.VaadinSession;
32
import com.vaadin.spring.annotation.SpringComponent;
33
import com.vaadin.spring.annotation.ViewScope;
34
import com.vaadin.ui.Notification;
35

    
36
import eu.etaxonomy.cdm.api.application.CdmRepository;
37
import eu.etaxonomy.cdm.i18n.Messages;
38
import eu.etaxonomy.cdm.model.common.CdmBase;
39
import eu.etaxonomy.cdm.model.common.DefinedTermBase;
40
import eu.etaxonomy.cdm.model.common.Language;
41
import eu.etaxonomy.cdm.model.common.OrderedTermVocabulary;
42
import eu.etaxonomy.cdm.model.common.Representation;
43
import eu.etaxonomy.cdm.model.common.TermVocabulary;
44
import eu.etaxonomy.cdm.model.description.DescriptionBase;
45
import eu.etaxonomy.cdm.model.description.DescriptionElementBase;
46
import eu.etaxonomy.cdm.model.description.Distribution;
47
import eu.etaxonomy.cdm.model.description.Feature;
48
import eu.etaxonomy.cdm.model.description.PresenceAbsenceTerm;
49
import eu.etaxonomy.cdm.model.description.TaxonDescription;
50
import eu.etaxonomy.cdm.model.location.NamedArea;
51
import eu.etaxonomy.cdm.model.taxon.Classification;
52
import eu.etaxonomy.cdm.model.taxon.Taxon;
53
import eu.etaxonomy.cdm.model.taxon.TaxonNode;
54
import eu.etaxonomy.cdm.service.CdmUserHelper;
55
import eu.etaxonomy.cdm.vaadin.container.CdmSQLContainer;
56
import eu.etaxonomy.cdm.vaadin.container.PresenceAbsenceTermContainer;
57
import eu.etaxonomy.cdm.vaadin.util.CdmQueryFactory;
58
import eu.etaxonomy.cdm.vaadin.util.CdmSpringContextHelper;
59
import eu.etaxonomy.cdm.vaadin.util.DistributionEditorUtil;
60
import eu.etaxonomy.cdm.vaadin.util.DistributionStatusQueryDefinition;
61
import eu.etaxonomy.cdm.vaadin.util.DistributionStatusQueryFactory;
62
import eu.etaxonomy.vaadin.mvp.AbstractPresenter;
63

    
64
/**
65
 * @author freimeier
66
 * @since 18.10.2017
67
 *
68
 */
69
@SpringComponent
70
@ViewScope
71
public class DistributionTablePresenter extends AbstractPresenter<IDistributionTableView> {
72

    
73
	private static final long serialVersionUID = 3313043335587777217L;
74

    
75
    @Autowired
76
    private CdmUserHelper userHelper;
77

    
78
    @Autowired
79
    @Qualifier("cdmRepository")
80
    private CdmRepository repo; // TODO remove, since this is already in the super class
81

    
82
	/**
83
     * {@inheritDoc}
84
     */
85
    @Override
86
    protected void eventViewBusSubscription(ViewEventBus viewEventBus) {
87
        // no point subscribing
88
    }
89

    
90
    public int updateDistributionField(NamedArea area, PresenceAbsenceTerm distributionStatus, Taxon taxon) {
91
	    TransactionStatus tx = repo.startTransaction();
92
	    taxon = (Taxon)repo.getTaxonService().find(taxon.getUuid());
93
	    if(area==null){
94
	    	Notification.show(Messages.getLocalizedString(Messages.DistributionTablePresenter_ERROR_UPDATE_DISTRIBUTION_TERM));
95
	    	repo.commitTransaction(tx);
96
	    	return -1;
97
	    }
98
	    List<Distribution> distributions = getDistributions(taxon);
99
	    Distribution distribution = null;
100
	    for(Distribution dist : distributions){
101
	        if(dist.getArea()!=null && dist.getArea().equals(area)){
102
	            distribution = dist;
103
	            break;
104
	        }
105
	    }
106
	    if(distribution==null){
107
	    	//create new distribution
108
	    	distribution = Distribution.NewInstance(area, distributionStatus);
109
			Set<TaxonDescription> descriptions = taxon.getDescriptions();
110
			if (descriptions != null && !descriptions.isEmpty()) {
111
			    for (TaxonDescription desc : descriptions) {
112
			        // add to first taxon description
113
			        desc.addElement(distribution);
114
			        repo.commitTransaction(tx);
115
			        return 0;
116
			    }
117
			} else {// there are no TaxonDescription yet.
118
			    TaxonDescription taxonDescription = TaxonDescription.NewInstance(taxon);
119
			    taxonDescription.addElement(distribution);
120
			    repo.commitTransaction(tx);
121
			    return 0;
122
			}
123
	    }
124
	    else if(distributionStatus == null){//delete descriptionElementBase
125
	        DescriptionBase<?> desc = distribution.getInDescription();
126
	        desc.removeElement(distribution);
127
	    	repo.commitTransaction(tx);
128
            return 1;
129
	    }
130
	    else{//update distribution
131
           distribution.setStatus(distributionStatus);
132
           repo.getCommonService().saveOrUpdate(distribution);
133
           repo.commitTransaction(tx);
134
           return 0;
135
        }
136
	    repo.commitTransaction(tx);
137
	    return -1;
138
	}
139

    
140
    public CdmSQLContainer getSQLContainer() throws SQLException{
141
         List<Integer> nodeIds = new ArrayList<>();
142
         for (TaxonNode taxonNode : getAllNodes()) {
143
             nodeIds.add(taxonNode.getId());
144
         }
145
         List<NamedArea> namedAreas = getChosenAreas();
146
         if(namedAreas!=null){
147
             return new CdmSQLContainer(CdmQueryFactory.generateTaxonDistributionQuery(nodeIds, namedAreas));
148
         }
149
         return null;
150
    }
151

    
152
    public PresenceAbsenceTermContainer getPresenceAbsenceTermContainer() {
153
        return PresenceAbsenceTermContainer.getInstance();
154
    }
155

    
156
    public List<DescriptionElementBase> listDescriptionElementsForTaxon(Taxon taxon, Set<Feature> setFeature){
157
        List<DescriptionElementBase> listDescriptionElementsForTaxon = CdmSpringContextHelper.getDescriptionService().listDescriptionElementsForTaxon(taxon, setFeature, null, null, null, DESCRIPTION_INIT_STRATEGY);
158
        sort(listDescriptionElementsForTaxon);
159
        return listDescriptionElementsForTaxon;
160
    }
161

    
162
    public List<NamedArea> getReadOnlyAreas(){
163
        List<NamedArea> readonly = new ArrayList<>();
164
        // TODO: HACK FOR RL 2017: Remove as soon as possible by receiving read only areas from cdm preferences
165
        readonly.add(this.getAreaFromString("Deutschland"));
166
        return readonly;
167
    }
168

    
169
    public NamedArea getAreaFromString(String areaString){
170
        List<NamedArea> namedAreas = getChosenAreas();
171
        NamedArea area = null;
172
        for(NamedArea namedArea:namedAreas){
173
            Representation representation = namedArea.getRepresentation(Language.DEFAULT());
174
            if(representation!=null){
175
                if(DistributionEditorUtil.isAbbreviatedLabels()){
176
                    String label = representation.getLabel();
177
                    String abbreviatedLabel = representation.getAbbreviatedLabel();
178
                    if(abbreviatedLabel!=null && abbreviatedLabel.equalsIgnoreCase(areaString)){
179
                        area = namedArea;
180
                        break;
181
                    }
182
                    else if(label!=null && label.equalsIgnoreCase(areaString)){
183
                        area = namedArea;
184
                        break;
185
                    }
186
                }
187
            }
188
            if(namedArea.getTitleCache().equalsIgnoreCase(areaString)){
189
                area = namedArea;
190
                break;
191
            }
192
        }
193
        return area;
194
    }
195

    
196
    private List<Distribution> getDistributions(Taxon taxon) {
197
        Set<Feature> setFeature = new HashSet<>(Arrays.asList(Feature.DISTRIBUTION()));
198
        List<Distribution> listTaxonDescription = CdmSpringContextHelper.getDescriptionService()
199
                .listDescriptionElementsForTaxon(taxon, setFeature, null, null, null, DESCRIPTION_INIT_STRATEGY);
200
        return listTaxonDescription;
201

    
202
    }
203

    
204
	private List<NamedArea> getChosenAreas(){
205
	    List<NamedArea> namedAreas = (List<NamedArea>)VaadinSession.getCurrent().getAttribute(DistributionEditorUtil.SATTR_SELECTED_AREAS);
206
	    if(namedAreas!=null && namedAreas.isEmpty()){
207
	        return getChosenAreasFromVoc();
208
	    }
209
	    return namedAreas;
210
	}
211

    
212
	private List<NamedArea> getChosenAreasFromVoc(){
213
	    VaadinSession session = VaadinSession.getCurrent();
214
	    UUID vocUUID = (UUID) session.getAttribute(DistributionEditorUtil.SATTR_SELECTED_AREA_VOCABULARY_UUID);
215
	    TermVocabulary<NamedArea> vocabulary = CdmSpringContextHelper.getVocabularyService().load(vocUUID, Arrays.asList("terms")); //$NON-NLS-1$
216
	    vocabulary = CdmBase.deproxy(vocabulary, TermVocabulary.class);
217
	    if (vocabulary instanceof OrderedTermVocabulary) {
218
	        List<NamedArea> list = new ArrayList<> (((OrderedTermVocabulary)vocabulary).getOrderedTerms());
219
	        Collections.reverse(list);
220
	        return list;
221
	    }else {
222
	        return vocabulary.getTermsOrderedByLabels(Language.DEFAULT()).stream().collect(Collectors.toCollection(ArrayList::new));
223
	    }
224

    
225
	}
226

    
227
   private List<TaxonNode> getChosenTaxonNodes() {
228
        VaadinSession session = VaadinSession.getCurrent();
229
        List<UUID> taxonNodeUUIDs = (List<UUID>) session.getAttribute(DistributionEditorUtil.SATTR_TAXON_NODES_UUID);
230
        UUID classificationUuid = (UUID)session.getAttribute(DistributionEditorUtil.SATTR_CLASSIFICATION);
231
        if((taxonNodeUUIDs==null || taxonNodeUUIDs.isEmpty()) && classificationUuid!=null){
232
            Classification classification = CdmSpringContextHelper.getClassificationService().load(classificationUuid);
233
            if(classification!=null){
234
                taxonNodeUUIDs = Collections.singletonList(classification.getRootNode().getUuid());
235
            }
236
        }
237
        List<TaxonNode> loadedNodes = CdmSpringContextHelper.getTaxonNodeService().load(taxonNodeUUIDs, null);
238
        if(loadedNodes!=null){
239
            return loadedNodes;
240
        }
241
        return Collections.emptyList();
242
    }
243

    
244
	private List<TaxonNode> getAllNodes(){
245
		List<TaxonNode> allNodes = new ArrayList<>();
246

    
247
		List<TaxonNode> taxonNodes = getChosenTaxonNodes();
248
		for (TaxonNode taxonNode : taxonNodes) {
249
			if(taxonNode.getTaxon()!=null){
250
				allNodes.add(taxonNode);
251
			}
252
			allNodes.addAll(CdmSpringContextHelper.getTaxonNodeService().loadChildNodesOfTaxonNode(taxonNode, null, true, null));
253
		}
254
		return allNodes;
255
	}
256

    
257
	protected static final List<String> DESCRIPTION_INIT_STRATEGY = Arrays.asList(new String []{
258
            "$", //$NON-NLS-1$
259
            "elements.*", //$NON-NLS-1$
260
            "elements.sources.citation.authorship.$", //$NON-NLS-1$
261
            "elements.sources.nameUsedInSource.originalNameString", //$NON-NLS-1$
262
            "elements.area.level", //$NON-NLS-1$
263
            "elements.modifyingText", //$NON-NLS-1$
264
            "elements.states.*", //$NON-NLS-1$
265
            "elements.media", //$NON-NLS-1$
266
            "elements.multilanguageText", //$NON-NLS-1$
267
            "multilanguageText", //$NON-NLS-1$
268
            "stateData.$", //$NON-NLS-1$
269
            "annotations", //$NON-NLS-1$
270
            "markers", //$NON-NLS-1$
271
            "sources.citation.authorship", //$NON-NLS-1$
272
            "sources.nameUsedInSource", //$NON-NLS-1$
273
            "multilanguageText", //$NON-NLS-1$
274
            "media", //$NON-NLS-1$
275
            "name.$", //$NON-NLS-1$
276
            "name.rank", //$NON-NLS-1$
277
            "name.status.type", //$NON-NLS-1$
278
            "taxon2.name", //$NON-NLS-1$
279
    });
280

    
281
	/**Helper Methods*/
282
	private void sort(List<DescriptionElementBase> list){
283
		Collections.sort(list, new Comparator<DescriptionElementBase>() {
284

    
285
			@Override
286
			public int compare(DescriptionElementBase o1, DescriptionElementBase o2) {
287
				String feature1 = o1.getFeature().getTitleCache();
288
				String feature2 = o2.getFeature().getTitleCache();
289
				if(feature1 !=null && feature2 !=null){
290
					return feature1.compareTo(feature2);
291
				}else{
292
					return 0;
293

    
294
				}
295
			}
296
		});
297
	}
298

    
299
	/**
300
	 *
301
	 * {@inheritDoc}
302
	 */
303
	@Override
304
	protected void onPresenterReady() {
305
	    /*
306
         * The area and taxon settings window should only be displayed after login
307
         * and only when no classification and areas are chosen yet.
308
         */
309
	    VaadinSession vaadinSession = VaadinSession.getCurrent();
310
	    if(userHelper.userIsAutheticated()
311
	            && !userHelper.userIsAnnonymous()
312
	            && (vaadinSession.getAttribute(DistributionEditorUtil.SATTR_CLASSIFICATION) == null
313
	            || vaadinSession.getAttribute(DistributionEditorUtil.SATTR_SELECTED_AREA_VOCABULARY_UUID) == null
314
	            || vaadinSession.getAttribute(DistributionEditorUtil.SATTR_SELECTED_AREAS) == null)) {
315
            getView().openAreaAndTaxonSettings();
316
        }
317
    }
318

    
319
	/**Unused Methods*/
320
	// TODO: Currently unused. Remove?
321
    private List<String> getAbbreviatedNamedAreas() {
322
        List<NamedArea> terms = getChosenAreasFromVoc();
323
        List<String> list = new ArrayList<>();
324
        for(DefinedTermBase<?> dtb: terms){
325
            for(Representation r : dtb.getRepresentations()){
326
                list.add(r.getAbbreviatedLabel());
327
            }
328
        }
329
        return list;
330
    }
331

    
332
    // TODO: Currently unused. Remove?
333
    private HashMap<DescriptionElementBase, Distribution> getDistribution(DefinedTermBase dt, Taxon taxon) {
334
        Set<Feature> setFeature = new HashSet<>(Arrays.asList(Feature.DISTRIBUTION()));
335
        List<DescriptionElementBase> listTaxonDescription = CdmSpringContextHelper.getDescriptionService().listDescriptionElementsForTaxon(taxon, setFeature, null, null, null, DESCRIPTION_INIT_STRATEGY);
336
        HashMap<DescriptionElementBase, Distribution> map = null;
337
        for(DescriptionElementBase deb : listTaxonDescription){
338
            if(deb instanceof Distribution){
339
                Distribution db = (Distribution)deb;
340
                String titleCache = dt.getTitleCache();
341
                if(db.getArea().getTitleCache().equalsIgnoreCase(titleCache)){
342
                    map = new HashMap<DescriptionElementBase, Distribution>();
343
                    map.put(deb, db);
344
                }
345
            }
346
        }
347
        return map;
348
    }
349

    
350
    public LazyQueryContainer getAreaDistributionStatusContainer() {
351
        List<UUID> nodeUuids = getAllNodes().stream().map(n -> n.getUuid()).collect(Collectors.toCollection(ArrayList::new));
352
        List<NamedArea> namedAreas = getChosenAreas();
353
        if(namedAreas!=null){
354
            QueryFactory factory = new DistributionStatusQueryFactory(this.repo, nodeUuids, namedAreas);
355
            QueryDefinition defintion = new DistributionStatusQueryDefinition(namedAreas, true, 50);
356
            return new LazyQueryContainer(defintion, factory);
357
        }
358
        return null;
359
    }
360
}
(1-1/4)