Project

General

Profile

Download (74.7 KB) Statistics
| Branch: | Tag: | Revision:
1
/**
2
 * Copyright (C) 2007 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

    
10
package eu.etaxonomy.taxeditor.preference;
11

    
12
import java.io.File;
13
import java.io.FileInputStream;
14
import java.io.FileOutputStream;
15
import java.io.IOException;
16
import java.net.URI;
17
import java.net.URISyntaxException;
18
import java.util.ArrayList;
19
import java.util.Arrays;
20
import java.util.Collections;
21
import java.util.HashMap;
22
import java.util.List;
23
import java.util.Map;
24
import java.util.Properties;
25
import java.util.Set;
26
import java.util.StringTokenizer;
27
import java.util.UUID;
28

    
29
import org.apache.commons.lang.StringUtils;
30
import org.apache.log4j.Logger;
31
import org.eclipse.core.runtime.preferences.ConfigurationScope;
32
import org.eclipse.core.runtime.preferences.IEclipsePreferences;
33
import org.eclipse.equinox.internal.p2.ui.model.MetadataRepositoryElement;
34
import org.eclipse.jface.preference.IPreferenceStore;
35
import org.eclipse.jface.window.Window;
36
import org.eclipse.swt.widgets.Composite;
37
import org.eclipse.swt.widgets.Control;
38
import org.eclipse.swt.widgets.Shell;
39
import org.eclipse.ui.PlatformUI;
40
import org.osgi.service.prefs.BackingStoreException;
41
import org.osgi.service.prefs.Preferences;
42

    
43
import eu.etaxonomy.cdm.api.application.ICdmRepository;
44
import eu.etaxonomy.cdm.api.facade.DerivedUnitFacadeConfigurator;
45
import eu.etaxonomy.cdm.api.service.ITermService;
46
import eu.etaxonomy.cdm.api.service.ITermTreeService;
47
import eu.etaxonomy.cdm.api.service.IVocabularyService;
48
import eu.etaxonomy.cdm.api.service.config.FindTaxaAndNamesConfiguratorImpl;
49
import eu.etaxonomy.cdm.api.service.config.IFindTaxaAndNamesConfigurator;
50
import eu.etaxonomy.cdm.common.CdmUtils;
51
import eu.etaxonomy.cdm.hibernate.HibernateProxyHelper;
52
import eu.etaxonomy.cdm.io.specimen.abcd206.in.Abcd206ImportConfigurator;
53
import eu.etaxonomy.cdm.model.common.ICdmBase;
54
import eu.etaxonomy.cdm.model.common.Language;
55
import eu.etaxonomy.cdm.model.common.MarkerType;
56
import eu.etaxonomy.cdm.model.description.Feature;
57
import eu.etaxonomy.cdm.model.metadata.CdmPreference;
58
import eu.etaxonomy.cdm.model.metadata.CdmPreference.PrefKey;
59
import eu.etaxonomy.cdm.model.metadata.IPreferencePredicate;
60
import eu.etaxonomy.cdm.model.metadata.PreferencePredicate;
61
import eu.etaxonomy.cdm.model.metadata.PreferenceSubject;
62
import eu.etaxonomy.cdm.model.metadata.TermDisplayEnum;
63
import eu.etaxonomy.cdm.model.metadata.TermOrder;
64
import eu.etaxonomy.cdm.model.name.NomenclaturalCode;
65
import eu.etaxonomy.cdm.model.term.IDefinedTerm;
66
import eu.etaxonomy.cdm.model.term.ISimpleTerm;
67
import eu.etaxonomy.cdm.model.term.TermBase;
68
import eu.etaxonomy.cdm.model.term.TermTree;
69
import eu.etaxonomy.cdm.model.term.TermType;
70
import eu.etaxonomy.cdm.model.term.TermVocabulary;
71
import eu.etaxonomy.cdm.model.term.VocabularyEnum;
72
import eu.etaxonomy.cdm.strategy.match.DefaultMatchStrategy;
73
import eu.etaxonomy.cdm.strategy.match.FieldMatcher;
74
import eu.etaxonomy.cdm.strategy.match.IMatchStrategy;
75
import eu.etaxonomy.cdm.strategy.match.MatchException;
76
import eu.etaxonomy.cdm.strategy.match.MatchMode;
77
import eu.etaxonomy.taxeditor.editor.definedterm.input.TermEditorInput;
78
import eu.etaxonomy.taxeditor.model.AbstractUtility;
79
import eu.etaxonomy.taxeditor.model.MessagingUtils;
80
import eu.etaxonomy.taxeditor.model.NomenclaturalCodeHelper;
81
import eu.etaxonomy.taxeditor.remoting.source.CdmRemoteSource;
82
import eu.etaxonomy.taxeditor.store.CdmStore;
83
import eu.etaxonomy.taxeditor.store.TermStore;
84
import eu.etaxonomy.taxeditor.store.internal.TaxeditorStorePlugin;
85
import eu.etaxonomy.taxeditor.ui.dialog.DefaultLanguageDialog;
86

    
87
/**
88
 * <p>
89
 * PreferencesUtil class.
90
 * </p>
91
 *
92
 * @author p.ciardelli
93
 * @author n.hoffmann
94
 * @created 05.12.2008
95
 */
