Project

General

Profile

Download (70.2 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.name.NomenclaturalCode;
63
import eu.etaxonomy.cdm.model.term.IDefinedTerm;
64
import eu.etaxonomy.cdm.model.term.ISimpleTerm;
65
import eu.etaxonomy.cdm.model.term.TermBase;
66
import eu.etaxonomy.cdm.model.term.TermTree;
67
import eu.etaxonomy.cdm.model.term.VocabularyEnum;
68
import eu.etaxonomy.cdm.strategy.match.DefaultMatchStrategy;
69
import eu.etaxonomy.cdm.strategy.match.FieldMatcher;
70
import eu.etaxonomy.cdm.strategy.match.IMatchStrategy;
71
import eu.etaxonomy.cdm.strategy.match.MatchException;
72
import eu.etaxonomy.cdm.strategy.match.MatchMode;
73
import eu.etaxonomy.taxeditor.model.AbstractUtility;
74
import eu.etaxonomy.taxeditor.model.MessagingUtils;
75
import eu.etaxonomy.taxeditor.model.NomenclaturalCodeHelper;
76
import eu.etaxonomy.taxeditor.remoting.source.CdmRemoteSource;
77
import eu.etaxonomy.taxeditor.store.CdmStore;
78
import eu.etaxonomy.taxeditor.store.TermStore;
79
import eu.etaxonomy.taxeditor.store.internal.TaxeditorStorePlugin;
80
import eu.etaxonomy.taxeditor.ui.dialog.DefaultLanguageDialog;
81

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

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

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

    
100
    private static TermTree preferredNameFeatureTree;
101

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

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

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

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

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

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

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

    
155
            }
156

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

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

    
181
    }
182

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

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

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

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

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

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

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

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

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

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

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

    
239
    }
240

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

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

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

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

    
294
    }
295

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

    
304
    }
305

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

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

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

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

    
328
    }
329

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

    
353
    }
354

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

    
383
    }
384

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

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

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

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

    
443
            }
444
        }
445
        return null;
446

    
447

    
448

    
449
    }
450

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

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

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

    
468
    }
469

    
470
    public static NomenclaturalCode getPreferredNomenclaturalCode() {
471

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

    
474

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

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

    
487
        return getPreferredNomenclaturalCode(preferredCode);
488

    
489
    }
490

    
491
    public static NomenclaturalCode getPreferredNomenclaturalCode(String preferenceKeyNomenclaturalCode) {
492

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

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

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

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

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

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

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

    
535
        return pref;
536

    
537
    }
538

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

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

    
553
        return prefs;
554

    
555
    }
556

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

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

    
573

    
574

    
575
    }
576

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

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

    
590
        return pref;
591

    
592
    }
593

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

    
610
    }
611

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
752

    
753

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

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

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

    
789
        return configurator;
790
    }
791

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

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

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

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

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

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

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

    
851

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

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

    
859
        }
860

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

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

    
886

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

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

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

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

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

    
915
    }
916

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

    
923

    
924

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

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

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

    
947
    }
948

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

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

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

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

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

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

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

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

    
1006
    public static Language getGlobalLanguage() {
1007

    
1008

    
1009
        String languageUuidString = getStringValue(
1010
                GLOBAL_LANGUAGE_UUID);
1011

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

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

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

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

    
1032
    }
1033

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

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

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

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

    
1047
        return result;
1048
    }
1049

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

    
1058
    }
1059

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

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

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

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

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

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

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

    
1159

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

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

    
1191
        return p2Repos;
1192
    }
1193

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

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

    
1214
    }
1215

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

    
1219
    }
1220

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

    
1225
    }
1226

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

    
1231
    }
1232

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

    
1237
    }
1238

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

    
1242
    }
1243

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

    
1247
    }
1248

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

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

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

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

    
1292
    public static String displayAreaInChecklistEditor() {
1293
        String result = getStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey());
1294
        if (StringUtils.isBlank(result)){
1295
            return ((TermDisplayEnum) PreferencePredicate.DisplayOfAreasInDistributionEditor.getDefaultValue()).getKey();
1296
        }
