Project

General

Profile

Download (71 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.StringTokenizer;
26
import java.util.UUID;
27

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

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

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

    
95
    public static final String PREFERRED_TERMS_CHANGE = "preferred_terms";
96

    
97
    public static final String P2_REPOSITORIES_DELIM = ",";
98
    public static final String P2_REPOSITORY_FIELDS_DELIM = ";";
99
    public static final String SUBJECT_DELIM = "/";
100

    
101
    private static TermTree preferredNameFeatureTree;
102

    
103
    private final static Logger logger = Logger.getLogger(PreferencesUtil.class);
104

    
105
    public static IPreferenceStore getPreferenceStore() {
106
       return TaxeditorStorePlugin.getDefault().getPreferenceStore();
107
    }
108

    
109
    public static String[] extractSubjectParts(String subject){
110
       String[] result = subject.split("/");
111
       return result;
112
    }
113

    
114
    public static IEclipsePreferences getEditorPreferences(){
115
        return ConfigurationScope.INSTANCE.getNode(EDITOR_PREFERENCES_NODE);
116
    }
117

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

    
132
        } catch (BackingStoreException e) {
133
            // TODO Auto-generated catch block
134
            e.printStackTrace();
135
        }
136
        return null;
137
    }
138

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

    
156
            }
157

    
158
        } catch (BackingStoreException e) {
159
            // TODO Auto-generated catch block
160
            e.printStackTrace();
161
        }
162
        return null;
163
    }
164

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

    
182
    }
183

    
184
    private static String prefKey(String name) {
185
        return name + "_"+  ((CdmRemoteSource)CdmStore.getActiveCdmSource()).toString();
186
    }
187

    
188
    public static String prefOverrideKey(String name) {
189
        return name + "_OVERRIDE_";
190
    }
191

    
192
    public static void setStringValue(String name, String value) {
193
        if (value != null){
194
            getPreferenceStore().setValue(prefKey(name), value);
195
        }else{
196
            getPreferenceStore().setToDefault(name);
197
        }
198
    }
199

    
200
    public static void setIntValue(String name, int value) {
201
        getPreferenceStore().setValue(prefKey(name), value);
202
    }
203

    
204
    public static void setBooleanValue(String name, boolean value) {
205
        getPreferenceStore().setValue(prefKey(name), value);
206
    }
207

    
208
    public static void setDoubleValue(String name, double value) {
209
        getPreferenceStore().setValue(prefKey(name), value);
210
    }
211

    
212
    public static void setFloatValue(String name, float value) {
213
        getPreferenceStore().setValue(prefKey(name), value);
214
    }
215

    
216
    public static void setLongValue(String name, long value) {
217
        getPreferenceStore().setValue(prefKey(name), value);
218
    }
219

    
220
    public static String getStringValue(String name, boolean local) {
221

    
222
        CdmPreference pref = getDBPreferenceValue(name);
223
        String prefValue = null;
224
        String overrideKey =  createPreferenceString(createOverridePreferenceString(name));
225
        boolean override = getPreferenceStore().getBoolean(overrideKey);
226

    
227
        if (local || pref == null || (pref != null && pref.isAllowOverride() && override)){
228
            String dbSpecific = prefKey(name);
229
            if (getPreferenceStore().contains(dbSpecific)){
230
                prefValue = getPreferenceStore().getString(dbSpecific);
231
            }else{
232
                prefValue = getPreferenceStore().
233
                        getString(name);
234
            }
235
       }else if (pref != null){
236
           prefValue = pref.getValue();
237
       }
238
        return prefValue;
239

    
240
    }
241

    
242
    public static String getStringValue(String name){
243
        return getStringValue(name, false);
244
    }
245

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

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

    
279
        String overrideKey =  createPreferenceString(createOverridePreferenceString(name));
280
        boolean override = true;
281
        if (getPreferenceStore().contains(overrideKey)){
282
            override = getPreferenceStore().getBoolean(overrideKey);
283
        }
284
        if (local || pref == null || (pref != null && pref.isAllowOverride() && override)){
285
            String dbSpecific = prefKey(name);
286
            if (getPreferenceStore().contains(dbSpecific)){
287
                result = getPreferenceStore().getInt(dbSpecific);
288
            }else{
289
                result =  getPreferenceStore().
290
                        getInt(name);
291
            }
292
        }
293
        return result;
294

    
295
    }
296

    
297
    public static boolean getBooleanValue(String name) {
298
        Boolean result = getBooleanValue(name, false);
299
        if (result == null){
300
            return false;
301
        }else{
302
            return result;
303
        }
304

    
305
    }
306

    
307
    public static Boolean getBooleanValue(String name, boolean local) {
308
        if (CdmStore.isActive()){
309
            CdmPreference pref = getDBPreferenceValue(name);
310

    
311
            String overrideKey =  createPreferenceString(createOverridePreferenceString(name));
312
            boolean override = getPreferenceStore().getBoolean(overrideKey);
313

    
314
            if (local || pref == null || (pref != null && pref.isAllowOverride() && override)){
315
                String dbSpecific = prefKey(name);
316
                if (getPreferenceStore().contains(dbSpecific)){
317
                    return getPreferenceStore().getBoolean(dbSpecific);
318
                }else{
319
                    return null;
320
                }
321
             }else{
322
                return Boolean.valueOf(pref.getValue());
323
            }
324

    
325
        }else{
326
            return getPreferenceStore().getBoolean(name);
327
        }
328

    
329
    }
330

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

    
354
    }
355

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

    
384
    }
385

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

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

    
430
            if (preferenceValue == null){
431
                preference = controller.getPreferenceService().find(key);
432
                if (preference == null){
433
                    return null;
434
                } else{
435
                    setStringValue(PREFERRED_NOMENCLATURAL_CODE_KEY,
436
                            preference.getValue());
437

    
438
                    return preference;
439
                }
440
            } else{
441
                preference = CdmPreference.NewInstance(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.NomenclaturalCode, preferenceValue);
442
                controller.getPreferenceService().set(preference);
443

    
444
            }
445
        }
446
        return null;
447

    
448

    
449

    
450
    }
451

    
452
    public static void setPreferredNomenclaturalCode(
453
        CdmPreference preference) {
454

    
455
        ICdmRepository controller;
456
        controller = CdmStore.getCurrentApplicationConfiguration();
457
        if (controller == null){
458
            return;
459
        }
460
        PrefKey key = null;
461
        try{
462
            key = CdmPreference.NewKey(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.NomenclaturalCode);
463
        }catch (Exception e){
464
            System.out.println(e.getStackTrace());
465
        }
466

    
467
        controller.getPreferenceService().set(preference);
468

    
469
    }
470

    
471
    public static NomenclaturalCode getPreferredNomenclaturalCode() {
472

    
473
        CdmPreference pref = getPreferenceFromDB(PreferencePredicate.NomenclaturalCode);
474

    
475

    
476
        String preferredCode;
477
        if(pref == null || (pref.isAllowOverride() && getBooleanValue(prefOverrideKey(PreferencePredicate.NomenclaturalCode.getKey())))){
478
            preferredCode = getStringValue(
479
                    PreferencePredicate.NomenclaturalCode.getKey(), true);
480

    
481
        }else{
482
            preferredCode = pref.getValue();
483
        }
484
        if (StringUtils.isBlank(preferredCode)){
485
            preferredCode = getPreferenceKey((NomenclaturalCode)PreferencePredicate.NomenclaturalCode.getDefaultValue());
486
        }
487

    
488
        return getPreferredNomenclaturalCode(preferredCode);
489

    
490
    }