96
public class PreferencesUtil implements IPreferenceKeys {
97
    private final static String EDITOR_PREFERENCES_NODE = "eu.etaxonomy.taxeditor";
98

    
99
    public static final String PREFERRED_TERMS_CHANGE = "preferred_terms";
100

    
101
    public static final String P2_REPOSITORIES_DELIM = ",";
102
    public static final String P2_REPOSITORY_FIELDS_DELIM = ";";
103
    public static final String SUBJECT_DELIM = "/";
104

    
105
    private static TermTree<Feature> preferredNameFeatureTree;
106

    
107
    private static TermTree<Feature> preferredTaxonFeatureTree;
108

    
109
    private final static Logger logger = Logger.getLogger(PreferencesUtil.class);
110

    
111
    public static IPreferenceStore getPreferenceStore() {
112
       return TaxeditorStorePlugin.getDefault().getPreferenceStore();
113
    }
114

    
115
    public static String[] extractSubjectParts(String subject){
116
       String[] result = subject.split("/");
117
       return result;
118
    }
119

    
120
    public static IEclipsePreferences getEditorPreferences(){
121
        return ConfigurationScope.INSTANCE.getNode(EDITOR_PREFERENCES_NODE);
122
    }
123

    
124
    public static String getPreferenceValue(PrefKey prefKey){
125
        try {
126
            if(getEditorPreferences().nodeExists(prefKey.getPredicate())){
127
                Preferences predicateNode = getEditorPreferences().node(prefKey.getPredicate());
128
                String[] splittedSubject = extractSubjectParts(prefKey.getSubject());
129
                String value = predicateNode.get(splittedSubject[splittedSubject.length-1], PreferencePredicate.getByKey(prefKey.getPredicate()).getDefaultValue() != null? PreferencePredicate.getByKey(prefKey.getPredicate()).getDefaultValue().toString(): "");
130
                int index = splittedSubject.length -2;
131
                while (value != null && index >= 0){
132
                   value = predicateNode.get(splittedSubject[index], prefKey.getPredicate());
133
                   index--;
134
                }
135
                return value;
136
            }
137

    
138
        } catch (BackingStoreException e) {
139
            // TODO Auto-generated catch block
140
            e.printStackTrace();
141
        }
142
        return null;
143
    }
144

    
145
    public static List<CdmPreference> getPreference(PreferencePredicate prefPredicate){
146
        try {
147
            List<CdmPreference> prefs = new ArrayList();
148
            CdmPreference pref;
149
            PreferenceSubject subject;
150
            if(getEditorPreferences().nodeExists(prefPredicate.getKey())){
151
                Preferences predicateNode = getEditorPreferences().node(prefPredicate.getKey());
152
                for (String childName: predicateNode.childrenNames()){
153
                    Preferences child = predicateNode.node(childName);
154
                    String subjectString = "";
155
                    subjectString = createSubjectStringForChildNodes(childName, child);
156
                    String value = child.get(subjectString, "");
157
                    subject = PreferenceSubject.NewInstance(subjectString);
158
                    pref = CdmPreference.NewInstance(subject, prefPredicate, value);
159
                    prefs.add(pref);
160
                }
161

    
162
            }
163

    
164
        } catch (BackingStoreException e) {
165
            // TODO Auto-generated catch block
166
            e.printStackTrace();
167
        }
168
        return null;
169
    }
170

    
171
    /**
172
     * @param childName
173
     * @param child
174
     */
175
    private static String createSubjectStringForChildNodes(String subject, Preferences parent) {
176
        try {
177
            for (String childName: parent.childrenNames()){
178
                subject = childName+SUBJECT_DELIM+subject;
179
                Preferences child = parent.node(childName);
180
                createSubjectStringForChildNodes(subject, child);
181
            }
182
        } catch (BackingStoreException e) {
183
            // TODO Auto-generated catch block
184
            e.printStackTrace();
185
        }
186
        return subject;
187

    
188
    }
189

    
190
    private static String prefKey(String name) {
191
        return name + "_"+  ((CdmRemoteSource)CdmStore.getActiveCdmSource()).toString();
192
    }
193

    
194
    public static String prefOverrideKey(String name) {
195
        return name + "_OVERRIDE_";
196
    }
197

    
198
    public static void setStringValue(String name, String value) {
199
        if (value != null){
200
            getPreferenceStore().setValue(prefKey(name), value);
201
        }else{
202
            getPreferenceStore().setToDefault(name);
203
        }
204
    }
205

    
206
    public static void setIntValue(String name, int value) {
207
        getPreferenceStore().setValue(prefKey(name), value);
208
    }
209

    
210
    public static void setBooleanValue(String name, boolean value) {
211
        getPreferenceStore().setValue(prefKey(name), value);
212
    }
213

    
214
    public static void setDoubleValue(String name, double value) {
215
        getPreferenceStore().setValue(prefKey(name), value);
216
    }
217

    
218
    public static void setFloatValue(String name, float value) {
219
        getPreferenceStore().setValue(prefKey(name), value);
220
    }
221

    
222
    public static void setLongValue(String name, long value) {
223
        getPreferenceStore().setValue(prefKey(name), value);
224
    }
225

    
226
    public static String getStringValue(String name, boolean local) {
227

    
228
        CdmPreference pref = getDBPreferenceValue(name);
229
        String prefValue = null;
230
        String overrideKey =  createPreferenceString(createOverridePreferenceString(name));
231
        boolean override = getPreferenceStore().getBoolean(overrideKey);
232

    
233
        if (local || pref == null || (pref != null && pref.isAllowOverride() && override)){
234
            String dbSpecific = prefKey(name);
235
            if (getPreferenceStore().contains(dbSpecific)){
236
                prefValue = getPreferenceStore().getString(dbSpecific);
237
            }else{
238
                prefValue = getPreferenceStore().
239
                        getString(name);
240
            }
241
       }else if (pref != null){
242
           prefValue = pref.getValue();
243
       }
244
        return prefValue;
245

    
246
    }
247

    
248
    public static String getStringValue(String name){
249
        return getStringValue(name, false);
250
    }
251

    
252
    private static CdmPreference getDBPreferenceValue(String name) {
253
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
254
        CdmPreference pref = null;
255
//
256
        pref = cache.get(name);
257
//        if (pref == null ){
258
//            //get default value for Predicate
259
//            IPreferencePredicate pred = PreferencePredicate.getByKey(name);
260
//            if (pred != null){
261
//                if (pred.getDefaultValue() != null){
262
//                    pref = CdmPreference.NewTaxEditorInstance(pred, pred.getDefaultValue().toString());
263
//                }else{
264
//                    pref = CdmPreference.NewTaxEditorInstance(pred, null);
265
//                }
266
//                pref.setAllowOverride(true);
267
//            }
268
//        }
269
        return pref;
270
    }
271

    
272
    public static int getIntValue(String name, boolean local) {
273
        CdmPreference pref= getDBPreferenceValue(name);
274
        String prefValue = null;
275
        if (pref != null){
276
            prefValue = pref.getValue();
277
        }
278
        Integer result = null;
279
        try{
280
            result = Integer.parseInt(prefValue);
281
        }catch(NumberFormatException e){
282
            logger.debug("Preference value of " + name + " is not a number");
283
        }
284

    
285
        String overrideKey =  createPreferenceString(createOverridePreferenceString(name));
286
        boolean override = true;
287
        if (getPreferenceStore().contains(overrideKey)){
288
            override = getPreferenceStore().getBoolean(overrideKey);
289
        }
290
        if (local || pref == null || (pref != null && pref.isAllowOverride() && override)){
291
            String dbSpecific = prefKey(name);
292
            if (getPreferenceStore().contains(dbSpecific)){
293
                result = getPreferenceStore().getInt(dbSpecific);
294
            }else{
295
                result =  getPreferenceStore().
296
                        getInt(name);
297
            }
298
        }
299
        return result;
300

    
301
    }
302

    
303
    public static boolean getBooleanValue(String name) {
304
        Boolean result = getBooleanValue(name, false);
305
        if (result == null){
306
            return false;
307
        }else{
308
            return result;
309
        }
310

    
311
    }
312

    
313
    public static Boolean getBooleanValue(String name, boolean local) {
314
        if (CdmStore.isActive()){
315
            CdmPreference pref = getDBPreferenceValue(name);
316

    
317
            String overrideKey =  createPreferenceString(createOverridePreferenceString(name));
318
            boolean override = getPreferenceStore().getBoolean(overrideKey);
319

    
320
            if (local || pref == null || (pref != null && pref.isAllowOverride() && override)){
321
                String dbSpecific = prefKey(name);
322
                if (getPreferenceStore().contains(dbSpecific)){
323
                    return getPreferenceStore().getBoolean(dbSpecific);
324
                }else{
325
                    return null;
326
                }
327
             }else{
328
                return Boolean.valueOf(pref.getValue());
329
            }
330

    
331
        }else{
332
            return getPreferenceStore().getBoolean(name);
333
        }
334

    
335
    }
336

    
337
    public static double getDoubleValue(String name) {
338
        CdmPreference pref = getDBPreferenceValue(name);
339
        String prefValue = null;
340
        if (pref != null){
341
            prefValue = pref.getValue();
342
        }
343
        Double result = null;
344
        try{
345
            result = Double.parseDouble(prefValue);
346
        }catch(NumberFormatException e){
347
            logger.debug("Preference value of " + name + " is not a number");
348
        }
349
        if (result == null){
350
            String dbSpecific = prefKey(name);
351
            if (getPreferenceStore().contains(dbSpecific)){
352
                result = getPreferenceStore().getDouble(dbSpecific);
353
            }else{
354
                result =  getPreferenceStore().
355
                        getDouble(name);
356
            }
357
        }
358
        return result;
359

    
360
    }
361

    
362
    public static float getFloatValue(String name, boolean local) {
363
        CdmPreference pref = getDBPreferenceValue(name);
364
        String prefValue = null;
365
        if (pref != null){
366
            prefValue = pref.getValue();
367
        }
368
        Float result = null;
369
        try{
370
            result = Float.parseFloat(prefValue);
371
        }catch(NumberFormatException e){
372
            logger.debug("Preference value of " + name + " is not a number");
373
        }
374
        String overrideKey =  createPreferenceString(createOverridePreferenceString(name));
375
        boolean override = true;
376
        if (getPreferenceStore().contains(overrideKey)){
377
            override = getPreferenceStore().getBoolean(overrideKey);
378
        }
379
        if (local || pref == null || (pref != null && pref.isAllowOverride() && override)){
380
            String dbSpecific = prefKey(name);
381
            if (getPreferenceStore().contains(dbSpecific)){
382
                result = getPreferenceStore().getFloat(dbSpecific);
383
            }else{
384
                result =  getPreferenceStore().
385
                        getFloat(name);
386
            }
387
        }
388
        return result;
389

    
390
    }
391

    
392
    public static long getLongValue(String name) {
393
        CdmPreference pref = getDBPreferenceValue(name);
394
        String prefValue = null;
395
        if (pref != null){
396
            prefValue = pref.getValue();
397
        }
398
        Long result = null;
399
        try{
400
            result = Long.parseLong(prefValue);
401
        }catch(NumberFormatException e){
402
            logger.debug("Preference value of " + name + " is not a number");
403
        }
404
        if (result == null){
405
            String dbSpecific = prefKey(name);
406
            if (getPreferenceStore().contains(dbSpecific)){
407
                result = getPreferenceStore().getLong(dbSpecific);
408
            }else{
409
                result =  getPreferenceStore().
410
                        getLong(name);
411
            }
412
        }
413
        return result;
414
    }
415

    
416
    public static CdmPreference setPreferredNomenclaturalCode(
417
            String preferenceValue, boolean local) {
418
        if (local){
419
            setStringValue(PREFERRED_NOMENCLATURAL_CODE_KEY,
420
                    preferenceValue);
421
        }
422
        else{
423
            ICdmRepository controller;
424
            controller = CdmStore.getCurrentApplicationConfiguration();
425
            if (controller == null){
426
                return null;
427
            }
428
            PrefKey key = null;
429
            try{
430
                key = CdmPreference.NewKey(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.NomenclaturalCode);
431
            }catch (Exception e){
432
                System.out.println(e.getStackTrace());
433
            }
434
            CdmPreference preference = null;
435

    
436
            if (preferenceValue == null){
437
                preference = controller.getPreferenceService().find(key);
438
                if (preference == null){
439
                    return null;
440
                } else{
441
                    setStringValue(PREFERRED_NOMENCLATURAL_CODE_KEY,
442
                            preference.getValue());
443

    
444
                    return preference;
445
                }
446
            } else{
447
                preference = CdmPreference.NewInstance(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.NomenclaturalCode, preferenceValue);
448
                controller.getPreferenceService().set(preference);
449

    
450
            }
451
        }
452
        return null;
453

    
454

    
455

    
456
    }
457

    
458
    public static void setPreferredNomenclaturalCode(
459
        CdmPreference preference) {
460

    
461
        ICdmRepository controller;
462
        controller = CdmStore.getCurrentApplicationConfiguration();
463
        if (controller == null){
464
            return;
465
        }
466

    
467
        if (preference == null){
468
            PrefKey key = null;
469
              try{
470
                  key = CdmPreference.NewKey(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.NomenclaturalCode);
471
              }catch (Exception e){
472
                  System.out.println(e.getStackTrace());
473
              }
474
            controller.getPreferenceService().remove(key);
475
        }else{
476
            controller.getPreferenceService().set(preference);
477
        }
478

    
479
    }
480

    
481
    public static NomenclaturalCode getPreferredNomenclaturalCode() {
482

    
483
        CdmPreference pref = getPreferenceFromDB(PreferencePredicate.NomenclaturalCode);
484

    
485

    
486
        String preferredCode;
487
        if(pref == null || (pref.isAllowOverride() && getBooleanValue(prefOverrideKey(PreferencePredicate.NomenclaturalCode.getKey())))){
488
            preferredCode = getStringValue(
489
                    PreferencePredicate.NomenclaturalCode.getKey());
490

    
491
        }else{
492
            preferredCode = pref.getValue();
493
        }
494
        if (StringUtils.isBlank(preferredCode)){
495
            preferredCode = getPreferenceKey((NomenclaturalCode)PreferencePredicate.NomenclaturalCode.getDefaultValue());
496
        }
497

    
498
        return getPreferredNomenclaturalCode(preferredCode);
499

    
500
    }
501

    
502
    public static NomenclaturalCode getPreferredNomenclaturalCode(String preferenceKeyNomenclaturalCode) {
503

    
504
        for (NomenclaturalCode code : NomenclaturalCodeHelper.getAllCodes()) {
505
            if (getPreferenceKey(code).equals(preferenceKeyNomenclaturalCode) || code.getKey().equals(preferenceKeyNomenclaturalCode)) {
506
                return code;
507
            }
508
        }
509
        return null;
510
    }
511

    
512
    public static boolean isShowTaxonAssociations(){
513
        boolean result = getBooleanValue(PreferencePredicate.ShowTaxonAssociations.getKey());
514
        return result;
515
    }
516

    
517
    public static boolean isShowLifeForm(){
518
        boolean result =  getBooleanValue(PreferencePredicate.ShowLifeForm.getKey());
519
        return result;
520
    }
521

    
522
    public static boolean isDeterminationOnlyForFieldUnits(){
523
        boolean result =  getBooleanValue(PreferencePredicate.DeterminationOnlyForFieldUnits.getKey());
524
        return result;
525
    }
526

    
527
    public static boolean isCollectingAreaInGeneralSection(){
528
        boolean result =  getBooleanValue(PreferencePredicate.ShowCollectingAreasInGeneralSection.getKey());
529
        return result;
530
    }
531

    
532
    public static CdmPreference getPreferenceFromDB(IPreferencePredicate predicate){
533
        ICdmRepository controller;
534
        CdmPreference pref = null;
535

    
536
        try{
537
            if(CdmStore.isActive()){
538
                controller = CdmStore.getCurrentApplicationConfiguration();
539
                PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), predicate);
540
                pref = controller.getPreferenceService().find(key);
541
            }
542
        }catch(Exception e){
543
            e.printStackTrace();
544
        }
