Project

General

Profile

Download (74 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.lang.reflect.Field;
17
import java.net.URI;
18
import java.net.URISyntaxException;
19
import java.util.ArrayList;
20
import java.util.Arrays;
21
import java.util.Collections;
22
import java.util.HashMap;
23
import java.util.List;
24
import java.util.Map;
25
import java.util.Properties;
26
import java.util.Set;
27
import java.util.StringTokenizer;
28
import java.util.UUID;
29

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

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

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

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

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

    
106
    private static TermTree<Feature> preferredNameFeatureTree;
107

    
108
    private static TermTree<Feature> preferredTaxonFeatureTree;
109

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

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

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

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

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

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

    
146
    public static List<CdmPreference> getPreference(PreferencePredicate prefPredicate){
147
        try {
148
            List<CdmPreference> prefs = new ArrayList<>();
149
            CdmPreference pref;
150
            PreferenceSubject subject;
151
            if(getEditorPreferences().nodeExists(prefPredicate.getKey())){
152
                Preferences predicateNode = getEditorPreferences().node(prefPredicate.getKey());
153
                for (String childName: predicateNode.childrenNames()){
154
                    Preferences child = predicateNode.node(childName);
155
                    String subjectString = "";
156
                    subjectString = createSubjectStringForChildNodes(childName, child);
157
                    String value = child.get(subjectString, "");
158
                    subject = PreferenceSubject.NewInstance(subjectString);
159
                    pref = CdmPreference.NewInstance(subject, prefPredicate, value);
160
                    prefs.add(pref);
161
                }
162
            }
163
        } catch (BackingStoreException e) {
164
            // TODO Auto-generated catch block
165
            e.printStackTrace();
166
        }
167
        return null;
168
    }
169

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

    
183
    }
184

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

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

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

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

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

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

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

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

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

    
223
        CdmPreference pref = getDBPreferenceValue(name);
224

    
225
        boolean override = getOverrideForPreference(name);
226

    
227
        if (local || (pref == null && override)|| (pref != null && pref.isAllowOverride() && override)){
228
            //local preference
229
            String dbSpecific = prefKey(name);
230
            if (getPreferenceStore().contains(dbSpecific)){
231
                return getPreferenceStore().getString(dbSpecific);
232
            }
233
         }else if (pref != null){
234
             //db preference
235
             if (pref.getValue() == null){
236
                 Object result = PreferencePredicate.getByKey(pref.getPredicate()).getDefaultValue();
237
                 if (result instanceof String){
238
                     return (String)result;
239
                 }else{
240
                     return result.toString();
241
                 }
242
             }
243
            return pref.getValue();
244
        }
245
        //no override but default value
246
        IPreferencePredicate<?> pred = PreferencePredicate.getByKey(name);
247
        if (pred != null){
248
            if (pred.getDefaultValue() instanceof String){
249
                return (String)pred.getDefaultValue();
250
            }else if (pred.getDefaultValue() != null){
251
                return pred.getDefaultValue().toString();
252
            }
253
        }
254
        return null;
255
    }
256

    
257
    public static String getStringValue(String name){
258
        return getStringValue(name, false);
259
    }
260

    
261
    private static CdmPreference getDBPreferenceValue(String name) {
262
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
263
        CdmPreference pref = null;
264
        pref = cache.get(name);
265

    
266
        return pref;
267
    }
268

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

    
282
        boolean override = getOverrideForPreference(name);
283
        if (local || (pref == null && override) || (pref != null && pref.isAllowOverride() && override)){
284
            String dbSpecific = prefKey(name);
285
            if (getPreferenceStore().contains(dbSpecific)){
286
                result = getPreferenceStore().getInt(dbSpecific);
287
            }
288
        }
289
        if (result == null){
290
            IPreferencePredicate<?> pred = PreferencePredicate.getByKey(name);
291
            if (pred != null){
292
                if (pred.getDefaultValue() instanceof Integer){
293
                    result = (Integer)pred.getDefaultValue();
294
                }else if (pred.getDefaultValue() != null){
295
                    try{
296
                        result = Integer.valueOf(pred.getDefaultValue().toString());
297
                    }catch(NumberFormatException e){
298
                        logger.debug("Preference value of " + name + " is not a number");
299
                        result = 0;
300
                    }
301
                }
302
            }
303
            //if no default value available
304
            if (result == null){
305
                result = 0;
306
            }
307
        }
308
        return result;
309
    }
310

    
311
    public static boolean getBooleanValue(String name) {
312
        Boolean result = getBooleanValue(name, false);
313
        if (result == null){
314
            return false;
315
        }else{
316
            return result;
317
        }
318
    }
319

    
320
    public static Boolean getBooleanValue(String name, boolean local) {
321
        if (CdmStore.isActive()){
322
            CdmPreference pref = getDBPreferenceValue(name);
323
            String overrideKey =  createPreferenceString(createOverridePreferenceString(name));
324
            boolean override = getPreferenceStore().getBoolean(overrideKey);
325
            if (local || (pref == null && override)|| (pref != null && pref.isAllowOverride() && override)){
326
                //local preference
327
                String dbSpecific = prefKey(name);
328
                return getPreferenceStore().getBoolean(dbSpecific);
329

    
330
             }else if (pref != null){
331
                 //db preference is available and override == false
332
                 if (pref.getValue() == null){
333
                     Object result = PreferencePredicate.getByKey(pref.getPredicate()).getDefaultValue();
334
                     if (result instanceof Boolean){
335
                         return (Boolean)result;
336
                     }else{
337
                         return Boolean.valueOf(result.toString());
338
                     }
339
                 }
340
                return Boolean.valueOf(pref.getValue());
341
            }
342
            //no override but default value
343
            IPreferencePredicate<?> pred = PreferencePredicate.getByKey(name);
344
            if (pred != null){
345
                if (pred.getDefaultValue() instanceof Boolean){
346
                    return (Boolean)pred.getDefaultValue();
347
                }else if (pred.getDefaultValue() != null){
348
                    return Boolean.valueOf(pred.getDefaultValue().toString());
349
                }
350
            }
351
            return false;
352
        }else{
353
            // no connection to db, use local preference
354
            return getPreferenceStore().getBoolean(name);
355
        }
356
    }
357

    
358
    public static float getFloatValue(String name, boolean local) {
359
        CdmPreference pref = getDBPreferenceValue(name);
360
        String prefValue = null;
361
        if (pref != null){
362
            prefValue = pref.getValue();
363
        }
364
        Float result = null;
365
        try{
366
            if (prefValue != null){
367
                result = Float.parseFloat(prefValue);
368
            }
369
        }catch(NumberFormatException e){
370
            logger.debug("Preference value of " + name + " is not a float");
371
        }
372

    
373
        boolean override = getOverrideForPreference(name);
374

    
375
        if (local || pref == null || (pref.isAllowOverride() && override)){
376
            String dbSpecific = prefKey(name);
377
            if (getPreferenceStore().contains(dbSpecific)){
378
                result = getPreferenceStore().getFloat(dbSpecific);
379
            }else{
380
                IPreferencePredicate<?> pred = PreferencePredicate.getByKey(name);
381
                if (pred != null){
382
                    if (pred.getDefaultValue() instanceof Float){
383
                        return (float)pred.getDefaultValue();
384
                    }else if (pred.getDefaultValue() != null){
385
                        return Float.valueOf(pred.getDefaultValue().toString());
386
                    }
387
                }
388
                return 0;
389
            }
390
        }
391
        return result;
392
    }
393

    
394
    public static CdmPreference setPreferredNomenclaturalCode(
395
            String preferenceValue, boolean local) {
396
        if (local){
397
            setStringValue(PreferencePredicate.NomenclaturalCode.getKey(),
398
                    preferenceValue);
399
        }
400
        else{
401
            ICdmRepository controller;
402
            controller = CdmStore.getCurrentApplicationConfiguration();
403
            if (controller == null){
404
                return null;
405
            }
406
            PrefKey key = null;
407
            try{
408
                key = CdmPreference.NewKey(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.NomenclaturalCode);
409
            }catch (Exception e){
410
                System.out.println(e.getStackTrace());
411
            }
412
            CdmPreference preference = null;
413

    
414
            if (preferenceValue == null){
415
                preference = controller.getPreferenceService().find(key);
416
                if (preference == null){
417
                    return null;
418
                } else{
419
                    setStringValue(PreferencePredicate.NomenclaturalCode.getKey(),
420
                            preference.getValue());
421

    
422
                    return preference;
423
                }
424
            } else{
425
                preference = CdmPreference.NewInstance(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.NomenclaturalCode, preferenceValue);
426
                controller.getPreferenceService().set(preference);
427

    
428
            }
429
        }
430
        return null;
431
    }