491

    
492
    public static NomenclaturalCode getPreferredNomenclaturalCode(String preferenceKeyNomenclaturalCode) {
493

    
494
        for (NomenclaturalCode code : NomenclaturalCodeHelper.getAllCodes()) {
495
            if (getPreferenceKey(code).equals(preferenceKeyNomenclaturalCode)) {
496
                return code;
497
            }
498
        }
499
        return null;
500
    }
501

    
502
    public static boolean isShowTaxonAssociations(){
503
        boolean result = getBooleanValue(PreferencePredicate.ShowTaxonAssociations.getKey());
504
        return result;
505
    }
506

    
507
    public static boolean isShowLifeForm(){
508
        boolean result =  getBooleanValue(PreferencePredicate.ShowLifeForm.getKey());
509
        return result;
510
    }
511

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

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

    
522
    public static CdmPreference getPreferenceFromDB(IPreferencePredicate predicate){
523
        ICdmRepository controller;
524
        CdmPreference pref = null;
525

    
526
        try{
527
            if(CdmStore.isActive()){
528
                controller = CdmStore.getCurrentApplicationConfiguration();
529
                PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), predicate);
530
                pref = controller.getPreferenceService().find(key);
531
            }
532
        }catch(Exception e){
533
            e.printStackTrace();
534
        }
535

    
536
        return pref;
537

    
538
    }
539

    
540
    public static List<CdmPreference> getPreferencesFromDB(IPreferencePredicate predicate){
541
        ICdmRepository controller;
542
        List<CdmPreference> prefs = null;
543

    
544
        try{
545
            if(CdmStore.isActive()){
546
                controller = CdmStore.getCurrentApplicationConfiguration();
547
                PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), predicate);
548
                prefs = controller.getPreferenceService().list(predicate);
549
            }
550
        }catch(Exception e){
551
            e.printStackTrace();
552
        }
553

    
554
        return prefs;
555

    
556
    }
557

    
558
    public static void setPreferencesToDB(CdmPreference preference, boolean setDefault){
559
        ICdmRepository controller;
560
        try{
561
            if(CdmStore.isActive()){
562
                controller = CdmStore.getCurrentApplicationConfiguration();
563

    
564
                if (setDefault){
565
                    controller.getPreferenceService().remove(preference.getKey());
566
                }else{
567
                    controller.getPreferenceService().set(preference);
568
                }
569
            }
570
        }catch(Exception e){
571
            e.printStackTrace();
572
        }
573

    
574

    
575

    
576
    }
577

    
578
    public static CdmPreference getPreferenceFromDB(PrefKey key){
579
        ICdmRepository controller;
580
        CdmPreference pref = null;
581

    
582
        try{
583
            if(CdmStore.isActive()){
584
                controller = CdmStore.getCurrentApplicationConfiguration();
585
                pref = controller.getPreferenceService().find(key);
586
            }
587
        }catch(Exception e){
588
            e.printStackTrace();
589
        }
590

    
591
        return pref;
592

    
593
    }
594

    
595
    public static void setPreferenceToDB(CdmPreference preference){
596
        ICdmRepository controller;
597
        try{
598
            if(CdmStore.isActive()){
599
                controller = CdmStore.getCurrentApplicationConfiguration();
600
                if (preference.getValue() == null && preference.isAllowOverride()){
601
                    controller.getPreferenceService().remove(preference.getKey());
602
                }else{
603
                    controller.getPreferenceService().set(preference);
604
                }
605
                CdmPreferenceCache.instance().put(preference);
606
            }
607
        }catch(Exception e){
608
            e.printStackTrace();
609
        }
610

    
611
    }
612

    
613
    public static String getPreferredDefaultLangugae(){
614
        String preferredLanguage = getStringValue(DEFAULT_LANGUAGE_EDITOR);
615
        if(StringUtils.isNotEmpty(preferredLanguage) && StringUtils.isNotBlank(preferredLanguage)){
616
            return preferredLanguage;
617
        }
618
        return null;
619
    }
620

    
621
    public static boolean isShowMediaPreview(){
622
        boolean isShowMediaPreview = getBooleanValue(SHOW_MEDIA_PREVIEW);
623
        return isShowMediaPreview;
624
    }
625

    
626
    /**
627
     * Get the match strategy for the given class that was stored in preferences
628
     * or the default strategy if it was not stored in preferences
629
     *
630
     * @param clazz
631
     *            a {@link java.lang.Class} object.
632
     * @return a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy} object.
633
     */
634
    public static IMatchStrategy getMatchStrategy(Class<?> clazz) {
635
        String className = clazz.getName();
636
        if (getBooleanValue(MATCH_STRATEGY_PREFIX + className)) {
637
            IMatchStrategy matchStrategy = getDefaultMatchStrategy(clazz);
638

    
639
            //TODO CacheMatchers (or multiple field matchers in future) are missing here
640
            for (FieldMatcher fieldMatcher : matchStrategy.getMatching().getFieldMatchers(false)) {
641
                String fieldName = fieldMatcher.getPropertyName();
642
                String matchModeName = getStringValue(
643
                        getMatchStrategyFieldName(className, fieldName));
644
                MatchMode matchMode = MatchMode.valueOf(matchModeName);
645
                try {
646
                    matchStrategy.setMatchMode(fieldName, matchMode);
647
                } catch (MatchException e) {
648
                    MessagingUtils.error(PreferencesUtil.class, e);
649
                    throw new RuntimeException(e);
650
                }
651
            }
652

    
653
            return matchStrategy;
654
        }
655
        return getDefaultMatchStrategy(clazz);
656
    }
657

    
658
    /**
659
     * Stores a matchStrategy into the preference store.
660
     *
661
     * @param matchStrategy
662
     *            a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy}
663
     *            object.
664
     */
665
    public static void setMatchStrategy(IMatchStrategy matchStrategy) {
666
        String className = "ANY class"; //FIXME was: matchStrategy.getMatchClass().getName(); seems currently not in use
667
        setBooleanValue(MATCH_STRATEGY_PREFIX + className, true);
668

    
669
        List<FieldMatcher> fieldMatchers = matchStrategy.getMatching().getFieldMatchers(false);
670

    
671
        for (FieldMatcher fieldMatcher : fieldMatchers) {
672
            String fieldName = fieldMatcher.getPropertyName();
673
            setStringValue(
674
                    getMatchStrategyFieldName(className, fieldName),
675
                    fieldMatcher.getMatchMode().name());
676
        }
677
    }
678

    
679
    /**
680
     * Helper method to create the preference property for a match field.
681
     *
682
     * @param className
683
     * @param fieldName
684
     * @return
685
     */