545

    
546
        return pref;
547

    
548
    }
549

    
550
    public static List<CdmPreference> getPreferencesFromDB(IPreferencePredicate predicate){
551
        ICdmRepository controller;
552
        List<CdmPreference> prefs = null;
553

    
554
        try{
555
            if(CdmStore.isActive()){
556
                controller = CdmStore.getCurrentApplicationConfiguration();
557
                PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), predicate);
558
                prefs = controller.getPreferenceService().list(predicate);
559
            }
560
        }catch(Exception e){
561
            e.printStackTrace();
562
        }
563

    
564
        return prefs;
565

    
566
    }
567

    
568
    public static void setPreferencesToDB(CdmPreference preference, boolean setDefault){
569
        ICdmRepository controller;
570
        try{
571
            if(CdmStore.isActive()){
572
                controller = CdmStore.getCurrentApplicationConfiguration();
573

    
574
                if (setDefault){
575
                    controller.getPreferenceService().remove(preference.getKey());
576
                }else{
577
                    controller.getPreferenceService().set(preference);
578
                }
579
            }
580
        }catch(Exception e){
581
            e.printStackTrace();
582
        }
583

    
584

    
585

    
586
    }
587

    
588
    public static CdmPreference getPreferenceFromDB(PrefKey key){
589
        ICdmRepository controller;
590
        CdmPreference pref = null;
591

    
592
        try{
593
            if(CdmStore.isActive()){
594
                controller = CdmStore.getCurrentApplicationConfiguration();
595
                pref = controller.getPreferenceService().find(key);
596
            }
597
        }catch(Exception e){
598
            e.printStackTrace();
599
        }
600

    
601
        return pref;
602

    
603
    }
604

    
605
    public static void setPreferenceToDB(CdmPreference preference){
606
        ICdmRepository controller;
607
        try{
608
            if(CdmStore.isActive()){
609
                controller = CdmStore.getCurrentApplicationConfiguration();
610
                if (preference.getValue() == null && preference.isAllowOverride()){
611
                    controller.getPreferenceService().remove(preference.getKey());
612
                }else{
613
                    controller.getPreferenceService().set(preference);
614
                }
615
                CdmPreferenceCache.instance().put(preference);
616
            }
617
        }catch(Exception e){
618
            e.printStackTrace();
619
        }
620

    
621
    }
622

    
623
    public static String getPreferredDefaultLangugae(){
624
        String preferredLanguage = getStringValue(DEFAULT_LANGUAGE_EDITOR);
625
        if(StringUtils.isNotEmpty(preferredLanguage) && StringUtils.isNotBlank(preferredLanguage)){
626
            return preferredLanguage;
627
        }
628
        return null;
629
    }
630

    
631
    public static boolean isShowMediaPreview(){
632
        boolean isShowMediaPreview = getBooleanValue(SHOW_MEDIA_PREVIEW);
633
        return isShowMediaPreview;
634
    }
635

    
636
    /**
637
     * Get the match strategy for the given class that was stored in preferences
638
     * or the default strategy if it was not stored in preferences
639
     *
640
     * @param clazz
641
     *            a {@link java.lang.Class} object.
642
     * @return a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy} object.
643
     */
644
    public static IMatchStrategy getMatchStrategy(Class<?> clazz) {
645
        String className = clazz.getName();
646
        if (getBooleanValue(MATCH_STRATEGY_PREFIX + className)) {
647
            IMatchStrategy matchStrategy = getDefaultMatchStrategy(clazz);
648

    
649
            //TODO CacheMatchers (or multiple field matchers in future) are missing here
650
            for (FieldMatcher fieldMatcher : matchStrategy.getMatching().getFieldMatchers(false)) {
651
                String fieldName = fieldMatcher.getPropertyName();
652
                String matchModeName = getStringValue(
653
                        getMatchStrategyFieldName(className, fieldName));
654
                MatchMode matchMode = MatchMode.valueOf(matchModeName);
655
                try {
656
                    matchStrategy.setMatchMode(fieldName, matchMode);
657
                } catch (MatchException e) {
658
                    MessagingUtils.error(PreferencesUtil.class, e);
659
                    throw new RuntimeException(e);
660
                }
661
            }
662

    
663
            return matchStrategy;
664
        }
665
        return getDefaultMatchStrategy(clazz);
666
    }
667

    
668
    /**
669
     * Stores a matchStrategy into the preference store.
670
     *
671
     * @param matchStrategy
672
     *            a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy}
673
     *            object.
674
     */
675
    public static void setMatchStrategy(IMatchStrategy matchStrategy) {
676
        String className = "ANY class"; //FIXME was: matchStrategy.getMatchClass().getName(); seems currently not in use
677
        setBooleanValue(MATCH_STRATEGY_PREFIX + className, true);
678

    
679
        List<FieldMatcher> fieldMatchers = matchStrategy.getMatching().getFieldMatchers(false);
680

    
681
        for (FieldMatcher fieldMatcher : fieldMatchers) {
682
            String fieldName = fieldMatcher.getPropertyName();
683
            setStringValue(
684
                    getMatchStrategyFieldName(className, fieldName),
685
                    fieldMatcher.getMatchMode().name());
686
        }
687
    }
688

    
689
    /**
690
     * Helper method to create the preference property for a match field.
691
     *
692
     * @param className
693
     * @param fieldName
694
     * @return
695
     */
696
    private static String getMatchStrategyFieldName(String className,
697
            String fieldName) {
698
        return MATCH_STRATEGY_PREFIX + className + "." + fieldName;
699
    }
700

    
701
    /**
702
     * Returns the default match strategy for a given class.
703
     *
704
     * @param clazz
705
     *            a {@link java.lang.Class} object.
706
     * @return a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy} object.
707
     */
708
    public static IMatchStrategy getDefaultMatchStrategy(Class clazz) {
709
        return DefaultMatchStrategy.NewInstance(clazz);
710
    }
711

    
712
    public static String getDateFormatPattern() {
713
        // TODO make this configurable in properties
714
        String pattern = "Y-M-d H:m";
715
        return pattern;
716
    }
717

    
718
    public static <T extends TermBase> void addTermToPreferredTerms(T term) {
719

    
720
        // VocabularyEnum vocabulary =
721
        // VocabularyEnum.getVocabularyEnum(term.getClass());
722
        //
723
        // getPreferenceStore().setValue(getPreferenceKey(term),
724
        // VocabularyStore.getTermVocabulary(vocabulary).getTerms().contains(term));
725
        //
726
        // firePreferencesChanged(term.getClass());
727
    }
728

    
729
    /**
730
     * Construct a unique key using the CdmBase object's uuid
731
     *
732
     * @param cdmBase
733
     * @return
734
     */
735
    private static String getPreferenceKey(ICdmBase cdmBase) {
736
        cdmBase = HibernateProxyHelper.deproxy(cdmBase);
737

    
738
        String key = cdmBase.getClass().getName().concat(".")
739
                .concat(cdmBase.getUuid().toString());
740
        if (key.contains("javassist")) {
741
            MessagingUtils.info("proxy");
742
        }
743
        return key;
744
    }
745

    
746
    /**
747
     * Construct a unique key using the CdmBase object's uuid
748
     *
749
     * @param cdmBase
750
     * @return
751
     */
752
    public static String getPreferenceKey(ISimpleTerm simpleTerm) {
753
        simpleTerm = HibernateProxyHelper.deproxy(simpleTerm);
754
        String key = simpleTerm.getClass().getName().concat(".")
755
                .concat(simpleTerm.getUuid().toString());
756
        if (key.contains("javassist")) {
757
            MessagingUtils.warn(PreferencesUtil.class,
758
                    "Trying to persist a preference based on a proxy class.");
759
        }
760
        return key;
761
    }
762

    
763

    
764

    
765
    /**
766
     * Construct a unique key using the CdmBase object's uuid
767
     *
768
     * @param cdmBase
769
     * @return
770
     */
771
    public static String getPreferenceKey(IDefinedTerm definedTerm) {
772
        definedTerm = HibernateProxyHelper.deproxy(definedTerm);
773
        String key = definedTerm.getClass().getName().concat(".")
774
                .concat(definedTerm.getUuid().toString());
775
        if (key.contains("javassist")) {
776
            MessagingUtils.warn(PreferencesUtil.class,
777
                    "Trying to persist a preference based on a proxy class.");
778
        }
779
        return key;
780
    }
781

    
782
    /**
783
     * Retrieves search preferences from the preference store
784
     *
785
     * @return an {@link ITaxonServiceConfigurator} to pass to search methods
786
     */
