Project

General

Profile

Download (14.2 KB) Statistics
| Branch: | Tag: | Revision:
1
/**
2
* Copyright (C) 2018 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.taxeditor.editor.descriptiveDataSet.matrix;
10

    
11
import java.util.ArrayList;
12
import java.util.Collection;
13
import java.util.List;
14
import java.util.Map;
15
import java.util.UUID;
16

    
17
import org.eclipse.core.runtime.ICoreRunnable;
18
import org.eclipse.core.runtime.IProgressMonitor;
19
import org.eclipse.core.runtime.IStatus;
20
import org.eclipse.core.runtime.Status;
21
import org.eclipse.core.runtime.SubMonitor;
22
import org.eclipse.core.runtime.jobs.IJobChangeEvent;
23
import org.eclipse.core.runtime.jobs.Job;
24
import org.eclipse.core.runtime.jobs.JobChangeAdapter;
25
import org.eclipse.jface.layout.GridDataFactory;
26
import org.eclipse.jface.window.Window;
27
import org.eclipse.swt.SWT;
28
import org.eclipse.swt.events.SelectionAdapter;
29
import org.eclipse.swt.events.SelectionEvent;
30
import org.eclipse.swt.layout.RowLayout;
31
import org.eclipse.swt.widgets.Button;
32
import org.eclipse.swt.widgets.Composite;
33

    
34
import eu.etaxonomy.cdm.api.application.CdmApplicationState;
35
import eu.etaxonomy.cdm.api.service.IDescriptiveDataSetService;
36
import eu.etaxonomy.cdm.api.service.IPolytomousKeyService;
37
import eu.etaxonomy.cdm.api.service.UpdateResult;
38
import eu.etaxonomy.cdm.api.service.config.IdentifiableServiceConfiguratorImpl;
39
import eu.etaxonomy.cdm.api.service.dto.RowWrapperDTO;
40
import eu.etaxonomy.cdm.api.service.dto.SpecimenRowWrapperDTO;
41
import eu.etaxonomy.cdm.common.CdmUtils;
42
import eu.etaxonomy.cdm.common.monitor.IRemotingProgressMonitor;
43
import eu.etaxonomy.cdm.hibernate.HibernateProxyHelper;
44
import eu.etaxonomy.cdm.model.description.CategoricalData;
45
import eu.etaxonomy.cdm.model.description.DescriptiveDataSet;
46
import eu.etaxonomy.cdm.model.description.Feature;
47
import eu.etaxonomy.cdm.model.description.PolytomousKey;
48
import eu.etaxonomy.cdm.model.description.QuantitativeData;
49
import eu.etaxonomy.cdm.model.description.SpecimenDescription;
50
import eu.etaxonomy.cdm.model.description.TaxonDescription;
51
import eu.etaxonomy.cdm.persistence.dto.SpecimenNodeWrapper;
52
import eu.etaxonomy.cdm.strategy.generate.PolytomousKeyGenerator;
53
import eu.etaxonomy.cdm.strategy.generate.PolytomousKeyGeneratorConfigurator;
54
import eu.etaxonomy.taxeditor.editor.internal.TaxeditorEditorPlugin;
55
import eu.etaxonomy.taxeditor.editor.l10n.Messages;
56
import eu.etaxonomy.taxeditor.model.ImageResources;
57
import eu.etaxonomy.taxeditor.model.MessagingUtils;
58
import eu.etaxonomy.taxeditor.preference.IPreferenceKeys;
59
import eu.etaxonomy.taxeditor.preference.PreferencesUtil;
60
import eu.etaxonomy.taxeditor.store.CdmStore;
61
import eu.etaxonomy.taxeditor.store.StoreUtil;
62

    
63
/**
64
 * @author pplitzner
65
 * @since Jul 9, 2018
66
 *
67
 */