686
    private static String getMatchStrategyFieldName(String className,
687
            String fieldName) {
688
        return MATCH_STRATEGY_PREFIX + className + "." + fieldName;
689
    }
690

    
691
    /**
692
     * Returns the default match strategy for a given class.
693
     *
694
     * @param clazz
695
     *            a {@link java.lang.Class} object.
696
     * @return a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy} object.
697
     */
698
    public static IMatchStrategy getDefaultMatchStrategy(Class clazz) {
699
        return DefaultMatchStrategy.NewInstance(clazz);
700
    }
701

    
702
    public static String getDateFormatPattern() {
703
        // TODO make this configurable in properties
704
        String pattern = "Y-M-d H:m";
705
        return pattern;
706
    }
707

    
708
    public static <T extends TermBase> void addTermToPreferredTerms(T term) {
709

    
710
        // VocabularyEnum vocabulary =
711
        // VocabularyEnum.getVocabularyEnum(term.getClass());
712
        //
713
        // getPreferenceStore().setValue(getPreferenceKey(term),
714
        // VocabularyStore.getTermVocabulary(vocabulary).getTerms().contains(term));
715
        //
716
        // firePreferencesChanged(term.getClass());
717
    }
718

    
719
    /**
720
     * Construct a unique key using the CdmBase object's uuid
721
     *
722
     * @param cdmBase
723
     * @return
724
     */
725
    private static String getPreferenceKey(ICdmBase cdmBase) {
726
        cdmBase = HibernateProxyHelper.deproxy(cdmBase);
727

    
728
        String key = cdmBase.getClass().getName().concat(".")
729
                .concat(cdmBase.getUuid().toString());
730
        if (key.contains("javassist")) {
731
            MessagingUtils.info("proxy");
732
        }
733
        return key;
734
    }
735

    
736
    /**
737
     * Construct a unique key using the CdmBase object's uuid
738
     *
739
     * @param cdmBase
740
     * @return
741
     */
742
    public static String getPreferenceKey(ISimpleTerm simpleTerm) {
743
        simpleTerm = HibernateProxyHelper.deproxy(simpleTerm);
744
        String key = simpleTerm.getClass().getName().concat(".")
745
                .concat(simpleTerm.getUuid().toString());
746
        if (key.contains("javassist")) {
747
            MessagingUtils.warn(PreferencesUtil.class,
748
                    "Trying to persist a preference based on a proxy class.");
749
        }
750
        return key;
751
    }
752

    
753

    
754

    
755
    /**
756
     * Construct a unique key using the CdmBase object's uuid
757
     *
758
     * @param cdmBase
759
     * @return
760
     */
761
    public static String getPreferenceKey(IDefinedTerm definedTerm) {
762
        definedTerm = HibernateProxyHelper.deproxy(definedTerm);
763
        String key = definedTerm.getClass().getName().concat(".")
764
                .concat(definedTerm.getUuid().toString());
765
        if (key.contains("javassist")) {
766
            MessagingUtils.warn(PreferencesUtil.class,
767
                    "Trying to persist a preference based on a proxy class.");
768
        }
769
        return key;
770
    }
771

    
772
    /**
773
     * Retrieves search preferences from the preference store
774
     *
775
     * @return an {@link ITaxonServiceConfigurator} to pass to search methods
776
     */
777
    public static IFindTaxaAndNamesConfigurator getSearchConfigurator() {
778
        IFindTaxaAndNamesConfigurator configurator = initializeSearchConfigurator();
779

    
780
        configurator.setDoTaxa(getBooleanValue(
781
                TAXON_SERVICE_CONFIGURATOR_TAXA));
782
        configurator.setDoSynonyms(getBooleanValue(
783
                TAXON_SERVICE_CONFIGURATOR_SYNONYMS));
784
        configurator.setDoNamesWithoutTaxa(getBooleanValue(
785
                TAXON_SERVICE_CONFIGURATOR_NAMES));
786
        configurator.setDoTaxaByCommonNames(getBooleanValue(
787
                TAXON_SERVICE_CONFIGURATOR_COMMON_NAMES));
788
        //configurator.setMatchMode(eu.etaxonomy.cdm.persistence.query.MatchMode.valueOf(getStringValue(TAXON_SERVICE_CONFIGURATOR_MATCH_MODE)));
789

    
790
        return configurator;
791
    }
792

    
793
    /**
794
     * create new preferences, setting all search options to true
795
     *
796
     * @return a
797
     *         {@link eu.etaxonomy.cdm.api.service.config.ITaxonServiceConfigurator}
798
     *         object.
799
     */
800
    public static IFindTaxaAndNamesConfigurator initializeSearchConfigurator() {
801
        IFindTaxaAndNamesConfigurator configurator = FindTaxaAndNamesConfiguratorImpl.NewInstance();
802

    
803
        configurator.setDoTaxa(true);
804
        configurator.setDoSynonyms(true);
805
        configurator.setDoNamesWithoutTaxa(true);
806
        configurator.setDoTaxaByCommonNames(true);
807

    
808
        configurator.setTaxonPropertyPath(Arrays.asList("$", "titleCache",
809
                "name", "name.$", "relationsFromThisTaxon.$"));
810

    
811
        configurator.setSynonymPropertyPath(Arrays.asList("$", "titleCache",
812
                "name", "name.$", "synonyms.relatedTo.*"));
813

    
814
        // DEFAULT VALUES
815
        // match mode is a simple like, actually all other match modes are kind
816
        // of bogus
817
        configurator
818
                .setMatchMode(eu.etaxonomy.cdm.persistence.query.MatchMode.ANYWHERE);
819
        // we set page number and size here as this should always be unlimited
820
        configurator.setPageNumber(0);
821
        // TODO currently limit results to 10000
822
        configurator.setPageSize(10000);
823
        //setSearchConfigurator(configurator) ;
824
        return configurator;
825
    }
826

    
827
    /**
828
     * Store search preferences
829
     *
830
     * @param configurator
831
     *            a
832
     *            {@link eu.etaxonomy.cdm.api.service.config.ITaxonServiceConfigurator}
833
     *            object.
834
     */
835
    public static void setSearchConfigurator(
836
            IFindTaxaAndNamesConfigurator configurator) {
837
        getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_TAXA,
838
                configurator.isDoTaxa());
839
        getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_SYNONYMS,
840
                configurator.isDoSynonyms());
841
        getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_NAMES,
842
                configurator.isDoNamesWithoutTaxa());
843
        getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_COMMON_NAMES,
844
                configurator.isDoTaxaByCommonNames());
845
    }
846

    
847
    public static void firePreferencesChanged(Class clazz) {
848
        getPreferenceStore().firePropertyChangeEvent(PREFERRED_TERMS_CHANGE,
849
                null, clazz);
850
    }
851

    
852

    
853
    public static String createPreferenceString(String property){
854
       return prefKey(property);
855

    
856
    }
857
    public static String createOverridePreferenceString(String property){
858
           return prefOverrideKey(property);
859

    
860
        }
861

    
862
    /**
863
     * Set default values for preferences
864
     */
865
    public static void setDefaults() {
866
        getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_TAXA, true);
867
        getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_SYNONYMS,
868
                true);