432

    
433
    public static void setPreferredNomenclaturalCode(
434
        CdmPreference preference) {
435

    
436
        ICdmRepository controller;
437
        controller = CdmStore.getCurrentApplicationConfiguration();
438
        if (controller == null){
439
            return;
440
        }
441

    
442
        if (preference == null){
443
            PrefKey key = null;
444
              try{
445
                  key = CdmPreference.NewKey(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.NomenclaturalCode);
446
              }catch (Exception e){
447
                  System.out.println(e.getStackTrace());
448
              }
449
            controller.getPreferenceService().remove(key);
450
        }else{
451
            controller.getPreferenceService().set(preference);
452
        }
453
    }
454

    
455
    public static NomenclaturalCode getPreferredNomenclaturalCode() {
456

    
457
        CdmPreference pref = getPreferenceFromDB(PreferencePredicate.NomenclaturalCode);
458

    
459
        String preferredCode;
460
        if(pref == null || (pref.isAllowOverride() && getBooleanValue(prefOverrideKey(PreferencePredicate.NomenclaturalCode.getKey())))){
461
            preferredCode = getStringValue(
462
                    PreferencePredicate.NomenclaturalCode.getKey(), true);
463

    
464
        }else{
465
            preferredCode = pref.getValue();
466
        }
467
        if (StringUtils.isBlank(preferredCode)){
468
            preferredCode = getPreferenceKey((NomenclaturalCode)PreferencePredicate.NomenclaturalCode.getDefaultValue());
469
        }
470

    
471
        return getPreferredNomenclaturalCode(preferredCode);
472

    
473
    }
474

    
475
    public static NomenclaturalCode getPreferredNomenclaturalCode(String preferenceKeyNomenclaturalCode) {
476

    
477
        for (NomenclaturalCode code : NomenclaturalCodeHelper.getAllCodes()) {
478
            if (getPreferenceKey(code).equals(preferenceKeyNomenclaturalCode) || code.getKey().equals(preferenceKeyNomenclaturalCode)) {
479
                return code;
480
            }
481
        }
482
        return null;
483
    }
484

    
485
    public static boolean isShowTaxonAssociations(){
486
        boolean result = getBooleanValue(PreferencePredicate.ShowTaxonAssociations.getKey());
487
        return result;
488
    }
489

    
490
    public static boolean isShowLifeForm(){
491
        boolean result =  getBooleanValue(PreferencePredicate.ShowLifeForm.getKey());
492
        return result;
493
    }
494

    
495
    public static boolean isDeterminationOnlyForFieldUnits(){
496
        boolean result =  getBooleanValue(PreferencePredicate.DeterminationOnlyForFieldUnits.getKey());
497
        return result;
498
    }
499

    
500
    public static boolean isCollectingAreaInGeneralSection(){
501
        boolean result =  getBooleanValue(PreferencePredicate.ShowCollectingAreasInGeneralSection.getKey());
502
        return result;
503
    }
504

    
505
    public static CdmPreference getPreferenceFromDB(IPreferencePredicate<?> predicate){
506
        ICdmRepository controller;
507
        CdmPreference pref = null;
508

    
509
        try{
510
            if(CdmStore.isActive()){
511
                controller = CdmStore.getCurrentApplicationConfiguration();
512
                PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), predicate);
513
                pref = controller.getPreferenceService().find(key);
514
            }
515
        }catch(Exception e){
516
            e.printStackTrace();
517
        }
518

    
519
        return pref;
520
    }
521

    
522
    public static List<CdmPreference> getPreferencesFromDB(IPreferencePredicate<?> predicate){
523
        ICdmRepository controller;
524
        List<CdmPreference> prefs = null;
525

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

    
536
        return prefs;
537

    
538
    }
539

    
540
    public static void setPreferencesToDB(CdmPreference preference, boolean setDefault){
541
        ICdmRepository controller;
542
        try{
543
            if(CdmStore.isActive()){
544
                controller = CdmStore.getCurrentApplicationConfiguration();
545

    
546
                if (setDefault){
547
                    controller.getPreferenceService().remove(preference.getKey());
548
                }else{
549
                    controller.getPreferenceService().set(preference);
550
                }
551
            }
552
        }catch(Exception e){
553
            e.printStackTrace();
554
        }
555
    }
556

    
557
    public static CdmPreference getPreferenceFromDB(PrefKey key){
558
        ICdmRepository controller;
559
        CdmPreference pref = null;
560

    
561
        try{
562
            if(CdmStore.isActive()){
563
                controller = CdmStore.getCurrentApplicationConfiguration();
564
                pref = controller.getPreferenceService().find(key);
565
            }
566
        }catch(Exception e){
567
            e.printStackTrace();
568
        }
569

    
570
        return pref;
571

    
572
    }
573

    
574
    public static void setPreferenceToDB(CdmPreference preference){
575
        ICdmRepository controller;
576
        try{
577
            if(CdmStore.isActive()){
578
                controller = CdmStore.getCurrentApplicationConfiguration();
579
                if (preference.getValue() == null && preference.isAllowOverride()){
580
                    controller.getPreferenceService().remove(preference.getKey());
581
                }else{
582
                    controller.getPreferenceService().set(preference);
583
                }
584
                CdmPreferenceCache.instance().put(preference);
585
            }
586
        }catch(Exception e){
587
            e.printStackTrace();
588
        }
589
    }
590

    
591
    public static String getPreferredDefaultLangugae(){
592
        String preferredLanguage = getStringValue(DEFAULT_LANGUAGE_EDITOR, true);
593
        if(StringUtils.isNotEmpty(preferredLanguage) && StringUtils.isNotBlank(preferredLanguage)){
594
            return preferredLanguage;
595
        }
596
        return null;
597
    }
598

    
599
    public static boolean isShowMediaPreview(){
600
        boolean isShowMediaPreview = getBooleanValue(SHOW_MEDIA_PREVIEW, true);
601
        return isShowMediaPreview;
602
    }
603

    
604
    /**
605
     * Get the match strategy for the given class that was stored in preferences
606
     * or the default strategy if it was not stored in preferences
607
     *
608
     * @param clazz
609
     *            a {@link java.lang.Class} object.
610
     * @return a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy} object.
611
     */
612
    public static IMatchStrategy getMatchStrategy(Class<?> clazz) {
613
        String className = clazz.getName();
614
        if (getBooleanValue(MATCH_STRATEGY_PREFIX + className, true)) {
615
            IMatchStrategy matchStrategy = getDefaultMatchStrategy(clazz);
616

    
617
            //TODO CacheMatchers (or multiple field matchers in future) are missing here
618
            for (FieldMatcher fieldMatcher : matchStrategy.getMatching().getFieldMatchers(false)) {
619
                String fieldName = fieldMatcher.getPropertyName();
620
                String matchModeName = getStringValue(
621
                        getMatchStrategyFieldName(className, fieldName), true);
622
                MatchMode matchMode = MatchMode.valueOf(matchModeName);
623
                try {
624
                    matchStrategy.setMatchMode(fieldName, matchMode);
625
                } catch (MatchException e) {
626
                    MessagingUtils.error(PreferencesUtil.class, e);
627
                    throw new RuntimeException(e);
628
                }
629
            }
630

    
631
            return matchStrategy;
632
        }
633
        return getDefaultMatchStrategy(clazz);
634
    }
635

    
636
    /**
637
     * Stores a matchStrategy into the preference store.
638
     *
639
     * @param matchStrategy
640
     *            a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy}
641
     *            object.
642
     */
643
    public static void setMatchStrategy(IMatchStrategy matchStrategy) {
644
        String className = "ANY class"; //FIXME was: matchStrategy.getMatchClass().getName(); seems currently not in use
645
        setBooleanValue(MATCH_STRATEGY_PREFIX + className, true);
646

    
647
        List<FieldMatcher> fieldMatchers = matchStrategy.getMatching().getFieldMatchers(false);
648

    
649
        for (FieldMatcher fieldMatcher : fieldMatchers) {
650
            String fieldName = fieldMatcher.getPropertyName();
651
            setStringValue(
652
                    getMatchStrategyFieldName(className, fieldName),
653
                    fieldMatcher.getMatchMode().name());
654
        }
655
    }
656

    
657
    /**
658
     * Helper method to create the preference property for a match field.
659
     *
660
     * @param className
661
     * @param fieldName
662
     * @return
663
     */
664
    private static String getMatchStrategyFieldName(String className,
665
            String fieldName) {
666
        return MATCH_STRATEGY_PREFIX + className + "." + fieldName;
667
    }
668

    
669
    /**
670
     * Returns the default match strategy for a given class.
671
     *
672
     * @param clazz
673
     *            a {@link java.lang.Class} object.
674
     * @return a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy} object.
675
     */