68
public class CharacterMatrixBottomToolbar extends Composite{
69

    
70
    private CharacterMatrix matrix;
71

    
72
    public CharacterMatrixBottomToolbar(CharacterMatrix matrix, int style) {
73
        super(matrix, style);
74
        this.matrix = matrix;
75

    
76
        init();
77
    }
78

    
79
    private void init() {
80

    
81
        setLayout(new RowLayout());
82
        GridDataFactory.fillDefaults().grab(true, false).applyTo(this);
83

    
84
        /**
85
         * Add description button
86
         */
87
        Button btnAddDescription = new Button(this, SWT.PUSH);
88
        btnAddDescription.setImage(ImageResources.getImage(ImageResources.ADD_ICON_GREEN));
89
        btnAddDescription.addSelectionListener(new SelectionAdapter() {
90
            @Override
91
            public void widgetSelected(SelectionEvent e) {
92
                if(StoreUtil.promptCheckIsDirty(matrix.getPart())){
93
                    return;
94
                }
95
                String error = ""; //$NON-NLS-1$
96
                SpecimenSelectionDialog dialog = new SpecimenSelectionDialog(matrix.getShell(), matrix);
97
                if(dialog.open()==Window.OK){
98
                    Collection<SpecimenNodeWrapper> wrappers = dialog.getSpecimen();
99
                    for (SpecimenNodeWrapper wrapper : wrappers) {
100
                        SpecimenDescription specimenDescription = CdmStore.getService(IDescriptiveDataSetService.class)
101
                                .findSpecimenDescription(matrix.getDescriptiveDataSet().getUuid(),
102
                                        wrapper.getUuidAndTitleCache().getUuid(), true);
103
                        SpecimenRowWrapperDTO rowWrapper = CdmStore.getService(IDescriptiveDataSetService.class)
104
                                .createSpecimenRowWrapper(specimenDescription, matrix.getDescriptiveDataSet());
105
                        if(rowWrapper==null){
106
                            error += specimenDescription;
107
                            continue;
108
                        }
109
                        //add specimen description
110
                        matrix.getDescriptions().add(rowWrapper);
111
                        matrix.getDescriptiveDataSet().addDescription(specimenDescription);
112
                        matrix.getCdmEntitiySession().load(specimenDescription, true);
113

    
114
                        matrix.setDirty();
115
                        matrix.getSpecimenCache().remove(wrapper);
116
                    }
117
                    if(CdmUtils.isNotBlank(error)){
118
                        MessagingUtils.warningDialog(Messages.CharacterMatrixBottomToolbar_ERROR_ROW_CREATION_TITLE, this,
119
                                String.format(Messages.CharacterMatrixBottomToolbar_ERROR_ROW_CREATION_MESSAGE, error));
120
                    }
121
                }
122
            }
123
        });
124
        /**
125
         * Remove description button
126
         */
127
        Button btnRemoveDescription = new Button(this, SWT.PUSH);
128
        btnRemoveDescription.setImage(ImageResources.getImage(ImageResources.ACTIVE_DELETE_ICON));
129
        btnRemoveDescription.addSelectionListener(new SelectionAdapter() {
130
            @Override
131
            public void widgetSelected(SelectionEvent e) {
132
                if(StoreUtil.promptCheckIsDirty(matrix.getPart())){
133
                    return;
134
                }
135
                if(!MessagingUtils.confirmDialog(Messages.CharacterMatrixBottomToolbar_CONFIRM_DELETE_TITLE, Messages.CharacterMatrixBottomToolbar_CONFIRM_DELETE_MESSAGE)){
136
                    return;
137
                }
138
                int[] fullySelectedRowPositions = matrix.getBodyLayer().getSelectionLayer().getFullySelectedRowPositions();
139
                List<RowWrapperDTO> toRemove = new ArrayList<>();
140
                for (int i : fullySelectedRowPositions) {
141
                    Object rowObject = matrix.getBodyDataProvider().getRowObject(i);
142
                    if(rowObject instanceof RowWrapperDTO){
143
                        toRemove.add((RowWrapperDTO) rowObject);
144
                    }
145
                }
146
                toRemove.forEach(rowToRemove -> {
147
                    matrix.getDescriptions().remove(rowToRemove);
148
                    CdmStore.getService(IDescriptiveDataSetService.class).removeDescription(
149
                            rowToRemove.getDescription().getUuid(), matrix.getDescriptiveDataSet().getUuid());
150
                });
151
            }
152
        });
153
        /**
154
         * Aggregate button
155
         */
156
        Button btnAggregate = new Button(this, SWT.PUSH);
157
        btnAggregate.setText(Messages.CharacterMatrixBottomToolbar_AGGREGATE);
158
        btnAggregate.addSelectionListener(new SelectionAdapter() {
159
            @Override
160
            public void widgetSelected(SelectionEvent e) {
161
                if(StoreUtil.promptCheckIsDirty(matrix.getPart())){
162
                    return;
163
                }
164
                aggregatDescriptiveDataSet(matrix.getDescriptiveDataSet().getUuid());
165

    
166
                aggregateCharts();
167
            }
168
        });
169
        if(PreferencesUtil.getBooleanValue(IPreferenceKeys.SHOW_EXPERIMENTAL_FEATURES)){
170
            /**
171
             * Key generation button
172
             */
173
            Button btnGenerateKey = new Button(this, SWT.PUSH);
174
            btnGenerateKey.setText("Generate Polytomous Key");
175
            btnGenerateKey.addSelectionListener(new SelectionAdapter() {
176
                @Override
177
                public void widgetSelected(SelectionEvent e) {
178
                    if(StoreUtil.promptCheckIsDirty(matrix.getPart())){
179
                        return;
180
                    }
181
                    PolytomousKeyGeneratorConfigurator keyConfig = new PolytomousKeyGeneratorConfigurator();
182
                    DescriptiveDataSet descriptiveDataSet = matrix.getDescriptiveDataSet();
183
                    keyConfig.setDataSet(descriptiveDataSet);
184
                    PolytomousKey key = new PolytomousKeyGenerator().invoke(keyConfig);
185
                    IPolytomousKeyService keyService = CdmStore.getService(IPolytomousKeyService.class);
186
                    IdentifiableServiceConfiguratorImpl<PolytomousKey> serviceConfig= new IdentifiableServiceConfiguratorImpl<>();
187
                    serviceConfig.setTitleSearchString(descriptiveDataSet.getTitleCache());
188
                    List<PolytomousKey> list = keyService.findByTitle(serviceConfig).getRecords();
189
                    if(list!=null){
190
                        // TODO clear old key
191
                        System.out.println("Key with same name found for this data set found");
192
                    }
193
                    key.setTitleCache(descriptiveDataSet.getTitleCache(), true);
194
                    keyService.save(key);
195
                    key.print(System.out);
196
                }
197
            });
198
        }
199
    }
200

    
201
    private void aggregatDescriptiveDataSet(UUID descriptiveDataSetUuid){
202
        UUID monitorUuid =  CdmApplicationState.getLongRunningTasksService().aggregateDescriptiveDataSet(descriptiveDataSetUuid);
203

    
204
        String jobLabel = "Aggregate Descriptive Data Set";
205
        Job job = Job.create(jobLabel, (ICoreRunnable) monitor -> {
206
            SubMonitor subMonitor = SubMonitor.convert(monitor);
207
            subMonitor.beginTask(jobLabel, IProgressMonitor.UNKNOWN);
208
            IRemotingProgressMonitor remotingMonitor;
209
            try {
210
                remotingMonitor = CdmStore.getProgressMonitorClientManager()
211
                        .pollMonitor(jobLabel,
212
                                monitorUuid,
213
                                50,
214
                                null,
215
                                (List)null,
216
                                subMonitor);
217
                Object resultObject = remotingMonitor.getResult();
218
                if(resultObject instanceof Exception){
219
                    MessagingUtils.errorDialog("Aggregation failed", this, "Aggregation was not successfull", TaxeditorEditorPlugin.PLUGIN_ID, (Exception)resultObject, true, true);
220
                }
221
                else if(resultObject instanceof UpdateResult){
222
                    UpdateResult result = (UpdateResult) resultObject;
223
                IDescriptiveDataSetService dataSetService = CdmStore.getService(IDescriptiveDataSetService.class);
224
                result.getUpdatedObjects().stream()
225
                .filter(o -> o instanceof TaxonDescription)
226
                .map(o -> HibernateProxyHelper.deproxy(o, TaxonDescription.class))
227
                .forEach(taxonDescription -> matrix.getDescriptions()
228
                        .add(dataSetService.createTaxonRowWrapper(
229
                                taxonDescription.getUuid(),
230
                                matrix.getDescriptiveDataSet().getUuid())));
231
                }
232
            } catch (InterruptedException e) {
233
                return;
234
            }
235
            monitor.done();
236
        });
237
        job.addJobChangeListener(new JobChangeAdapter(){
238
            @Override
239
            public void done(IJobChangeEvent event) {
240
                CharacterMatrixBottomToolbar.this.getDisplay().asyncExec(()->{
241
                    matrix.redraw();
242
                });
243
            }
244
        });
245
        job.schedule();
246
    }
247

    
248
    private void aggregateCharts() {
249
        new Job("aggregate charts") {
250

    
251
            @Override
252
            protected IStatus run(IProgressMonitor monitor) {
253
                aggregateCategorcialHistogram(matrix.getFeatureToHistogramMap());
254
                aggregateQuantitativeSummary(matrix.getFeatureToQuantDataStatisticsMap());
255
                return Status.OK_STATUS;
256
            }
257
        }.schedule();
258
    }
259

    
260
    @SuppressWarnings("unchecked")
261
    private void aggregateCategorcialHistogram(Map<Feature, CategoricalDataHistogram> featureToHistogramMap) {
262
        featureToHistogramMap.clear();
263
        matrix.getDescriptions().stream()
264
        .filter(desc->desc instanceof SpecimenRowWrapperDTO)
265
        .forEach(o -> ((SpecimenRowWrapperDTO) o).getDescription().getElements().stream()
266
                .filter(descriptionElement -> descriptionElement instanceof CategoricalData)
267
                .forEach(categoricalData -> {
268
                    Feature feature = ((CategoricalData) categoricalData).getFeature();
269
                    CategoricalDataHistogram dataHistogram = featureToHistogramMap.get(feature);
270
                    if(dataHistogram==null){
271
                        dataHistogram = new CategoricalDataHistogram(feature);
272
                    }
273
                    featureToHistogramMap.put(feature, dataHistogram);
274
                    ((CategoricalData) categoricalData).getStateData()
275
                    .forEach(stateData -> featureToHistogramMap.get(feature).addState(stateData.getState()));
276
                }));
277
    }
278

    
279
    @SuppressWarnings("unchecked")
280
    private void aggregateQuantitativeSummary(Map<Feature, QuantitativeDataStatistics> featureToQuantDataStatisticsMap) {
281
        featureToQuantDataStatisticsMap.clear();
282
        matrix.getDescriptions().stream()
283
        .filter(desc->desc instanceof SpecimenRowWrapperDTO)
284
        .forEach(o -> ((SpecimenRowWrapperDTO) o).getDescription().getElements().stream()
285
                .filter(descriptionElement -> descriptionElement instanceof QuantitativeData)
286
                .forEach(quantData -> {
287
                    Feature feature = ((QuantitativeData) quantData).getFeature();
288
                    QuantitativeDataStatistics dataStatistics = featureToQuantDataStatisticsMap.get(feature);
289
                    if(dataStatistics==null){
290
                        dataStatistics = new QuantitativeDataStatistics();
291
                    }
292
                    featureToQuantDataStatisticsMap.put(feature, dataStatistics);
293
                    dataStatistics.addQuantitativeData((QuantitativeData) quantData);
294
                }));
295
    }
296

    
297
}
(7-7/21)