1297
       return result;
1298
    }
1299

    
1300
    public static String displayStatusInChecklistEditor() {
1301
        String result = getStringValue(PreferencePredicate.DisplayOfStatus.getKey());
1302
        if (StringUtils.isBlank(result)){
1303
            return((TermDisplayEnum) PreferencePredicate.DisplayOfStatus.getDefaultValue()).getKey();
1304
        }
1305
       return result;
1306
    }
1307
    public static void setDisplayStatusInChecklistEditor(String selection) {
1308
        setStringValue(PreferencePredicate.DisplayOfStatus.getKey(), selection);
1309

    
1310
    }
1311

    
1312
    public static boolean isShowRankInChecklistEditor() {
1313
        return getBooleanValue(PreferencePredicate.ShowRankInDistributionEditor.getKey());
1314
    }
1315
    public static void setShowRankInChecklistEditor(boolean selection) {
1316
       setBooleanValue(PreferencePredicate.ShowRankInDistributionEditor.getKey(), selection);
1317
    }
1318

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

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

    
1367
    public static NameDetailsConfigurator getPreferredNameDetailsConfiguration() {
1368
        NameDetailsConfigurator config = new NameDetailsConfigurator(true);
1369

    
1370
        String value;
1371

    
1372
        value = getStringValue(PreferencePredicate.NameDetailsView.getKey(), false);
1373
        if (value != null){
1374
            String [] sections = value.split(";");
1375
            Map<String, Boolean> sectionMap = new HashMap<String, Boolean>();
1376
            String[] sectionValues;
1377
            for (String sectionValue: sections){
1378
                sectionValues = sectionValue.split(":");
1379
                sectionMap.put(sectionValues[0], Boolean.valueOf(sectionValues[1]));
1380
            }
1381

    
1382
            config.setSimpleDetailsViewActivated(getValue(sectionMap, "simpleViewActivated"));
1383

    
1384
            config.setTaxonSectionActivated(getValue(sectionMap, "taxon"));
1385

    
1386
            config.setSecDetailsActivated(getValue(sectionMap, "taxon.SecDetails"));
1387
            config.setSecEnabled(getValue(sectionMap, "taxon.SecEnabled"));
1388

    
1389
            config.setLSIDActivated(getValue(sectionMap, "lsid"));
1390

    
1391
            config.setNomenclaturalCodeActived(getValue(sectionMap, "nc"));
1392

    
1393
            config.setAppendedPhraseActivated(getValue(sectionMap, "ap"));
1394

    
1395
            config.setRankActivated(getValue(sectionMap, "rank"));
1396

    
1397
            config.setAtomisedEpithetsActivated(getValue(sectionMap, "atomisedEpithets"));
1398

    
1399
            config.setAuthorshipSectionActivated(getValue(sectionMap,"author"));
1400

    
1401
            config.setNomenclaturalReferenceSectionActivated(sectionMap.get("nomRef"));
1402

    
1403
            config.setNomenclaturalStatusSectionActivated(getValue(sectionMap, "nomStat"));
1404

    
1405
            config.setProtologueActivated(getValue(sectionMap,"protologue"));
1406

    
1407
            config.setTypeDesignationSectionActivated(getValue(sectionMap,"typeDes"));
1408

    
1409
            config.setNameRelationsSectionActivated(getValue(sectionMap,"nameRelation"));
1410

    
1411
                config.setHybridActivated(getValue(sectionMap,"hybrid"));
1412
        }
1413
        return config;
1414
    }
1415

    
1416
    public static void setPreferredNameDetailsConfiguration(NameDetailsConfigurator config, boolean local) {
1417
        CdmPreference preference = null;
1418

    
1419
        if (!local) {
1420
            preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.NameDetailsView, config.toString());
1421

    
1422
            setPreferenceToDB(preference);
1423
        }
1424
        else{
1425
            setStringValue(PreferencePredicate.NameDetailsView.getKey(), config.toString());
1426
        }
1427

    
1428

    
1429
    }