676
    public static IMatchStrategy getDefaultMatchStrategy(Class clazz) {
677
        return DefaultMatchStrategy.NewInstance(clazz);
678
    }
679

    
680
    public static String getDateFormatPattern() {
681
        // TODO make this configurable in properties
682
        String pattern = "Y-M-d H:m";
683
        return pattern;
684
    }
685

    
686
    public static <T extends TermBase> void addTermToPreferredTerms(T term) {
687

    
688
        // VocabularyEnum vocabulary =
689
        // VocabularyEnum.getVocabularyEnum(term.getClass());
690
        //
691
        // getPreferenceStore().setValue(getPreferenceKey(term),
692
        // VocabularyStore.getTermVocabulary(vocabulary).getTerms().contains(term));
693
        //
694
        // firePreferencesChanged(term.getClass());
695
    }
696

    
697
    /**
698
     * Construct a unique key using the CdmBase object's uuid
699
     *
700
     * @param cdmBase
701
     * @return
702
     */
703
    private static String getPreferenceKey(ICdmBase cdmBase) {
704
        cdmBase = HibernateProxyHelper.deproxy(cdmBase);
705

    
706
        String key = cdmBase.getClass().getName().concat(".")
707
                .concat(cdmBase.getUuid().toString());
708
        if (key.contains("javassist")) {
709
            MessagingUtils.info("proxy");
710
        }
711
        return key;
712
    }
713

    
714
    /**
715
     * Construct a unique key using the CdmBase object's uuid
716
     *
717
     * @param cdmBase
718
     * @return
719
     */
720
    public static String getPreferenceKey(ISimpleTerm<?> simpleTerm) {
721
        simpleTerm = HibernateProxyHelper.deproxy(simpleTerm);
722
        String key = simpleTerm.getClass().getName().concat(".")
723
                .concat(simpleTerm.getUuid().toString());
724
        if (key.contains("javassist")) {
725
            MessagingUtils.warn(PreferencesUtil.class,
726
                    "Trying to persist a preference based on a proxy class.");
727
        }
728
        return key;
729
    }
730

    
731
    /**
732
     * Construct a unique key using the CdmBase object's uuid
733
     */
734
    public static String getPreferenceKey(IDefinedTerm definedTerm) {
735
        definedTerm = HibernateProxyHelper.deproxy(definedTerm);
736
        String key = definedTerm.getClass().getName().concat(".")
737
                .concat(definedTerm.getUuid().toString());
738
        if (key.contains("javassist")) {
739
            MessagingUtils.warn(PreferencesUtil.class,
740
                    "Trying to persist a preference based on a proxy class.");
741
        }
742
        return key;
743
    }
744

    
745
    /**
746
     * Retrieves search preferences from the preference store
747
     *
748
     * @return an {@link ITaxonServiceConfigurator} to pass to search methods
749
     */
750
    public static IFindTaxaAndNamesConfigurator getSearchConfigurator() {
751
        IFindTaxaAndNamesConfigurator configurator = initializeSearchConfigurator();
752

    
753
        configurator.setDoTaxa(PreferencesUtil.getPreferenceStore().contains(IPreferenceKeys.TAXON_SERVICE_CONFIGURATOR_TAXA)? PreferencesUtil.getPreferenceStore().getBoolean(
754
                IPreferenceKeys.TAXON_SERVICE_CONFIGURATOR_TAXA): true);
755
        configurator.setDoSynonyms(PreferencesUtil.getPreferenceStore().contains(IPreferenceKeys.TAXON_SERVICE_CONFIGURATOR_SYNONYMS)? PreferencesUtil.getPreferenceStore().getBoolean(
756
                IPreferenceKeys.TAXON_SERVICE_CONFIGURATOR_SYNONYMS): true);
757
        configurator.setDoNamesWithoutTaxa(PreferencesUtil.getPreferenceStore().contains(IPreferenceKeys.TAXON_SERVICE_CONFIGURATOR_NAMES)? PreferencesUtil.getPreferenceStore().getBoolean(
758
                IPreferenceKeys.TAXON_SERVICE_CONFIGURATOR_NAMES): true);
759
        configurator.setDoTaxaByCommonNames(PreferencesUtil.getPreferenceStore().contains(IPreferenceKeys.TAXON_SERVICE_CONFIGURATOR_COMMON_NAMES)? PreferencesUtil.getPreferenceStore().getBoolean(
760
                IPreferenceKeys.TAXON_SERVICE_CONFIGURATOR_COMMON_NAMES): true);
761
        //configurator.setMatchMode(eu.etaxonomy.cdm.persistence.query.MatchMode.valueOf(getStringValue(TAXON_SERVICE_CONFIGURATOR_MATCH_MODE)));
762

    
763
        return configurator;
764
    }
765

    
766
    /**
767
     * create new preferences, setting all search options to true
768
     *
769
     * @return a
770
     *         {@link eu.etaxonomy.cdm.api.service.config.ITaxonServiceConfigurator}
771
     *         object.
772
     */
773
    public static IFindTaxaAndNamesConfigurator initializeSearchConfigurator() {
774
        IFindTaxaAndNamesConfigurator configurator = FindTaxaAndNamesConfiguratorImpl.NewInstance();
775

    
776
        configurator.setDoTaxa(true);
777
        configurator.setDoSynonyms(true);
778
        configurator.setDoNamesWithoutTaxa(true);
779
        configurator.setDoTaxaByCommonNames(true);
780

    
781
        configurator.setTaxonPropertyPath(Arrays.asList("$", "titleCache",
782
                "name", "name.$", "relationsFromThisTaxon.$"));
783

    
784
        configurator.setSynonymPropertyPath(Arrays.asList("$", "titleCache",
785
                "name", "name.$", "synonyms.relatedTo.*"));
786

    
787
        // DEFAULT VALUES
788
        // match mode is a simple like, actually all other match modes are kind
789
        // of bogus
790
        configurator
791
                .setMatchMode(eu.etaxonomy.cdm.persistence.query.MatchMode.ANYWHERE);
792
        // we set page number and size here as this should always be unlimited
793
        configurator.setPageNumber(0);
794
        // TODO currently limit results to 10000
795
        configurator.setPageSize(10000);
796
        //setSearchConfigurator(configurator) ;
797
        return configurator;
798
    }
799

    
800
    /**
801
     * Store search preferences
802
     *
803
     * @param configurator
804
     *            a
805
     *            {@link eu.etaxonomy.cdm.api.service.config.ITaxonServiceConfigurator}
806
     *            object.
807
     */
808
    public static void setSearchConfigurator(
809
            IFindTaxaAndNamesConfigurator configurator) {
810
        getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_TAXA,
811
                configurator.isDoTaxa());
812
        getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_SYNONYMS,
813
                configurator.isDoSynonyms());
814
        getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_NAMES,
815
                configurator.isDoNamesWithoutTaxa());
816
        getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_COMMON_NAMES,
817
                configurator.isDoTaxaByCommonNames());
818
    }
819

    
820
    public static void firePreferencesChanged(Class clazz) {
821
        getPreferenceStore().firePropertyChangeEvent(PREFERRED_TERMS_CHANGE,
822
                null, clazz);
823
    }
824

    
825

    
826
    public static String createPreferenceString(String property){
827
       return prefKey(property);
828
    }
829
    public static String createOverridePreferenceString(String property){
830
           return prefOverrideKey(property);
831
    }
832

    
833
    public static boolean getOverrideForPreference(String preferenceString){
834
        return PreferencesUtil.getBooleanValue(PreferencesUtil.createOverridePreferenceString(preferenceString), true);
835
    }
836

    
837
    /**
838
     * Set default values for preferences
839
     */
840
    public static void setDefaults() {
841

    
842
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.EditMapServiceAccessPoint.getKey()),
843
                "http://edit.africamuseum.be/edit_wp5/v1.2/rest_gen.php");
844
        //FIXME : changed default for SHOULD_CONNECT_AT_STARTUP to false (ticket 3828) until resolution
845
        getPreferenceStore().setDefault(createPreferenceString(SHOULD_CONNECT_AT_STARTUP), false);
846
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.MobotOpenUrlServiceAccessPoint.getKey()),
847
                "http://www.biodiversitylibrary.org/openurl");
848
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.MobotOpenUrlServiceMaxWidth.getKey()), "1000");
849
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.MobotOpenUrlServiceMaxHeight.getKey()), "1000");
850
        getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_TAXA, true);
851
        getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_SYNONYMS, true);
852
        getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_NAMES, true);
853
        getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_COMMON_NAMES, true);
854

    
855
        //Name Details
856
       // getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.NameDetailsView.getKey()), new NameDetailsConfigurator(false).toString());
857

    
858
        //Navigator preferences
