Project

General

Profile

Download (46.4 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.taxeditor.editor.workingSet.matrix;
10

    
11
import java.io.File;
12
import java.io.FileInputStream;
13
import java.io.FileOutputStream;
14
import java.io.IOException;
15
import java.util.ArrayList;
16
import java.util.Arrays;
17
import java.util.Collection;
18
import java.util.Collections;
19
import java.util.HashMap;
20
import java.util.HashSet;
21
import java.util.List;
22
import java.util.Map;
23
import java.util.Properties;
24
import java.util.Set;
25
import java.util.UUID;
26

    
27
import javax.annotation.PostConstruct;
28
import javax.annotation.PreDestroy;
29
import javax.inject.Inject;
30

    
31
import org.apache.commons.collections4.map.LinkedMap;
32
import org.eclipse.core.runtime.IProgressMonitor;
33
import org.eclipse.e4.ui.di.Focus;
34
import org.eclipse.e4.ui.di.Persist;
35
import org.eclipse.e4.ui.model.application.ui.MDirtyable;
36
import org.eclipse.e4.ui.model.application.ui.basic.MPart;
37
import org.eclipse.e4.ui.workbench.modeling.ESelectionService;
38
import org.eclipse.jface.layout.GridDataFactory;
39
import org.eclipse.jface.viewers.ArrayContentProvider;
40
import org.eclipse.jface.viewers.ComboViewer;
41
import org.eclipse.jface.viewers.LabelProvider;
42
import org.eclipse.jface.viewers.StructuredSelection;
43
import org.eclipse.jface.window.Window;
44
import org.eclipse.nebula.widgets.nattable.NatTable;
45
import org.eclipse.nebula.widgets.nattable.config.AbstractRegistryConfiguration;
46
import org.eclipse.nebula.widgets.nattable.config.CellConfigAttributes;
47
import org.eclipse.nebula.widgets.nattable.config.ConfigRegistry;
48
import org.eclipse.nebula.widgets.nattable.config.DefaultNatTableStyleConfiguration;
49
import org.eclipse.nebula.widgets.nattable.config.IConfigRegistry;
50
import org.eclipse.nebula.widgets.nattable.config.IEditableRule;
51
import org.eclipse.nebula.widgets.nattable.data.IDataProvider;
52
import org.eclipse.nebula.widgets.nattable.data.ListDataProvider;
53
import org.eclipse.nebula.widgets.nattable.edit.EditConfigAttributes;
54
import org.eclipse.nebula.widgets.nattable.edit.editor.IComboBoxDataProvider;
55
import org.eclipse.nebula.widgets.nattable.export.command.ExportCommand;
56
import org.eclipse.nebula.widgets.nattable.export.command.ExportCommandHandler;
57
import org.eclipse.nebula.widgets.nattable.extension.glazedlists.GlazedListsEventLayer;
58
import org.eclipse.nebula.widgets.nattable.extension.glazedlists.GlazedListsSortModel;
59
import org.eclipse.nebula.widgets.nattable.extension.glazedlists.tree.GlazedListTreeData;
60
import org.eclipse.nebula.widgets.nattable.extension.glazedlists.tree.GlazedListTreeRowModel;
61
import org.eclipse.nebula.widgets.nattable.grid.GridRegion;
62
import org.eclipse.nebula.widgets.nattable.grid.command.ClientAreaResizeCommand;
63
import org.eclipse.nebula.widgets.nattable.grid.data.DefaultColumnHeaderDataProvider;
64
import org.eclipse.nebula.widgets.nattable.grid.data.DefaultCornerDataProvider;
65
import org.eclipse.nebula.widgets.nattable.grid.data.DefaultRowHeaderDataProvider;
66
import org.eclipse.nebula.widgets.nattable.grid.data.FixedSummaryRowHeaderLayer;
67
import org.eclipse.nebula.widgets.nattable.grid.layer.ColumnHeaderLayer;
68
import org.eclipse.nebula.widgets.nattable.grid.layer.CornerLayer;
69
import org.eclipse.nebula.widgets.nattable.grid.layer.DefaultRowHeaderDataLayer;
70
import org.eclipse.nebula.widgets.nattable.grid.layer.GridLayer;
71
import org.eclipse.nebula.widgets.nattable.grid.layer.config.DefaultRowStyleConfiguration;
72
import org.eclipse.nebula.widgets.nattable.hideshow.ColumnHideShowLayer;
73
import org.eclipse.nebula.widgets.nattable.hideshow.RowHideShowLayer;
74
import org.eclipse.nebula.widgets.nattable.layer.CompositeLayer;
75
import org.eclipse.nebula.widgets.nattable.layer.DataLayer;
76
import org.eclipse.nebula.widgets.nattable.layer.ILayer;
77
import org.eclipse.nebula.widgets.nattable.layer.ILayerListener;
78
import org.eclipse.nebula.widgets.nattable.layer.cell.ColumnOverrideLabelAccumulator;
79
import org.eclipse.nebula.widgets.nattable.layer.cell.ILayerCell;
80
import org.eclipse.nebula.widgets.nattable.layer.config.DefaultColumnHeaderStyleConfiguration;
81
import org.eclipse.nebula.widgets.nattable.layer.config.DefaultRowHeaderStyleConfiguration;
82
import org.eclipse.nebula.widgets.nattable.layer.event.ILayerEvent;
83
import org.eclipse.nebula.widgets.nattable.persistence.PersistenceHelper;
84
import org.eclipse.nebula.widgets.nattable.persistence.command.DisplayPersistenceDialogCommand;
85
import org.eclipse.nebula.widgets.nattable.persistence.command.DisplayPersistenceDialogCommandHandler;
86
import org.eclipse.nebula.widgets.nattable.persistence.command.IStateChangedListener;
87
import org.eclipse.nebula.widgets.nattable.persistence.command.StateChangeEvent;
88
import org.eclipse.nebula.widgets.nattable.persistence.gui.PersistenceDialog;
89
import org.eclipse.nebula.widgets.nattable.reorder.ColumnReorderLayer;
90
import org.eclipse.nebula.widgets.nattable.reorder.RowReorderLayer;
91
import org.eclipse.nebula.widgets.nattable.selection.SelectionLayer;
92
import org.eclipse.nebula.widgets.nattable.selection.config.DefaultSelectionStyleConfiguration;
93
import org.eclipse.nebula.widgets.nattable.selection.event.CellSelectionEvent;
94
import org.eclipse.nebula.widgets.nattable.sort.SortHeaderLayer;
95
import org.eclipse.nebula.widgets.nattable.sort.config.SingleClickSortConfiguration;
96
import org.eclipse.nebula.widgets.nattable.style.CellStyleAttributes;
97
import org.eclipse.nebula.widgets.nattable.style.DisplayMode;
98
import org.eclipse.nebula.widgets.nattable.style.HorizontalAlignmentEnum;
99
import org.eclipse.nebula.widgets.nattable.style.Style;
100
import org.eclipse.nebula.widgets.nattable.style.VerticalAlignmentEnum;
101
import org.eclipse.nebula.widgets.nattable.summaryrow.FixedSummaryRowLayer;
102
import org.eclipse.nebula.widgets.nattable.summaryrow.SummaryRowLayer;
103
import org.eclipse.nebula.widgets.nattable.tree.ITreeRowModel;
104
import org.eclipse.nebula.widgets.nattable.tree.TreeLayer;
105
import org.eclipse.nebula.widgets.nattable.tree.command.TreeCollapseAllCommand;
106
import org.eclipse.nebula.widgets.nattable.tree.command.TreeExpandAllCommand;
107
import org.eclipse.nebula.widgets.nattable.ui.menu.AbstractHeaderMenuConfiguration;
108
import org.eclipse.nebula.widgets.nattable.ui.menu.PopupMenuBuilder;
109
import org.eclipse.nebula.widgets.nattable.util.GUIHelper;
110
import org.eclipse.nebula.widgets.nattable.viewport.ViewportLayer;
111
import org.eclipse.swt.SWT;
112
import org.eclipse.swt.events.SelectionAdapter;
113
import org.eclipse.swt.events.SelectionEvent;
114
import org.eclipse.swt.graphics.Color;
115
import org.eclipse.swt.graphics.FontData;
116
import org.eclipse.swt.layout.GridData;
117
import org.eclipse.swt.layout.GridLayout;
118
import org.eclipse.swt.layout.RowLayout;
119
import org.eclipse.swt.widgets.Button;
120
import org.eclipse.swt.widgets.Composite;
121
import org.eclipse.swt.widgets.Label;
122

    
123
import ca.odell.glazedlists.EventList;
124
import ca.odell.glazedlists.GlazedLists;
125
import ca.odell.glazedlists.SortedList;
126
import ca.odell.glazedlists.TreeList;
127
import eu.etaxonomy.cdm.api.conversation.ConversationHolder;
128
import eu.etaxonomy.cdm.api.conversation.IConversationEnabled;
129
import eu.etaxonomy.cdm.api.service.IWorkingSetService;
130
import eu.etaxonomy.cdm.model.common.TermVocabulary;
131
import eu.etaxonomy.cdm.model.description.DescriptionBase;
132
import eu.etaxonomy.cdm.model.description.DescriptionElementBase;
133
import eu.etaxonomy.cdm.model.description.Feature;
134
import eu.etaxonomy.cdm.model.description.FeatureTree;
135
import eu.etaxonomy.cdm.model.description.MeasurementUnit;
136
import eu.etaxonomy.cdm.model.description.SpecimenDescription;
137
import eu.etaxonomy.cdm.model.description.State;
138
import eu.etaxonomy.cdm.model.description.WorkingSet;
139
import eu.etaxonomy.cdm.model.occurrence.SpecimenOrObservationBase;
140
import eu.etaxonomy.cdm.persistence.hibernate.CdmDataChangeMap;
141
import eu.etaxonomy.taxeditor.editor.workingSet.matrix.categorical.CategoricalDataCellEditor;
142
import eu.etaxonomy.taxeditor.editor.workingSet.matrix.categorical.CategoricalDataDisplayConverter;
143
import eu.etaxonomy.taxeditor.editor.workingSet.matrix.quantitative.QuantitativeDataCellEditor;
144
import eu.etaxonomy.taxeditor.editor.workingSet.matrix.quantitative.QuantitativeDataDisplayConverter;
145
import eu.etaxonomy.taxeditor.editor.workingSet.matrix.supplementalInfo.SupplementalInfoDisplayConverter;
146
import eu.etaxonomy.taxeditor.model.ColorResources;
147
import eu.etaxonomy.taxeditor.model.DescriptionHelper;
148
import eu.etaxonomy.taxeditor.model.IDirtyMarkable;
149
import eu.etaxonomy.taxeditor.model.IPartContentHasDetails;
150
import eu.etaxonomy.taxeditor.model.ImageResources;
151
import eu.etaxonomy.taxeditor.model.MessagingUtils;
152
import eu.etaxonomy.taxeditor.preference.Resources;
153
import eu.etaxonomy.taxeditor.session.ICdmEntitySession;
154
import eu.etaxonomy.taxeditor.session.ICdmEntitySessionEnabled;
155
import eu.etaxonomy.taxeditor.store.CdmStore;
156
import eu.etaxonomy.taxeditor.workbench.WorkbenchUtility;
157
import eu.etaxonomy.taxeditor.workbench.part.IE4SavablePart;
158

    
159
/**
160
 * @author pplitzner
161
 * @since Nov 26, 2017
162
 *
163
 */
164
public class CharacterMatrix implements IE4SavablePart, IPartContentHasDetails, IConversationEnabled, IDirtyMarkable,
165
ICdmEntitySessionEnabled{
166

    
167
    private static final List<String> WS_PROPERTY_PATH = Arrays.asList(new String[] {
168
            "descriptions", //$NON-NLS-1$
169
            "descriptions.descriptionElements", //$NON-NLS-1$
170
            "descriptions.descriptionElements.inDescription", //$NON-NLS-1$
171
            "descriptions.descriptionElements.inDescription.descriptionElements", //$NON-NLS-1$
172
            "descriptions.descriptionElements.feature", //$NON-NLS-1$
173
    });
174

    
175
    private static final String CHARACTER_MATRIX_STATE_PROPERTIES = "characterMatrixState.properties";
176

    
177
    private static final int LEADING_COLUMN_COUNT = 4;
178
    private static final String TAXON_COLUMN = "taxon_column";
179
    private static final String COLLECTOR_COLUMN = "collector_column";
180
    private static final String IDENTIFIER_COLUMN = "identifier_column";
181
    private static final String COUNTRY_COLUMN = "country_column";
182

    
183
    private WorkingSet workingSet;
184

    
185
    private ConversationHolder conversation;
186

    
187
    private ICdmEntitySession cdmEntitySession;
188

    
189
    @Inject
190
    private ESelectionService selService;
191

    
192
    @Inject
193
    private MDirtyable dirty;
194

    
195
    @Inject
196
    private MPart thisPart;
197

    
198
    private NatTable natTable;
199

    
200
    private Map<Integer, Feature> indexToFeatureMap = new HashMap<>();
201

    
202
    private LinkedMap<String, String> propertyToLabelMap = new LinkedMap<>();
203

    
204
    private Properties natTableState;
205

    
206
    private EventList<Object> descriptions;
207

    
208
    private Collection<SpecimenOrObservationBase> specimenCache = null;
209

    
210
    private ListDataProvider<Object> bodyDataProvider;
211

    
212
    private Label wsLabel;
213

    
214
    private Composite parent;
215

    
216
    private List<Feature> features;
217

    
218
    private DisplayPersistenceDialogCommandHandler displayPersistenceDialogCommandHandler;
219

    
220
    @PostConstruct
221
    public void create(Composite parent) {
222
        if(CdmStore.isActive() && conversation==null){
223
            conversation = CdmStore.createConversation();
224
        }
225
        if(cdmEntitySession == null){
226
            cdmEntitySession = CdmStore.getCurrentSessionManager().newSession(this, true);
227
        }
228
        else{
229
            return;
230
        }
231
        this.parent = parent;
232
        parent.setLayout(new GridLayout());
233

    
234
        Composite toolbarComposite = new Composite(parent, SWT.NONE);
235
        toolbarComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
236
        toolbarComposite.setLayout(new GridLayout(8, false));
237
        natTable = new NatTable(parent, false);
238

    
239
        wsLabel = new Label(toolbarComposite, SWT.NONE);
240

    
241
        Button btnToggleTree = new Button(toolbarComposite, SWT.PUSH);
242
        Button btnToggleFlat = new Button(toolbarComposite, SWT.PUSH);
243
        Button btnCollapseAll = new Button(toolbarComposite, SWT.PUSH);
244
        Button btnExpandAll = new Button(toolbarComposite, SWT.PUSH);
245
        ComboViewer comboStates = new ComboViewer(toolbarComposite, SWT.DROP_DOWN);
246
        Button btnManageState = new Button(toolbarComposite, SWT.PUSH);
247
        Button btnExcelExport = new Button(toolbarComposite, SWT.PUSH);
248

    
249
        /**
250
         * Toogle tree button
251
         */
252
        btnToggleTree.setImage(ImageResources.getImage(ImageResources.HIERARCHICAL));
253
        btnToggleTree.setToolTipText("Show taxon hierarchy");
254
        btnToggleTree.setSelection(true);
255
        btnToggleTree.setEnabled(false);
256
        btnToggleTree.addSelectionListener(new SelectionAdapter() {
257
            @Override
258
            public void widgetSelected(SelectionEvent e) {
259
                toggleTreeFlat(true, btnToggleFlat, btnToggleTree, btnCollapseAll, btnExpandAll);
260
            }
261
        });
262

    
263
        /**
264
         * Toogle flat button
265
         */
266
        btnToggleFlat.setImage(ImageResources.getImage(ImageResources.FLAT));
267
        btnToggleFlat.setToolTipText("Show flat list");
268
        btnToggleFlat.addSelectionListener(new SelectionAdapter() {
269
            @Override
270
            public void widgetSelected(SelectionEvent e) {
271
                toggleTreeFlat(false, btnToggleFlat, btnToggleTree, btnCollapseAll, btnExpandAll);
272
            }
273
        });
274

    
275
        /**
276
         *
277
         * Collapse button
278
         */
279
        btnCollapseAll.setImage(ImageResources.getImage(ImageResources.COLLAPSE_ALL));
280
        btnCollapseAll.setToolTipText("Collapse all");
281
        btnCollapseAll.addSelectionListener(new SelectionAdapter() {
282
            @Override
283
            public void widgetSelected(SelectionEvent e) {
284
                natTable.doCommand(new TreeCollapseAllCommand());
285
            }
286
        });
287

    
288
        /**
289
         * Expand button
290
         */
291
        btnExpandAll.setImage(ImageResources.getImage(ImageResources.EXPAND_ALL));
292
        btnExpandAll.setToolTipText("Expand all");
293
        btnExpandAll.addSelectionListener(new SelectionAdapter() {
294
            @Override
295
            public void widgetSelected(SelectionEvent e) {
296
                natTable.doCommand(new TreeExpandAllCommand());
297
            }
298
        });
299

    
300
        /**
301
         * Table state persistence
302
         */
303
        natTableState = new Properties();
304
        //load persisted state
305
        File statePropertiesFile = getStatePropertiesFile();
306
        FileInputStream inputStream;
307
        try {
308
            inputStream = new FileInputStream(statePropertiesFile);
309
            natTableState.load(inputStream);
310
        } catch (IOException e) {
311
            MessagingUtils.info("No initial state properties file found for character matrix");
312
        }
313

    
314
        // create a combobox for showing the available view states
315
        Collection<String> availableStates = PersistenceHelper.getAvailableStates(natTableState);
316
        comboStates.setLabelProvider(new LabelProvider(){
317
            @Override
318
            public String getText(Object element) {
319
                if(element instanceof String && ((String) element).isEmpty()){
320
                    return "-default-";
321
                }
322
                return super.getText(element);
323
            }
324
        });
325
        comboStates.setContentProvider(new ArrayContentProvider());
326
        comboStates.addSelectionChangedListener(e->
327
        {
328
            int index = comboStates.getCombo().getSelectionIndex();
329
            if (index >= 0) {
330
                String selected = comboStates.getCombo().getItem(index);
331
                // load the state
332
                natTable.loadState(selected, natTableState);
333
                natTableState.setProperty(PersistenceDialog.ACTIVE_VIEW_CONFIGURATION_KEY, selected);
334
            }
335
        });
336
        comboStates.setInput(availableStates);
337
        if(comboStates.getCombo().getItemCount()>0){
338
            comboStates.getCombo().select(0);
339
        }
340

    
341
        displayPersistenceDialogCommandHandler = new DisplayPersistenceDialogCommandHandler(natTableState, natTable);
342
        // add listener to update the combo on view state management changes
343
        displayPersistenceDialogCommandHandler.addStateChangeListener(new IStateChangedListener() {
344
            @Override
345
            public void handleStateChange(StateChangeEvent event) {
346
                comboStates.setInput(PersistenceHelper.getAvailableStates(natTableState));
347
                selectStateItem(comboStates, event.getViewConfigName());
348
            }
349
        });
350

    
351
        // add button to show dialog
352
        btnManageState.setImage(ImageResources.getImage(ImageResources.SETTINGS));
353
        btnManageState.setToolTipText("View configuration");
354
        btnManageState.addSelectionListener(new SelectionAdapter() {
355
            @Override
356
            public void widgetSelected(SelectionEvent e) {
357
                natTable.doCommand(new DisplayPersistenceDialogCommand(natTable));
358
                selectStateItem(comboStates, natTableState.get(PersistenceDialog.ACTIVE_VIEW_CONFIGURATION_KEY).toString());
359
            }
360
        });
361

    
362
        /**
363
         * excel export
364
         */
365
        btnExcelExport.setToolTipText("Export to Excel");
366
        btnExcelExport.setImage(ImageResources.getImage(ImageResources.EXPORT));
367
        btnExcelExport.addSelectionListener(new SelectionAdapter() {
368
            @Override
369
            public void widgetSelected(SelectionEvent e) {
370
                natTable.doCommand(
371
                        new ExportCommand(
372
                                natTable.getConfigRegistry(),
373
                                natTable.getShell()));
374
            }
375
        });
376

    
377
        Composite buttonPanel = new Composite(parent, SWT.NONE);
378

    
379
        buttonPanel.setLayout(new RowLayout());
380
        GridDataFactory.fillDefaults().grab(true, false).applyTo(buttonPanel);
381

    
382
        /**
383
         * Add description button
384
         */
385
        Button btnAddDescription = new Button(buttonPanel, SWT.PUSH);
386
        btnAddDescription.setImage(ImageResources.getImage(ImageResources.ADD_ICON));
387
        btnAddDescription.addSelectionListener(new SelectionAdapter() {
388
            @Override
389
            public void widgetSelected(SelectionEvent e) {
390
                SpecimenSelectionDialog dialog = new SpecimenSelectionDialog(natTable.getShell(), CharacterMatrix.this);
391
                if(dialog.open()==Window.OK){
392
                    Collection<SpecimenOrObservationBase> specimens = dialog.getSpecimen();
393
                    boolean hasAdded = false;
394
                    for (SpecimenOrObservationBase specimen : specimens) {
395
                        SpecimenDescription description = getDescriptionForWorkingSet(specimen);
396
                        if(!workingSet.getDescriptions().contains(description)){
397
                            CharacterMatrix.this.descriptions.add(new RowWrapper(description));
398
                            workingSet.addDescription(description);
399
                            hasAdded = true;
400
                        }
401
                    }
402
                    if(hasAdded){
403
                        setDirty();
404
                    }
405
                }
406
            }
407
        });
408

    
409
        applyStyles();
410
    }
411

    
412
    private void applyStyles(){
413
        // NOTE: Getting the colors and fonts from the GUIHelper ensures that
414
        // they are disposed properly (required by SWT)
415
        DefaultNatTableStyleConfiguration natTableConfiguration = new DefaultNatTableStyleConfiguration();
416
        natTableConfiguration.bgColor = GUIHelper.getColor(249, 172, 7);
417
        natTableConfiguration.fgColor = GUIHelper.getColor(30, 76, 19);
418
        natTableConfiguration.hAlign = HorizontalAlignmentEnum.LEFT;
419
        natTableConfiguration.vAlign = VerticalAlignmentEnum.TOP;
420
//        natTableConfiguration.borderStyle = new BorderStyle(1, GUIHelper.getColor(249, 172, 7), LineStyleEnum.SOLID);
421

    
422
        // Setup even odd row colors - row colors override the NatTable default
423
        // colors
424
        DefaultRowStyleConfiguration rowStyleConfiguration = new DefaultRowStyleConfiguration();
425
        rowStyleConfiguration.oddRowBgColor = ColorResources.getColor(Resources.COLOR_LIST_ODD);
426
        rowStyleConfiguration.evenRowBgColor = ColorResources.getColor(Resources.COLOR_LIST_EVEN);
427

    
428
        // Setup selection styling
429
        DefaultSelectionStyleConfiguration selectionStyle = new DefaultSelectionStyleConfiguration();
430
//        selectionStyle.selectionFont = GUIHelper.getFont(new FontData("Verdana", 8, SWT.NORMAL));
431
//        selectionStyle.selectionBgColor = GUIHelper.getColor(217, 232, 251);
432
//        selectionStyle.selectionFgColor = GUIHelper.COLOR_BLACK;
433
//        selectionStyle.anchorBorderStyle = new BorderStyle(1, GUIHelper.COLOR_DARK_GRAY, LineStyleEnum.SOLID);
434
//        selectionStyle.anchorBgColor = GUIHelper.getColor(65, 113, 43);
435
        selectionStyle.selectedHeaderBgColor = GUIHelper.getColor(156, 209, 103);
436

    
437
        // Add all style configurations to NatTable
438
        natTable.addConfiguration(natTableConfiguration);
439
        natTable.addConfiguration(rowStyleConfiguration);
440
        natTable.addConfiguration(selectionStyle);
441

    
442
        // Column/Row header style and custom painters
443
        DefaultRowHeaderStyleConfiguration rowHeaderConfig = new DefaultRowHeaderStyleConfiguration();
444
        Color rowColumnColor = GUIHelper.getColor(230, 255, 255);
445
        rowHeaderConfig.bgColor = rowColumnColor;
446
        natTable.addConfiguration(rowHeaderConfig);
447
        DefaultColumnHeaderStyleConfiguration columnHeaderStyle = new DefaultColumnHeaderStyleConfiguration();
448
        columnHeaderStyle.bgColor = rowColumnColor;
449
        columnHeaderStyle.font = GUIHelper.getFont(new FontData("Verdana", 9, SWT.BOLD));
450
        natTable.addConfiguration(columnHeaderStyle);
451

    
452
    }
453

    
454
    private void toggleTreeFlat(boolean isTree, Button btnToggleFlat, Button btnToggleTree, Button btnCollapseAll, Button btnExpandAll) {
455
        init(workingSet.getUuid(), isTree);
456
        btnToggleFlat.setEnabled(isTree);
457
        btnToggleTree.setEnabled(!isTree);
458
        btnCollapseAll.setEnabled(isTree);
459
        btnExpandAll.setEnabled(isTree);
460
        natTable.doCommand(new ClientAreaResizeCommand(natTable));
461
    }
462

    
463
    public void init(UUID workingSetUuid, boolean treeView) {
464
        if(workingSet==null){
465
            this.workingSet = CdmStore.getService(IWorkingSetService.class).load(workingSetUuid, WS_PROPERTY_PATH);
466
            if(workingSet.getDescriptiveSystem()==null){
467
                MessagingUtils.informationDialog("Editor could not be opened", "The working set has no feature tree selected.");
468
                return;
469
            }
470
            thisPart.setLabel(workingSet.getLabel());
471

    
472
            //get features/columns stored in working set
473
            FeatureTree tree = workingSet.getDescriptiveSystem();
474
            features = new ArrayList<>(tree.getDistinctFeatures());
475
            Collections.sort(features);
476

    
477
            descriptions = GlazedLists.eventList(getDescriptions(workingSet));
478
        }
479
        // use the SortedList constructor with 'null' for the Comparator
480
        // because the Comparator will be set by configuration
481
        SortedList<Object> sortedList = new SortedList<>(descriptions, new MatrixRowComparator());
482
        // wrap the SortedList with the TreeList
483
        TreeList<Object> treeList = new TreeList(sortedList, new DescriptionTreeFormat(workingSet.getMaxRank()), TreeList.NODES_START_EXPANDED);
484
        /**
485
         * data provider
486
         */
487
        SpecimenColumnPropertyAccessor columnPropertyAccessor = new SpecimenColumnPropertyAccessor(this);
488
        bodyDataProvider = treeView?new ListDataProvider<>(treeList, columnPropertyAccessor):new ListDataProvider<>(sortedList, columnPropertyAccessor);
489

    
490
        ConfigRegistry configRegistry = new ConfigRegistry();
491

    
492

    
493
        /**
494
         * BODY layer
495
         *
496
         *
497

    
498
        CompositeLayer
499
         - (top) SummaryRowLayer
500
         - (bottom) ViewportLayer
501

    
502
             ^
503
        ViewportLayer
504

    
505
             ^
506
        TreeLayer (default visible)
507

    
508
             ^
509
        SelectionLayer
510

    
511
             ^
512
        RowHideShowLayer
513

    
514
             ^
515
        ColumnHideShowLayer
516

    
517
             ^
518
        ColumnReorderLayer
519

    
520
             ^
521
        RowReorderLayer
522

    
523
             ^
524
        DataLayer
525

    
526
         *
527

    
528
         */
529
        DataLayer bodyDataLayer = new DataLayer(bodyDataProvider);
530

    
531
        //register labels for columns
532
        ColumnOverrideLabelAccumulator bodyColumnLabelAccumulator =new ColumnOverrideLabelAccumulator(bodyDataLayer);
533
        bodyDataLayer.setConfigLabelAccumulator(bodyColumnLabelAccumulator);
534
        propertyToLabelMap.put(TAXON_COLUMN, "Taxon");
535
        bodyColumnLabelAccumulator.registerColumnOverrides(0, TAXON_COLUMN);
536
        propertyToLabelMap.put(COLLECTOR_COLUMN, "Collector + No");
537
        bodyColumnLabelAccumulator.registerColumnOverrides(1, COLLECTOR_COLUMN);
538
        propertyToLabelMap.put(IDENTIFIER_COLUMN, "Identifier");
539
        bodyColumnLabelAccumulator.registerColumnOverrides(2, IDENTIFIER_COLUMN);
540
        propertyToLabelMap.put(COUNTRY_COLUMN, "Country");
541
        bodyColumnLabelAccumulator.registerColumnOverrides(3, COUNTRY_COLUMN);
542
        for(int i=0;i<features.size();i++){
543
            Feature feature = features.get(i);
544
            initLabels(bodyColumnLabelAccumulator, i, feature);
545
        }
546

    
547
        // layer for event handling of GlazedLists and PropertyChanges
548
        GlazedListsEventLayer eventLayer = new GlazedListsEventLayer<>(bodyDataLayer, treeList);
549
        GlazedListTreeData treeData = new GlazedListTreeData<>(treeList);
550
        ITreeRowModel treeRowModel = new GlazedListTreeRowModel<>(treeData);
551

    
552
        ColumnReorderLayer columnReorderLayer;
553
        ColumnHideShowLayer columnHideShowLayer;
554
        SelectionLayer selectionLayer;
555
        TreeLayer treeLayer;
556
        ViewportLayer viewportLayer;
557
        if(treeView){
558
            columnReorderLayer = new ColumnReorderLayer(eventLayer);
559
            columnHideShowLayer = new ColumnHideShowLayer(columnReorderLayer);
560
            selectionLayer = new SelectionLayer(columnHideShowLayer);
561
            treeLayer = new TreeLayer(selectionLayer, treeRowModel);
562
            viewportLayer = treeView?new ViewportLayer(treeLayer):new ViewportLayer(selectionLayer);
563
        }
564
        else{
565
            RowReorderLayer rowReorderLayer = new RowReorderLayer(eventLayer);
566
            columnReorderLayer = new ColumnReorderLayer(rowReorderLayer);
567
            columnHideShowLayer = new ColumnHideShowLayer(columnReorderLayer);
568
            RowHideShowLayer rowHideShowLayer = new RowHideShowLayer(columnHideShowLayer);
569
            selectionLayer = new SelectionLayer(rowHideShowLayer);
570
            treeLayer = new TreeLayer(selectionLayer, treeRowModel);
571
            viewportLayer = treeView?new ViewportLayer(treeLayer):new ViewportLayer(selectionLayer);
572
        }
573

    
574
        // create a standalone FixedSummaryRowLayer
575
        // since the summary row should be fixed at the top of the body
576
        // region the horizontal dependency of the FixedSummaryRowLayer
577
        // is the ViewportLayer
578
        FixedSummaryRowLayer summaryRowLayer =
579
                new FixedSummaryRowLayer(bodyDataLayer, viewportLayer, configRegistry, false);
580
        //register labels with summary prefix for summary layer
581
        ColumnOverrideLabelAccumulator summaryColumnLabelAccumulator =new ColumnOverrideLabelAccumulator(bodyDataLayer);
582
        summaryRowLayer.setConfigLabelAccumulator(summaryColumnLabelAccumulator);
583
        for(int i=0;i<features.size();i++){
584
            Feature feature = features.get(i);
585
            summaryColumnLabelAccumulator.registerColumnOverrides(
586
                    i+LEADING_COLUMN_COUNT,
587
                    SummaryRowLayer.DEFAULT_SUMMARY_COLUMN_CONFIG_LABEL_PREFIX+MatrixUtility.getProperty(feature));
588
        }
589
        // because the horizontal dependency is the ViewportLayer
590
        // we need to set the composite dependency to false
591
        summaryRowLayer.setHorizontalCompositeDependency(false);
592

    
593
        CompositeLayer composite = new CompositeLayer(1, 2);
594
        composite.setChildLayer("SUMMARY", summaryRowLayer, 0, 0);
595
        composite.setChildLayer(GridRegion.BODY, viewportLayer, 0, 1);
596

    
597

    
598
        /**
599
         * column header layer
600
         */
601
        IDataProvider columnHeaderDataProvider = new DefaultColumnHeaderDataProvider(
602
                propertyToLabelMap.values().toArray(new String[] {}), propertyToLabelMap);
603
        DataLayer columnHeaderDataLayer = new DataLayer(columnHeaderDataProvider);
604
        ColumnHeaderLayer columnHeaderLayer = new ColumnHeaderLayer(columnHeaderDataLayer, viewportLayer, selectionLayer);
605

    
606
        // add the SortHeaderLayer to the column header layer stack
607
        // as we use GlazedLists, we use the GlazedListsSortModel which
608
        // delegates the sorting to the SortedList
609
        final SortHeaderLayer<SpecimenDescription> sortHeaderLayer = new SortHeaderLayer<>(
610
                columnHeaderLayer,
611
                new GlazedListsSortModel<>(
612
                        sortedList,
613
                        columnPropertyAccessor,
614
                        configRegistry,
615
                        columnHeaderDataLayer));
616

    
617

    
618
        /**
619
         * row header layer
620
         */
621
        IDataProvider rowHeaderDataProvider = new DefaultRowHeaderDataProvider(bodyDataProvider);
622
        DefaultRowHeaderDataLayer rowHeaderDataLayer = new DefaultRowHeaderDataLayer(rowHeaderDataProvider);
623
        FixedSummaryRowHeaderLayer fixedSummaryRowHeaderLayer = new FixedSummaryRowHeaderLayer(rowHeaderDataLayer,
624
                composite, selectionLayer);
625
        fixedSummaryRowHeaderLayer.setSummaryRowLabel("\u2211");
626

    
627

    
628
        /**
629
         * corner layer
630
         */
631
        ILayer cornerLayer = new CornerLayer(
632
                new DataLayer(new DefaultCornerDataProvider(columnHeaderDataProvider, rowHeaderDataProvider)),
633
                fixedSummaryRowHeaderLayer, sortHeaderLayer);
634

    
635

    
636
        /**
637
         * GRID layer (composition of all other layers)
638
         */
639
        GridLayer gridLayer = new GridLayer(composite, sortHeaderLayer, fixedSummaryRowHeaderLayer, cornerLayer);
640

    
641
        natTable.setLayer(gridLayer);
642

    
643
        /**
644
         * CONFIGURATION
645
         */
646
        natTable.setConfigRegistry(configRegistry);
647

    
648
        //add default configuration because autoconfigure is set to false in constructor
649
        natTable.addConfiguration(new DefaultNatTableStyleConfiguration());
650

    
651
        //FIXME: this is for DEBUG ONLY
652
        //        natTable.addConfiguration(new DebugMenuConfiguration(natTable));
653

    
654
        // override the default sort configuration and change the mouse bindings
655
        // to sort on a single click
656
        if(!treeView){
657
            natTable.addConfiguration(new SingleClickSortConfiguration());
658
        }
659

    
660
        // add the header menu configuration for adding the column header menu
661
        // with hide/show actions
662
        natTable.addConfiguration(new AbstractHeaderMenuConfiguration(natTable) {
663

    
664
            @Override
665
            protected PopupMenuBuilder createColumnHeaderMenu(NatTable natTable) {
666
                return super.createColumnHeaderMenu(natTable)
667
                        .withHideColumnMenuItem()
668
                        .withShowAllColumnsMenuItem();
669
            }
670

    
671
        });
672

    
673
        Style cellStyle = new Style();
674
        cellStyle.setAttributeValue(CellStyleAttributes.HORIZONTAL_ALIGNMENT, HorizontalAlignmentEnum.LEFT);
675

    
676
        // add custom configuration for data conversion and add column labels to viewport layer
677
        viewportLayer.addConfiguration(new AbstractRegistryConfiguration() {
678
            @Override
679
            public void configureRegistry(IConfigRegistry configRegistry) {
680
                //add display converter for string representation
681
                configRegistry.registerConfigAttribute(
682
                        CellConfigAttributes.DISPLAY_CONVERTER,
683
                        new SupplementalInfoDisplayConverter(),
684
                        DisplayMode.NORMAL,
685
                        TAXON_COLUMN);
686
                configRegistry.registerConfigAttribute(
687
                        CellConfigAttributes.CELL_STYLE,
688
                        cellStyle,
689
                        DisplayMode.NORMAL,
690
                        TAXON_COLUMN);
691
                configRegistry.registerConfigAttribute(
692
                        CellConfigAttributes.DISPLAY_CONVERTER,
693
                        new SupplementalInfoDisplayConverter(),
694
                        DisplayMode.NORMAL,
695
                        COLLECTOR_COLUMN);
696
                configRegistry.registerConfigAttribute(
697
                        CellConfigAttributes.CELL_STYLE,
698
                        cellStyle,
699
                        DisplayMode.NORMAL,
700
                        COLLECTOR_COLUMN);
701
                configRegistry.registerConfigAttribute(
702
                        CellConfigAttributes.DISPLAY_CONVERTER,
703
                        new SupplementalInfoDisplayConverter(),
704
                        DisplayMode.NORMAL,
705
                        IDENTIFIER_COLUMN);
706
                configRegistry.registerConfigAttribute(
707
                        CellConfigAttributes.CELL_STYLE,
708
                        cellStyle,
709
                        DisplayMode.NORMAL,
710
                        IDENTIFIER_COLUMN);
711
                configRegistry.registerConfigAttribute(
712
                        CellConfigAttributes.DISPLAY_CONVERTER,
713
                        new SupplementalInfoDisplayConverter(),
714
                        DisplayMode.NORMAL,
715
                        COUNTRY_COLUMN);
716
                configRegistry.registerConfigAttribute(
717
                        CellConfigAttributes.CELL_STYLE,
718
                        cellStyle,
719
                        DisplayMode.NORMAL,
720
                        COUNTRY_COLUMN);
721
                features.forEach(feature->registerColumnConfiguration(feature, configRegistry));
722
            }
723

    
724
        });
725

    
726
        //register aggregation configuration for each feature
727
        features.forEach(feature->summaryRowLayer.addConfiguration(new AggregationConfiguration(bodyDataProvider, feature)));
728

    
729
        // add the ExportCommandHandler to the ViewportLayer in order to make
730
        // exporting work
731
        viewportLayer.registerCommandHandler(new ExportCommandHandler(viewportLayer));
732

    
733
        //propagate single cell selection
734
        natTable.addLayerListener(new ILayerListener() {
735
            @Override
736
            public void handleLayerEvent(ILayerEvent event) {
737
                if(event instanceof CellSelectionEvent){
738
                    CellSelectionEvent cellSelectionEvent = (CellSelectionEvent)event;
739
                    int columnPosition = cellSelectionEvent.getColumnPosition();
740
                    if(columnPosition>LEADING_COLUMN_COUNT){
741
                        Collection<ILayerCell> selectedCells = cellSelectionEvent.getSelectionLayer().getSelectedCells();
742
                        StructuredSelection selection = new StructuredSelection();
743
                        if(selectedCells.size()==1){
744
                            ILayerCell cell = selectedCells.iterator().next();
745
                            Object dataValue = cell.getDataValue();
746
                            if(dataValue!=null){
747
                                selection = new StructuredSelection(dataValue);
748
                            }
749
                        }
750
                        selService.setSelection(selection);
751
                    }
752
                }
753
            }
754
        });
755

    
756
        //register handler for view configuration menu
757
        natTable.registerCommandHandler(displayPersistenceDialogCommandHandler);
758

    
759
        natTable.configure();
760

    
761
        GridDataFactory.fillDefaults().grab(true, true).applyTo(natTable);
762

    
763
        wsLabel.setText(workingSet.getLabel());
764
        wsLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
765
        wsLabel.getParent().layout();
766

    
767
        parent.layout();
768
    }
769

    
770
    private void selectStateItem(ComboViewer comboStates, String stateName){
771
        String[] items = comboStates.getCombo().getItems();
772
        for(int i=0;i<items.length;i++){
773
            if(items[i].equals(stateName)){
774
                comboStates.getCombo().select(i);
775
                break;
776
            }
777
        }
778
    }
779

    
780
    private SpecimenDescription getDescriptionForWorkingSet(SpecimenOrObservationBase specimen){
781
        Set<Feature> wsFeatures = workingSet.getDescriptiveSystem().getDistinctFeatures();
782
        List<DescriptionElementBase> matchingDescriptionElements = new ArrayList<>();
783

    
784
        for (SpecimenDescription specimenDescription : (Set<SpecimenDescription>) specimen.getDescriptions()) {
785
            Set<Feature> specimenDescriptionFeatures = new HashSet<>();
786
            //gather specimen description features and check for match with WS features
787
            for (DescriptionElementBase specimenDescriptionElement : specimenDescription.getElements()) {
788
                Feature feature = specimenDescriptionElement.getFeature();
789
                specimenDescriptionFeatures.add(feature);
790
                if(wsFeatures.contains(feature)){
791
                    matchingDescriptionElements.add(specimenDescriptionElement);
792
                }
793
            }
794
            //if description with the exact same features is found return the description
795
            if(specimenDescriptionFeatures.equals(wsFeatures)){
796
                return specimenDescription;
797
            }
798
        }
799
        //Create new specimen description if no match was found
800
        setDirty();
801
        SpecimenDescription newDesription = SpecimenDescription.NewInstance(specimen);
802
        newDesription.setTitleCache("WorkingSet "+workingSet.getLabel()+": "+newDesription.generateTitle(), true);
803

    
804
        //check for equals description element (same feature and same values)
805
        Map<Feature, List<DescriptionElementBase>> featureToElementMap = new HashMap<>();
806
        for(DescriptionElementBase element:matchingDescriptionElements){
807
            List<DescriptionElementBase> list = featureToElementMap.get(element.getFeature());
808
            if(list==null){
809
                list = new ArrayList<>();
810
            }
811
            list.add(element);
812
            featureToElementMap.put(element.getFeature(), list);
813
        }
814
        Set<DescriptionElementBase> descriptionElementsToClone = new HashSet<>();
815
        for(Feature feature:featureToElementMap.keySet()){
816
            List<DescriptionElementBase> elements = featureToElementMap.get(feature);
817
            //no duplicate description elements found for this feature
818
            if(elements.size()==1){
819
                descriptionElementsToClone.add(elements.get(0));
820
            }
821
            //duplicates found -> check if all are equal
822
            else{
823
                DescriptionElementBase match = null;
824
                for (DescriptionElementBase descriptionElementBase : elements) {
825
                    if(match==null){
826
                        match = descriptionElementBase;
827
                    }
828
                    else if(!new DescriptionElementCompareWrapper(match).equals(new DescriptionElementCompareWrapper(descriptionElementBase))){
829
                        match = null;
830
                        MessagingUtils.informationDialog("Multiple data found",
831
                                String.format("Multiple description elements with different values "
832
                                        + "found for feature '%s'.\nData will not be copied to new specimen description.", feature.getLabel()));
833
                        break;
834
                    }
835
                }
836
                if(match!=null){
837
                    descriptionElementsToClone.add(match);
838
                }
839
            }
840
        }
841
        //clone matching descriptionElements
842
        for (DescriptionElementBase descriptionElementBase : descriptionElementsToClone) {
843
            DescriptionElementBase clone;
844
            try {
845
                clone = descriptionElementBase.clone(newDesription);
846
                clone.getSources().forEach(source -> source.setOriginalNameString(DescriptionHelper.getLabel(descriptionElementBase)));
847
            } catch (CloneNotSupportedException e) {
848
                MessagingUtils.error(CharacterMatrix.class, e);
849
            }
850
        }
851
        return newDesription;
852

    
853
    }
854

    
855
    private void initLabels(final ColumnOverrideLabelAccumulator columnLabelAccumulator,
856
            int index, Feature feature) {
857

    
858
        columnLabelAccumulator.registerColumnOverrides(index+LEADING_COLUMN_COUNT, MatrixUtility.getProperty(feature));
859
        indexToFeatureMap.put(index+LEADING_COLUMN_COUNT, feature);
860

    
861
        String featureLabel = feature.getLabel();
862
        String property = featureLabel;
863
        //show unit for quantitative data
864
        if(feature.isSupportsQuantitativeData()){
865
            Set<MeasurementUnit> recommendedMeasurementUnits = feature.getRecommendedMeasurementUnits();
866
            if(recommendedMeasurementUnits.size()!=1){
867
                MessagingUtils.warningDialog("Column initialization problem", CharacterMatrix.class,
868
                        String.format("Only one unit is allowed for quantitative data: %s", feature.getLabel()));
869
                return;
870
            }
871
            MeasurementUnit unit = recommendedMeasurementUnits.iterator().next();
872
            featureLabel += " ["+unit.getIdInVocabulary()+"]";
873
        }
874
        propertyToLabelMap.put(property, featureLabel);
875
    }
876

    
877
    private void registerColumnConfiguration(Feature feature, IConfigRegistry configRegistry) {
878
        //make cell editable
879
        configRegistry.registerConfigAttribute(
880
                EditConfigAttributes.CELL_EDITABLE_RULE,
881
                IEditableRule.ALWAYS_EDITABLE,
882
                DisplayMode.EDIT,
883
                MatrixUtility.getProperty(feature)
884
                );
885
        if(feature.isSupportsQuantitativeData()){
886
            //add display converter for string representation
887
            configRegistry.registerConfigAttribute(
888
                    CellConfigAttributes.DISPLAY_CONVERTER,
889
                    new QuantitativeDataDisplayConverter(),
890
                    DisplayMode.NORMAL,
891
                    MatrixUtility.getProperty(feature));
892
            //register quantitative editor
893
            configRegistry.registerConfigAttribute(
894
                    EditConfigAttributes.CELL_EDITOR,
895
                    new QuantitativeDataCellEditor(feature, this),
896
                    DisplayMode.EDIT,
897
                    MatrixUtility.getProperty(feature));
898
        }
899
        else if(feature.isSupportsCategoricalData()){
900
            //add display converter for string representation
901
            configRegistry.registerConfigAttribute(
902
                    CellConfigAttributes.DISPLAY_CONVERTER,
903
                    new CategoricalDataDisplayConverter(),
904
                    DisplayMode.NORMAL,
905
                    MatrixUtility.getProperty(feature));
906

    
907
            //add combo box cell editor
908
            CategoricalDataCellEditor comboBoxCellEditor = new CategoricalDataCellEditor(new IComboBoxDataProvider() {
909

    
910
                @Override
911
                public List<?> getValues(int columnIndex, int rowIndex) {
912
                    List<State> states = new ArrayList<>();
913
                    Feature feature = indexToFeatureMap.get(columnIndex);
914
                    if(feature.isSupportsCategoricalData()){
915
                        Set<TermVocabulary<State>> stateVocs = feature.getSupportedCategoricalEnumerations();
916
                        for (TermVocabulary<State> voc : stateVocs) {
917
                            states.addAll(voc.getTerms());
918
                        }
919
                    }
920
                    return states;
921
                }
922
            }, 5, this, feature);
923
            //register editor
924
            configRegistry.registerConfigAttribute(EditConfigAttributes.CELL_EDITOR,
925
                    comboBoxCellEditor,
926
                    DisplayMode.EDIT,
927
                    MatrixUtility.getProperty(feature));
928

    
929
        }
930

    
931
    }
932

    
933
    private List<RowWrapper> getDescriptions(WorkingSet workingSet) {
934
        List<RowWrapper> rowWrappers = new ArrayList<>();
935
        Set<DescriptionBase> wsDescriptions = workingSet.getDescriptions();
936
        for (DescriptionBase descriptionBase : wsDescriptions) {
937
            if(descriptionBase instanceof SpecimenDescription){
938
                rowWrappers.add(new RowWrapper((SpecimenDescription) descriptionBase));
939
            }
940
        }
941
        return rowWrappers;
942
    }
943

    
944
    public Map<Integer, Feature> getIndexToFeatureMap() {
945
        return indexToFeatureMap;
946
    }
947

    
948
    public LinkedMap<String, String> getPropertyToLabelMap() {
949
        return propertyToLabelMap;
950
    }
951

    
952
    public void setDirty() {
953
        this.dirty.setDirty(true);
954
    }
955

    
956
    public NatTable getNatTable() {
957
        return natTable;
958
    }
959

    
960
    public WorkingSet getWorkingSet() {
961
        return workingSet;
962
    }
963

    
964
    public Collection<SpecimenOrObservationBase> getSpecimenCache() {
965
        return specimenCache;
966
    }
967

    
968
    public void setSpecimenCache(Collection<SpecimenOrObservationBase> specimenCache) {
969
        this.specimenCache = specimenCache;
970
    }
971

    
972
    /**
973
     * @return the bodyDataProvider
974
     */
975
    public ListDataProvider<Object> getBodyDataProvider() {
976
        return bodyDataProvider;
977
    }
978

    
979
    @Persist
980
    @Override
981
    public void save(IProgressMonitor monitor) {
982
        CdmStore.getService(IWorkingSetService.class).merge(workingSet, true);
983
        conversation.commit();
984
        dirty.setDirty(false);
985
    }
986

    
987
    @Focus
988
    public void setFocus(){
989
        if(conversation!=null){
990
            conversation.bind();
991
        }
992
        if(cdmEntitySession != null) {
993
            cdmEntitySession.bind();
994
        }
995
    }
996

    
997
    @PreDestroy
998
    public void dispose(){
999
        if (conversation != null) {
1000
            conversation.close();
1001
            conversation = null;
1002
        }
1003
        if(cdmEntitySession != null) {
1004
            cdmEntitySession.dispose();
1005
            cdmEntitySession = null;
1006
        }
1007
        dirty.setDirty(false);
1008
        if(natTableState!=null){
1009
            try (FileOutputStream tableStateStream =
1010
                    new FileOutputStream(getStatePropertiesFile())) {
1011
                natTableState.store(tableStateStream, null);
1012
            } catch (IOException ioe) {
1013
                ioe.printStackTrace();
1014
            }
1015
        }
1016
    }
1017

    
1018
    private File getStatePropertiesFile() {
1019
        return new File(WorkbenchUtility.getBaseLocation(), CHARACTER_MATRIX_STATE_PROPERTIES);
1020
    }
1021

    
1022
    /**
1023
     * {@inheritDoc}
1024
     */
1025
    @Override
1026
    public void update(CdmDataChangeMap arg0) {
1027
    }
1028

    
1029
    /**
1030
     * {@inheritDoc}
1031
     */
1032
    @Override
1033
    public ConversationHolder getConversationHolder() {
1034
        return conversation;
1035
    }
1036

    
1037
    /**
1038
     * {@inheritDoc}
1039
     */
1040
    @Override
1041
    public void changed(Object element) {
1042
        setDirty();
1043
        natTable.refresh();
1044
    }
1045

    
1046
    /**
1047
     * {@inheritDoc}
1048
     */
1049
    @Override
1050
    public void forceDirty() {
1051
        setDirty();
1052
    }
1053

    
1054

    
1055
    /**
1056
     * {@inheritDoc}
1057
     */
1058
    @Override
1059
    public ICdmEntitySession getCdmEntitySession() {
1060
        return cdmEntitySession;
1061
    }
1062

    
1063

    
1064
    /**
1065
     * {@inheritDoc}
1066
     */
1067
    @Override
1068
    public Collection<WorkingSet> getRootEntities() {
1069
        return Collections.singleton(this.workingSet);
1070
    }
1071

    
1072

    
1073
    /**
1074
     * {@inheritDoc}
1075
     */
1076
    @Override
1077
    public Map<Object, List<String>> getPropertyPathsMap() {
1078
        Map<Object, List<String>> propertyMap = new HashMap<>();
1079
        propertyMap.put(SpecimenOrObservationBase.class,WS_PROPERTY_PATH);
1080
        return propertyMap;
1081
    }
1082

    
1083
}
(2-2/11)