1430

    
1431
    private static Boolean getValue(Map<String, Boolean> sectionMap, String string) {
1432
        if (sectionMap.containsKey(string)){
1433
            return sectionMap.get(string);
1434
        }else{
1435
            return true;
1436
        }
1437

    
1438
    }
1439

    
1440
    public static Abcd206ImportConfigurator getDBAbcdImportConfigurationPreference() {
1441

    
1442
        Abcd206ImportConfigurator config = Abcd206ImportConfigurator.NewInstance(null,null);
1443
        ICdmRepository controller;
1444
        controller = CdmStore.getCurrentApplicationConfiguration();
1445
        PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AbcdImportConfig);
1446
        CdmPreference preference = null;
1447
        if (controller == null){
1448
            return null;
1449
        }
1450
        preference = controller.getPreferenceService().find(key);
1451
        if (preference == null){
1452
            return config;
1453
         } else{
1454
             String configString = preference.getValue();
1455
             extractAbcdConfiguratorFromPreferenceString(config, configString);
1456
         }
1457
        return config;
1458
    }
1459

    
1460
    public static void extractAbcdConfiguratorFromPreferenceString(Abcd206ImportConfigurator config,
1461
            String configString) {
1462
        if(configString!=null){
1463
             String[] configArray = configString.split(";");
1464

    
1465
             for (String configItem: configArray){
1466
                 String[] keyValue = configItem.split(":");
1467
                 String keyString = keyValue[0];
1468
                 String valueString = null;
1469
                 if (keyValue.length>1){
1470
                     valueString = keyValue[1];
1471
                     if (keyValue.length>2){
1472

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

    
1524

    
1525
             }
1526
         }
1527
    }
1528

    
1529
    public static Abcd206ImportConfigurator getLocalAbcdImportConfigurator(){
1530
       Abcd206ImportConfigurator config = Abcd206ImportConfigurator.NewInstance(null,null);
1531
       String configString = getStringValue(PreferencePredicate.AbcdImportConfig.getKey(), true);
1532
       extractAbcdConfiguratorFromPreferenceString(config, configString);
1533
       return config;
1534

    
1535
    }
1536

    
1537
    public static void updateAbcdImportConfigurationPreference() {
1538
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1539

    
1540
        CdmPreference pref = cache.findBestMatching(CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AbcdImportConfig));
1541

    
1542
        if (!getBooleanValue(prefOverrideKey(PreferencePredicate.AbcdImportConfig.getKey())) || !pref.isAllowOverride()){
1543
            resetToDBPreferenceAbcdCOnfigurator();
1544

    
1545
        }
1546
    }
1547

    
1548
    public static void resetToDBPreferenceAbcdCOnfigurator(){
1549
        Abcd206ImportConfigurator config = getDBAbcdImportConfigurationPreference();
1550
        setStringValue(PreferencePredicate.AbcdImportConfig.getKey(), config.toString());
1551

    
1552
    }
1553

    
1554
    public static boolean isSortTaxaByRankAndName() {
1555

    
1556
        return getBooleanValue(IPreferenceKeys.SORT_TAXA_BY_RANK_AND_NAME);
1557
    }
1558

    
1559
    public static String getSortNamedAreasInDistributionEditor() {
1560

    
1561
        return getStringValue(PreferencePredicate.AreasSortedInDistributionEditor.getKey());
1562
    }
1563

    
1564
    public static void setSortNamedAreasInDistributionEditor(String isSortByVocabularyOrder) {
1565
        setStringValue(PreferencePredicate.AreasSortedInDistributionEditor.getKey(), isSortByVocabularyOrder);
1566

    
1567
    }
1568

    
1569
    public static void setLastSelectedReference(
1570
            List<String> lastSelectedReferences) {
1571

    
1572
        setStringValue(PreferencesUtil.LAST_SELECTED_REFERENCES, lastSelectedReferences.toString());
1573
    }
1574

    
1575
    public static List<String> getLastSelectedReferences() {
1576

    
1577
        //IPreferenceStore preferenceStore = PreferencesUtil.getPreferenceStore();
1578
        String lastSelected = getStringValue(PreferencesUtil.LAST_SELECTED_REFERENCES);
1579
        List<String> result = new ArrayList<>();
1580
        if (!StringUtils.isBlank(lastSelected)){
1581
            Collections.addAll(result, lastSelected.substring(1,lastSelected.length()-1).split(", "));
1582
        }
1583
        return result;
1584
    }
1585

    
1586
    public static void setPreferredNamedAreasForDistributionEditor(
1587
            String saveCheckedElements, String saveGrayedElements, boolean local) {
1588
        if (local){
1589
            setStringValue(PreferencePredicate.AvailableDistributionAreaTerms.getKey(), saveCheckedElements);
1590

    
1591
        }
1592
        else{
1593
            CdmPreference preference = null;
1594

    
1595
            if (saveCheckedElements == null){
1596
                preference = getPreferenceFromDB(PreferencePredicate.AvailableDistributionAreaTerms);
1597

    
1598
                if (preference == null){
1599
                    return ;
1600
                } else{
1601
                    setStringValue(PreferencePredicate.AvailableDistributionAreaTerms.getKey(),
1602
                            saveCheckedElements);
1603
                    preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AvailableDistributionAreaTerms, saveCheckedElements);
1604
                    setPreferenceToDB(preference);
1605

    
1606
                }
1607
            } else{
1608
                preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AvailableDistributionAreaTerms, saveCheckedElements);
1609
                setPreferenceToDB(preference);
1610
                setStringValue(PreferencePredicate.AvailableDistributionAreaTerms.getKey(),
1611
                        saveCheckedElements);
1612

    
1613
            }
1614
        }