859
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.TaxonNodeOrder.getKey()), NavigatorOrderEnum.RankAndNameOrder.getKey());
860

    
861
        //getPreferenceStore().setDefault(createPreferenceString(Prefe), true);
862

    
863
        getPreferenceStore().setDefault(createPreferenceString(SHOW_ADVANCED_MEDIA_SECTION), false);
864

    
865
        getPreferenceStore().setDefault(createPreferenceString(SHOW_MEDIA_PREVIEW), false);
866
        //override db preferences
867
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.AbcdImportConfig.getKey())), false);
868
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.NameDetailsView.getKey())), false);
869
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.CommonNameAreaVocabularies.getKey())), false);
870
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.CommonNameReferencesWithMarker.getKey()), false);
871
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowTaxonNodeWizard.getKey()), Boolean.valueOf(PreferencePredicate.ShowTaxonNodeWizard.getDefaultValue().toString()));
872
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowNamespaceInSource.getKey()), Boolean.valueOf(PreferencePredicate.ShowNamespaceInSource.getDefaultValue().toString()));
873
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowIdInSource.getKey()), Boolean.valueOf(PreferencePredicate.ShowIdInSource.getDefaultValue().toString()));
874
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.DisableMultiClassification.getKey()), Boolean.valueOf(PreferencePredicate.DisableMultiClassification.getDefaultValue().toString()));
875
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowImportExportMenu.getKey()), Boolean.valueOf(PreferencePredicate.ShowImportExportMenu.getDefaultValue().toString()));
876
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowSpecimen.getKey()), Boolean.valueOf(PreferencePredicate.ShowSpecimen.getDefaultValue().toString()));
877
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.SearchForIdentifierAndTitleCache.getKey()), Boolean.valueOf(PreferencePredicate.SearchForIdentifierAndTitleCache.getDefaultValue().toString()));
878
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.SearchForIdentifierAndTitleCache.getKey())), false);
879
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.SearchForIdentifierAsDefault.getKey()), Boolean.valueOf(PreferencePredicate.SearchForIdentifierAsDefault.getDefaultValue().toString()));
880
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.SearchForIdentifierAsDefault.getKey())), false);
881
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.ShowModifierFreeText.getKey())), false);
882
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.ShowModifier.getKey())), false);
883
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.DistributionEditorActivated.getKey())), false);
884
    }
885

    
886
    public static void checkNomenclaturalCode() {
887
        // First time Editor is opened, no nomenclatural code has been set
888
        if (PreferencesUtil.getPreferredNomenclaturalCode() == null) {
889
            PreferencesUtil.setPreferredNomenclaturalCode(getPreferenceKey(NomenclaturalCode.ICNAFP), true);
890
        }
891
    }
892

    
893
    public static void setNomenclaturalCodePreferences(){
894
        ICdmRepository controller;
895
        controller = CdmStore.getCurrentApplicationConfiguration();
896
        PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.NomenclaturalCode);
897
        CdmPreference preference = null;
898
        if (controller == null){
899
            return ;
900
        }
901
        preference = controller.getPreferenceService().find(key);
902
        if (preference == null){
903
            return;
904
        }
905
//        setBooleanValue(ALLOW_OVERRIDE_NOMENCLATURAL_CODE_KEY, preference.isAllowOverride());
906

    
907
        int index = StringUtils.lastIndexOf(preference.getValue(), ".");
908
        UUID uuid = UUID.fromString(preference.getValue().substring(index +1, preference.getValue().length()));
909
        NomenclaturalCode preferredCode = NomenclaturalCode.getByUuid(uuid);
910

    
911
        setStringValue(PreferencePredicate.NomenclaturalCode.getKey(),
912
                getPreferenceKey(preferredCode));
913
    }
914

    
915
    public static void checkDefaultLanguage(){
916
        if(PreferencesUtil.getPreferredDefaultLangugae() == null){
917
           Shell shell = AbstractUtility.getShell();
918
           int open = new DefaultLanguageDialog(shell).open();
919
           if(open == Window.OK){
920
               PlatformUI.getWorkbench().restart();
921
           }
922
        }else{
923
            //TODO:In case of a reinstall, the config.ini will be overwritten
924
            //     here you create config.ini with the stored key from preferences
925
        }
926
    }
927

    
928
    public static String getMapServiceAccessPoint() {
929
        return getStringValue(PreferencePredicate.EditMapServiceAccessPoint.getKey());
930
    }
931

    
932
    public static boolean shouldConnectAtStartUp() {
933
        //FIXME :  force SHOULD_CONNECT_AT_STARTUP to false (ticket 3828) until resolution
934
        //return getBooleanValue(SHOULD_CONNECT_AT_STARTUP);
935
        return false;
936
    }
937

    
938
    public static TermTree<?> getDefaultFeatureTreeForTextualDescription() {
939
        String uuidString = getStringValue(
940
                FEATURE_TREE_DEFAULT_TEXT, true);
941
        if (StringUtils.isBlank(uuidString)) {
942
            return null;
943
        }
944
        TermTree<?> tree = CdmStore.getService(
945
                ITermTreeService.class).load(UUID.fromString(uuidString));
946

    
947
        if (tree == null || tree.getId() == 0) {
948
            return null;
949
        }
950
        return tree;
951
    }
952

    
953
    public static TermTree<?> getDefaultFeatureTreeForStructuredDescription() {
954
        String uuidString = getStringValue(
955
                FEATURE_TREE_DEFAULT_STRUCTURE, true);
956
        return StringUtils.isBlank(uuidString) ? null : CdmStore.getService(
957
                ITermTreeService.class).load(UUID.fromString(uuidString));
958
    }
959

    
960
    public static void setSortRanksHierarchichally(boolean selection) {
961
        setBooleanValue(PreferencePredicate.SortRanksHierarchichally.getKey(), selection);
962
    }
963

    
964
    public static boolean getSortRanksHierarchichally() {
965
        return getBooleanValue(PreferencePredicate.SortRanksHierarchichally.getKey());
966
    }
967

    
968
    public static boolean isMultilanguageTextEditingCapability() {
969
        return getBooleanValue(
970
                PreferencePredicate.MultiLanguageTextEditing.getKey());
971
    }
972

    
973
    public static Language getGlobalLanguage() {
974

    
975
        String languageUuidString = getStringValue(
976
                GLOBAL_LANGUAGE_UUID, true);
977

    
978
        if(!CdmStore.isActive()) {
979
            MessagingUtils.noDataSourceWarningDialog(languageUuidString);
980
            return null;
981
        }
982

    
983
        if (CdmUtils.isBlank(languageUuidString)) {
984
            return Language.getDefaultLanguage();
985
        }
986

    
987
        UUID languageUuid = UUID.fromString(languageUuidString);
988
        return (Language) CdmStore.getService(ITermService.class).load(
989
                languageUuid);
990
    }
991

    
992
    public static void setGlobalLanguage(Language language) {
993
        if(language != null) {
994
            setStringValue(GLOBAL_LANGUAGE_UUID,language.getUuid().toString());
995
            CdmStore.setDefaultLanguage(language);
996
        }
997
    }
998

    
999
    public static Map<MarkerType, Boolean> getEditMarkerTypePreferences() {
1000
        List<MarkerType> markerTypes = CdmStore.getTermManager()
1001
                .getPreferredTerms(MarkerType.class);
1002

    
1003
        Map<MarkerType, Boolean> result = new HashMap<>();
1004

    
1005
        for (MarkerType markerType : markerTypes) {
1006
            String name = getMarkerTypeEditingPreferenceKey(markerType);
1007
            Boolean value = getBooleanValue(name);
1008
            result.put(markerType, value);
1009
        }
1010

    
1011
        return result;
1012
    }
1013

    
1014
    public static void setEditMarkerTypePreferences(
1015
            Map<MarkerType, Boolean> markerTypeEditingMap) {
1016
        for (MarkerType markerType : markerTypeEditingMap.keySet()) {
1017
            String name = getMarkerTypeEditingPreferenceKey(markerType);
1018
            setBooleanValue(name,
1019
                    markerTypeEditingMap.get(markerType));
1020
        }
1021
    }
1022

    
1023
    private static String getMarkerTypeEditingPreferenceKey(
1024
            MarkerType markerType) {
1025
        markerType = HibernateProxyHelper.deproxy(markerType);
1026
        return markerType.getClass().getName() + EDIT_MARKER_TYPE_PREFIX;
1027
    }
1028

    
1029
    public static void setEditMarkerTypePreference(MarkerType markerType,
1030
            boolean edit) {
1031
        setBooleanValue(
1032
                getMarkerTypeEditingPreferenceKey(markerType), edit);
1033
    }