869
        getPreferenceStore().setDefault(createPreferenceString(EDIT_MAP_SERVICE_ACCES_POINT),
870
                "http://edit.africamuseum.be/edit_wp5/v1.2/rest_gen.php");
871
        //FIXME : changed default for SHOULD_CONNECT_AT_STARTUP to false (ticket 3828) until resolution
872
        getPreferenceStore().setDefault(createPreferenceString(SHOULD_CONNECT_AT_STARTUP), false);
873
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.MobotOpenUrlServiceAccessPoint.getKey()),
874
                "http://www.biodiversitylibrary.org/openurl");
875
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.MobotOpenUrlServiceMaxWidth.getKey()), "1000");
876
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.MobotOpenUrlServiceMaxHeight.getKey()), "1000");
877
        getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_TAXA, true);
878
        getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_SYNONYMS, true);
879
        getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_NAMES, true);
880
        getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_COMMON_NAMES, true);
881

    
882
        //Distribution Editor:
883
//      getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.DistributionEditorActivated.getKey()), Boolean.valueOf(PreferencePredicate.DistributionEditorActivated.getDefaultValue().toString()));
884
//      getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey()), PreferencePredicate.DisplayOfAreasInDistributionEditor.getDefaultValue().toString());
885
//      getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.DisplayOfStatus.getKey()), PreferencePredicate.DisplayOfStatus.getDefaultValue().toString());
886

    
887

    
888
        //Name Details
889
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.NameDetailsView.getKey()), new NameDetailsConfigurator(false).toString());
890

    
891
        //Navigator preferences
892
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.TaxonNodeOrder.getKey()), NavigatorOrderEnum.RankAndNameOrder.getKey());
893

    
894
        //getPreferenceStore().setDefault(createPreferenceString(Prefe), true);
895

    
896
        getPreferenceStore().setDefault(createPreferenceString(SHOW_ADVANCED_MEDIA_SECTION), false);
897

    
898
        getPreferenceStore().setDefault(createPreferenceString(SHOW_MEDIA_PREVIEW), false);
899
        //override db preferences
900
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.AbcdImportConfig.getKey())), false);
901
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.ShowSpecimen.getKey())), true);
902
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.NameDetailsView.getKey())), false);
903
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.DistributionEditorActivated.getKey())), true);
904
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.AvailableDistributionStatus.getKey())), true);
905
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.AvailableDistributionAreaTerms.getKey())), true);
906
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey())), true);
907
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.CommonNameAreaVocabularies.getKey())), false);
908
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.CommonNameReferencesWithMarker.getKey()), false);
909
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowTaxonNodeWizard.getKey()), Boolean.valueOf(PreferencePredicate.ShowTaxonNodeWizard.getDefaultValue().toString()));
910
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowNamespaceInSource.getKey()), Boolean.valueOf(PreferencePredicate.ShowNamespaceInSource.getDefaultValue().toString()));
911
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowIdInSource.getKey()), Boolean.valueOf(PreferencePredicate.ShowIdInSource.getDefaultValue().toString()));
912
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.DisableMultiClassification.getKey()), Boolean.valueOf(PreferencePredicate.DisableMultiClassification.getDefaultValue().toString()));
913
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowImportExportMenu.getKey()), Boolean.valueOf(PreferencePredicate.ShowImportExportMenu.getDefaultValue().toString()));
914
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowSpecimen.getKey()), Boolean.valueOf(PreferencePredicate.ShowSpecimen.getDefaultValue().toString()));
915

    
916
    }
917

    
918
    public static void checkNomenclaturalCode() {
919
        // First time Editor is opened, no nomenclatural code has been set
920
        if (PreferencesUtil.getPreferredNomenclaturalCode() == null) {
921
            PreferencesUtil.setPreferredNomenclaturalCode(getPreferenceKey(NomenclaturalCode.ICNAFP), true);
922
        }
923

    
924

    
925

    
926
    }
927
    public static void setNomenclaturalCodePreferences(){
928
        ICdmRepository controller;
929
        controller = CdmStore.getCurrentApplicationConfiguration();
930
        PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.NomenclaturalCode);
931
        CdmPreference preference = null;
932
        if (controller == null){
933
            return ;
934
        }
935
        preference = controller.getPreferenceService().find(key);
936
        if (preference == null){
937
            return;
938
        }
939
//        setBooleanValue(ALLOW_OVERRIDE_NOMENCLATURAL_CODE_KEY, preference.isAllowOverride());
940

    
941
        int index = StringUtils.lastIndexOf(preference.getValue(), ".");
942
        UUID uuid = UUID.fromString(preference.getValue().substring(index +1, preference.getValue().length()));
943
        NomenclaturalCode preferredCode = NomenclaturalCode.getByUuid(uuid);
944

    
945
        setStringValue(PREFERRED_NOMENCLATURAL_CODE_KEY,
946
                getPreferenceKey(preferredCode));
947

    
948
    }
949

    
950
    public static void checkDefaultLanguage(){
951
        if(PreferencesUtil.getPreferredDefaultLangugae() == null){
952
           Shell shell = AbstractUtility.getShell();
953
           int open = new DefaultLanguageDialog(shell).open();
954
           if(open == Window.OK){
955
               PlatformUI.getWorkbench().restart();
956
           }
957
        }else{
958
            //TODO:In case of a reinstall, the config.ini will be overwritten
959
            //     here you create config.ini with the stored key from preferences
960
        }
961
    }
962

    
963
    public static String getMapServiceAccessPoint() {
964
        return getStringValue(EDIT_MAP_SERVICE_ACCES_POINT);
965
    }
966

    
967
    public static boolean shouldConnectAtStartUp() {
968
        //FIXME :  force SHOULD_CONNECT_AT_STARTUP to false (ticket 3828) until resolution
969
        //return getBooleanValue(SHOULD_CONNECT_AT_STARTUP);
970
        return false;
971
    }
972

    
973
    public static TermTree getDefaultFeatureTreeForTextualDescription() {
974
        String uuidString = getStringValue(
975
                FEATURE_TREE_DEFAULT_TEXT);
976
        if (StringUtils.isBlank(uuidString)) {
977
            return null;
978
        }
979
        TermTree tree = CdmStore.getService(
980
                ITermTreeService.class).load(UUID.fromString(uuidString));
981
        if (tree.getId() == 0) {
982
            return null;
983
        }
984
        return tree;
985
    }
986

    
987
    public static TermTree getDefaultFeatureTreeForStructuredDescription() {
988
        String uuidString = getStringValue(
989
                FEATURE_TREE_DEFAULT_STRUCTURE);
990
        return StringUtils.isBlank(uuidString) ? null : CdmStore.getService(
991
                ITermTreeService.class).load(UUID.fromString(uuidString));
992
    }
993

    
994
    public static void setSortRanksHierarchichally(boolean selection) {
995
        setBooleanValue(SORT_RANKS_HIERARCHICHALLY, selection);
996
    }
997

    
998
    public static boolean getSortRanksHierarchichally() {
999
        return getBooleanValue(SORT_RANKS_HIERARCHICHALLY);
1000
    }