787
    public static IFindTaxaAndNamesConfigurator getSearchConfigurator() {
788
        IFindTaxaAndNamesConfigurator configurator = initializeSearchConfigurator();
789

    
790
        configurator.setDoTaxa(getBooleanValue(
791
                TAXON_SERVICE_CONFIGURATOR_TAXA));
792
        configurator.setDoSynonyms(getBooleanValue(
793
                TAXON_SERVICE_CONFIGURATOR_SYNONYMS));
794
        configurator.setDoNamesWithoutTaxa(getBooleanValue(
795
                TAXON_SERVICE_CONFIGURATOR_NAMES));
796
        configurator.setDoTaxaByCommonNames(getBooleanValue(
797
                TAXON_SERVICE_CONFIGURATOR_COMMON_NAMES));
798
        //configurator.setMatchMode(eu.etaxonomy.cdm.persistence.query.MatchMode.valueOf(getStringValue(TAXON_SERVICE_CONFIGURATOR_MATCH_MODE)));
799

    
800
        return configurator;
801
    }
802

    
803
    /**
804
     * create new preferences, setting all search options to true
805
     *
806
     * @return a
807
     *         {@link eu.etaxonomy.cdm.api.service.config.ITaxonServiceConfigurator}
808
     *         object.
809
     */
810
    public static IFindTaxaAndNamesConfigurator initializeSearchConfigurator() {
811
        IFindTaxaAndNamesConfigurator configurator = FindTaxaAndNamesConfiguratorImpl.NewInstance();
812

    
813
        configurator.setDoTaxa(true);
814
        configurator.setDoSynonyms(true);
815
        configurator.setDoNamesWithoutTaxa(true);
816
        configurator.setDoTaxaByCommonNames(true);
817

    
818
        configurator.setTaxonPropertyPath(Arrays.asList("$", "titleCache",
819
                "name", "name.$", "relationsFromThisTaxon.$"));
820

    
821
        configurator.setSynonymPropertyPath(Arrays.asList("$", "titleCache",
822
                "name", "name.$", "synonyms.relatedTo.*"));
823

    
824
        // DEFAULT VALUES
825
        // match mode is a simple like, actually all other match modes are kind
826
        // of bogus
827
        configurator
828
                .setMatchMode(eu.etaxonomy.cdm.persistence.query.MatchMode.ANYWHERE);
829
        // we set page number and size here as this should always be unlimited
830
        configurator.setPageNumber(0);
831
        // TODO currently limit results to 10000
832
        configurator.setPageSize(10000);
833
        //setSearchConfigurator(configurator) ;
834
        return configurator;
835
    }
836

    
837
    /**
838
     * Store search preferences
839
     *
840
     * @param configurator
841
     *            a
842
     *            {@link eu.etaxonomy.cdm.api.service.config.ITaxonServiceConfigurator}
843
     *            object.
844
     */
845
    public static void setSearchConfigurator(
846
            IFindTaxaAndNamesConfigurator configurator) {
847
        getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_TAXA,
848
                configurator.isDoTaxa());
849
        getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_SYNONYMS,
850
                configurator.isDoSynonyms());
851
        getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_NAMES,
852
                configurator.isDoNamesWithoutTaxa());
853
        getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_COMMON_NAMES,
854
                configurator.isDoTaxaByCommonNames());
855
    }
856

    
857
    public static void firePreferencesChanged(Class clazz) {
858
        getPreferenceStore().firePropertyChangeEvent(PREFERRED_TERMS_CHANGE,
859
                null, clazz);
860
    }
861

    
862

    
863
    public static String createPreferenceString(String property){
864
       return prefKey(property);
865

    
866
    }
867
    public static String createOverridePreferenceString(String property){
868
           return prefOverrideKey(property);
869

    
870
        }
871

    
872
    /**
873
     * Set default values for preferences
874
     */
875
    public static void setDefaults() {
876
        getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_TAXA, true);
877
        getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_SYNONYMS,
878
                true);
879
        getPreferenceStore().setDefault(createPreferenceString(EDIT_MAP_SERVICE_ACCES_POINT),
880
                "http://edit.africamuseum.be/edit_wp5/v1.2/rest_gen.php");
881
        //FIXME : changed default for SHOULD_CONNECT_AT_STARTUP to false (ticket 3828) until resolution
882
        getPreferenceStore().setDefault(createPreferenceString(SHOULD_CONNECT_AT_STARTUP), false);
883
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.MobotOpenUrlServiceAccessPoint.getKey()),
884
                "http://www.biodiversitylibrary.org/openurl");
885
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.MobotOpenUrlServiceMaxWidth.getKey()), "1000");
886
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.MobotOpenUrlServiceMaxHeight.getKey()), "1000");
887
        getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_TAXA, true);
888
        getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_SYNONYMS, true);
889
        getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_NAMES, true);
890
        getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_COMMON_NAMES, true);
891

    
892
        //Distribution Editor:
893
//      getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.DistributionEditorActivated.getKey()), Boolean.valueOf(PreferencePredicate.DistributionEditorActivated.getDefaultValue().toString()));
894
//      getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey()), PreferencePredicate.DisplayOfAreasInDistributionEditor.getDefaultValue().toString());
895
//      getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.DisplayOfStatus.getKey()), PreferencePredicate.DisplayOfStatus.getDefaultValue().toString());
896

    
897

    
898
        //Name Details
899
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.NameDetailsView.getKey()), new NameDetailsConfigurator(false).toString());
900

    
901
        //Navigator preferences
902
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.TaxonNodeOrder.getKey()), NavigatorOrderEnum.RankAndNameOrder.getKey());
903

    
904
        //getPreferenceStore().setDefault(createPreferenceString(Prefe), true);
905

    
906
        getPreferenceStore().setDefault(createPreferenceString(SHOW_ADVANCED_MEDIA_SECTION), false);
907

    
908
        getPreferenceStore().setDefault(createPreferenceString(SHOW_MEDIA_PREVIEW), false);
909
        //override db preferences
910
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.AbcdImportConfig.getKey())), false);
911
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.ShowSpecimen.getKey())), true);
912
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.NameDetailsView.getKey())), false);
913
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.DistributionEditorActivated.getKey())), true);
914
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.AvailableDistributionStatus.getKey())), true);
915
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.AvailableDistributionAreaTerms.getKey())), true);
916
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey())), true);
917
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.CommonNameAreaVocabularies.getKey())), false);
918
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.CommonNameReferencesWithMarker.getKey()), false);
919
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowTaxonNodeWizard.getKey()), Boolean.valueOf(PreferencePredicate.ShowTaxonNodeWizard.getDefaultValue().toString()));
920
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowNamespaceInSource.getKey()), Boolean.valueOf(PreferencePredicate.ShowNamespaceInSource.getDefaultValue().toString()));
921
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowIdInSource.getKey()), Boolean.valueOf(PreferencePredicate.ShowIdInSource.getDefaultValue().toString()));
922
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.DisableMultiClassification.getKey()), Boolean.valueOf(PreferencePredicate.DisableMultiClassification.getDefaultValue().toString()));
923
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowImportExportMenu.getKey()), Boolean.valueOf(PreferencePredicate.ShowImportExportMenu.getDefaultValue().toString()));
924
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowSpecimen.getKey()), Boolean.valueOf(PreferencePredicate.ShowSpecimen.getDefaultValue().toString()));
925

    
926
    }
927

    
928
    public static void checkNomenclaturalCode() {
929
        // First time Editor is opened, no nomenclatural code has been set
930
        if (PreferencesUtil.getPreferredNomenclaturalCode() == null) {
931
            PreferencesUtil.setPreferredNomenclaturalCode(getPreferenceKey(NomenclaturalCode.ICNAFP), true);
932
        }
933

    
934

    
935

    
936
    }
937
    public static void setNomenclaturalCodePreferences(){
938
        ICdmRepository controller;
939
        controller = CdmStore.getCurrentApplicationConfiguration();
940
        PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.NomenclaturalCode);
941
        CdmPreference preference = null;
942
        if (controller == null){
943
            return ;
944
        }
945
        preference = controller.getPreferenceService().find(key);
946
        if (preference == null){
947
            return;
948
        }
949
//        setBooleanValue(ALLOW_OVERRIDE_NOMENCLATURAL_CODE_KEY, preference.isAllowOverride());
950

    
951
        int index = StringUtils.lastIndexOf(preference.getValue(), ".");
952
        UUID uuid = UUID.fromString(preference.getValue().substring(index +1, preference.getValue().length()));
953
        NomenclaturalCode preferredCode = NomenclaturalCode.getByUuid(uuid);
954

    
955
        setStringValue(PREFERRED_NOMENCLATURAL_CODE_KEY,
956
                getPreferenceKey(preferredCode));
957

    
958
    }
959

    
960
    public static void checkDefaultLanguage(){
961
        if(PreferencesUtil.getPreferredDefaultLangugae() == null){
962
           Shell shell = AbstractUtility.getShell();
963
           int open = new DefaultLanguageDialog(shell).open();
964
           if(open == Window.OK){
965
               PlatformUI.getWorkbench().restart();
966
           }
967
        }else{
968
            //TODO:In case of a reinstall, the config.ini will be overwritten
969
            //     here you create config.ini with the stored key from preferences
970
        }
971
    }
972

    
973
    public static String getMapServiceAccessPoint() {
974
        return getStringValue(EDIT_MAP_SERVICE_ACCES_POINT);
975
    }
976

    
977
    public static boolean shouldConnectAtStartUp() {
978
        //FIXME :  force SHOULD_CONNECT_AT_STARTUP to false (ticket 3828) until resolution
979
        //return getBooleanValue(SHOULD_CONNECT_AT_STARTUP);
980
        return false;
981
    }
982

    
983
    public static TermTree getDefaultFeatureTreeForTextualDescription() {
984
        String uuidString = getStringValue(
985
                FEATURE_TREE_DEFAULT_TEXT);
986
        if (StringUtils.isBlank(uuidString)) {
987
            return null;
988
        }
989
        TermTree tree = CdmStore.getService(
990
                ITermTreeService.class).load(UUID.fromString(uuidString));
991

    
992
        if (tree == null || tree.getId() == 0) {
993
            return null;
994
        }
995
        return tree;
996
    }