1034

    
1035
    public static DerivedUnitFacadeConfigurator getDerivedUnitConfigurator() {
1036
        DerivedUnitFacadeConfigurator configurator = DerivedUnitFacadeConfigurator
1037
                .NewInstance();
1038
        configurator.setMoveDerivedUnitMediaToGallery(true);
1039
        configurator.setMoveFieldObjectMediaToGallery(true);
1040
        return configurator;
1041
    }
1042

    
1043
    /**
1044
     * This method will write language properties to the config.ini located in the configuration folder
1045
     * of the Taxonomic Ediitor. <b>This method is only used to set the default language for Taxonomic Editor.</b>
1046
     *
1047
     * @param setLanguage 0 is for german and 1 for english.
1048
     * @throws IOException
1049
     */
1050
    public void writePropertyToConfigFile(int setLanguage) throws IOException {
1051
        File file = org.eclipse.core.runtime.preferences.ConfigurationScope.INSTANCE.getLocation().toFile();
1052
        //give warning to user if the directory has no write access
1053
        if(file == null){
1054
            throw new IOException();
1055
        }
1056
        Properties properties = load(file.getAbsolutePath()+"/config.ini");
1057
        switch(setLanguage){
1058
        case 0:
1059
            properties.setProperty("osgi.nl", "de");
1060
            setStringValue(IPreferenceKeys.DEFAULT_LANGUAGE_EDITOR, "de");
1061
            break;
1062
        case 1:
1063
            properties.setProperty("osgi.nl", "en");
1064
            setStringValue(IPreferenceKeys.DEFAULT_LANGUAGE_EDITOR, "en");
1065
            break;
1066
        default:
1067
            break;
1068
        }
1069
        save(file+"/config.ini", properties);
1070
    }
1071

    
1072
    /**
1073
     * This method loads a property from a given file and returns it.
1074
     *
1075
     * @param filename
1076
     * @return
1077
     * @throws IOException
1078
     */
1079
    private Properties load(String filename) throws IOException {
1080
        FileInputStream in = new FileInputStream(filename);
1081
        Properties prop = new Properties();
1082
        prop.load(in);
1083
        in.close();
1084
        return prop;
1085
    }
1086

    
1087
    /**
1088
     * This method saves a property to the specified file.
1089
     *
1090
     * @param filename
1091
     * @param properties
1092
     * @throws IOException
1093
     */
1094
    private void save(String filename, Properties properties) throws IOException{
1095
        FileOutputStream fos =  new FileOutputStream(filename);
1096
        properties.store(fos, "");
1097
        fos.close();
1098
    }
1099

    
1100
    /**
1101
     * Saves a list of P2 Metadata Repositories as string with specified delimiters
1102
     *
1103
     * @param p2Repos
1104
     */
1105
    public static void setP2Repositories(List<MetadataRepositoryElement> p2Repos) {
1106
        StringBuilder sb = new StringBuilder();
1107
        for(MetadataRepositoryElement p2Repo : p2Repos) {
1108
            sb.append(P2_REPOSITORIES_DELIM);
1109
            if(p2Repo.getName() == null || p2Repo.getName().isEmpty()) {
1110
                sb.append("-");
1111
            } else {
1112
                sb.append(p2Repo.getName());
1113
            }
1114
            sb.append(P2_REPOSITORY_FIELDS_DELIM);
1115
            sb.append(p2Repo.getLocation().toString());
1116
            sb.append(P2_REPOSITORY_FIELDS_DELIM);
1117
            sb.append(String.valueOf(p2Repo.isEnabled()));
1118
        }
1119
        getPreferenceStore().setValue(P2_REPOSITORY_LIST, sb.toString());
1120
    }
1121

    
1122

    
1123
    /**
1124
     * Retrieves a list of previously saved P2 repositories
1125
     */
1126
    public static List<MetadataRepositoryElement> getP2Repositories() {
1127
        List<MetadataRepositoryElement> p2Repos = new ArrayList<MetadataRepositoryElement>();
1128
        String p2ReposPref =  getStringValue(P2_REPOSITORY_LIST, true);
1129
        if(p2ReposPref != null && !p2ReposPref.isEmpty()) {
1130
            StringTokenizer p2ReposPrefST = new StringTokenizer(p2ReposPref,P2_REPOSITORIES_DELIM);
1131

    
1132
            while(p2ReposPrefST.hasMoreTokens()) {
1133
                String p2RepoStr = p2ReposPrefST.nextToken();
1134
                StringTokenizer p2ReposStrST = new StringTokenizer(p2RepoStr,P2_REPOSITORY_FIELDS_DELIM);
1135
                if(p2ReposStrST.countTokens()==3) {
1136
                    String nickname = p2ReposStrST.nextToken();
1137
                    URI uri = null;
1138
                    try {
1139
                        uri = new URI(p2ReposStrST.nextToken());
1140
                    } catch (URISyntaxException e) {
1141
                        continue;
1142
                    }
1143
                    boolean enabled = Boolean.parseBoolean(p2ReposStrST.nextToken());
1144
                    MetadataRepositoryElement mre = new MetadataRepositoryElement(null, uri, true);
1145
                    mre.setNickname(nickname);
1146
                    mre.setEnabled(enabled);
1147
                    p2Repos.add(mre);
1148
                }
1149
            }
1150
        }
1151

    
1152
        return p2Repos;
1153
    }
1154

    
1155
    /**
1156
     * enables/disables nested composite. <br>
1157
     *
1158
     * @param ctrl - Composite to be en-/disabeld
1159
     * @param enabled - boolean
1160
     */
1161
    public static void recursiveSetEnabled(Control ctrl, boolean enabled) {
1162
        if (ctrl instanceof Composite) {
1163
            Composite comp = (Composite) ctrl;
1164
            for (Control c : comp.getChildren()) {
1165
                recursiveSetEnabled(c, enabled);
1166
            }
1167
        } else {
1168
            ctrl.setEnabled(enabled);
1169
        }
1170
    }
1171

    
1172
    public static void setSortNodes(NavigatorOrderEnum nodesOrder) {
1173
        if (nodesOrder == null){
1174
            setStringValue(PreferencePredicate.TaxonNodeOrder.getKey(), null);
1175
        }else{
1176
            setStringValue(PreferencePredicate.TaxonNodeOrder.getKey(), nodesOrder.key);
1177
        }
1178
    }
1179

    
1180
    public static NavigatorOrderEnum getSortNodes() {
1181
        return NavigatorOrderEnum.valueOf(getStringValue(PreferencePredicate.TaxonNodeOrder.getKey()));
1182
    }
1183

    
1184
    public static boolean isNodesSortedNaturally() {
1185
        NavigatorOrderEnum value = NavigatorOrderEnum.valueOf(getStringValue(PreferencePredicate.TaxonNodeOrder.getKey()));
1186
        return value.equals(NavigatorOrderEnum.NaturalOrder);
1187
    }
1188

    
1189
    public static boolean isNodesSortedByName() {
1190
        NavigatorOrderEnum value = NavigatorOrderEnum.valueOf(getStringValue(PreferencePredicate.TaxonNodeOrder.getKey()));
1191
        return value.equals(NavigatorOrderEnum.AlphabeticalOrder);
1192
    }
1193

    
1194
    public static boolean isNodesSortedByNameAndRank() {
1195
        NavigatorOrderEnum value = NavigatorOrderEnum.valueOf(getStringValue(PreferencePredicate.TaxonNodeOrder.getKey()));
1196
        return value.equals(NavigatorOrderEnum.RankAndNameOrder);
1197
    }
1198

    
1199
    public static boolean isStoreNavigatorState() {
1200
        return getBooleanValue(RESTORE_NAVIGATOR_STATE);
1201
    }
1202

    
1203
    public static void setStoreNavigatorState(boolean selection) {
1204
        setBooleanValue(RESTORE_NAVIGATOR_STATE, selection);
1205
    }
1206

    
1207
    public static boolean isShowUpWidgetIsDisposedMessages() {
1208
       return getBooleanValue(IS_SHOW_UP_WIDGET_IS_DISPOSED);
1209
    }
1210

    
1211
    public static void setShowUpWidgetIsDisposedMessages(boolean selection) {
1212
        setBooleanValue(IS_SHOW_UP_WIDGET_IS_DISPOSED, selection);
1213
    }
1214

    
1215
    public static boolean isShowIdInVocabularyInChecklistEditor() {
1216
        String area_display = getStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey());
1217
        if (area_display.equals(TermDisplayEnum.IdInVocabulary.getKey())) {
1218
            return true;
1219
        }else{
1220
            return false;
1221
        }
1222
    }
1223
    public static boolean isShowSymbol1InChecklistEditor() {
1224
        String area_display = getStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey());
1225
        if (area_display.equals(TermDisplayEnum.Symbol1.getKey())) {
1226
            return true;
1227
        }else{
1228
            return false;
1229
        }