1001

    
1002
    public static boolean isMultilanguageTextEditingCapability() {
1003
        return getBooleanValue(
1004
                MULTILANGUAGE_TEXT_EDITING_CAPABILITY);
1005
    }
1006

    
1007
    public static Language getGlobalLanguage() {
1008

    
1009

    
1010
        String languageUuidString = getStringValue(
1011
                GLOBAL_LANGUAGE_UUID);
1012

    
1013
        if(!CdmStore.isActive()) {
1014
            MessagingUtils.noDataSourceWarningDialog(languageUuidString);
1015
            return null;
1016
        }
1017

    
1018
        if (CdmUtils.isBlank(languageUuidString)) {
1019
            return Language.getDefaultLanguage();
1020
        }
1021

    
1022
        UUID languageUuid = UUID.fromString(languageUuidString);
1023
        return (Language) CdmStore.getService(ITermService.class).load(
1024
                languageUuid);
1025
    }
1026

    
1027
    public static void setGlobalLanguage(Language language) {
1028
        if(language != null) {
1029
            setStringValue(GLOBAL_LANGUAGE_UUID,language.getUuid().toString());
1030
            CdmStore.setDefaultLanguage(language);
1031
        }
1032

    
1033
    }
1034

    
1035
    public static Map<MarkerType, Boolean> getEditMarkerTypePreferences() {
1036
        List<MarkerType> markerTypes = CdmStore.getTermManager()
1037
                .getPreferredTerms(MarkerType.class);
1038

    
1039
        Map<MarkerType, Boolean> result = new HashMap<MarkerType, Boolean>();
1040

    
1041
        for (MarkerType markerType : markerTypes) {
1042
            String name = getMarkerTypeEditingPreferenceKey(markerType);
1043
            Boolean value = getBooleanValue(name);
1044

    
1045
            result.put(markerType, value);
1046
        }
1047

    
1048
        return result;
1049
    }
1050

    
1051
    public static void setEditMarkerTypePreferences(
1052
            Map<MarkerType, Boolean> markerTypeEditingMap) {
1053
        for (MarkerType markerType : markerTypeEditingMap.keySet()) {
1054
            String name = getMarkerTypeEditingPreferenceKey(markerType);
1055
            setBooleanValue(name,
1056
                    markerTypeEditingMap.get(markerType));
1057
        }
1058

    
1059
    }
1060

    
1061
    private static String getMarkerTypeEditingPreferenceKey(
1062
            MarkerType markerType) {
1063
        markerType = HibernateProxyHelper.deproxy(markerType);
1064
        return markerType.getClass().getName() + EDIT_MARKER_TYPE_PREFIX;
1065
    }
1066

    
1067
    public static void setEditMarkerTypePreference(MarkerType markerType,
1068
            boolean edit) {
1069
        setBooleanValue(
1070
                getMarkerTypeEditingPreferenceKey(markerType), edit);
1071
    }
1072

    
1073
    public static DerivedUnitFacadeConfigurator getDerivedUnitConfigurator() {
1074
        DerivedUnitFacadeConfigurator configurator = DerivedUnitFacadeConfigurator
1075
                .NewInstance();
1076
        configurator.setMoveDerivedUnitMediaToGallery(true);
1077
        configurator.setMoveFieldObjectMediaToGallery(true);
1078
        return configurator;
1079
    }
1080

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

    
1110
    /**
1111
     * This method loads a property from a given file and returns it.
1112
     *
1113
     * @param filename
1114
     * @return
1115
     * @throws IOException
1116
     */
1117
    private Properties load(String filename) throws IOException {
1118
        FileInputStream in = new FileInputStream(filename);
1119
        Properties prop = new Properties();
1120
        prop.load(in);
1121
        in.close();
1122
        return prop;
1123
    }
1124

    
1125
    /**
1126
     * This method saves a property to the specified file.
1127
     *
1128
     * @param filename
1129
     * @param properties
1130
     * @throws IOException
1131
     */
1132
    private void save(String filename, Properties properties) throws IOException{
1133
        FileOutputStream fos =  new FileOutputStream(filename);
1134
        properties.store(fos, "");
1135
        fos.close();
1136
    }
1137

    
1138
    /**
1139
     * Saves a list of P2 Metadata Repositories as string with specified delimiters
1140
     *
1141
     * @param p2Repos
1142
     */
1143
    public static void setP2Repositories(List<MetadataRepositoryElement> p2Repos) {
1144
        StringBuilder sb = new StringBuilder();
1145
        for(MetadataRepositoryElement p2Repo : p2Repos) {
1146
            sb.append(P2_REPOSITORIES_DELIM);
1147
            if(p2Repo.getName() == null || p2Repo.getName().isEmpty()) {
1148
                sb.append("-");
1149
            } else {
1150
                sb.append(p2Repo.getName());
1151
            }
1152
            sb.append(P2_REPOSITORY_FIELDS_DELIM);
1153
            sb.append(p2Repo.getLocation().toString());
1154
            sb.append(P2_REPOSITORY_FIELDS_DELIM);
1155
            sb.append(String.valueOf(p2Repo.isEnabled()));
1156
        }
1157
        getPreferenceStore().setValue(P2_REPOSITORY_LIST, sb.toString());
1158
    }
1159

    
1160

    
1161
    /**
1162
     * Retrieves a list of previously saved P2 repositories
1163
     *
1164
     * @return
1165
     */
1166
    public static List<MetadataRepositoryElement> getP2Repositories() {
1167
        List<MetadataRepositoryElement> p2Repos = new ArrayList<MetadataRepositoryElement>();
1168
        String p2ReposPref =  getStringValue(P2_REPOSITORY_LIST);
1169
        if(p2ReposPref != null && !p2ReposPref.isEmpty()) {
1170
            StringTokenizer p2ReposPrefST = new StringTokenizer(p2ReposPref,P2_REPOSITORIES_DELIM);
1171

    
1172
            while(p2ReposPrefST.hasMoreTokens()) {
1173
                String p2RepoStr = p2ReposPrefST.nextToken();
1174
                StringTokenizer p2ReposStrST = new StringTokenizer(p2RepoStr,P2_REPOSITORY_FIELDS_DELIM);
1175
                if(p2ReposStrST.countTokens()==3) {
1176
                    String nickname = p2ReposStrST.nextToken();
1177
                    URI uri = null;
1178
                    try {
1179
                        uri = new URI(p2ReposStrST.nextToken());
1180
                    } catch (URISyntaxException e) {
1181
                        continue;
1182
                    }
1183
                    boolean enabled = Boolean.parseBoolean(p2ReposStrST.nextToken());
1184
                    MetadataRepositoryElement mre = new MetadataRepositoryElement(null, uri, true);
1185
                    mre.setNickname(nickname);
1186
                    mre.setEnabled(enabled);
1187
                    p2Repos.add(mre);
1188
                }
1189
            }
1190
        }
1191

    
1192
        return p2Repos;
1193
    }
1194

    
1195
    /**
1196
     * enables/disables nested composite. <br>
1197
     *
1198
     * @param ctrl - Composite to be en-/disabeld
1199
     * @param enabled - boolean
1200
     */
