Project

General

Profile

Download (14 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 Set<DefinedTermBase> getChosenTerms() {
164
		VaadinSession session = VaadinSession.getCurrent();
165
		UUID vocUUID = (UUID) session.getAttribute(DistributionEditorUtil.SATTR_SELECTED_AREA_VOCABULARY_UUID);
166
//		getConversationHolder().getSession();
167
		TermVocabulary<DefinedTermBase> voc = CdmSpringContextHelper.getVocabularyService().load(vocUUID, Arrays.asList("terms")); //$NON-NLS-1$
168
//		voc = CdmBase.deproxy(voc);
169
		return voc.getTerms();
170
	}
171

    
172
	public List<String> getAbbreviatedTermList() {
173
		List<NamedArea> terms = getTermSet();
174
		List<String> list = new ArrayList<>();
175
		for(DefinedTermBase<?> dtb: terms){
176
		    for(Representation r : dtb.getRepresentations()){
177
		        list.add(r.getAbbreviatedLabel());
178
		    }
179
		}
180
		return list;
181
	}
182

    
183
	public List<NamedArea> getNamedAreas(){
184
	    List<NamedArea> namedAreas = (List<NamedArea>)VaadinSession.getCurrent().getAttribute(DistributionEditorUtil.SATTR_SELECTED_AREAS);
185
	    if(namedAreas!=null && namedAreas.isEmpty()){
186
	        return getTermSet();
187
	    }
188
	    return namedAreas;
189
	}
190

    
191
	private List<NamedArea> getTermSet(){
192
	    VaadinSession session = VaadinSession.getCurrent();
193
	    UUID vocUUID = (UUID) session.getAttribute(DistributionEditorUtil.SATTR_SELECTED_AREA_VOCABULARY_UUID);
194
	    TermVocabulary<NamedArea> vocabulary = CdmSpringContextHelper.getVocabularyService().load(vocUUID, Arrays.asList("terms")); //$NON-NLS-1$
195
	    vocabulary = CdmBase.deproxy(vocabulary, TermVocabulary.class);
196
	    if (vocabulary instanceof OrderedTermVocabulary) {
197
	        List<NamedArea> list = new ArrayList<> (((OrderedTermVocabulary)vocabulary).getOrderedTerms());
198
	        Collections.reverse(list);
199
	        return list;
200
	    }else {
201
	        return vocabulary.getTermsOrderedByLabels(Language.DEFAULT()).stream().collect(Collectors.toCollection(ArrayList::new));
202
	    }
203

    
204
	}
205

    
206
	public HashMap<DescriptionElementBase, Distribution> getDistribution(DefinedTermBase dt, Taxon taxon) {
207
		Set<Feature> setFeature = new HashSet<>(Arrays.asList(Feature.DISTRIBUTION()));
208
		List<DescriptionElementBase> listTaxonDescription = CdmSpringContextHelper.getDescriptionService().listDescriptionElementsForTaxon(taxon, setFeature, null, null, null, DESCRIPTION_INIT_STRATEGY);
209
		HashMap<DescriptionElementBase, Distribution> map = null;
210
		for(DescriptionElementBase deb : listTaxonDescription){
211
			if(deb instanceof Distribution){
212
				Distribution db = (Distribution)deb;
213
				String titleCache = dt.getTitleCache();
214
				if(db.getArea().getTitleCache().equalsIgnoreCase(titleCache)){
215
					map = new HashMap<DescriptionElementBase, Distribution>();
216
					map.put(deb, db);
217
				}
218
			}
219
		}
220
		return map;
221
	}
222

    
223
	public List<DescriptionElementBase> listDescriptionElementsForTaxon(Taxon taxon, Set<Feature> setFeature){
224
		List<DescriptionElementBase> listDescriptionElementsForTaxon = CdmSpringContextHelper.getDescriptionService().listDescriptionElementsForTaxon(taxon, setFeature, null, null, null, DESCRIPTION_INIT_STRATEGY);
225
		sort(listDescriptionElementsForTaxon);
226
		return listDescriptionElementsForTaxon;
227
	}
228

    
229
	public List<Distribution> getDistributions(Taxon taxon) {
230
		Set<Feature> setFeature = new HashSet<>(Arrays.asList(Feature.DISTRIBUTION()));
231
		List<Distribution> listTaxonDescription = CdmSpringContextHelper.getDescriptionService()
232
		        .listDescriptionElementsForTaxon(taxon, setFeature, null, null, null, DESCRIPTION_INIT_STRATEGY);
233
		return listTaxonDescription;
234

    
235
	}
236

    
237
	public List<TaxonNode> getAllNodes(){
238
		List<TaxonNode> allNodes = new ArrayList<>();
239

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

    
250

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

    
268
   public LazyQueryContainer getAreaDistributionStatusContainer() {
269
        List<UUID> nodeUuids = getAllNodes().stream().map(n -> n.getUuid()).collect(Collectors.toCollection(ArrayList::new));
270
        List<NamedArea> namedAreas = getNamedAreas();
271
        if(namedAreas!=null){
272
            QueryFactory factory = new DistributionStatusQueryFactory(this.repo, nodeUuids, namedAreas);
273
            QueryDefinition defintion = new DistributionStatusQueryDefinition(namedAreas, true, 50);
274
            return new LazyQueryContainer(defintion, factory);
275
        }
276
        return null;
277
    }
278

    
279
	public CdmSQLContainer getSQLContainer() throws SQLException{
280
		List<Integer> nodeIds = new ArrayList<>();
281
		for (TaxonNode taxonNode : getAllNodes()) {
282
			nodeIds.add(taxonNode.getId());
283
		}
284
		List<NamedArea> namedAreas = getNamedAreas();
285
		if(namedAreas!=null){
286
			return new CdmSQLContainer(CdmQueryFactory.generateTaxonDistributionQuery(nodeIds, namedAreas));
287
		}
288
		return null;
289
	}
290

    
291
	public PresenceAbsenceTermContainer getPresenceAbsenceTermContainer() {
292
	    return PresenceAbsenceTermContainer.getInstance();
293
	}
294

    
295
	protected static final List<String> DESCRIPTION_INIT_STRATEGY = Arrays.asList(new String []{
296
            "$", //$NON-NLS-1$
297
            "elements.*", //$NON-NLS-1$
298
            "elements.sources.citation.authorship.$", //$NON-NLS-1$
299
            "elements.sources.nameUsedInSource.originalNameString", //$NON-NLS-1$
300
            "elements.area.level", //$NON-NLS-1$
301
            "elements.modifyingText", //$NON-NLS-1$
302
            "elements.states.*", //$NON-NLS-1$
303
            "elements.media", //$NON-NLS-1$
304
            "elements.multilanguageText", //$NON-NLS-1$
305
            "multilanguageText", //$NON-NLS-1$
306
            "stateData.$", //$NON-NLS-1$
307
            "annotations", //$NON-NLS-1$
308
            "markers", //$NON-NLS-1$
309
            "sources.citation.authorship", //$NON-NLS-1$
310
            "sources.nameUsedInSource", //$NON-NLS-1$
311
            "multilanguageText", //$NON-NLS-1$
312
            "media", //$NON-NLS-1$
313
            "name.$", //$NON-NLS-1$
314
            "name.rank", //$NON-NLS-1$
315
            "name.status.type", //$NON-NLS-1$
316
            "taxon2.name", //$NON-NLS-1$
317
    });
318

    
319
	/**Helper Methods*/
320
	private void sort(List<DescriptionElementBase> list){
321
		Collections.sort(list, new Comparator<DescriptionElementBase>() {
322

    
323
			@Override
324
			public int compare(DescriptionElementBase o1, DescriptionElementBase o2) {
325
				String feature1 = o1.getFeature().getTitleCache();
326
				String feature2 = o2.getFeature().getTitleCache();
327
				if(feature1 !=null && feature2 !=null){
328
					return feature1.compareTo(feature2);
329
				}else{
330
					return 0;
331

    
332
				}
333
			}
334
		});
335
	}
336

    
337
	/**
338
	 *
339
	 * {@inheritDoc}
340
	 */
341
	@Override
342
	protected void onPresenterReady() {
343
	    /*
344
         * The area and taxon settings window should only be displayed after login
345
         * and only when no classification and areas are chosen yet.
346
         */
347
	    VaadinSession vaadinSession = VaadinSession.getCurrent();
348
	    if(userHelper.userIsAutheticated()
349
	            && !userHelper.userIsAnnonymous()
350
	            && (vaadinSession.getAttribute(DistributionEditorUtil.SATTR_CLASSIFICATION) == null
351
	            || vaadinSession.getAttribute(DistributionEditorUtil.SATTR_SELECTED_AREA_VOCABULARY_UUID) == null
352
	            || vaadinSession.getAttribute(DistributionEditorUtil.SATTR_SELECTED_AREAS) == null)) {
353
            getView().openAreaAndTaxonSettings();
354
        }
355
    }
356

    
357
}
(3-3/7)