997

    
998
    public static TermTree getDefaultFeatureTreeForStructuredDescription() {
999
        String uuidString = getStringValue(
1000
                FEATURE_TREE_DEFAULT_STRUCTURE);
1001
        return StringUtils.isBlank(uuidString) ? null : CdmStore.getService(
1002
                ITermTreeService.class).load(UUID.fromString(uuidString));
1003
    }
1004

    
1005
    public static void setSortRanksHierarchichally(boolean selection) {
1006
        setBooleanValue(SORT_RANKS_HIERARCHICHALLY, selection);
1007
    }
1008

    
1009
    public static boolean getSortRanksHierarchichally() {
1010
        return getBooleanValue(SORT_RANKS_HIERARCHICHALLY);
1011
    }
1012

    
1013
    public static boolean isMultilanguageTextEditingCapability() {
1014
        return getBooleanValue(
1015
                MULTILANGUAGE_TEXT_EDITING_CAPABILITY);
1016
    }
1017

    
1018
    public static Language getGlobalLanguage() {
1019

    
1020

    
1021
        String languageUuidString = getStringValue(
1022
                GLOBAL_LANGUAGE_UUID);
1023

    
1024
        if(!CdmStore.isActive()) {
1025
            MessagingUtils.noDataSourceWarningDialog(languageUuidString);
1026
            return null;
1027
        }
1028

    
1029
        if (CdmUtils.isBlank(languageUuidString)) {
1030
            return Language.getDefaultLanguage();
1031
        }
1032

    
1033
        UUID languageUuid = UUID.fromString(languageUuidString);
1034
        return (Language) CdmStore.getService(ITermService.class).load(
1035
                languageUuid);
1036
    }
1037

    
1038
    public static void setGlobalLanguage(Language language) {
1039
        if(language != null) {
1040
            setStringValue(GLOBAL_LANGUAGE_UUID,language.getUuid().toString());
1041
            CdmStore.setDefaultLanguage(language);
1042
        }
1043

    
1044
    }
1045

    
1046
    public static Map<MarkerType, Boolean> getEditMarkerTypePreferences() {
1047
        List<MarkerType> markerTypes = CdmStore.getTermManager()
1048
                .getPreferredTerms(MarkerType.class);
1049

    
1050
        Map<MarkerType, Boolean> result = new HashMap<MarkerType, Boolean>();
1051

    
1052
        for (MarkerType markerType : markerTypes) {
1053
            String name = getMarkerTypeEditingPreferenceKey(markerType);
1054
            Boolean value = getBooleanValue(name);
1055

    
1056
            result.put(markerType, value);
1057
        }
1058

    
1059
        return result;
1060
    }
1061

    
1062
    public static void setEditMarkerTypePreferences(
1063
            Map<MarkerType, Boolean> markerTypeEditingMap) {
1064
        for (MarkerType markerType : markerTypeEditingMap.keySet()) {
1065
            String name = getMarkerTypeEditingPreferenceKey(markerType);
1066
            setBooleanValue(name,
1067
                    markerTypeEditingMap.get(markerType));
1068
        }
1069

    
1070
    }
1071

    
1072
    private static String getMarkerTypeEditingPreferenceKey(
1073
            MarkerType markerType) {
1074
        markerType = HibernateProxyHelper.deproxy(markerType);
1075
        return markerType.getClass().getName() + EDIT_MARKER_TYPE_PREFIX;
1076
    }
1077

    
1078
    public static void setEditMarkerTypePreference(MarkerType markerType,
1079
            boolean edit) {
1080
        setBooleanValue(
1081
                getMarkerTypeEditingPreferenceKey(markerType), edit);
1082
    }
1083

    
1084
    public static DerivedUnitFacadeConfigurator getDerivedUnitConfigurator() {
1085
        DerivedUnitFacadeConfigurator configurator = DerivedUnitFacadeConfigurator
1086
                .NewInstance();
1087
        configurator.setMoveDerivedUnitMediaToGallery(true);
1088
        configurator.setMoveFieldObjectMediaToGallery(true);
1089
        return configurator;
1090
    }
1091

    
1092
    /**
1093
     * This method will write language properties to the config.ini located in the configuration folder
1094
     * of the Taxonomic Ediitor. <b>This method is only used to set the default language for Taxonomic Editor.</b>
1095
     *
1096
     * @param setLanguage 0 is for german and 1 for english.
1097
     * @throws IOException
1098
     */
1099
    public void writePropertyToConfigFile(int setLanguage) throws IOException {
1100
        File file = org.eclipse.core.runtime.preferences.ConfigurationScope.INSTANCE.getLocation().toFile();
1101
        //give warning to user if the directory has no write access
1102
        if(file == null){
1103
            throw new IOException();
1104
        }
1105
        Properties properties = load(file.getAbsolutePath()+"/config.ini");
1106
        switch(setLanguage){
1107
        case 0:
1108
            properties.setProperty("osgi.nl", "de");
1109
            setStringValue(IPreferenceKeys.DEFAULT_LANGUAGE_EDITOR, "de");
1110
            break;
1111
        case 1:
1112
            properties.setProperty("osgi.nl", "en");
1113
            setStringValue(IPreferenceKeys.DEFAULT_LANGUAGE_EDITOR, "en");
1114
            break;
1115
        default:
1116
            break;
1117
        }
1118
        save(file+"/config.ini", properties);
1119
    }
1120

    
1121
    /**
1122
     * This method loads a property from a given file and returns it.
1123
     *
1124
     * @param filename
1125
     * @return
1126
     * @throws IOException
1127
     */
1128
    private Properties load(String filename) throws IOException {
1129
        FileInputStream in = new FileInputStream(filename);
1130
        Properties prop = new Properties();
1131
        prop.load(in);
1132
        in.close();
1133
        return prop;
1134
    }
1135

    
1136
    /**
1137
     * This method saves a property to the specified file.
1138
     *
1139
     * @param filename
1140
     * @param properties
1141
     * @throws IOException
1142
     */
1143
    private void save(String filename, Properties properties) throws IOException{
1144
        FileOutputStream fos =  new FileOutputStream(filename);
1145
        properties.store(fos, "");
1146
        fos.close();
1147
    }
1148

    
1149
    /**
1150
     * Saves a list of P2 Metadata Repositories as string with specified delimiters
1151
     *
1152
     * @param p2Repos
1153
     */
1154
    public static void setP2Repositories(List<MetadataRepositoryElement> p2Repos) {
1155
        StringBuilder sb = new StringBuilder();
1156
        for(MetadataRepositoryElement p2Repo : p2Repos) {
1157
            sb.append(P2_REPOSITORIES_DELIM);
1158
            if(p2Repo.getName() == null || p2Repo.getName().isEmpty()) {
1159
                sb.append("-");
1160
            } else {
1161
                sb.append(p2Repo.getName());
1162
            }
1163
            sb.append(P2_REPOSITORY_FIELDS_DELIM);
1164
            sb.append(p2Repo.getLocation().toString());
1165
            sb.append(P2_REPOSITORY_FIELDS_DELIM);
1166
            sb.append(String.valueOf(p2Repo.isEnabled()));
1167
        }
1168
        getPreferenceStore().setValue(P2_REPOSITORY_LIST, sb.toString());
1169
    }
1170

    
1171

    
1172
    /**
1173
     * Retrieves a list of previously saved P2 repositories
1174
     *
1175
     * @return
1176
     */
1177
    public static List<MetadataRepositoryElement> getP2Repositories() {
1178
        List<MetadataRepositoryElement> p2Repos = new ArrayList<MetadataRepositoryElement>();
1179
        String p2ReposPref =  getStringValue(P2_REPOSITORY_LIST);
1180
        if(p2ReposPref != null && !p2ReposPref.isEmpty()) {
1181
            StringTokenizer p2ReposPrefST = new StringTokenizer(p2ReposPref,P2_REPOSITORIES_DELIM);
1182

    
1183
            while(p2ReposPrefST.hasMoreTokens()) {
1184
                String p2RepoStr = p2ReposPrefST.nextToken();
1185
                StringTokenizer p2ReposStrST = new StringTokenizer(p2RepoStr,P2_REPOSITORY_FIELDS_DELIM);
1186
                if(p2ReposStrST.countTokens()==3) {
1187
                    String nickname = p2ReposStrST.nextToken();
1188
                    URI uri = null;
1189
                    try {
1190
                        uri = new URI(p2ReposStrST.nextToken());
1191
                    } catch (URISyntaxException e) {
1192
                        continue;
1193
                    }
1194
                    boolean enabled = Boolean.parseBoolean(p2ReposStrST.nextToken());
1195
                    MetadataRepositoryElement mre = new MetadataRepositoryElement(null, uri, true);
1196
                    mre.setNickname(nickname);
1197
                    mre.setEnabled(enabled);
1198
                    p2Repos.add(mre);
1199
                }
1200
            }
1201
        }
1202

    
1203
        return p2Repos;
1204
    }
1205

    
1206
    /**
1207
     * enables/disables nested composite. <br>
1208
     *
1209
     * @param ctrl - Composite to be en-/disabeld
1210
     * @param enabled - boolean
1211
     */
1212
    public static void recursiveSetEnabled(Control ctrl, boolean enabled) {
1213
        if (ctrl instanceof Composite) {
1214
            Composite comp = (Composite) ctrl;
1215
            for (Control c : comp.getChildren()) {
1216
                recursiveSetEnabled(c, enabled);
1217
            }
1218
        } else {
1219
            ctrl.setEnabled(enabled);
1220
        }
1221
    }
1222

    
1223
    public static void setSortNodes(NavigatorOrderEnum nodesOrder) {
1224
        setStringValue(PreferencePredicate.TaxonNodeOrder.getKey(), nodesOrder.key);
1225

    
1226
    }
1227

    
1228
    public static NavigatorOrderEnum getSortNodes() {
1229
        return NavigatorOrderEnum.valueOf(getStringValue(PreferencePredicate.TaxonNodeOrder.getKey()));
1230

    
1231
    }
1232

    
1233
    public static boolean isNodesSortedNaturally() {
1234
        NavigatorOrderEnum value = NavigatorOrderEnum.valueOf(getStringValue(PreferencePredicate.TaxonNodeOrder.getKey()));
1235
        return value.equals(NavigatorOrderEnum.NaturalOrder);
1236

    
1237
    }