1201
    public static void recursiveSetEnabled(Control ctrl, boolean enabled) {
1202
        if (ctrl instanceof Composite) {
1203
            Composite comp = (Composite) ctrl;
1204
            for (Control c : comp.getChildren()) {
1205
                recursiveSetEnabled(c, enabled);
1206
            }
1207
        } else {
1208
            ctrl.setEnabled(enabled);
1209
        }
1210
    }
1211

    
1212
    public static void setSortNodes(NavigatorOrderEnum nodesOrder) {
1213
        setStringValue(PreferencePredicate.TaxonNodeOrder.getKey(), nodesOrder.key);
1214

    
1215
    }
1216

    
1217
    public static NavigatorOrderEnum getSortNodes() {
1218
        return NavigatorOrderEnum.valueOf(getStringValue(PreferencePredicate.TaxonNodeOrder.getKey()));
1219

    
1220
    }
1221

    
1222
    public static boolean isNodesSortedNaturally() {
1223
        NavigatorOrderEnum value = NavigatorOrderEnum.valueOf(getStringValue(PreferencePredicate.TaxonNodeOrder.getKey()));
1224
        return value.equals(NavigatorOrderEnum.NaturalOrder);
1225

    
1226
    }
1227

    
1228
    public static boolean isNodesSortedByName() {
1229
        NavigatorOrderEnum value = NavigatorOrderEnum.valueOf(getStringValue(PreferencePredicate.TaxonNodeOrder.getKey()));
1230
        return value.equals(NavigatorOrderEnum.AlphabeticalOrder);
1231

    
1232
    }
1233

    
1234
    public static boolean isNodesSortedByNameAndRank() {
1235
        NavigatorOrderEnum value = NavigatorOrderEnum.valueOf(getStringValue(PreferencePredicate.TaxonNodeOrder.getKey()));
1236
        return value.equals(NavigatorOrderEnum.RankAndNameOrder);
1237

    
1238
    }
1239

    
1240
    public static boolean isStoreNavigatorState() {
1241
        return getBooleanValue(RESTORE_NAVIGATOR_STATE);
1242

    
1243
    }
1244

    
1245
    public static void setStoreNavigatorState(boolean selection) {
1246
        setBooleanValue(RESTORE_NAVIGATOR_STATE, selection);
1247

    
1248
    }
1249

    
1250
    public static boolean isShowUpWidgetIsDisposedMessages() {
1251
       return getBooleanValue(IS_SHOW_UP_WIDGET_IS_DISPOSED);
1252
    }
1253
    public static void setShowUpWidgetIsDisposedMessages(boolean selection) {
1254
        setBooleanValue(IS_SHOW_UP_WIDGET_IS_DISPOSED, selection);
1255
    }
1256

    
1257
    public static boolean isShowIdInVocabularyInChecklistEditor() {
1258
        String area_display = getStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey());
1259
        if (area_display.equals(TermDisplayEnum.IdInVocabulary.getKey())) {
1260
            return true;
1261
        }else{
1262
            return false;
1263
        }
1264
    }
1265
    public static boolean isShowSymbol1InChecklistEditor() {
1266
        String area_display = getStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey());
1267
        if (area_display.equals(TermDisplayEnum.Symbol1.getKey())) {
1268
            return true;
1269
        }else{
1270
            return false;
1271
        }
1272
     }
1273
    public static boolean isShowSymbol2InChecklistEditor() {
1274
        String area_display = getStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey());
1275
        if (area_display.equals(TermDisplayEnum.Symbol2.getKey())) {
1276
            return true;
1277
        }else{
1278
            return false;
1279
        }
1280
     }
1281
    public static void setAreaDisplayInChecklistEditor(String selection) {
1282
        setStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey(), selection);
1283
    }
1284

    
1285
    public static void setOwnDescriptionForChecklistEditor(boolean selection) {
1286
        setBooleanValue(PreferencePredicate.OwnDescriptionForDistributionEditor.getKey(), selection);
1287
    }
1288

    
1289
    public static boolean isOwnDescriptionForChecklistEditor() {
1290
        return getBooleanValue(PreferencePredicate.OwnDescriptionForDistributionEditor.getKey());
1291
    }
1292

    
1293
    public static TermDisplayEnum displayAreaInChecklistEditor() {
1294
        TermDisplayEnum result;
1295
        try{
1296
            result = TermDisplayEnum.byKey(getStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey()));
1297
        }catch (IllegalArgumentException e){
1298
           result = ((TermDisplayEnum) PreferencePredicate.DisplayOfAreasInDistributionEditor.getDefaultValue());
1299
        }
1300
       return result;
1301
    }
1302

    
1303
    public static TermDisplayEnum displayStatusInChecklistEditor() {
1304
        TermDisplayEnum result;
1305
        try{
1306
            result = TermDisplayEnum.byKey(getStringValue(PreferencePredicate.DisplayOfStatus.getKey()));
1307
        }catch (IllegalArgumentException e){
1308
           result = ((TermDisplayEnum) PreferencePredicate.DisplayOfStatus.getDefaultValue());
1309
        }
1310
       return result;
1311
    }
1312
    public static void setDisplayStatusInChecklistEditor(String selection) {
1313
        setStringValue(PreferencePredicate.DisplayOfStatus.getKey(), selection);
1314

    
1315
    }
1316

    
1317
    public static boolean isShowRankInChecklistEditor() {
1318
        return getBooleanValue(PreferencePredicate.ShowRankInDistributionEditor.getKey());
1319
    }
1320
    public static void setShowRankInChecklistEditor(boolean selection) {
1321
       setBooleanValue(PreferencePredicate.ShowRankInDistributionEditor.getKey(), selection);
1322
    }