1615

    
1616
    }
1617

    
1618
    public static void setPreferredVocabulariesForDistributionEditor(String saveCheckedElements,
1619
            boolean local, boolean isOverride) {
1620
        if (local){
1621
            setStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(), saveCheckedElements);
1622
            setBooleanValue(prefOverrideKey(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey()), isOverride);
1623
        }
1624
        else{
1625
            ICdmRepository controller;
1626
            CdmPreference preference = null;
1627

    
1628
            if (saveCheckedElements == null){
1629
                preference = getPreferenceFromDB(PreferencePredicate.AvailableDistributionAreaVocabularies);
1630

    
1631
                if (preference == null){
1632
                    return ;
1633
                } else{
1634
                    setStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(),
1635
                            saveCheckedElements);
1636
                    preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AvailableDistributionAreaVocabularies, saveCheckedElements);
1637
                    preference.setAllowOverride(isOverride);
1638
                    setPreferenceToDB(preference);
1639
                }
1640
            } else{
1641
                preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AvailableDistributionAreaVocabularies, saveCheckedElements);
1642
                preference.setAllowOverride(isOverride);
1643
                setPreferenceToDB(preference);
1644
                setStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(),
1645
                        saveCheckedElements);
1646

    
1647
            }
1648
        }
1649
    }
1650

    
1651
    public static String getPreferredVocabulariesForDistributionEditor(boolean local) {
1652
        if (local){
1653

    
1654
            String pref = getStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(), local);
1655
            return pref;
1656
        }
1657
        else{
1658
            CdmPreference preference = null;
1659
            preference = getPreferenceFromDB(PreferencePredicate.AvailableDistributionAreaVocabularies);
1660
            if (preference == null){
1661
                return null;
1662
            } else{
1663
                return preference.getValue();
1664
            }
1665

    
1666
        }
1667
    }
1668

    
1669
    public static List<UUID> createUUIDListFromStringPref(String prefKey) {
1670
        String prefValue = PreferencesUtil.getStringValue(prefKey);
1671
        if (prefValue == null){
1672
            return null;
1673
        }
1674
        String[] stringArray = prefValue.split(";");
1675
        List<UUID> uuidList = new ArrayList();
1676
        for (String uuid: stringArray){
1677
            if (!StringUtils.isBlank(uuid)){
1678
                uuidList.add(UUID.fromString(uuid));
1679
            }
1680
        }
1681
        return uuidList;
1682
    }