1238

    
1239
    public static boolean isNodesSortedByName() {
1240
        NavigatorOrderEnum value = NavigatorOrderEnum.valueOf(getStringValue(PreferencePredicate.TaxonNodeOrder.getKey()));
1241
        return value.equals(NavigatorOrderEnum.AlphabeticalOrder);
1242

    
1243
    }
1244

    
1245
    public static boolean isNodesSortedByNameAndRank() {
1246
        NavigatorOrderEnum value = NavigatorOrderEnum.valueOf(getStringValue(PreferencePredicate.TaxonNodeOrder.getKey()));
1247
        return value.equals(NavigatorOrderEnum.RankAndNameOrder);
1248

    
1249
    }
1250

    
1251
    public static boolean isStoreNavigatorState() {
1252
        return getBooleanValue(RESTORE_NAVIGATOR_STATE);
1253

    
1254
    }
1255

    
1256
    public static void setStoreNavigatorState(boolean selection) {
1257
        setBooleanValue(RESTORE_NAVIGATOR_STATE, selection);
1258

    
1259
    }
1260

    
1261
    public static boolean isShowUpWidgetIsDisposedMessages() {
1262
       return getBooleanValue(IS_SHOW_UP_WIDGET_IS_DISPOSED);
1263
    }
1264
    public static void setShowUpWidgetIsDisposedMessages(boolean selection) {
1265
        setBooleanValue(IS_SHOW_UP_WIDGET_IS_DISPOSED, selection);
1266
    }
1267

    
1268
    public static boolean isShowIdInVocabularyInChecklistEditor() {
1269
        String area_display = getStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey());
1270
        if (area_display.equals(TermDisplayEnum.IdInVocabulary.getKey())) {
1271
            return true;
1272
        }else{
1273
            return false;
1274
        }
1275
    }
1276
    public static boolean isShowSymbol1InChecklistEditor() {
1277
        String area_display = getStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey());
1278
        if (area_display.equals(TermDisplayEnum.Symbol1.getKey())) {
1279
            return true;
1280
        }else{
1281
            return false;
1282
        }
1283
     }
1284
    public static boolean isShowSymbol2InChecklistEditor() {
1285
        String area_display = getStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey());
1286
        if (area_display.equals(TermDisplayEnum.Symbol2.getKey())) {
1287
            return true;
1288
        }else{
1289
            return false;
1290
        }
1291
     }
1292
    public static void setAreaDisplayInChecklistEditor(String selection) {
1293
        setStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey(), selection);
1294
    }
1295

    
1296
    public static void setOwnDescriptionForChecklistEditor(boolean selection) {
1297
        setBooleanValue(PreferencePredicate.OwnDescriptionForDistributionEditor.getKey(), selection);
1298
    }
1299

    
1300
    public static boolean isOwnDescriptionForChecklistEditor() {
1301
        return getBooleanValue(PreferencePredicate.OwnDescriptionForDistributionEditor.getKey());
1302
    }
1303

    
1304
    public static TermDisplayEnum displayAreaInChecklistEditor() {
1305
        TermDisplayEnum result;
1306
        try{
1307
            result = TermDisplayEnum.byKey(getStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey()));
1308
        }catch (IllegalArgumentException e){
1309
           result = ((TermDisplayEnum) PreferencePredicate.DisplayOfAreasInDistributionEditor.getDefaultValue());
1310
        }
1311
       return result;
1312
    }
1313

    
1314
    public static TermDisplayEnum displayStatusInChecklistEditor() {
1315
        TermDisplayEnum result;
1316
        try{
1317
            result = TermDisplayEnum.byKey(getStringValue(PreferencePredicate.DisplayOfStatus.getKey()));
1318
        }catch (IllegalArgumentException e){
1319
           result = ((TermDisplayEnum) PreferencePredicate.DisplayOfStatus.getDefaultValue());
1320
        }
1321
       return result;
1322
    }
1323
    public static void setDisplayStatusInChecklistEditor(String selection) {
1324
        setStringValue(PreferencePredicate.DisplayOfStatus.getKey(), selection);
1325

    
1326
    }
1327

    
1328
    public static boolean isShowRankInChecklistEditor() {
1329
        return getBooleanValue(PreferencePredicate.ShowRankInDistributionEditor.getKey());
1330
    }
1331
    public static void setShowRankInChecklistEditor(boolean selection) {
1332
       setBooleanValue(PreferencePredicate.ShowRankInDistributionEditor.getKey(), selection);
1333
    }
1334

    
1335
    public static NameDetailsConfigurator getPreferredNameDetailsConfiguration( boolean local) {
1336
        NameDetailsConfigurator config = new NameDetailsConfigurator(true);
1337
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1338
        CdmPreference preference = null;
1339
        String value;
1340
        if (!local) {
1341
            PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.NameDetailsView);
1342
            preference =  getPreferenceFromDB(PreferencePredicate.NameDetailsView);
1343
            if (preference == null){
1344
                return null;
1345
            }
1346

    
1347
        //    setBooleanValue(ALLOW_OVERRIDE_NAME_DETAILS, preference.isAllowOverride());
1348
            value = preference.getValue();
1349
            config.setAllowOverride(preference.isAllowOverride());
1350
            //the preference value is build like this:
1351
            //<section1>:true;<section2>:false....
1352
        }else{
1353
            value = getStringValue(PreferencePredicate.NameDetailsView.getKey(), local);
1354
        }
1355
        if (value!= null){
1356
            String [] sections = value.split(";");
1357
            Map<String, Boolean> sectionMap = new HashMap<String, Boolean>();
1358
            String[] sectionValues;
1359
            for (String sectionValue: sections){
1360
                sectionValues = sectionValue.split(":");
1361
                sectionMap.put(sectionValues[0], Boolean.valueOf(sectionValues[1]));
1362
            }
1363
            config.setSimpleDetailsViewActivated(getValue(sectionMap, "simpleViewActivated"));
1364
            config.setTaxonSectionActivated(getValue(sectionMap, "taxon"));
1365
            config.setSecDetailsActivated(getValue(sectionMap, "taxon.SecDetails"));
1366
            config.setSecEnabled(getValue(sectionMap, "taxon.SecEnabled"));
1367
            config.setLSIDActivated(getValue(sectionMap, "lsid"));
1368
            config.setNomenclaturalCodeActived(getValue(sectionMap, "nc"));
1369
            config.setAppendedPhraseActivated(getValue(sectionMap, "ap"));
1370
            config.setRankActivated(getValue(sectionMap, "rank"));
1371
            config.setNameCacheActivated(getValue(sectionMap, "nameCache"));
1372
            config.setAtomisedEpithetsActivated(getValue(sectionMap, "atomisedEpithets"));
1373
            config.setAuthorshipSectionActivated(getValue(sectionMap,"author"));
1374
            config.setAuthorCacheActivated(getValue(sectionMap, "authorCache"));
1375
            config.setNomenclaturalReferenceSectionActivated(sectionMap.get("nomRef"));
1376
            config.setNomenclaturalStatusSectionActivated(getValue(sectionMap, "nomStat"));
1377
            config.setProtologueActivated(getValue(sectionMap,"protologue"));
1378
            config.setTypeDesignationSectionActivated(getValue(sectionMap,"typeDes"));
1379
            config.setNameRelationsSectionActivated(getValue(sectionMap,"nameRelation"));
1380
            config.setHybridActivated(getValue(sectionMap,"hybrid"));
1381
            config.setNameApprobiationActivated(getValue(sectionMap, "nameApproviation"));
1382
        }else {
1383
            return null;
1384
        }
1385
        return config;
1386
    }
1387

    
1388
    public static NameDetailsConfigurator getPreferredNameDetailsConfiguration() {
1389
        NameDetailsConfigurator config = new NameDetailsConfigurator(true);
1390

    
1391
        String value;
1392

    
1393
        value = getStringValue(PreferencePredicate.NameDetailsView.getKey(), false);
1394
        if (value != null){
1395
            String [] sections = value.split(";");
1396
            Map<String, Boolean> sectionMap = new HashMap<String, Boolean>();
1397
            String[] sectionValues;
1398
            for (String sectionValue: sections){
1399
                sectionValues = sectionValue.split(":");
1400
                sectionMap.put(sectionValues[0], Boolean.valueOf(sectionValues[1]));
1401
            }
1402

    
1403
            config.setSimpleDetailsViewActivated(getValue(sectionMap, "simpleViewActivated"));
1404

    
1405
            config.setTaxonSectionActivated(getValue(sectionMap, "taxon"));
1406

    
1407
            config.setSecDetailsActivated(getValue(sectionMap, "taxon.SecDetails"));
1408
            config.setSecEnabled(getValue(sectionMap, "taxon.SecEnabled"));
1409

    
1410
            config.setLSIDActivated(getValue(sectionMap, "lsid"));
1411

    
1412
            config.setNomenclaturalCodeActived(getValue(sectionMap, "nc"));
1413

    
1414
            config.setAppendedPhraseActivated(getValue(sectionMap, "ap"));
1415

    
1416
            config.setRankActivated(getValue(sectionMap, "rank"));
1417

    
1418
            config.setAtomisedEpithetsActivated(getValue(sectionMap, "atomisedEpithets"));
1419

    
1420
            config.setAuthorshipSectionActivated(getValue(sectionMap,"author"));
1421

    
1422
            config.setNomenclaturalReferenceSectionActivated(sectionMap.get("nomRef"));
1423

    
1424
            config.setNomenclaturalStatusSectionActivated(getValue(sectionMap, "nomStat"));
1425

    
1426
            config.setProtologueActivated(getValue(sectionMap,"protologue"));
1427

    
1428
            config.setTypeDesignationSectionActivated(getValue(sectionMap,"typeDes"));
1429

    
1430
            config.setNameRelationsSectionActivated(getValue(sectionMap,"nameRelation"));
1431

    
1432
                config.setHybridActivated(getValue(sectionMap,"hybrid"));
1433
        }
1434
        return config;
1435
    }