1323

    
1324
    public static NameDetailsConfigurator getPreferredNameDetailsConfiguration( boolean local) {
1325
        NameDetailsConfigurator config = new NameDetailsConfigurator(true);
1326
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1327
        CdmPreference preference = null;
1328
        String value;
1329
        if (!local) {
1330
            PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.NameDetailsView);
1331
            preference =  getPreferenceFromDB(PreferencePredicate.NameDetailsView);
1332
            if (preference == null){
1333
                return null;
1334
            }
1335

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

    
1375
    public static NameDetailsConfigurator getPreferredNameDetailsConfiguration() {
1376
        NameDetailsConfigurator config = new NameDetailsConfigurator(true);
1377

    
1378
        String value;
1379

    
1380
        value = getStringValue(PreferencePredicate.NameDetailsView.getKey(), false);
1381
        if (value != null){
1382
            String [] sections = value.split(";");
1383
            Map<String, Boolean> sectionMap = new HashMap<String, Boolean>();
1384
            String[] sectionValues;
1385
            for (String sectionValue: sections){
1386
                sectionValues = sectionValue.split(":");
1387
                sectionMap.put(sectionValues[0], Boolean.valueOf(sectionValues[1]));
1388
            }
1389

    
1390
            config.setSimpleDetailsViewActivated(getValue(sectionMap, "simpleViewActivated"));
1391

    
1392
            config.setTaxonSectionActivated(getValue(sectionMap, "taxon"));
1393

    
1394
            config.setSecDetailsActivated(getValue(sectionMap, "taxon.SecDetails"));
1395
            config.setSecEnabled(getValue(sectionMap, "taxon.SecEnabled"));
1396

    
1397
            config.setLSIDActivated(getValue(sectionMap, "lsid"));
1398

    
1399
            config.setNomenclaturalCodeActived(getValue(sectionMap, "nc"));
1400

    
1401
            config.setAppendedPhraseActivated(getValue(sectionMap, "ap"));
1402

    
1403
            config.setRankActivated(getValue(sectionMap, "rank"));
1404

    
1405
            config.setAtomisedEpithetsActivated(getValue(sectionMap, "atomisedEpithets"));
1406

    
1407
            config.setAuthorshipSectionActivated(getValue(sectionMap,"author"));
1408

    
1409
            config.setNomenclaturalReferenceSectionActivated(sectionMap.get("nomRef"));
1410

    
1411
            config.setNomenclaturalStatusSectionActivated(getValue(sectionMap, "nomStat"));
1412

    
1413
            config.setProtologueActivated(getValue(sectionMap,"protologue"));
1414

    
1415
            config.setTypeDesignationSectionActivated(getValue(sectionMap,"typeDes"));
1416

    
1417
            config.setNameRelationsSectionActivated(getValue(sectionMap,"nameRelation"));
1418

    
1419
                config.setHybridActivated(getValue(sectionMap,"hybrid"));
1420
        }
1421
        return config;
1422
    }
1423

    
1424
    public static void setPreferredNameDetailsConfiguration(NameDetailsConfigurator config, boolean local) {
1425
        CdmPreference preference = null;
1426

    
1427
        if (!local) {
1428
            preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.NameDetailsView, config.toString());
1429

    
1430
            setPreferenceToDB(preference);
1431
        }
1432
        else{
1433
            setStringValue(PreferencePredicate.NameDetailsView.getKey(), config.toString());
1434
        }
1435

    
1436

    
1437
    }
1438

    
1439
    private static Boolean getValue(Map<String, Boolean> sectionMap, String string) {
1440
        if (sectionMap.containsKey(string)){
1441
            return sectionMap.get(string);
1442
        }else{
1443
            return true;
1444
        }
1445

    
1446
    }
1447

    
1448
    public static Abcd206ImportConfigurator getDBAbcdImportConfigurationPreference() {
1449

    
1450
        Abcd206ImportConfigurator config = Abcd206ImportConfigurator.NewInstance(null,null);
1451
        ICdmRepository controller;
1452
        controller = CdmStore.getCurrentApplicationConfiguration();
1453
        PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AbcdImportConfig);
1454
        CdmPreference preference = null;
1455
        if (controller == null){
1456
            return null;
1457
        }
1458
        preference = controller.getPreferenceService().find(key);
1459
        if (preference == null){
1460
            return config;
1461
         } else{
1462
             String configString = preference.getValue();
1463
             extractAbcdConfiguratorFromPreferenceString(config, configString);
1464
         }
1465
        return config;
1466
    }
1467

    
1468
    public static void extractAbcdConfiguratorFromPreferenceString(Abcd206ImportConfigurator config,
1469
            String configString) {
1470
        if(configString!=null){
1471
             String[] configArray = configString.split(";");
1472

    
1473
             for (String configItem: configArray){
1474
                 String[] keyValue = configItem.split(":");
1475
                 String keyString = keyValue[0];
1476
                 String valueString = null;
1477
                 if (keyValue.length>1){
1478
                     valueString = keyValue[1];
1479
                     if (keyValue.length>2){
1480

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

    
1532

    
1533
             }
1534
         }
1535
    }
1536

    
1537
    public static Abcd206ImportConfigurator getLocalAbcdImportConfigurator(){
1538
       Abcd206ImportConfigurator config = Abcd206ImportConfigurator.NewInstance(null,null);
1539
       String configString = getStringValue(PreferencePredicate.AbcdImportConfig.getKey(), true);
1540
       extractAbcdConfiguratorFromPreferenceString(config, configString);
1541
       return config;
1542

    
1543
    }
1544

    
1545
    public static void updateAbcdImportConfigurationPreference() {
1546
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1547

    
1548
        CdmPreference pref = cache.findBestMatching(CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AbcdImportConfig));
1549

    
1550
        if (!getBooleanValue(prefOverrideKey(PreferencePredicate.AbcdImportConfig.getKey())) || !pref.isAllowOverride()){
1551
            resetToDBPreferenceAbcdCOnfigurator();
1552

    
1553
        }
1554
    }
1555

    
1556
    public static void resetToDBPreferenceAbcdCOnfigurator(){
1557
        Abcd206ImportConfigurator config = getDBAbcdImportConfigurationPreference();
1558
        setStringValue(PreferencePredicate.AbcdImportConfig.getKey(), config.toString());
1559

    
1560
    }
1561

    
1562
    public static boolean isSortTaxaByRankAndName() {
1563

    
1564
        return getBooleanValue(IPreferenceKeys.SORT_TAXA_BY_RANK_AND_NAME);
1565
    }
1566

    
1567
    public static TermOrder getSortNamedAreasInDistributionEditor() {
1568
        TermOrder result;
1569
        try{
1570
            result = TermOrder.valueOf(getStringValue(PreferencePredicate.AreasSortedInDistributionEditor.getKey()));
1571
        }catch (IllegalArgumentException e){
1572
            result = (TermOrder)PreferencePredicate.AreasSortedInDistributionEditor.getDefaultValue();
1573
        }
1574
        return result;
1575
    }
1576

    
1577
    public static void setSortNamedAreasInDistributionEditor(String isSortByVocabularyOrder) {
1578
        setStringValue(PreferencePredicate.AreasSortedInDistributionEditor.getKey(), isSortByVocabularyOrder);
1579

    
1580
    }
1581

    
1582
    public static void setLastSelectedReference(
1583
            List<String> lastSelectedReferences) {
1584

    
1585
        setStringValue(PreferencesUtil.LAST_SELECTED_REFERENCES, lastSelectedReferences.toString());
1586
    }
1587

    
1588
    public static List<String> getLastSelectedReferences() {
1589

    
1590
        //IPreferenceStore preferenceStore = PreferencesUtil.getPreferenceStore();
1591
        String lastSelected = getStringValue(PreferencesUtil.LAST_SELECTED_REFERENCES);
1592
        List<String> result = new ArrayList<>();
1593
        if (!StringUtils.isBlank(lastSelected)){
1594
            Collections.addAll(result, lastSelected.substring(1,lastSelected.length()-1).split(", "));
1595
        }
1596
        return result;
1597
    }
1598

    
1599
    public static void setPreferredNamedAreasForDistributionEditor(
1600
            String saveCheckedElements, String saveGrayedElements, boolean local) {
1601
        if (local){
1602
            setStringValue(PreferencePredicate.AvailableDistributionAreaTerms.getKey(), saveCheckedElements);
1603

    
1604
        }
1605
        else{
1606
            CdmPreference preference = null;
1607

    
1608
            if (saveCheckedElements == null){
1609
                preference = getPreferenceFromDB(PreferencePredicate.AvailableDistributionAreaTerms);
1610

    
1611
                if (preference == null){
1612
                    return ;
1613
                } else{
1614
                    setStringValue(PreferencePredicate.AvailableDistributionAreaTerms.getKey(),
1615
                            saveCheckedElements);
1616
                    preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AvailableDistributionAreaTerms, saveCheckedElements);
1617
                    setPreferenceToDB(preference);
1618

    
1619
                }
1620
            } else{
1621
                preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AvailableDistributionAreaTerms, saveCheckedElements);
1622
                setPreferenceToDB(preference);
1623
                setStringValue(PreferencePredicate.AvailableDistributionAreaTerms.getKey(),
1624
                        saveCheckedElements);
1625

    
1626
            }
1627
        }