1230
    }
1231
    public static boolean isShowSymbol2InChecklistEditor() {
1232
        String area_display = getStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey());
1233
        if (area_display.equals(TermDisplayEnum.Symbol2.getKey())) {
1234
            return true;
1235
        }else{
1236
            return false;
1237
        }
1238
    }
1239

    
1240
    public static void setAreaDisplayInChecklistEditor(String selection) {
1241
        setStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey(), selection);
1242
    }
1243

    
1244
    public static void setOwnDescriptionForChecklistEditor(boolean selection) {
1245
        setBooleanValue(PreferencePredicate.OwnDescriptionForDistributionEditor.getKey(), selection);
1246
    }
1247

    
1248
    public static boolean isOwnDescriptionForChecklistEditor() {
1249
        return getBooleanValue(PreferencePredicate.OwnDescriptionForDistributionEditor.getKey());
1250
    }
1251

    
1252
    public static TermDisplayEnum displayAreaInChecklistEditor() {
1253
        TermDisplayEnum result;
1254
        try{
1255
            result = TermDisplayEnum.byKey(getStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey()));
1256
        }catch (IllegalArgumentException e){
1257
           result = ((TermDisplayEnum) PreferencePredicate.DisplayOfAreasInDistributionEditor.getDefaultValue());
1258
        }
1259
       return result;
1260
    }
1261

    
1262
    public static TermDisplayEnum displayStatusInChecklistEditor() {
1263
        TermDisplayEnum result;
1264
        try{
1265
            result = TermDisplayEnum.byKey(getStringValue(PreferencePredicate.DisplayOfStatus.getKey()));
1266
        }catch (IllegalArgumentException e){
1267
           result = ((TermDisplayEnum) PreferencePredicate.DisplayOfStatus.getDefaultValue());
1268
        }
1269
       return result;
1270
    }
1271

    
1272
    public static void setDisplayStatusInChecklistEditor(String selection) {
1273
        setStringValue(PreferencePredicate.DisplayOfStatus.getKey(), selection);
1274
    }
1275

    
1276
    public static boolean isShowRankInChecklistEditor() {
1277
        return getBooleanValue(PreferencePredicate.ShowRankInDistributionEditor.getKey());
1278
    }
1279

    
1280
    public static void setShowRankInChecklistEditor(boolean selection) {
1281
       setBooleanValue(PreferencePredicate.ShowRankInDistributionEditor.getKey(), selection);
1282
    }
1283

    
1284
    public static NameDetailsConfigurator getPreferredNameDetailsConfiguration( boolean local) {
1285
        NameDetailsConfigurator config = new NameDetailsConfigurator();
1286
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1287
        CdmPreference preference = null;
1288
        String value;
1289
        if (!local) {
1290
            PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.NameDetailsView);
1291
            preference =  getPreferenceFromDB(PreferencePredicate.NameDetailsView);
1292
            if (preference == null){
1293
                return null;
1294
            }
1295

    
1296
        //    setBooleanValue(ALLOW_OVERRIDE_NAME_DETAILS, preference.isAllowOverride());
1297
            value = preference.getValue();
1298
            config.setAllowOverride(preference.isAllowOverride());
1299
            //the preference value is build like this:
1300
            //<section1>:true;<section2>:false....
1301
        }else{
1302
            value = getStringValue(PreferencePredicate.NameDetailsView.getKey(), local);
1303
        }
1304
        if (value!= null){
1305
            fillNameDetailsConfigurator(config, value);
1306

    
1307

    
1308
        }else {
1309
            return null;
1310
        }
1311
        return config;
1312
    }
1313

    
1314
    public static void fillNameDetailsConfigurator(NameDetailsConfigurator config, String value) {
1315
        String [] sections = value.split(";");
1316
        Map<String, Boolean> sectionMap = new HashMap<>();
1317
        String[] sectionValues;
1318
        for (String sectionValue: sections){
1319
            if (sectionValue.contains(":")){
1320
                sectionValues = sectionValue.split(":");
1321
                sectionMap.put(sectionValues[0], Boolean.valueOf(sectionValues[1]));
1322
            }
1323
        }
1324
        for (Field field: config.getClass().getDeclaredFields()){
1325
            try {
1326
                config.getClass().getDeclaredField(field.getName()).set(config, getValue(sectionMap, field.getName()));
1327
            } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException
1328
                    | SecurityException e) {
1329
               logger.debug(e.getMessage());
1330
            }
1331
        }
1332
    }
1333

    
1334
    public static NameDetailsConfigurator getPreferredNameDetailsConfiguration() {
1335
        NameDetailsConfigurator config = new NameDetailsConfigurator();
1336

    
1337
        String value;
1338

    
1339
        value = getStringValue(PreferencePredicate.NameDetailsView.getKey(), false);
1340
        if (value != null){
1341
            fillNameDetailsConfigurator(config, value);
1342
        }else {
1343
            return null;
1344
        }
1345
        return config;
1346
    }
1347

    
1348
    public static void setPreferredNameDetailsConfiguration(NameDetailsConfigurator config, boolean local) {
1349
        CdmPreference preference = null;
1350

    
1351
        if (!local) {
1352
            preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.NameDetailsView, config.toString());
1353

    
1354
            setPreferenceToDB(preference);
1355
        }
1356
        else{
1357
            setStringValue(PreferencePredicate.NameDetailsView.getKey(), config.toString());
1358
        }
1359
    }
1360

    
1361
    private static Boolean getValue(Map<String, Boolean> sectionMap, String string) {
1362
        if (sectionMap.containsKey(string)){
1363
            return sectionMap.get(string);
1364
        }else{
1365
            return true;
1366
        }
1367
    }
1368

    
1369
    public static Abcd206ImportConfigurator getDBAbcdImportConfigurationPreference() {
1370

    
1371
        Abcd206ImportConfigurator config = Abcd206ImportConfigurator.NewInstance(null,null);
1372
        ICdmRepository controller;
1373
        controller = CdmStore.getCurrentApplicationConfiguration();
1374
        PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AbcdImportConfig);
1375
        CdmPreference preference = null;
1376
        if (controller == null){
1377
            return null;
1378
        }
1379
        preference = controller.getPreferenceService().find(key);
1380
        if (preference == null){
1381
            return config;
1382
         } else{
1383
             String configString = preference.getValue();
1384
             extractAbcdConfiguratorFromPreferenceString(config, configString);
1385
         }
1386
        return config;
1387
    }
1388

    
1389
    public static void extractAbcdConfiguratorFromPreferenceString(Abcd206ImportConfigurator config,
1390
            String configString) {
1391
        if(configString != null){
1392
             String[] configArray = configString.split(";");
1393

    
1394
             for (String configItem: configArray){
1395
                 String[] keyValue = configItem.split(":");
1396
                 String keyString = keyValue[0];
1397
                 String valueString = null;
1398
                 if (keyValue.length>1){
1399
                     valueString = keyValue[1];
1400
                     if (keyValue.length>2){
1401

    
1402
                         for (int index = 2; index< keyValue.length; index++){
1403
                             valueString += ":"+ keyValue[index];
1404
                         }
1405
                     }
1406
                 }
1407
                 if (keyString.equals("ignoreImportOfExistingSpecimen")){
1408
                     config.setIgnoreImportOfExistingSpecimen(Boolean.valueOf(valueString));
1409
                 }else if (keyString.equals("addIndividualsAssociationsSuchAsSpecimenAndObservations")){
1410
                     config.setAddIndividualsAssociationsSuchAsSpecimenAndObservations(Boolean.valueOf(valueString));
1411
                 }else if (keyString.equals("reuseExistingTaxaWhenPossible")){
1412
                     config.setReuseExistingTaxaWhenPossible(Boolean.valueOf(valueString));
1413
                 }else if (keyString.equals("ignoreAuthorship")){
1414
                     config.setIgnoreAuthorship(Boolean.valueOf(valueString));
1415
                 }else if (keyString.equals("addMediaAsMediaSpecimen")){
1416
                     config.setAddMediaAsMediaSpecimen(Boolean.valueOf(valueString));
1417
                 }else if (keyString.equals("reuseExistingMetaData")){
1418
                     config.setReuseExistingMetaData(Boolean.valueOf(valueString));
1419
                 }else if (keyString.equals("reuseExistingDescriptiveGroups")){
1420
                     config.setReuseExistingDescriptiveGroups(Boolean.valueOf(valueString));
1421
                 }else if (keyString.equals("allowReuseOtherClassifications")){
1422
                     config.setAllowReuseOtherClassifications(Boolean.valueOf(valueString));
1423
                 }else if (keyString.equals("deduplicateReferences")){
1424
                     config.setDeduplicateReferences(Boolean.valueOf(valueString));
1425
                 }else if (keyString.equals("deduplicateClassifications")){
1426
                     config.setDeduplicateClassifications(Boolean.valueOf(valueString));
1427
                 }else if (keyString.equals("moveNewTaxaToDefaultClassification")){
1428
                     config.setMoveNewTaxaToDefaultClassification(Boolean.valueOf(valueString));
1429
                 }else if (keyString.equals("mapUnitIdToCatalogNumber")){
1430
                     config.setMapUnitIdToCatalogNumber(Boolean.valueOf(valueString));
1431
                 }else if (keyString.equals("mapUnitIdToAccessionNumber")){
1432
                     config.setMapUnitIdToAccessionNumber(Boolean.valueOf(valueString));
1433
                 }else if (keyString.equals("mapUnitIdToBarcode")){
1434
                     config.setMapUnitIdToBarcode(Boolean.valueOf(valueString));
1435
                 }else if (keyString.equals("overwriteExistingSpecimens")){
1436
                     config.setOverwriteExistingSpecimens(Boolean.valueOf(valueString));
1437
                 }else if (keyString.equals("nomenclaturalCode")){
1438
                     config.setNomenclaturalCode(NomenclaturalCode.fromString(valueString));
1439
                 }else if (keyString.equals("removeCountryFromLocalityText")){
1440
                     config.setRemoveCountryFromLocalityText(Boolean.valueOf(valueString));
1441
                 }else if (keyString.equals("getSiblings")){
1442
                     config.setGetSiblings(Boolean.valueOf(valueString));
1443
                 }else if (keyString.equals("dnaSource")){
1444
                     try{
1445
                         config.setDnaSoure(URI.create(valueString));
1446
                     }catch(Exception e){
1447
                         config.setDnaSoure(null);
1448
                     }
1449
                 }else{
1450
                     logger.debug("This key of the abcd configurator needs to be added to the transformer: " + keyString);
1451
                 }
1452

    
1453

    
1454
             }
1455
         }
1456
    }