1436

    
1437
    public static void setPreferredNameDetailsConfiguration(NameDetailsConfigurator config, boolean local) {
1438
        CdmPreference preference = null;
1439

    
1440
        if (!local) {
1441
            preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.NameDetailsView, config.toString());
1442

    
1443
            setPreferenceToDB(preference);
1444
        }
1445
        else{
1446
            setStringValue(PreferencePredicate.NameDetailsView.getKey(), config.toString());
1447
        }
1448

    
1449

    
1450
    }
1451

    
1452
    private static Boolean getValue(Map<String, Boolean> sectionMap, String string) {
1453
        if (sectionMap.containsKey(string)){
1454
            return sectionMap.get(string);
1455
        }else{
1456
            return true;
1457
        }
1458

    
1459
    }
1460

    
1461
    public static Abcd206ImportConfigurator getDBAbcdImportConfigurationPreference() {
1462

    
1463
        Abcd206ImportConfigurator config = Abcd206ImportConfigurator.NewInstance(null,null);
1464
        ICdmRepository controller;
1465
        controller = CdmStore.getCurrentApplicationConfiguration();
1466
        PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AbcdImportConfig);
1467
        CdmPreference preference = null;
1468
        if (controller == null){
1469
            return null;
1470
        }
1471
        preference = controller.getPreferenceService().find(key);
1472
        if (preference == null){
1473
            return config;
1474
         } else{
1475
             String configString = preference.getValue();
1476
             extractAbcdConfiguratorFromPreferenceString(config, configString);
1477
         }
1478
        return config;
1479
    }
1480

    
1481
    public static void extractAbcdConfiguratorFromPreferenceString(Abcd206ImportConfigurator config,
1482
            String configString) {
1483
        if(configString!=null){
1484
             String[] configArray = configString.split(";");
1485

    
1486
             for (String configItem: configArray){
1487
                 String[] keyValue = configItem.split(":");
1488
                 String keyString = keyValue[0];
1489
                 String valueString = null;
1490
                 if (keyValue.length>1){
1491
                     valueString = keyValue[1];
1492
                     if (keyValue.length>2){
1493

    
1494
                         for (int index = 2; index< keyValue.length; index++){
1495
                             valueString += ":"+ keyValue[index];
1496
                         }
1497
                     }
1498
                 }
1499
                 if (keyString.equals("ignoreImportOfExistingSpecimen")){
1500
                     config.setIgnoreImportOfExistingSpecimen(Boolean.valueOf(valueString));
1501
                 }else if (keyString.equals("addIndividualsAssociationsSuchAsSpecimenAndObservations")){
1502
                     config.setAddIndividualsAssociationsSuchAsSpecimenAndObservations(Boolean.valueOf(valueString));
1503
                 }else if (keyString.equals("reuseExistingTaxaWhenPossible")){
1504
                     config.setReuseExistingTaxaWhenPossible(Boolean.valueOf(valueString));
1505
                 }else if (keyString.equals("ignoreAuthorship")){
1506
                     config.setIgnoreAuthorship(Boolean.valueOf(valueString));
1507
                 }else if (keyString.equals("addMediaAsMediaSpecimen")){
1508
                     config.setAddMediaAsMediaSpecimen(Boolean.valueOf(valueString));
1509
                 }else if (keyString.equals("reuseExistingMetaData")){
1510
                     config.setReuseExistingMetaData(Boolean.valueOf(valueString));
1511
                 }else if (keyString.equals("reuseExistingDescriptiveGroups")){
1512
                     config.setReuseExistingDescriptiveGroups(Boolean.valueOf(valueString));
1513
                 }else if (keyString.equals("allowReuseOtherClassifications")){
1514
                     config.setAllowReuseOtherClassifications(Boolean.valueOf(valueString));
1515
                 }else if (keyString.equals("deduplicateReferences")){
1516
                     config.setDeduplicateReferences(Boolean.valueOf(valueString));
1517
                 }else if (keyString.equals("deduplicateClassifications")){
1518
                     config.setDeduplicateClassifications(Boolean.valueOf(valueString));
1519
                 }else if (keyString.equals("moveNewTaxaToDefaultClassification")){
1520
                     config.setMoveNewTaxaToDefaultClassification(Boolean.valueOf(valueString));
1521
                 }else if (keyString.equals("mapUnitIdToCatalogNumber")){
1522
                     config.setMapUnitIdToCatalogNumber(Boolean.valueOf(valueString));
1523
                 }else if (keyString.equals("mapUnitIdToAccessionNumber")){
1524
                     config.setMapUnitIdToAccessionNumber(Boolean.valueOf(valueString));
1525
                 }else if (keyString.equals("mapUnitIdToBarcode")){
1526
                     config.setMapUnitIdToBarcode(Boolean.valueOf(valueString));
1527
                 }else if (keyString.equals("overwriteExistingSpecimens")){
1528
                     config.setOverwriteExistingSpecimens(Boolean.valueOf(valueString));
1529
                 }else if (keyString.equals("nomenclaturalCode")){
1530
                     config.setNomenclaturalCode(NomenclaturalCode.fromString(valueString));
1531
                 }else if (keyString.equals("removeCountryFromLocalityText")){
1532
                     config.setRemoveCountryFromLocalityText(Boolean.valueOf(valueString));
1533
                 }else if (keyString.equals("getSiblings")){
1534
                     config.setGetSiblings(Boolean.valueOf(valueString));
1535
                 }else if (keyString.equals("dnaSource")){
1536
                     try{
1537
                         config.setDnaSoure(URI.create(valueString));
1538
                     }catch(Exception e){
1539
                         config.setDnaSoure(null);
1540
                     }
1541
                 }else{
1542
                     logger.debug("This key of the abcd configurator needs to be added to the transformer: " + keyString);
1543
                 }
1544

    
1545

    
1546
             }
1547
         }
1548
    }
1549

    
1550
    public static Abcd206ImportConfigurator getLocalAbcdImportConfigurator(){
1551
       Abcd206ImportConfigurator config = Abcd206ImportConfigurator.NewInstance(null,null);
1552
       String configString = getStringValue(PreferencePredicate.AbcdImportConfig.getKey(), true);
1553
       extractAbcdConfiguratorFromPreferenceString(config, configString);
1554
       return config;
1555

    
1556
    }
1557

    
1558
    public static void updateAbcdImportConfigurationPreference() {
1559
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1560

    
1561
        CdmPreference pref = cache.findBestMatching(CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AbcdImportConfig));
1562

    
1563
        if (!getBooleanValue(prefOverrideKey(PreferencePredicate.AbcdImportConfig.getKey())) || !pref.isAllowOverride()){
1564
            resetToDBPreferenceAbcdCOnfigurator();
1565

    
1566
        }
1567
    }
1568

    
1569
    public static void resetToDBPreferenceAbcdCOnfigurator(){
1570
        Abcd206ImportConfigurator config = getDBAbcdImportConfigurationPreference();
1571
        setStringValue(PreferencePredicate.AbcdImportConfig.getKey(), config.toString());
1572

    
1573
    }
1574

    
1575
    public static boolean isSortTaxaByRankAndName() {
1576

    
1577
        return getBooleanValue(IPreferenceKeys.SORT_TAXA_BY_RANK_AND_NAME);
1578
    }
1579

    
1580
    public static TermOrder getSortNamedAreasInDistributionEditor() {
1581
        TermOrder result;
1582
        try{
1583
            result = TermOrder.valueOf(getStringValue(PreferencePredicate.AreasSortedInDistributionEditor.getKey()));
1584
        }catch (IllegalArgumentException e){
1585
            result = (TermOrder)PreferencePredicate.AreasSortedInDistributionEditor.getDefaultValue();
1586
        }
1587
        return result;
1588
    }
1589

    
1590
    public static void setSortNamedAreasInDistributionEditor(String isSortByVocabularyOrder) {
1591
        setStringValue(PreferencePredicate.AreasSortedInDistributionEditor.getKey(), isSortByVocabularyOrder);
1592

    
1593
    }
1594

    
1595
    public static void setLastSelectedReference(
1596
            List<String> lastSelectedReferences) {
1597

    
1598
        setStringValue(PreferencesUtil.LAST_SELECTED_REFERENCES, lastSelectedReferences.toString());
1599
    }
1600

    
1601
    public static List<String> getLastSelectedReferences() {
1602

    
1603
        //IPreferenceStore preferenceStore = PreferencesUtil.getPreferenceStore();
1604
        String lastSelected = getStringValue(PreferencesUtil.LAST_SELECTED_REFERENCES);
1605
        List<String> result = new ArrayList<>();
1606
        if (!StringUtils.isBlank(lastSelected)){
1607
            Collections.addAll(result, lastSelected.substring(1,lastSelected.length()-1).split(", "));
1608
        }
1609
        return result;
1610
    }
1611

    
1612
    public static void setPreferredNamedAreasForDistributionEditor(
1613
            String saveCheckedElements, String saveGrayedElements, boolean local) {
1614
        if (local){
1615
            setStringValue(PreferencePredicate.AvailableDistributionAreaTerms.getKey(), saveCheckedElements);
1616

    
1617
        }
1618
        else{
1619
            CdmPreference preference = null;
1620

    
1621
            if (saveCheckedElements == null){
1622
                preference = getPreferenceFromDB(PreferencePredicate.AvailableDistributionAreaTerms);
1623

    
1624
                if (preference == null){
1625
                    return ;
1626
                } else{
1627
                    setStringValue(PreferencePredicate.AvailableDistributionAreaTerms.getKey(),
1628
                            saveCheckedElements);
1629
                    preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AvailableDistributionAreaTerms, saveCheckedElements);
1630
                    setPreferenceToDB(preference);
1631

    
1632
                }
1633
            } else{
1634
                preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AvailableDistributionAreaTerms, saveCheckedElements);
1635
                setPreferenceToDB(preference);
1636
                setStringValue(PreferencePredicate.AvailableDistributionAreaTerms.getKey(),
1637
                        saveCheckedElements);
1638

    
1639
            }
1640
        }
1641

    
1642
    }