1628

    
1629
    }
1630

    
1631
    public static void setPreferredVocabulariesForDistributionEditor(String saveCheckedElements,
1632
            boolean local, boolean isOverride) {
1633
        if (local){
1634
            setStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(), saveCheckedElements);
1635
            setBooleanValue(prefOverrideKey(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey()), isOverride);
1636
        }
1637
        else{
1638
            ICdmRepository controller;
1639
            CdmPreference preference = null;
1640

    
1641
            if (saveCheckedElements == null){
1642
                preference = getPreferenceFromDB(PreferencePredicate.AvailableDistributionAreaVocabularies);
1643

    
1644
                if (preference == null){
1645
                    return ;
1646
                } else{
1647
                    setStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(),
1648
                            saveCheckedElements);
1649
                    preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AvailableDistributionAreaVocabularies, saveCheckedElements);
1650
                    preference.setAllowOverride(isOverride);
1651
                    setPreferenceToDB(preference);
1652
                }
1653
            } else{
1654
                preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AvailableDistributionAreaVocabularies, saveCheckedElements);
1655
                preference.setAllowOverride(isOverride);
1656
                setPreferenceToDB(preference);
1657
                setStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(),
1658
                        saveCheckedElements);
1659

    
1660
            }
1661
        }
1662
    }
1663

    
1664
    public static String getPreferredVocabulariesForDistributionEditor(boolean local) {
1665
        if (local){
1666

    
1667
            String pref = getStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(), local);
1668
            return pref;
1669
        }
1670
        else{
1671
            CdmPreference preference = null;
1672
            preference = getPreferenceFromDB(PreferencePredicate.AvailableDistributionAreaVocabularies);
1673
            if (preference == null){
1674
                return null;
1675
            } else{
1676
                return preference.getValue();
1677
            }
1678

    
1679
        }
1680
    }
1681

    
1682
    public static List<UUID> createUUIDListFromStringPref(String prefKey) {
1683
        String prefValue = PreferencesUtil.getStringValue(prefKey);
1684
        if (prefValue == null){
1685
            return null;
1686
        }
1687
        String[] stringArray = prefValue.split(";");
1688
        List<UUID> uuidList = new ArrayList();
1689
        for (String uuid: stringArray){
1690
            if (!StringUtils.isBlank(uuid)){
1691
                uuidList.add(UUID.fromString(uuid));
1692
            }
1693
        }
1694
        return uuidList;
1695
    }
1696

    
1697
    public static boolean getFilterCommonNameReferences(){
1698
        Boolean result = getBooleanValue(PreferencesUtil.FILTER_COMMON_NAME_REFERENCES);
1699
        if (result == null){
1700
            return false;
1701
        }
1702
        return result;
1703
    }
1704

    
1705
    public static void updateDBPreferences() {
1706

    
1707

    
1708
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1709
        cache.getAllTaxEditorDBPreferences();
1710

    
1711
        //ABCD Configurator
1712

    
1713
        //updateAbcdImportConfigurationPreference();
1714

    
1715
        //Name Details
1716
        NameDetailsConfigurator config = getPreferredNameDetailsConfiguration(false);
1717
        //    if (config != null ){
1718
        //        if (!getBooleanValue(OVERRIDE_NAME_DETAILS) ||  !getBooleanValue(ALLOW_OVERRIDE_NAME_DETAILS)){
1719
        //            setPreferredNameDetailsConfiguration(config, false);
1720
        //        }
1721
        //    }
1722

    
1723
    }
1724

    
1725
    public static void setPreferencesToDB(List<CdmPreference> preferences) {
1726

    
1727
        ICdmRepository controller;
1728
        //try{
1729
            if(CdmStore.isActive()){
1730
                controller = CdmStore.getCurrentApplicationConfiguration();
1731
                for (CdmPreference preference: preferences){
1732
                    if (preference.getValue() == null && preference.isAllowOverride()){
1733
                        controller.getPreferenceService().remove(preference.getKey());
1734

    
1735
                    }else{
1736
                        controller.getPreferenceService().set(preference);
1737

    
1738
                    }
1739

    
1740
                }
1741
                CdmPreferenceCache.instance().getAllTaxEditorDBPreferences();
1742

    
1743
            }
1744
        /*}catch(Exception e){
1745
            e.printStackTrace();
1746
        }*/
1747
    }
1748

    
1749
    /**
1750
     * Returns whether the named preference is known.
1751
     * @param prefKey the key of the preference
1752
     * @return <code>true</code> if the preference is known, <code>false</code> otherwise
1753
     */
1754
    public static boolean contains(String prefKey){
1755
        return getPreferenceStore().contains(prefKey(prefKey));
1756
    }
1757

    
1758
    /**
1759
     *
1760
     */
1761
    public static TermTree getPreferredFeatureTreeForNameDescription() {
1762
        if(preferredNameFeatureTree != null){
1763
            return preferredNameFeatureTree;
1764
        }
1765
        createPreferredFeatureTreeForNameDescription();
1766
        return preferredNameFeatureTree;
1767

    
1768
    }
1769

    
1770
    public static void createPreferredFeatureTreeForNameDescription() {
1771

    
1772
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1773
        CdmPreference pref = cache.get(PreferencePredicate.NameFeatures.getKey());
1774
        List<Feature> terms;
1775
        boolean override = PreferencesUtil.getBooleanValue(PreferencesUtil.createOverridePreferenceString(PreferencePredicate.NameFeatures.getKey()));
1776
        if (pref != null ){
1777
            List<UUID> uuids = PreferencesUtil.createUUIDListFromStringPref(pref.getValue());
1778
            terms = CdmStore.getTermManager().getTerms(uuids, Feature.class);
1779
        }else if (override){
1780
            terms = CdmStore.getTermManager().getPreferredTerms(CdmStore.getService(IVocabularyService.class).load(VocabularyEnum.NameFeature.getUuid()));
1781
        }else{
1782
            terms = new ArrayList();
1783
            terms.addAll(TermStore.getTerms(CdmStore.getService(IVocabularyService.class).load(VocabularyEnum.NameFeature.getUuid()), null));
1784
        }
1785
        terms.remove(Feature.PROTOLOGUE());
1786
        preferredNameFeatureTree = TermTree.NewInstance(terms);
1787

    
1788

    
1789
    }
1790

    
1791

    
1792

    
1793
}
(35-35/51)