1457

    
1458
    public static Abcd206ImportConfigurator getLocalAbcdImportConfigurator(){
1459
        return getLocalAbcdImportConfigurator(true);
1460
    }
1461

    
1462
    public static Abcd206ImportConfigurator getLocalAbcdImportConfigurator(boolean skipCheckOverride){
1463
       Abcd206ImportConfigurator config = Abcd206ImportConfigurator.NewInstance(null,null);
1464
       CdmPreference pref = CdmPreferenceCache.instance().get(PreferencePredicate.AbcdImportConfig.getKey());
1465
       if (pref  == null || pref.isAllowOverride()){
1466
       String configString = PreferencesUtil.getStringValue(PreferencePredicate.AbcdImportConfig.getKey());
1467
           if (StringUtils.isBlank(configString)){
1468
               configString = getStringValue(PreferencePredicate.AbcdImportConfig.getKey(), skipCheckOverride);
1469
               extractAbcdConfiguratorFromPreferenceString(config, configString);
1470
               if (config.getNomenclaturalCode() == null){
1471
                   config.setNomenclaturalCode(getPreferredNomenclaturalCode());
1472
               }
1473
           }else{
1474
               config = Abcd206ImportConfigurator.NewInstance(null, null);
1475
               PreferencesUtil.extractAbcdConfiguratorFromPreferenceString(config, configString);
1476
           }
1477
       }else{
1478
           extractAbcdConfiguratorFromPreferenceString(config, pref.getValue());
1479
       }
1480

    
1481
       return config;
1482

    
1483
    }
1484

    
1485
    public static Abcd206ImportConfigurator getLastUsedAbcdImportConfigurator(){
1486
        Abcd206ImportConfigurator config = Abcd206ImportConfigurator.NewInstance(null,null);
1487

    
1488
       String configString = PreferencesUtil.getStringValue(IPreferenceKeys.LAST_USED_ABCD_CONFIG, true);
1489
       if (configString != null){
1490
           extractAbcdConfiguratorFromPreferenceString(config, configString);
1491
           if (config != null){
1492
               if (config.getNomenclaturalCode() == null){
1493
                   config.setNomenclaturalCode(getPreferredNomenclaturalCode());
1494
               }
1495
           }
1496
       }else{
1497
           config = PreferencesUtil.getLocalAbcdImportConfigurator(false);
1498
       }
1499

    
1500
        return config;
1501

    
1502
    }
1503

    
1504
    public static void updateAbcdImportConfigurationPreference() {
1505
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1506

    
1507
        CdmPreference pref = cache.findBestMatching(CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AbcdImportConfig));
1508

    
1509
        if (!getBooleanValue(prefOverrideKey(PreferencePredicate.AbcdImportConfig.getKey())) || !pref.isAllowOverride()){
1510
            resetToDBPreferenceAbcdCOnfigurator();
1511

    
1512
        }
1513
    }
1514

    
1515
    public static void resetToDBPreferenceAbcdCOnfigurator(){
1516
        Abcd206ImportConfigurator config = getDBAbcdImportConfigurationPreference();
1517
        setStringValue(PreferencePredicate.AbcdImportConfig.getKey(), config.toString());
1518
    }
1519

    
1520
    public static boolean isSortTaxaByRankAndName() {
1521
        return getBooleanValue(PreferencePredicate.SortTaxaByRankAndName.getKey());
1522
    }
1523

    
1524
    public static TermOrder getSortNamedAreasInDistributionEditor() {
1525
        TermOrder result;
1526
        try{
1527
            result = TermOrder.valueOf(getStringValue(PreferencePredicate.AreasSortedInDistributionEditor.getKey()));
1528
        }catch (IllegalArgumentException e){
1529
            result = (TermOrder)PreferencePredicate.AreasSortedInDistributionEditor.getDefaultValue();
1530
        }
1531
        return result;
1532
    }
1533

    
1534
    public static void setSortNamedAreasInDistributionEditor(String isSortByVocabularyOrder) {
1535
        setStringValue(PreferencePredicate.AreasSortedInDistributionEditor.getKey(), isSortByVocabularyOrder);
1536
    }
1537

    
1538
    public static void setLastSelectedReference(
1539
            List<String> lastSelectedReferences) {
1540

    
1541
        setStringValue(IPreferenceKeys.LAST_SELECTED_REFERENCES, lastSelectedReferences.toString());
1542
    }
1543

    
1544
    public static List<String> getLastSelectedReferences() {
1545

    
1546
        //IPreferenceStore preferenceStore = PreferencesUtil.getPreferenceStore();
1547
        String lastSelected = getStringValue(IPreferenceKeys.LAST_SELECTED_REFERENCES, true);
1548
        List<String> result = new ArrayList<>();
1549
        if (!StringUtils.isBlank(lastSelected)){
1550
            Collections.addAll(result, lastSelected.substring(1,lastSelected.length()-1).split(", "));
1551
        }
1552
        return result;
1553
    }
1554

    
1555
    public static void setPreferredNamedAreasForDistributionEditor(
1556
            String saveCheckedElements, String saveGrayedElements, boolean local) {
1557
        if (local){
1558
            setStringValue(PreferencePredicate.AvailableDistributionAreaTerms.getKey(), saveCheckedElements);
1559
        }
1560
        else{
1561
            CdmPreference preference = null;
1562

    
1563
            if (saveCheckedElements == null){
1564
                preference = getPreferenceFromDB(PreferencePredicate.AvailableDistributionAreaTerms);
1565

    
1566
                if (preference == null){
1567
                    return ;
1568
                } else{
1569
                    setStringValue(PreferencePredicate.AvailableDistributionAreaTerms.getKey(),
1570
                            saveCheckedElements);
1571
                    preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AvailableDistributionAreaTerms, saveCheckedElements);
1572
                    setPreferenceToDB(preference);
1573

    
1574
                }
1575
            } else{
1576
                preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AvailableDistributionAreaTerms, saveCheckedElements);
1577
                setPreferenceToDB(preference);
1578
                setStringValue(PreferencePredicate.AvailableDistributionAreaTerms.getKey(),
1579
                        saveCheckedElements);
1580

    
1581
            }
1582
        }
1583
    }
1584

    
1585
    public static void setPreferredVocabulariesForDistributionEditor(String saveCheckedElements,
1586
            boolean local, boolean isOverride) {
1587
        if (local){
1588
            setStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(), saveCheckedElements);
1589
            setBooleanValue(prefOverrideKey(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey()), isOverride);
1590
        }
1591
        else{
1592
            CdmPreference preference = null;
1593

    
1594
            if (saveCheckedElements == null){
1595
                preference = getPreferenceFromDB(PreferencePredicate.AvailableDistributionAreaVocabularies);
1596

    
1597
                if (preference == null){
1598
                    return ;
1599
                } else{
1600
                    setStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(),
1601
                            saveCheckedElements);
1602
                    preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AvailableDistributionAreaVocabularies, saveCheckedElements);
1603
                    preference.setAllowOverride(isOverride);
1604
                    setPreferenceToDB(preference);
1605
                }