1643

    
1644
    public static void setPreferredVocabulariesForDistributionEditor(String saveCheckedElements,
1645
            boolean local, boolean isOverride) {
1646
        if (local){
1647
            setStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(), saveCheckedElements);
1648
            setBooleanValue(prefOverrideKey(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey()), isOverride);
1649
        }
1650
        else{
1651
            ICdmRepository controller;
1652
            CdmPreference preference = null;
1653

    
1654
            if (saveCheckedElements == null){
1655
                preference = getPreferenceFromDB(PreferencePredicate.AvailableDistributionAreaVocabularies);
1656

    
1657
                if (preference == null){
1658
                    return ;
1659
                } else{
1660
                    setStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(),
1661
                            saveCheckedElements);
1662
                    preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AvailableDistributionAreaVocabularies, saveCheckedElements);
1663
                    preference.setAllowOverride(isOverride);
1664
                    setPreferenceToDB(preference);
1665
                }
1666
            } else{
1667
                preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AvailableDistributionAreaVocabularies, saveCheckedElements);
1668
                preference.setAllowOverride(isOverride);
1669
                setPreferenceToDB(preference);
1670
                setStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(),
1671
                        saveCheckedElements);
1672

    
1673
            }
1674
        }
1675
    }
1676

    
1677
    public static String getPreferredVocabulariesForDistributionEditor(boolean local) {
1678
        if (local){
1679

    
1680
            String pref = getStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(), local);
1681
            return pref;
1682
        }
1683
        else{
1684
            CdmPreference preference = null;
1685
            preference = getPreferenceFromDB(PreferencePredicate.AvailableDistributionAreaVocabularies);
1686
            if (preference == null){
1687
                return null;
1688
            } else{
1689
                return preference.getValue();
1690
            }
1691

    
1692
        }
1693
    }
1694

    
1695
    public static List<UUID> createUUIDListFromStringPref(String prefKey) {
1696
        String prefValue = PreferencesUtil.getStringValue(prefKey);
1697
        if (prefValue == null){
1698
            return null;
1699
        }
1700
        String[] stringArray = prefValue.split(";");
1701
        List<UUID> uuidList = new ArrayList();
1702
        for (String uuid: stringArray){
1703
            if (!StringUtils.isBlank(uuid)){
1704
                uuidList.add(UUID.fromString(uuid));
1705
            }
1706
        }
1707
        return uuidList;
1708
    }
1709

    
1710
    public static boolean getFilterCommonNameReferences(){
1711
        Boolean result = getBooleanValue(PreferencesUtil.FILTER_COMMON_NAME_REFERENCES);
1712
        if (result == null){
1713
            return false;
1714
        }
1715
        return result;
1716
    }
1717

    
1718
    public static void updateDBPreferences() {
1719

    
1720

    
1721
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1722
        cache.getAllTaxEditorDBPreferences();
1723

    
1724
        //ABCD Configurator
1725

    
1726
        //updateAbcdImportConfigurationPreference();
1727

    
1728
        //Name Details
1729
        NameDetailsConfigurator config = getPreferredNameDetailsConfiguration(false);
1730
        //    if (config != null ){
1731
        //        if (!getBooleanValue(OVERRIDE_NAME_DETAILS) ||  !getBooleanValue(ALLOW_OVERRIDE_NAME_DETAILS)){
1732
        //            setPreferredNameDetailsConfiguration(config, false);
1733
        //        }
1734
        //    }
1735

    
1736
    }
1737

    
1738
    public static void setPreferencesToDB(List<CdmPreference> preferences) {
1739

    
1740
        ICdmRepository controller;
1741
        //try{
1742
            if(CdmStore.isActive()){
1743
                controller = CdmStore.getCurrentApplicationConfiguration();
1744
                for (CdmPreference preference: preferences){
1745
                    if (preference.getValue() == null && preference.isAllowOverride()){
1746
                        controller.getPreferenceService().remove(preference.getKey());
1747

    
1748
                    }else{
1749
                        controller.getPreferenceService().set(preference);
1750

    
1751
                    }
1752

    
1753
                }
1754
                CdmPreferenceCache.instance().getAllTaxEditorDBPreferences();
1755

    
1756
            }
1757
        /*}catch(Exception e){
1758
            e.printStackTrace();
1759
        }*/
1760
    }
1761

    
1762
    /**
1763
     * Returns whether the named preference is known.
1764
     * @param prefKey the key of the preference
1765
     * @return <code>true</code> if the preference is known, <code>false</code> otherwise
1766
     */
1767
    public static boolean contains(String prefKey){
1768
        return getPreferenceStore().contains(prefKey(prefKey));
1769
    }
1770

    
1771
    /**
1772
     *
1773
     */
1774
    public static TermTree getPreferredFeatureTreeForNameDescription(boolean createNew) {
1775
        if(preferredNameFeatureTree != null && !createNew){
1776
            return preferredNameFeatureTree;
1777
        }
1778
        createPreferredFeatureTreeForNameDescription();
1779
        return preferredNameFeatureTree;
1780

    
1781
    }
1782

    
1783
    public static void createPreferredFeatureTreeForNameDescription() {
1784

    
1785
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1786
        CdmPreference pref = cache.get(PreferencePredicate.NameFeatures.getKey());
1787
        List<Feature> terms;
1788
        boolean override = PreferencesUtil.getBooleanValue(PreferencesUtil.createOverridePreferenceString(PreferencePredicate.NameFeatures.getKey()));
1789
        List<UUID> uuids = PreferencesUtil.createUUIDListFromStringPref(pref.getPredicate());
1790
        if (uuids != null && !uuids.isEmpty()){
1791

    
1792
            terms = CdmStore.getTermManager().getTerms(uuids, Feature.class);
1793
//        }else if (override){
1794
//            List<TermDto>  termDtos= CdmStore.getTermManager().getPreferredTerms(CdmStore.getService(IVocabularyService.class).load(VocabularyEnum.NameFeature.getUuid()));
1795
//            List<UUID> uuidList = new ArrayList<>();
1796
//
1797
//            for (Object term: termDtos){
1798
//                if (term instanceof TermDto){
1799
//                    uuidList.add(((TermDto)term).getUuid());
1800
//                }
1801
//            }
1802
//            if (!uuidList.isEmpty()){
1803
//                terms = CdmStore.getTermManager().getTerms(uuidList, Feature.class);
1804
//            }else{
1805
//                terms = CdmStore.getTermManager().getPreferredTerms(CdmStore.getService(IVocabularyService.class).load(VocabularyEnum.NameFeature.getUuid()));
1806
//            }
1807
//
1808

    
1809

    
1810
        }else{
1811
            terms = new ArrayList();
1812
            terms.addAll(TermStore.getTerms(CdmStore.getService(IVocabularyService.class).load(VocabularyEnum.NameFeature.getUuid()), null));
1813

    
1814
        }
1815
        terms.remove(Feature.PROTOLOGUE());
1816
        if (terms.isEmpty()){
1817
            preferredNameFeatureTree = TermEditorInput.getDefaultNameFeatureTree();
1818
        }else{
1819
            preferredNameFeatureTree = TermTree.NewInstance(terms);
1820
        }
1821

    
1822

    
1823
    }
1824

    
1825
    /**
1826
     * @param prefsToDelete
1827
     */
1828
    public static void removeFromDB(List<CdmPreference> prefsToDelete) {
1829
        ICdmRepository controller;
1830
        //try{
1831
            if(CdmStore.isActive()){
1832
                controller = CdmStore.getCurrentApplicationConfiguration();
1833
                for (CdmPreference preference: prefsToDelete){
1834
                    controller.getPreferenceService().remove(preference.getKey());
1835
                }
1836
                CdmPreferenceCache.instance().getAllTaxEditorDBPreferences();
1837
            }
1838

    
1839
    }
1840

    
1841
    /**
1842
     * @return
1843
     */
1844
    public static TermTree<?> getPreferredFeatureTreeForTaxonDescription(boolean createNew) {
1845
        if(preferredTaxonFeatureTree != null && !createNew){
1846
            return preferredTaxonFeatureTree;
1847
        }
1848
        createPreferredFeatureTreeForTaxonDescription();
1849
        return preferredTaxonFeatureTree;
1850

    
1851
    }
1852

    
1853
    public static void createPreferredFeatureTreeForTaxonDescription() {
1854

    
1855
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1856
        CdmPreference pref = cache.get(PreferencePredicate.TaxonFeatures.getKey());
1857
        List<Feature> terms;
1858
        boolean override = PreferencesUtil.getBooleanValue(PreferencesUtil.createOverridePreferenceString(PreferencePredicate.TaxonFeatures.getKey()));
1859
        if (pref != null && !override){
1860
            List<UUID> uuids = PreferencesUtil.createUUIDListFromStringPref(pref.getValue());
1861
            terms = CdmStore.getTermManager().getTerms(uuids, Feature.class);
1862
        }else if (override){
1863
            terms= CdmStore.getTermManager().getPreferredTerms(TermType.Feature);
1864
            TermVocabulary nameVocabulary = CdmStore.getService(IVocabularyService.class).load(VocabularyEnum.NameFeature.getUuid());
1865
            Set<Feature> nameFeature = nameVocabulary.getTerms();
1866
            terms.removeAll(nameFeature);
1867

    
1868
        }else{
1869
            terms= CdmStore.getTermManager().getPreferredTerms(TermType.Feature);
1870
            TermVocabulary nameVocabulary = CdmStore.getService(IVocabularyService.class).load(VocabularyEnum.NameFeature.getUuid());
1871
            Set<Feature> nameFeature = nameVocabulary.getTerms();
1872
            terms.removeAll(nameFeature);
1873

    
1874
        }
1875

    
1876
        if (terms.isEmpty()){
1877
            preferredTaxonFeatureTree = TermEditorInput.getDefaultFeatureTree();
1878
        }else{
1879
            preferredTaxonFeatureTree = TermTree.NewInstance(terms);
1880
        }
1881

    
1882

    
1883
    }
1884

    
1885

    
1886

    
1887

    
1888
}
(36-36/52)