Project

General

Profile

Download (14.5 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(String distributionAreaString, Object comboValue, Taxon taxon) {
91
	    TransactionStatus tx = repo.startTransaction();
92
	    taxon = (Taxon)repo.getTaxonService().find(taxon.getUuid());
93
	    Set<DefinedTermBase> chosenTerms = getChosenTerms();
94
	    NamedArea namedArea = null;
95
	    for(DefinedTermBase term:chosenTerms){
96
	    	Representation representation = term.getRepresentation(Language.DEFAULT());
97
	    	if(representation!=null){
98
	    		if(DistributionEditorUtil.isAbbreviatedLabels()){
99
	    			String label = representation.getLabel();
100
	    			String abbreviatedLabel = representation.getAbbreviatedLabel();
101
					if(abbreviatedLabel!=null && abbreviatedLabel.equalsIgnoreCase(distributionAreaString)){
102
	    				namedArea = (NamedArea) term;
103
	    				break;
104
	    			}
105
					else if(label!=null && label.equalsIgnoreCase(distributionAreaString)){
106
						namedArea = (NamedArea) term;
107
						break;
108
					}
109
	    		}
110
	    	}
111
	        if(term.getTitleCache().equalsIgnoreCase(distributionAreaString)){
112
	        	namedArea = (NamedArea) term;
113
	        	break;
114
	        }
115
	    }
116
	    if(namedArea==null){
117
	    	Notification.show(Messages.getLocalizedString(Messages.DistributionTablePresenter_ERROR_UPDATE_DISTRIBUTION_TERM));
118
	    	repo.commitTransaction(tx);
119
	    	return -1;
120
	    }
121
	    List<Distribution> distributions = getDistributions(taxon);
122
	    Distribution distribution = null;
123
	    for(Distribution dist : distributions){
124
	        if(dist.getArea()!=null && dist.getArea().equals(namedArea)){
125
	            distribution = dist;
126
	            break;
127
	        }
128
	    }
129
	    if(distribution==null){
130
	    	//create new distribution
131
	    	distribution = Distribution.NewInstance(namedArea, (PresenceAbsenceTerm) comboValue);
132
			Set<TaxonDescription> descriptions = taxon.getDescriptions();
133
			if (descriptions != null && !descriptions.isEmpty()) {
134
			    for (TaxonDescription desc : descriptions) {
135
			        // add to first taxon description
136
			        desc.addElement(distribution);
137
			        repo.commitTransaction(tx);
138
			        return 0;
139
			    }
140
			} else {// there are no TaxonDescription yet.
141
			    TaxonDescription taxonDescription = TaxonDescription.NewInstance(taxon);
142
			    taxonDescription.addElement(distribution);
143
			    repo.commitTransaction(tx);
144
			    return 0;
145
			}
146
	    }
147
	    else if(comboValue == null){//delete descriptionElementBase
148
	        DescriptionBase<?> desc = distribution.getInDescription();
149
	        desc.removeElement(distribution);
150
	    	repo.commitTransaction(tx);
151
            return 1;
152
	    }
153
	    else{//update distribution
154
           distribution.setStatus((PresenceAbsenceTerm)comboValue);
155
           repo.getCommonService().saveOrUpdate(distribution);
156
           repo.commitTransaction(tx);
157
           return 0;
158
        }
159
	    repo.commitTransaction(tx);
160
	    return -1;
161
	}
162

    
163
    public LazyQueryContainer getAreaDistributionStatusContainer() {
164
         List<UUID> nodeUuids = getAllNodes().stream().map(n -> n.getUuid()).collect(Collectors.toCollection(ArrayList::new));
165
         List<NamedArea> namedAreas = getNamedAreas();
166
         if(namedAreas!=null){
167
             QueryFactory factory = new DistributionStatusQueryFactory(this.repo, nodeUuids, namedAreas);
168
             QueryDefinition defintion = new DistributionStatusQueryDefinition(namedAreas, true, 50);
169
             return new LazyQueryContainer(defintion, factory);
170
         }
171
         return null;
172
     }
173

    
174
    public CdmSQLContainer getSQLContainer() throws SQLException{
175
         List<Integer> nodeIds = new ArrayList<>();
176
         for (TaxonNode taxonNode : getAllNodes()) {
177
             nodeIds.add(taxonNode.getId());
178
         }
179
         List<NamedArea> namedAreas = getNamedAreas();
180
         if(namedAreas!=null){
181
             return new CdmSQLContainer(CdmQueryFactory.generateTaxonDistributionQuery(nodeIds, namedAreas));
182
         }
183
         return null;
184
    }
185

    
186
    public PresenceAbsenceTermContainer getPresenceAbsenceTermContainer() {
187
        return PresenceAbsenceTermContainer.getInstance();
188
    }
189

    
190
    public List<DescriptionElementBase> listDescriptionElementsForTaxon(Taxon taxon, Set<Feature> setFeature){
191
        List<DescriptionElementBase> listDescriptionElementsForTaxon = CdmSpringContextHelper.getDescriptionService().listDescriptionElementsForTaxon(taxon, setFeature, null, null, null, DESCRIPTION_INIT_STRATEGY);
192
        sort(listDescriptionElementsForTaxon);
193
        return listDescriptionElementsForTaxon;
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 Set<DefinedTermBase> getChosenTerms() {
205
        VaadinSession session = VaadinSession.getCurrent();
206
        UUID vocUUID = (UUID) session.getAttribute(DistributionEditorUtil.SATTR_SELECTED_AREA_VOCABULARY_UUID);
207
//      getConversationHolder().getSession();
208
        TermVocabulary<DefinedTermBase> voc = CdmSpringContextHelper.getVocabularyService().load(vocUUID, Arrays.asList("terms")); //$NON-NLS-1$
209
//      voc = CdmBase.deproxy(voc);
210
        return voc.getTerms();
211
    }
212

    
213
	private List<NamedArea> getNamedAreas(){
214
	    List<NamedArea> namedAreas = (List<NamedArea>)VaadinSession.getCurrent().getAttribute(DistributionEditorUtil.SATTR_SELECTED_AREAS);
215
	    if(namedAreas!=null && namedAreas.isEmpty()){
216
	        return getNamedAreasFromVoc();
217
	    }
218
	    return namedAreas;
219
	}
220

    
221
	private List<NamedArea> getNamedAreasFromVoc(){
222
	    VaadinSession session = VaadinSession.getCurrent();
223
	    UUID vocUUID = (UUID) session.getAttribute(DistributionEditorUtil.SATTR_SELECTED_AREA_VOCABULARY_UUID);
224
	    TermVocabulary<NamedArea> vocabulary = CdmSpringContextHelper.getVocabularyService().load(vocUUID, Arrays.asList("terms")); //$NON-NLS-1$
225
	    vocabulary = CdmBase.deproxy(vocabulary, TermVocabulary.class);
226
	    if (vocabulary instanceof OrderedTermVocabulary) {
227
	        List<NamedArea> list = new ArrayList<> (((OrderedTermVocabulary)vocabulary).getOrderedTerms());
228
	        Collections.reverse(list);
229
	        return list;
230
	    }else {
231
	        return vocabulary.getTermsOrderedByLabels(Language.DEFAULT()).stream().collect(Collectors.toCollection(ArrayList::new));
232
	    }
233

    
234
	}
235

    
236
	private List<TaxonNode> getAllNodes(){
237
		List<TaxonNode> allNodes = new ArrayList<>();
238

    
239
		List<TaxonNode> taxonNodes = getChosenTaxonNodes();
240
		for (TaxonNode taxonNode : taxonNodes) {
241
			if(taxonNode.getTaxon()!=null){
242
				allNodes.add(taxonNode);
243
			}
244
			allNodes.addAll(CdmSpringContextHelper.getTaxonNodeService().loadChildNodesOfTaxonNode(taxonNode, null, true, null));
245
		}
246
		return allNodes;
247
	}
248

    
249
	private List<TaxonNode> getChosenTaxonNodes() {
250
		VaadinSession session = VaadinSession.getCurrent();
251
		List<UUID> taxonNodeUUIDs = (List<UUID>) session.getAttribute(DistributionEditorUtil.SATTR_TAXON_NODES_UUID);
252
		UUID classificationUuid = (UUID)session.getAttribute(DistributionEditorUtil.SATTR_CLASSIFICATION);
253
		if((taxonNodeUUIDs==null || taxonNodeUUIDs.isEmpty()) && classificationUuid!=null){
254
			Classification classification = CdmSpringContextHelper.getClassificationService().load(classificationUuid);
255
			if(classification!=null){
256
				taxonNodeUUIDs = Collections.singletonList(classification.getRootNode().getUuid());
257
			}
258
		}
259
		List<TaxonNode> loadedNodes = CdmSpringContextHelper.getTaxonNodeService().load(taxonNodeUUIDs, null);
260
		if(loadedNodes!=null){
261
			return loadedNodes;
262
		}
263
		return Collections.emptyList();
264
	}
265

    
266
	protected static final List<String> DESCRIPTION_INIT_STRATEGY = Arrays.asList(new String []{
267
            "$", //$NON-NLS-1$
268
            "elements.*", //$NON-NLS-1$
269
            "elements.sources.citation.authorship.$", //$NON-NLS-1$
270
            "elements.sources.nameUsedInSource.originalNameString", //$NON-NLS-1$
271
            "elements.area.level", //$NON-NLS-1$
272
            "elements.modifyingText", //$NON-NLS-1$
273
            "elements.states.*", //$NON-NLS-1$
274
            "elements.media", //$NON-NLS-1$
275
            "elements.multilanguageText", //$NON-NLS-1$
276
            "multilanguageText", //$NON-NLS-1$
277
            "stateData.$", //$NON-NLS-1$
278
            "annotations", //$NON-NLS-1$
279
            "markers", //$NON-NLS-1$
280
            "sources.citation.authorship", //$NON-NLS-1$
281
            "sources.nameUsedInSource", //$NON-NLS-1$
282
            "multilanguageText", //$NON-NLS-1$
283
            "media", //$NON-NLS-1$
284
            "name.$", //$NON-NLS-1$
285
            "name.rank", //$NON-NLS-1$
286
            "name.status.type", //$NON-NLS-1$
287
            "taxon2.name", //$NON-NLS-1$
288
    });
289

    
290
	/**Helper Methods*/
291
	private void sort(List<DescriptionElementBase> list){
292
		Collections.sort(list, new Comparator<DescriptionElementBase>() {
293

    
294
			@Override
295
			public int compare(DescriptionElementBase o1, DescriptionElementBase o2) {
296
				String feature1 = o1.getFeature().getTitleCache();
297
				String feature2 = o2.getFeature().getTitleCache();
298
				if(feature1 !=null && feature2 !=null){
299
					return feature1.compareTo(feature2);
300
				}else{
301
					return 0;
302

    
303
				}
304
			}
305
		});
306
	}
307

    
308
	/**
309
	 *
310
	 * {@inheritDoc}
311
	 */
312
	@Override
313
	protected void onPresenterReady() {
314
	    /*
315
         * The area and taxon settings window should only be displayed after login
316
         * and only when no classification and areas are chosen yet.
317
         */
318
	    VaadinSession vaadinSession = VaadinSession.getCurrent();
319
	    if(userHelper.userIsAutheticated()
320
	            && !userHelper.userIsAnnonymous()
321
	            && (vaadinSession.getAttribute(DistributionEditorUtil.SATTR_CLASSIFICATION) == null
322
	            || vaadinSession.getAttribute(DistributionEditorUtil.SATTR_SELECTED_AREA_VOCABULARY_UUID) == null
323
	            || vaadinSession.getAttribute(DistributionEditorUtil.SATTR_SELECTED_AREAS) == null)) {
324
            getView().openAreaAndTaxonSettings();
325
        }
326
    }
327

    
328
	/**Unused Methods*/
329
	// TODO: Currently unused. Remove?
330
    private List<String> getAbbreviatedNamedAreas() {
331
        List<NamedArea> terms = getNamedAreasFromVoc();
332
        List<String> list = new ArrayList<>();
333
        for(DefinedTermBase<?> dtb: terms){
334
            for(Representation r : dtb.getRepresentations()){
335
                list.add(r.getAbbreviatedLabel());
336
            }
337
        }
338
        return list;
339
    }
340

    
341
    // TODO: Currently unused. Remove?
342
    private HashMap<DescriptionElementBase, Distribution> getDistribution(DefinedTermBase dt, Taxon taxon) {
343
        Set<Feature> setFeature = new HashSet<>(Arrays.asList(Feature.DISTRIBUTION()));
344
        List<DescriptionElementBase> listTaxonDescription = CdmSpringContextHelper.getDescriptionService().listDescriptionElementsForTaxon(taxon, setFeature, null, null, null, DESCRIPTION_INIT_STRATEGY);
345
        HashMap<DescriptionElementBase, Distribution> map = null;
346
        for(DescriptionElementBase deb : listTaxonDescription){
347
            if(deb instanceof Distribution){
348
                Distribution db = (Distribution)deb;
349
                String titleCache = dt.getTitleCache();
350
                if(db.getArea().getTitleCache().equalsIgnoreCase(titleCache)){
351
                    map = new HashMap<DescriptionElementBase, Distribution>();
352
                    map.put(deb, db);
353
                }
354
            }
355
        }
356
        return map;
357
    }
358

    
359

    
360
}
(1-1/4)