1606
            } else{
1607
                preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AvailableDistributionAreaVocabularies, saveCheckedElements);
1608
                preference.setAllowOverride(isOverride);
1609
                setPreferenceToDB(preference);
1610
                setStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(),
1611
                        saveCheckedElements);
1612
            }
1613
        }
1614
    }
1615

    
1616
    public static String getPreferredVocabulariesForDistributionEditor(boolean local) {
1617
        if (local){
1618

    
1619
            String pref = getStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(), local);
1620
            return pref;
1621
        }
1622
        else{
1623
            CdmPreference preference = null;
1624
            preference = getPreferenceFromDB(PreferencePredicate.AvailableDistributionAreaVocabularies);
1625
            if (preference == null){
1626
                return null;
1627
            } else{
1628
                return preference.getValue();
1629
            }
1630
        }
1631
    }
1632

    
1633
    public static List<UUID> createUUIDListFromStringPref(String prefKey, boolean local) {
1634
        if (prefKey == null){
1635
            return null;
1636
        }
1637
        String prefValue = PreferencesUtil.getStringValue(prefKey, local);
1638
        if (prefValue == null){
1639
            return null;
1640
        }
1641
        List<UUID> uuidList = createUuidList(prefValue);
1642
        return uuidList;
1643
    }
1644

    
1645
    public static List<UUID> createUuidList(String prefValue) {
1646
        String[] stringArray = prefValue.split(";");
1647
        List<UUID> uuidList = new ArrayList<>();
1648
        for (String uuid: stringArray){
1649
            if (!StringUtils.isBlank(uuid)){
1650
                uuidList.add(UUID.fromString(uuid));
1651
            }
1652
        }
1653
        return uuidList;
1654
    }
1655

    
1656
    public static boolean getFilterCommonNameReferences(){
1657
        Boolean result = getBooleanValue(PreferencePredicate.CommonNameReferencesWithMarker.getKey());
1658
        if (result == null){
1659
            return false;
1660
        }
1661
        return result;
1662
    }
1663

    
1664
    public static void updateDBPreferences() {
1665

    
1666
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1667
        cache.getAllTaxEditorDBPreferences();
1668

    
1669
        //ABCD Configurator
1670

    
1671
        //updateAbcdImportConfigurationPreference();
1672

    
1673
        //Name Details
1674
        NameDetailsConfigurator config = getPreferredNameDetailsConfiguration(false);
1675
        //    if (config != null ){
1676
        //        if (!getBooleanValue(OVERRIDE_NAME_DETAILS) ||  !getBooleanValue(ALLOW_OVERRIDE_NAME_DETAILS)){
1677
        //            setPreferredNameDetailsConfiguration(config, false);
1678
        //        }
1679
        //    }
1680

    
1681
    }
1682

    
1683
    public static void setPreferencesToDB(List<CdmPreference> preferences) {
1684

    
1685
        ICdmRepository controller;
1686
        if(CdmStore.isActive()){
1687
            controller = CdmStore.getCurrentApplicationConfiguration();
1688
            for (CdmPreference preference: preferences){
1689
                if (preference.getValue() == null && preference.isAllowOverride()){
1690
                    controller.getPreferenceService().remove(preference.getKey());
1691

    
1692
                }else{
1693
                    controller.getPreferenceService().set(preference);
1694

    
1695
                }
1696

    
1697
            }
1698
            CdmPreferenceCache.instance().getAllTaxEditorDBPreferences();
1699
        }
1700
    }
1701

    
1702
    /**
1703
     * Returns whether the named preference is known.
1704
     * @param prefKey the key of the preference
1705
     * @return <code>true</code> if the preference is known, <code>false</code> otherwise
1706
     */
1707
    public static boolean contains(String prefKey){
1708
        return getPreferenceStore().contains(prefKey(prefKey));
1709
    }
1710

    
1711
    /**
1712
     *
1713
     */
1714
    public static TermTree<?> getPreferredFeatureTreeForNameDescription(boolean createNew) {
1715
        if(preferredNameFeatureTree != null && !createNew){
1716
            return preferredNameFeatureTree;
1717
        }
1718
        createPreferredFeatureTreeForNameDescription();
1719
        return preferredNameFeatureTree;
1720
    }
1721

    
1722
    public static void createPreferredFeatureTreeForNameDescription() {
1723

    
1724
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1725
        CdmPreference pref = cache.get(PreferencePredicate.NameFeatures.getKey());
1726
        List<Feature> terms = new ArrayList<>();
1727
        boolean override = PreferencesUtil.getOverrideForPreference(PreferencePredicate.NameFeatures.getKey());
1728

    
1729
        List<UUID> uuids = PreferencesUtil.createUUIDListFromStringPref(PreferencePredicate.NameFeatures.getKey(), false);
1730
        if (uuids != null && !uuids.isEmpty()){
1731
            terms = CdmStore.getTermManager().getTerms(uuids, Feature.class);
1732
        }
1733

    
1734
       if (terms.isEmpty()){
1735
           terms.addAll(TermStore.getTerms(CdmStore.getService(IVocabularyService.class).load(VocabularyEnum.NameFeature.getUuid()), null));
1736
        }
1737
        terms.remove(Feature.PROTOLOGUE());
1738
        if (terms.isEmpty()){
1739
            preferredNameFeatureTree = TermEditorInput.getDefaultNameFeatureTree();
1740
        }else{
1741
            preferredNameFeatureTree = TermTree.NewInstance(terms);
1742
        }
1743
    }
1744

    
1745
    public static void removeFromDB(List<CdmPreference> prefsToDelete) {
1746
        ICdmRepository controller;
1747
        //try{
1748
            if(CdmStore.isActive()){
1749
                controller = CdmStore.getCurrentApplicationConfiguration();
1750
                for (CdmPreference preference: prefsToDelete){
1751
                    controller.getPreferenceService().remove(preference.getKey());
1752
                }
1753
                CdmPreferenceCache.instance().getAllTaxEditorDBPreferences();
1754
            }
1755
    }
1756

    
1757
    public static void removeFromDB(CdmPreference prefToDelete) {
1758
        ICdmRepository controller;
1759

    
1760
        if(CdmStore.isActive()){
1761
            controller = CdmStore.getCurrentApplicationConfiguration();
1762
            controller.getPreferenceService().remove(prefToDelete.getKey());
1763

    
1764
            CdmPreferenceCache.instance().getAllTaxEditorDBPreferences();
1765
        }
1766
    }
1767

    
1768
    public static TermTree<?> getPreferredFeatureTreeForTaxonDescription(boolean createNew) {
1769
        if(preferredTaxonFeatureTree != null && !createNew){
1770
            return preferredTaxonFeatureTree;
1771
        }
1772
        createPreferredFeatureTreeForTaxonDescription();
1773
        return preferredTaxonFeatureTree;
1774
    }
1775

    
1776
    public static void createPreferredFeatureTreeForTaxonDescription() {
1777

    
1778
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1779
        CdmPreference pref = cache.get(PreferencePredicate.TaxonFeatures.getKey());
1780
        List<Feature> terms = null;
1781
        boolean override = PreferencesUtil.getOverrideForPreference(PreferencePredicate.TaxonFeatures.getKey());
1782
        List<UUID> uuids = PreferencesUtil.createUUIDListFromStringPref(PreferencePredicate.TaxonFeatures.getKey(), false);
1783
        if (uuids != null && !uuids.isEmpty()){
1784
            terms = CdmStore.getTermManager().getTerms(uuids, Feature.class);
1785
        }
1786
        if (terms == null || terms.isEmpty()){
1787
            terms= CdmStore.getTermManager().getPreferredTerms(TermType.Feature);
1788
            TermVocabulary nameVocabulary = CdmStore.getService(IVocabularyService.class).load(VocabularyEnum.NameFeature.getUuid());
1789
            Set<Feature> nameFeature = nameVocabulary.getTerms();
1790
            terms.removeAll(nameFeature);
1791

    
1792
        }
1793

    
1794
        if (terms.isEmpty()){
1795
            preferredTaxonFeatureTree = TermEditorInput.getDefaultFeatureTree();
1796
        }else{
1797
            preferredTaxonFeatureTree = TermTree.NewInstance(terms);
1798
        }
1799
    }
1800

    
1801
    public static void setLastSelectedBiocaseProvider(String lastAccessPoint) {
1802
        setStringValue(LAST_USED_BIOCASE_PROVIDER, lastAccessPoint);
1803
    }
1804
}
(41-41/57)