Project

General

Profile

Download (13.7 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

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

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

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

    
72
	private static final long serialVersionUID = 3313043335587777217L;
73

    
74
    @Autowired
75
    private CdmUserHelper userHelper;
76

    
77
    @Autowired
78
    @Qualifier("cdmRepository")
79
    private CdmRepository repo;
80

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

    
154
	public Set<DefinedTermBase> getChosenTerms() {
155
		VaadinSession session = VaadinSession.getCurrent();
156
		UUID vocUUID = (UUID) session.getAttribute(DistributionEditorUtil.SATTR_SELECTED_AREA_VOCABULARY_UUID);
157
//		getConversationHolder().getSession();
158
		TermVocabulary<DefinedTermBase> voc = CdmSpringContextHelper.getVocabularyService().load(vocUUID, Arrays.asList("terms")); //$NON-NLS-1$
159
//		voc = CdmBase.deproxy(voc);
160
		return voc.getTerms();
161
	}
162

    
163
	public List<String> getAbbreviatedTermList() {
164
		List<NamedArea> terms = getTermSet();
165
		List<String> list = new ArrayList<>();
166
		for(DefinedTermBase<?> dtb: terms){
167
		    for(Representation r : dtb.getRepresentations()){
168
		        list.add(r.getAbbreviatedLabel());
169
		    }
170
		}
171
		return list;
172
	}
173

    
174
	public List<NamedArea> getNamedAreas(){
175
	    List<NamedArea> namedAreas = (List<NamedArea>)VaadinSession.getCurrent().getAttribute(DistributionEditorUtil.SATTR_SELECTED_AREAS);
176
	    if(namedAreas!=null && namedAreas.isEmpty()){
177
	        return getTermSet();
178
	    }
179
	    return namedAreas;
180
	}
181

    
182
	private List<NamedArea> getTermSet(){
183
	    VaadinSession session = VaadinSession.getCurrent();
184
	    UUID vocUUID = (UUID) session.getAttribute(DistributionEditorUtil.SATTR_SELECTED_AREA_VOCABULARY_UUID);
185
	    TermVocabulary<NamedArea> vocabulary = CdmSpringContextHelper.getVocabularyService().load(vocUUID, Arrays.asList("terms")); //$NON-NLS-1$
186
	    vocabulary = CdmBase.deproxy(vocabulary, TermVocabulary.class);
187
	    if (vocabulary instanceof OrderedTermVocabulary) {
188
	        List<NamedArea> list = new ArrayList<> (((OrderedTermVocabulary)vocabulary).getOrderedTerms());
189
	        Collections.reverse(list);
190
	        return list;
191
	    }else {
192
	        return vocabulary.getTermsOrderedByLabels(Language.DEFAULT()).stream().collect(Collectors.toCollection(ArrayList::new));
193
	    }
194

    
195
	}
196

    
197
	public HashMap<DescriptionElementBase, Distribution> getDistribution(DefinedTermBase dt, Taxon taxon) {
198
		Set<Feature> setFeature = new HashSet<>(Arrays.asList(Feature.DISTRIBUTION()));
199
		List<DescriptionElementBase> listTaxonDescription = CdmSpringContextHelper.getDescriptionService().listDescriptionElementsForTaxon(taxon, setFeature, null, null, null, DESCRIPTION_INIT_STRATEGY);
200
		HashMap<DescriptionElementBase, Distribution> map = null;
201
		for(DescriptionElementBase deb : listTaxonDescription){
202
			if(deb instanceof Distribution){
203
				Distribution db = (Distribution)deb;
204
				String titleCache = dt.getTitleCache();
205
				if(db.getArea().getTitleCache().equalsIgnoreCase(titleCache)){
206
					map = new HashMap<DescriptionElementBase, Distribution>();
207
					map.put(deb, db);
208
				}
209
			}
210
		}
211
		return map;
212
	}
213

    
214
	public List<DescriptionElementBase> listDescriptionElementsForTaxon(Taxon taxon, Set<Feature> setFeature){
215
		List<DescriptionElementBase> listDescriptionElementsForTaxon = CdmSpringContextHelper.getDescriptionService().listDescriptionElementsForTaxon(taxon, setFeature, null, null, null, DESCRIPTION_INIT_STRATEGY);
216
		sort(listDescriptionElementsForTaxon);
217
		return listDescriptionElementsForTaxon;
218
	}
219

    
220
	public List<Distribution> getDistributions(Taxon taxon) {
221
		Set<Feature> setFeature = new HashSet<>(Arrays.asList(Feature.DISTRIBUTION()));
222
		List<Distribution> listTaxonDescription = CdmSpringContextHelper.getDescriptionService()
223
		        .listDescriptionElementsForTaxon(taxon, setFeature, null, null, null, DESCRIPTION_INIT_STRATEGY);
224
		return listTaxonDescription;
225

    
226
	}
227

    
228
	public List<TaxonNode> getAllNodes(){
229
		List<TaxonNode> allNodes = new ArrayList<>();
230

    
231
		List<TaxonNode> taxonNodes = getChosenTaxonNodes();
232
		for (TaxonNode taxonNode : taxonNodes) {
233
			if(taxonNode.getTaxon()!=null){
234
				allNodes.add(taxonNode);
235
			}
236
			allNodes.addAll(CdmSpringContextHelper.getTaxonNodeService().loadChildNodesOfTaxonNode(taxonNode, null, true, null));
237
		}
238
		return allNodes;
239
	}
240

    
241

    
242
	public List<TaxonNode> getChosenTaxonNodes() {
243
		VaadinSession session = VaadinSession.getCurrent();
244
		List<UUID> taxonNodeUUIDs = (List<UUID>) session.getAttribute(DistributionEditorUtil.SATTR_TAXON_NODES_UUID);
245
		UUID classificationUuid = (UUID)session.getAttribute(DistributionEditorUtil.SATTR_CLASSIFICATION);
246
		if((taxonNodeUUIDs==null || taxonNodeUUIDs.isEmpty()) && classificationUuid!=null){
247
			Classification classification = CdmSpringContextHelper.getClassificationService().load(classificationUuid);
248
			if(classification!=null){
249
				taxonNodeUUIDs = Collections.singletonList(classification.getRootNode().getUuid());
250
			}
251
		}
252
		List<TaxonNode> loadedNodes = CdmSpringContextHelper.getTaxonNodeService().load(taxonNodeUUIDs, null);
253
		if(loadedNodes!=null){
254
			return loadedNodes;
255
		}
256
		return Collections.emptyList();
257
	}
258

    
259
   public LazyQueryContainer getAreaDistributionStatusContainer() {
260
        List<UUID> nodeUuids = getAllNodes().stream().map(n -> n.getUuid()).collect(Collectors.toCollection(ArrayList::new));
261
        List<NamedArea> namedAreas = getNamedAreas();
262
        if(namedAreas!=null){
263
            QueryFactory factory = new DistributionStatusQueryFactory(this.repo, nodeUuids, namedAreas);
264
            QueryDefinition defintion = new DistributionStatusQueryDefinition(namedAreas, true, 50);
265
            return new LazyQueryContainer(defintion, factory);
266
        }
267
        return null;
268
    }
269

    
270
	public CdmSQLContainer getSQLContainer() throws SQLException{
271
		List<Integer> nodeIds = new ArrayList<>();
272
		for (TaxonNode taxonNode : getAllNodes()) {
273
			nodeIds.add(taxonNode.getId());
274
		}
275
		List<NamedArea> namedAreas = getNamedAreas();
276
		if(namedAreas!=null){
277
			return new CdmSQLContainer(CdmQueryFactory.generateTaxonDistributionQuery(nodeIds, namedAreas));
278
		}
279
		return null;
280
	}
281

    
282
	public PresenceAbsenceTermContainer getPresenceAbsenceTermContainer() {
283
	    return PresenceAbsenceTermContainer.getInstance();
284
	}
285

    
286
	protected static final List<String> DESCRIPTION_INIT_STRATEGY = Arrays.asList(new String []{
287
            "$", //$NON-NLS-1$
288
            "elements.*", //$NON-NLS-1$
289
            "elements.sources.citation.authorship.$", //$NON-NLS-1$
290
            "elements.sources.nameUsedInSource.originalNameString", //$NON-NLS-1$
291
            "elements.area.level", //$NON-NLS-1$
292
            "elements.modifyingText", //$NON-NLS-1$
293
            "elements.states.*", //$NON-NLS-1$
294
            "elements.media", //$NON-NLS-1$
295
            "elements.multilanguageText", //$NON-NLS-1$
296
            "multilanguageText", //$NON-NLS-1$
297
            "stateData.$", //$NON-NLS-1$
298
            "annotations", //$NON-NLS-1$
299
            "markers", //$NON-NLS-1$
300
            "sources.citation.authorship", //$NON-NLS-1$
301
            "sources.nameUsedInSource", //$NON-NLS-1$
302
            "multilanguageText", //$NON-NLS-1$
303
            "media", //$NON-NLS-1$
304
            "name.$", //$NON-NLS-1$
305
            "name.rank", //$NON-NLS-1$
306
            "name.status.type", //$NON-NLS-1$
307
            "taxon2.name", //$NON-NLS-1$
308
    });
309

    
310
	/**Helper Methods*/
311
	private void sort(List<DescriptionElementBase> list){
312
		Collections.sort(list, new Comparator<DescriptionElementBase>() {
313

    
314
			@Override
315
			public int compare(DescriptionElementBase o1, DescriptionElementBase o2) {
316
				String feature1 = o1.getFeature().getTitleCache();
317
				String feature2 = o2.getFeature().getTitleCache();
318
				if(feature1 !=null && feature2 !=null){
319
					return feature1.compareTo(feature2);
320
				}else{
321
					return 0;
322

    
323
				}
324
			}
325
		});
326
	}
327

    
328
	/**
329
	 *
330
	 * {@inheritDoc}
331
	 */
332
	@Override
333
	protected void onPresenterReady() {
334
	    /*
335
         * The area and taxon settings window should only be displayed after login
336
         * and only when no classification and areas are chosen yet.
337
         */
338
	    VaadinSession vaadinSession = VaadinSession.getCurrent();
339
	    if(userHelper.userIsAutheticated()
340
	            && !userHelper.userIsAnnonymous()
341
	            && (vaadinSession.getAttribute(DistributionEditorUtil.SATTR_CLASSIFICATION) == null
342
	            || vaadinSession.getAttribute(DistributionEditorUtil.SATTR_SELECTED_AREA_VOCABULARY_UUID) == null
343
	            || vaadinSession.getAttribute(DistributionEditorUtil.SATTR_SELECTED_AREAS) == null)) {
344
            getView().openAreaAndTaxonSettings();
345
        }
346
    }
347

    
348
}
(3-3/7)