1683

    
1684
    public static boolean getFilterCommonNameReferences(){
1685
        Boolean result = getBooleanValue(PreferencesUtil.FILTER_COMMON_NAME_REFERENCES);
1686
        if (result == null){
1687
            return false;
1688
        }
1689
        return result;
1690
    }
1691

    
1692
    public static void updateDBPreferences() {
1693

    
1694

    
1695
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1696
        cache.getAllTaxEditorDBPreferences();
1697

    
1698
        //ABCD Configurator
1699

    
1700
        //updateAbcdImportConfigurationPreference();
1701

    
1702
        //Name Details
1703
        NameDetailsConfigurator config = getPreferredNameDetailsConfiguration(false);
1704
        //    if (config != null ){
1705
        //        if (!getBooleanValue(OVERRIDE_NAME_DETAILS) ||  !getBooleanValue(ALLOW_OVERRIDE_NAME_DETAILS)){
1706
        //            setPreferredNameDetailsConfiguration(config, false);
1707
        //        }
1708
        //    }
1709

    
1710
    }
1711

    
1712
    public static void setPreferencesToDB(List<CdmPreference> preferences) {
1713

    
1714
        ICdmRepository controller;
1715
        //try{
1716
            if(CdmStore.isActive()){
1717
                controller = CdmStore.getCurrentApplicationConfiguration();
1718
                for (CdmPreference preference: preferences){
1719
                    if (preference.getValue() == null && preference.isAllowOverride()){
1720
                        controller.getPreferenceService().remove(preference.getKey());
1721

    
1722
                    }else{
1723
                        controller.getPreferenceService().set(preference);
1724

    
1725
                    }
1726

    
1727
                }
1728
                CdmPreferenceCache.instance().getAllTaxEditorDBPreferences();
1729

    
1730
            }
1731
        /*}catch(Exception e){
1732
            e.printStackTrace();
1733
        }*/
1734
    }
1735

    
1736
    /**
1737
     * Returns whether the named preference is known.
1738
     * @param prefKey the key of the preference
1739
     * @return <code>true</code> if the preference is known, <code>false</code> otherwise
1740
     */
1741
    public static boolean contains(String prefKey){
1742
        return getPreferenceStore().contains(prefKey(prefKey));
1743
    }
1744

    
1745
    /**
1746
     *
1747
     */
1748
    public static TermTree getPreferredFeatureTreeForNameDescription() {
1749
        if(preferredNameFeatureTree != null){
1750
            return preferredNameFeatureTree;
1751
        }
1752
        createPreferredFeatureTreeForNameDescription();
1753
        return preferredNameFeatureTree;
1754

    
1755
    }
1756

    
1757
    public static void createPreferredFeatureTreeForNameDescription() {
1758

    
1759
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1760
        CdmPreference pref = cache.get(PreferencePredicate.NameFeatures.getKey());
1761
        List<Feature> terms;
1762
        boolean override = PreferencesUtil.getBooleanValue(PreferencesUtil.createOverridePreferenceString(PreferencePredicate.NameFeatures.getKey()));
1763
        if (pref != null ){
1764
            List<UUID> uuids = PreferencesUtil.createUUIDListFromStringPref(pref.getValue());
1765
            terms = CdmStore.getTermManager().getTerms(uuids, Feature.class);
1766
        }else if (override){
1767
            terms = CdmStore.getTermManager().getPreferredTerms(CdmStore.getService(IVocabularyService.class).load(VocabularyEnum.NameFeature.getUuid()));
1768
        }else{
1769
            terms = new ArrayList();
1770
            terms.addAll(TermStore.getTerms(CdmStore.getService(IVocabularyService.class).load(VocabularyEnum.NameFeature.getUuid()), null));
1771
        }
1772
        terms.remove(Feature.PROTOLOGUE());
1773
        preferredNameFeatureTree = TermTree.NewInstance(terms);
1774

    
1775

    
1776
    }
1777

    
1778

    
1779

    
1780
}
(35-35/51)