Project

General

Profile

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

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

    
43
import eu.etaxonomy.cdm.api.application.ICdmRepository;
44
import eu.etaxonomy.cdm.api.facade.DerivedUnitFacadeConfigurator;
45
import eu.etaxonomy.cdm.api.service.ITermService;
46
import eu.etaxonomy.cdm.api.service.ITermTreeService;
47
import eu.etaxonomy.cdm.api.service.IVocabularyService;
48
import eu.etaxonomy.cdm.api.service.config.FindTaxaAndNamesConfiguratorImpl;
49
import eu.etaxonomy.cdm.api.service.config.IFindTaxaAndNamesConfigurator;
50
import eu.etaxonomy.cdm.common.CdmUtils;
51
import eu.etaxonomy.cdm.common.URI;
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
        String nomString = getStringValue(PreferencePredicate.NomenclaturalCode.getKey());
458
        return getPreferredNomenclaturalCode(nomString);
459
    }
460

    
461
    public static NomenclaturalCode getPreferredNomenclaturalCode(String preferenceKeyNomenclaturalCode) {
462

    
463
        for (NomenclaturalCode code : NomenclaturalCodeHelper.getAllCodes()) {
464
            if (getPreferenceKey(code).equals(preferenceKeyNomenclaturalCode) || code.getKey().equals(preferenceKeyNomenclaturalCode)) {
465
                return code;
466
            }
467
        }
468
        return null;
469
    }
470

    
471
    public static boolean isShowTaxonAssociations(){
472
        boolean result = getBooleanValue(PreferencePredicate.ShowTaxonAssociations.getKey());
473
        return result;
474
    }
475

    
476
    public static boolean isShowLifeForm(){
477
        boolean result =  getBooleanValue(PreferencePredicate.ShowLifeForm.getKey());
478
        return result;
479
    }
480

    
481
    public static boolean isDeterminationOnlyForFieldUnits(){
482
        boolean result =  getBooleanValue(PreferencePredicate.DeterminationOnlyForFieldUnits.getKey());
483
        return result;
484
    }
485

    
486
    public static boolean isCollectingAreaInGeneralSection(){
487
        boolean result =  getBooleanValue(PreferencePredicate.ShowCollectingAreasInGeneralSection.getKey());
488
        return result;
489
    }
490

    
491
    public static CdmPreference getPreferenceFromDB(IPreferencePredicate<?> predicate){
492
        ICdmRepository controller;
493
        CdmPreference pref = null;
494

    
495
        try{
496
            if(CdmStore.isActive()){
497
                controller = CdmStore.getCurrentApplicationConfiguration();
498
                PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), predicate);
499
                pref = controller.getPreferenceService().find(key);
500
            }
501
        }catch(Exception e){
502
            e.printStackTrace();
503
        }
504

    
505
        return pref;
506
    }
507

    
508
    public static List<CdmPreference> getPreferencesFromDB(IPreferencePredicate<?> predicate){
509
        ICdmRepository controller;
510
        List<CdmPreference> prefs = null;
511

    
512
        try{
513
            if(CdmStore.isActive()){
514
                controller = CdmStore.getCurrentApplicationConfiguration();
515
                PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), predicate);
516
                prefs = controller.getPreferenceService().list(predicate);
517
            }
518
        }catch(Exception e){
519
            e.printStackTrace();
520
        }
521

    
522
        return prefs;
523

    
524
    }
525

    
526
    public static void setPreferencesToDB(CdmPreference preference, boolean setDefault){
527
        ICdmRepository controller;
528
        try{
529
            if(CdmStore.isActive()){
530
                controller = CdmStore.getCurrentApplicationConfiguration();
531

    
532
                if (setDefault){
533
                    controller.getPreferenceService().remove(preference.getKey());
534
                }else{
535
                    controller.getPreferenceService().set(preference);
536
                }
537
            }
538
        }catch(Exception e){
539
            e.printStackTrace();
540
        }
541
    }
542

    
543
    public static CdmPreference getPreferenceFromDB(PrefKey key){
544
        ICdmRepository controller;
545
        CdmPreference pref = null;
546

    
547
        try{
548
            if(CdmStore.isActive()){
549
                controller = CdmStore.getCurrentApplicationConfiguration();
550
                pref = controller.getPreferenceService().find(key);
551
            }
552
        }catch(Exception e){
553
            e.printStackTrace();
554
        }
555

    
556
        return pref;
557

    
558
    }
559

    
560
    public static void setPreferenceToDB(CdmPreference preference){
561
        ICdmRepository controller;
562
        try{
563
            if(CdmStore.isActive()){
564
                controller = CdmStore.getCurrentApplicationConfiguration();
565
                if (preference.getValue() == null && preference.isAllowOverride()){
566
                    controller.getPreferenceService().remove(preference.getKey());
567
                }else{
568
                    controller.getPreferenceService().set(preference);
569
                }
570
                CdmPreferenceCache.instance().put(preference);
571
            }
572
        }catch(Exception e){
573
            e.printStackTrace();
574
        }
575
    }
576

    
577
    public static String getPreferredDefaultLangugae(){
578
        String preferredLanguage = getStringValue(DEFAULT_LANGUAGE_EDITOR, true);
579
        if(StringUtils.isNotEmpty(preferredLanguage) && StringUtils.isNotBlank(preferredLanguage)){
580
            return preferredLanguage;
581
        }
582
        return null;
583
    }
584

    
585
    public static boolean isShowMediaPreview(){
586
        boolean isShowMediaPreview = getBooleanValue(SHOW_MEDIA_PREVIEW, true);
587
        return isShowMediaPreview;
588
    }
589

    
590
    /**
591
     * Get the match strategy for the given class that was stored in preferences
592
     * or the default strategy if it was not stored in preferences
593
     *
594
     * @param clazz
595
     *            a {@link java.lang.Class} object.
596
     * @return a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy} object.
597
     */
598
    public static IMatchStrategy getMatchStrategy(Class<?> clazz) {
599
        String className = clazz.getName();
600
        if (getBooleanValue(MATCH_STRATEGY_PREFIX + className, true)) {
601
            IMatchStrategy matchStrategy = getDefaultMatchStrategy(clazz);
602

    
603
            //TODO CacheMatchers (or multiple field matchers in future) are missing here
604
            for (FieldMatcher fieldMatcher : matchStrategy.getMatching().getFieldMatchers(false)) {
605
                String fieldName = fieldMatcher.getPropertyName();
606
                String matchModeName = getStringValue(
607
                        getMatchStrategyFieldName(className, fieldName), true);
608
                MatchMode matchMode = MatchMode.valueOf(matchModeName);
609
                try {
610
                    matchStrategy.setMatchMode(fieldName, matchMode);
611
                } catch (MatchException e) {
612
                    MessagingUtils.error(PreferencesUtil.class, e);
613
                    throw new RuntimeException(e);
614
                }
615
            }
616

    
617
            return matchStrategy;
618
        }
619
        return getDefaultMatchStrategy(clazz);
620
    }
621

    
622
    /**
623
     * Stores a matchStrategy into the preference store.
624
     *
625
     * @param matchStrategy
626
     *            a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy}
627
     *            object.
628
     */
629
    public static void setMatchStrategy(IMatchStrategy matchStrategy) {
630
        String className = "ANY class"; //FIXME was: matchStrategy.getMatchClass().getName(); seems currently not in use
631
        setBooleanValue(MATCH_STRATEGY_PREFIX + className, true);
632

    
633
        List<FieldMatcher> fieldMatchers = matchStrategy.getMatching().getFieldMatchers(false);
634

    
635
        for (FieldMatcher fieldMatcher : fieldMatchers) {
636
            String fieldName = fieldMatcher.getPropertyName();
637
            setStringValue(
638
                    getMatchStrategyFieldName(className, fieldName),
639
                    fieldMatcher.getMatchMode().name());
640
        }
641
    }
642

    
643
    /**
644
     * Helper method to create the preference property for a match field.
645
     *
646
     * @param className
647
     * @param fieldName
648
     * @return
649
     */
650
    private static String getMatchStrategyFieldName(String className,
651
            String fieldName) {
652
        return MATCH_STRATEGY_PREFIX + className + "." + fieldName;
653
    }
654

    
655
    /**
656
     * Returns the default match strategy for a given class.
657
     *
658
     * @param clazz
659
     *            a {@link java.lang.Class} object.
660
     * @return a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy} object.
661
     */
662
    public static IMatchStrategy getDefaultMatchStrategy(Class clazz) {
663
        return DefaultMatchStrategy.NewInstance(clazz);
664
    }
665

    
666
    public static String getDateFormatPattern() {
667
        // TODO make this configurable in properties
668
        String pattern = "Y-M-d H:m";
669
        return pattern;
670
    }
671

    
672
    public static <T extends TermBase> void addTermToPreferredTerms(T term) {
673

    
674
        // VocabularyEnum vocabulary =
675
        // VocabularyEnum.getVocabularyEnum(term.getClass());
676
        //
677
        // getPreferenceStore().setValue(getPreferenceKey(term),
678
        // VocabularyStore.getTermVocabulary(vocabulary).getTerms().contains(term));
679
        //
680
        // firePreferencesChanged(term.getClass());
681
    }
682

    
683
    /**
684
     * Construct a unique key using the CdmBase object's uuid
685
     *
686
     * @param cdmBase
687
     * @return
688
     */
689
    private static String getPreferenceKey(ICdmBase cdmBase) {
690
        cdmBase = HibernateProxyHelper.deproxy(cdmBase);
691

    
692
        String key = cdmBase.getClass().getName().concat(".")
693
                .concat(cdmBase.getUuid().toString());
694
        if (key.contains("javassist")) {
695
            MessagingUtils.info("proxy");
696
        }
697
        return key;
698
    }
699

    
700
    /**
701
     * Construct a unique key using the CdmBase object's uuid
702
     *
703
     * @param cdmBase
704
     * @return
705
     */
706
    public static String getPreferenceKey(ISimpleTerm<?> simpleTerm) {
707
        simpleTerm = HibernateProxyHelper.deproxy(simpleTerm);
708
        String key = simpleTerm.getClass().getName().concat(".")
709
                .concat(simpleTerm.getUuid().toString());
710
        if (key.contains("javassist")) {
711
            MessagingUtils.warn(PreferencesUtil.class,
712
                    "Trying to persist a preference based on a proxy class.");
713
        }
714
        return key;
715
    }
716

    
717
    /**
718
     * Construct a unique key using the CdmBase object's uuid
719
     */
720
    public static String getPreferenceKey(IDefinedTerm definedTerm) {
721
        definedTerm = HibernateProxyHelper.deproxy(definedTerm);
722
        String key = definedTerm.getClass().getName().concat(".")
723
                .concat(definedTerm.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
     * Retrieves search preferences from the preference store
733
     *
734
     * @return an {@link ITaxonServiceConfigurator} to pass to search methods
735
     */
736
    public static IFindTaxaAndNamesConfigurator getSearchConfigurator() {
737
        IFindTaxaAndNamesConfigurator configurator = initializeSearchConfigurator();
738

    
739
        configurator.setDoTaxa(PreferencesUtil.getPreferenceStore().contains(IPreferenceKeys.TAXON_SERVICE_CONFIGURATOR_TAXA)? PreferencesUtil.getPreferenceStore().getBoolean(
740
                IPreferenceKeys.TAXON_SERVICE_CONFIGURATOR_TAXA): true);
741
        configurator.setDoSynonyms(PreferencesUtil.getPreferenceStore().contains(IPreferenceKeys.TAXON_SERVICE_CONFIGURATOR_SYNONYMS)? PreferencesUtil.getPreferenceStore().getBoolean(
742
                IPreferenceKeys.TAXON_SERVICE_CONFIGURATOR_SYNONYMS): true);
743
        configurator.setDoNamesWithoutTaxa(PreferencesUtil.getPreferenceStore().contains(IPreferenceKeys.TAXON_SERVICE_CONFIGURATOR_NAMES)? PreferencesUtil.getPreferenceStore().getBoolean(
744
                IPreferenceKeys.TAXON_SERVICE_CONFIGURATOR_NAMES): true);
745
        configurator.setDoTaxaByCommonNames(PreferencesUtil.getPreferenceStore().contains(IPreferenceKeys.TAXON_SERVICE_CONFIGURATOR_COMMON_NAMES)? PreferencesUtil.getPreferenceStore().getBoolean(
746
                IPreferenceKeys.TAXON_SERVICE_CONFIGURATOR_COMMON_NAMES): true);
747
        //configurator.setMatchMode(eu.etaxonomy.cdm.persistence.query.MatchMode.valueOf(getStringValue(TAXON_SERVICE_CONFIGURATOR_MATCH_MODE)));
748

    
749
        return configurator;
750
    }
751

    
752
    /**
753
     * create new preferences, setting all search options to true
754
     *
755
     * @return a
756
     *         {@link eu.etaxonomy.cdm.api.service.config.ITaxonServiceConfigurator}
757
     *         object.
758
     */
759
    public static IFindTaxaAndNamesConfigurator initializeSearchConfigurator() {
760
        IFindTaxaAndNamesConfigurator configurator = FindTaxaAndNamesConfiguratorImpl.NewInstance();
761

    
762
        configurator.setDoTaxa(true);
763
        configurator.setDoSynonyms(true);
764
        configurator.setDoNamesWithoutTaxa(true);
765
        configurator.setDoTaxaByCommonNames(true);
766

    
767
        configurator.setTaxonPropertyPath(Arrays.asList("$", "titleCache",
768
                "name", "name.$", "relationsFromThisTaxon.$"));
769

    
770
        configurator.setSynonymPropertyPath(Arrays.asList("$", "titleCache",
771
                "name", "name.$", "synonyms.relatedTo.*"));
772

    
773
        // DEFAULT VALUES
774
        // match mode is a simple like, actually all other match modes are kind
775
        // of bogus
776
        configurator
777
                .setMatchMode(eu.etaxonomy.cdm.persistence.query.MatchMode.ANYWHERE);
778
        // we set page number and size here as this should always be unlimited
779
        configurator.setPageNumber(0);
780
        // TODO currently limit results to 10000
781
        configurator.setPageSize(10000);
782
        //setSearchConfigurator(configurator) ;
783
        return configurator;
784
    }
785

    
786
    /**
787
     * Store search preferences
788
     *
789
     * @param configurator
790
     *            a
791
     *            {@link eu.etaxonomy.cdm.api.service.config.ITaxonServiceConfigurator}
792
     *            object.
793
     */
794
    public static void setSearchConfigurator(
795
            IFindTaxaAndNamesConfigurator configurator) {
796
        getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_TAXA,
797
                configurator.isDoTaxa());
798
        getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_SYNONYMS,
799
                configurator.isDoSynonyms());
800
        getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_NAMES,
801
                configurator.isDoNamesWithoutTaxa());
802
        getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_COMMON_NAMES,
803
                configurator.isDoTaxaByCommonNames());
804
    }
805

    
806
    public static void firePreferencesChanged(Class clazz) {
807
        getPreferenceStore().firePropertyChangeEvent(PREFERRED_TERMS_CHANGE,
808
                null, clazz);
809
    }
810

    
811

    
812
    public static String createPreferenceString(String property){
813
       return prefKey(property);
814
    }
815
    public static String createOverridePreferenceString(String property){
816
           return prefOverrideKey(property);
817
    }
818

    
819
    public static boolean getOverrideForPreference(String preferenceString){
820
        return PreferencesUtil.getBooleanValue(PreferencesUtil.createOverridePreferenceString(preferenceString), true);
821
    }
822

    
823
    /**
824
     * Set default values for preferences
825
     */
826
    public static void setDefaults() {
827

    
828
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.EditMapServiceAccessPoint.getKey()),
829
                "http://edit.africamuseum.be/edit_wp5/v1.2/rest_gen.php");
830
        //FIXME : changed default for SHOULD_CONNECT_AT_STARTUP to false (ticket 3828) until resolution
831
        getPreferenceStore().setDefault(createPreferenceString(SHOULD_CONNECT_AT_STARTUP), false);
832
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.MobotOpenUrlServiceAccessPoint.getKey()),
833
                "http://www.biodiversitylibrary.org/openurl");
834
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.MobotOpenUrlServiceMaxWidth.getKey()), "1000");
835
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.MobotOpenUrlServiceMaxHeight.getKey()), "1000");
836
        getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_TAXA, true);
837
        getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_SYNONYMS, true);
838
        getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_NAMES, true);
839
        getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_COMMON_NAMES, true);
840

    
841
        //Name Details
842
       // getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.NameDetailsView.getKey()), new NameDetailsConfigurator(false).toString());
843

    
844
        //Navigator preferences
845
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.TaxonNodeOrder.getKey()), NavigatorOrderEnum.RankAndNameOrder.getKey());
846

    
847
        //getPreferenceStore().setDefault(createPreferenceString(Prefe), true);
848

    
849
        getPreferenceStore().setDefault(createPreferenceString(SHOW_ADVANCED_MEDIA_SECTION), false);
850

    
851
        getPreferenceStore().setDefault(createPreferenceString(SHOW_MEDIA_PREVIEW), false);
852
        //override db preferences
853
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.AbcdImportConfig.getKey())), false);
854
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.NameDetailsView.getKey())), false);
855
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.CommonNameAreaVocabularies.getKey())), false);
856
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.CommonNameReferencesWithMarker.getKey()), false);
857
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowTaxonNodeWizard.getKey()), Boolean.valueOf(PreferencePredicate.ShowTaxonNodeWizard.getDefaultValue().toString()));
858
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowNamespaceInSource.getKey()), Boolean.valueOf(PreferencePredicate.ShowNamespaceInSource.getDefaultValue().toString()));
859
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowIdInSource.getKey()), Boolean.valueOf(PreferencePredicate.ShowIdInSource.getDefaultValue().toString()));
860
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.DisableMultiClassification.getKey()), Boolean.valueOf(PreferencePredicate.DisableMultiClassification.getDefaultValue().toString()));
861
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowImportExportMenu.getKey()), Boolean.valueOf(PreferencePredicate.ShowImportExportMenu.getDefaultValue().toString()));
862
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowSpecimen.getKey()), Boolean.valueOf(PreferencePredicate.ShowSpecimen.getDefaultValue().toString()));
863
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.SearchForIdentifierAndTitleCache.getKey()), Boolean.valueOf(PreferencePredicate.SearchForIdentifierAndTitleCache.getDefaultValue().toString()));
864
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.SearchForIdentifierAndTitleCache.getKey())), false);
865
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.SearchForIdentifierAsDefault.getKey()), Boolean.valueOf(PreferencePredicate.SearchForIdentifierAsDefault.getDefaultValue().toString()));
866
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.SearchForIdentifierAsDefault.getKey())), false);
867
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.ShowModifierFreeText.getKey())), false);
868
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.ShowModifier.getKey())), false);
869
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.DistributionEditorActivated.getKey())), false);
870
    }
871

    
872
    public static void checkNomenclaturalCode() {
873
        // First time Editor is opened, no nomenclatural code has been set
874
        if (PreferencesUtil.getPreferredNomenclaturalCode() == null) {
875
            PreferencesUtil.setPreferredNomenclaturalCode(getPreferenceKey(NomenclaturalCode.ICNAFP), true);
876
        }
877
    }
878

    
879
    public static void setNomenclaturalCodePreferences(){
880
        ICdmRepository controller;
881
        controller = CdmStore.getCurrentApplicationConfiguration();
882
        PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.NomenclaturalCode);
883
        CdmPreference preference = null;
884
        if (controller == null){
885
            return ;
886
        }
887
        preference = controller.getPreferenceService().find(key);
888
        if (preference == null){
889
            return;
890
        }
891
//        setBooleanValue(ALLOW_OVERRIDE_NOMENCLATURAL_CODE_KEY, preference.isAllowOverride());
892

    
893
        int index = StringUtils.lastIndexOf(preference.getValue(), ".");
894
        UUID uuid = UUID.fromString(preference.getValue().substring(index +1, preference.getValue().length()));
895
        NomenclaturalCode preferredCode = NomenclaturalCode.getByUuid(uuid);
896

    
897
        setStringValue(PreferencePredicate.NomenclaturalCode.getKey(),
898
                getPreferenceKey(preferredCode));
899
    }
900

    
901
    public static void checkDefaultLanguage(){
902
        if(PreferencesUtil.getPreferredDefaultLangugae() == null){
903
           Shell shell = AbstractUtility.getShell();
904
           int open = new DefaultLanguageDialog(shell).open();
905
           if(open == Window.OK){
906
               PlatformUI.getWorkbench().restart();
907
           }
908
        }else{
909
            //TODO:In case of a reinstall, the config.ini will be overwritten
910
            //     here you create config.ini with the stored key from preferences
911
        }
912
    }
913

    
914
    public static String getMapServiceAccessPoint() {
915
        return getStringValue(PreferencePredicate.EditMapServiceAccessPoint.getKey());
916
    }
917

    
918
    public static boolean shouldConnectAtStartUp() {
919
        //FIXME :  force SHOULD_CONNECT_AT_STARTUP to false (ticket 3828) until resolution
920
        //return getBooleanValue(SHOULD_CONNECT_AT_STARTUP);
921
        return false;
922
    }
923

    
924
    public static TermTree<?> getDefaultFeatureTreeForTextualDescription() {
925
        String uuidString = getStringValue(
926
                FEATURE_TREE_DEFAULT_TEXT, true);
927
        if (StringUtils.isBlank(uuidString)) {
928
            return null;
929
        }
930
        TermTree<?> tree = CdmStore.getService(
931
                ITermTreeService.class).load(UUID.fromString(uuidString));
932

    
933
        if (tree == null || tree.getId() == 0) {
934
            return null;
935
        }
936
        return tree;
937
    }
938

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

    
946
    public static void setSortRanksHierarchichally(boolean selection) {
947
        setBooleanValue(PreferencePredicate.SortRanksHierarchichally.getKey(), selection);
948
    }
949

    
950
    public static boolean getSortRanksHierarchichally() {
951
        return getBooleanValue(PreferencePredicate.SortRanksHierarchichally.getKey());
952
    }
953

    
954
    public static boolean isMultilanguageTextEditingCapability() {
955
        return getBooleanValue(
956
                PreferencePredicate.MultiLanguageTextEditing.getKey());
957
    }
958

    
959
    public static Language getGlobalLanguage() {
960

    
961
        String languageUuidString = getStringValue(
962
                GLOBAL_LANGUAGE_UUID, true);
963

    
964
        if(!CdmStore.isActive()) {
965
            MessagingUtils.noDataSourceWarningDialog(languageUuidString);
966
            return null;
967
        }
968

    
969
        if (CdmUtils.isBlank(languageUuidString)) {
970
            return Language.getDefaultLanguage();
971
        }
972

    
973
        UUID languageUuid = UUID.fromString(languageUuidString);
974
        return (Language) CdmStore.getService(ITermService.class).load(
975
                languageUuid);
976
    }
977

    
978
    public static void setGlobalLanguage(Language language) {
979
        if(language != null) {
980
            setStringValue(GLOBAL_LANGUAGE_UUID,language.getUuid().toString());
981
            CdmStore.setDefaultLanguage(language);
982
        }
983
    }
984

    
985
    public static Map<MarkerType, Boolean> getEditMarkerTypePreferences() {
986
        List<MarkerType> markerTypes = CdmStore.getTermManager()
987
                .getPreferredTerms(MarkerType.class);
988

    
989
        Map<MarkerType, Boolean> result = new HashMap<>();
990

    
991
        for (MarkerType markerType : markerTypes) {
992
            String name = getMarkerTypeEditingPreferenceKey(markerType);
993
            Boolean value = getBooleanValue(name);
994
            result.put(markerType, value);
995
        }
996

    
997
        return result;
998
    }
999

    
1000
    public static void setEditMarkerTypePreferences(
1001
            Map<MarkerType, Boolean> markerTypeEditingMap) {
1002
        for (MarkerType markerType : markerTypeEditingMap.keySet()) {
1003
            String name = getMarkerTypeEditingPreferenceKey(markerType);
1004
            setBooleanValue(name,
1005
                    markerTypeEditingMap.get(markerType));
1006
        }
1007
    }
1008

    
1009
    private static String getMarkerTypeEditingPreferenceKey(
1010
            MarkerType markerType) {
1011
        markerType = HibernateProxyHelper.deproxy(markerType);
1012
        return markerType.getClass().getName() + EDIT_MARKER_TYPE_PREFIX;
1013
    }
1014

    
1015
    public static void setEditMarkerTypePreference(MarkerType markerType,
1016
            boolean edit) {
1017
        setBooleanValue(
1018
                getMarkerTypeEditingPreferenceKey(markerType), edit);
1019
    }
1020

    
1021
    public static DerivedUnitFacadeConfigurator getDerivedUnitConfigurator() {
1022
        DerivedUnitFacadeConfigurator configurator = DerivedUnitFacadeConfigurator
1023
                .NewInstance();
1024
        configurator.setMoveDerivedUnitMediaToGallery(true);
1025
        configurator.setMoveFieldObjectMediaToGallery(true);
1026
        return configurator;
1027
    }
1028

    
1029
    /**
1030
     * This method will write language properties to the config.ini located in the configuration folder
1031
     * of the Taxonomic Ediitor. <b>This method is only used to set the default language for Taxonomic Editor.</b>
1032
     *
1033
     * @param setLanguage 0 is for german and 1 for english.
1034
     * @throws IOException
1035
     */
1036
    public void writePropertyToConfigFile(int setLanguage) throws IOException {
1037
        File file = org.eclipse.core.runtime.preferences.ConfigurationScope.INSTANCE.getLocation().toFile();
1038
        //give warning to user if the directory has no write access
1039
        if(file == null){
1040
            throw new IOException();
1041
        }
1042
        Properties properties = load(file.getAbsolutePath()+"/config.ini");
1043
        switch(setLanguage){
1044
        case 0:
1045
            properties.setProperty("osgi.nl", "de");
1046
            setStringValue(IPreferenceKeys.DEFAULT_LANGUAGE_EDITOR, "de");
1047
            break;
1048
        case 1:
1049
            properties.setProperty("osgi.nl", "en");
1050
            setStringValue(IPreferenceKeys.DEFAULT_LANGUAGE_EDITOR, "en");
1051
            break;
1052
        default:
1053
            break;
1054
        }
1055
        save(file+"/config.ini", properties);
1056
    }
1057

    
1058
    /**
1059
     * This method loads a property from a given file and returns it.
1060
     *
1061
     * @param filename
1062
     * @return
1063
     * @throws IOException
1064
     */
1065
    private Properties load(String filename) throws IOException {
1066
        FileInputStream in = new FileInputStream(filename);
1067
        Properties prop = new Properties();
1068
        prop.load(in);
1069
        in.close();
1070
        return prop;
1071
    }
1072

    
1073
    /**
1074
     * This method saves a property to the specified file.
1075
     *
1076
     * @param filename
1077
     * @param properties
1078
     * @throws IOException
1079
     */
1080
    private void save(String filename, Properties properties) throws IOException{
1081
        FileOutputStream fos =  new FileOutputStream(filename);
1082
        properties.store(fos, "");
1083
        fos.close();
1084
    }
1085

    
1086
    /**
1087
     * Saves a list of P2 Metadata Repositories as string with specified delimiters
1088
     *
1089
     * @param p2Repos
1090
     */
1091
    public static void setP2Repositories(List<MetadataRepositoryElement> p2Repos) {
1092
        StringBuilder sb = new StringBuilder();
1093
        for(MetadataRepositoryElement p2Repo : p2Repos) {
1094
            sb.append(P2_REPOSITORIES_DELIM);
1095
            if(p2Repo.getName() == null || p2Repo.getName().isEmpty()) {
1096
                sb.append("-");
1097
            } else {
1098
                sb.append(p2Repo.getName());
1099
            }
1100
            sb.append(P2_REPOSITORY_FIELDS_DELIM);
1101
            sb.append(p2Repo.getLocation().toString());
1102
            sb.append(P2_REPOSITORY_FIELDS_DELIM);
1103
            sb.append(String.valueOf(p2Repo.isEnabled()));
1104
        }
1105
        getPreferenceStore().setValue(P2_REPOSITORY_LIST, sb.toString());
1106
    }
1107

    
1108

    
1109
    /**
1110
     * Retrieves a list of previously saved P2 repositories
1111
     */
1112
    public static List<MetadataRepositoryElement> getP2Repositories() {
1113
        List<MetadataRepositoryElement> p2Repos = new ArrayList<MetadataRepositoryElement>();
1114
        String p2ReposPref =  getStringValue(P2_REPOSITORY_LIST, true);
1115
        if(p2ReposPref != null && !p2ReposPref.isEmpty()) {
1116
            StringTokenizer p2ReposPrefST = new StringTokenizer(p2ReposPref,P2_REPOSITORIES_DELIM);
1117

    
1118
            while(p2ReposPrefST.hasMoreTokens()) {
1119
                String p2RepoStr = p2ReposPrefST.nextToken();
1120
                StringTokenizer p2ReposStrST = new StringTokenizer(p2RepoStr,P2_REPOSITORY_FIELDS_DELIM);
1121
                if(p2ReposStrST.countTokens()==3) {
1122
                    String nickname = p2ReposStrST.nextToken();
1123
                    URI uri = null;
1124
                    try {
1125
                        uri = new URI(p2ReposStrST.nextToken());
1126
                    } catch (URISyntaxException e) {
1127
                        continue;
1128
                    }
1129
                    boolean enabled = Boolean.parseBoolean(p2ReposStrST.nextToken());
1130
                    MetadataRepositoryElement mre = new MetadataRepositoryElement(null, uri.getJavaUri(), true);
1131
                    mre.setNickname(nickname);
1132
                    mre.setEnabled(enabled);
1133
                    p2Repos.add(mre);
1134
                }
1135
            }
1136
        }
1137

    
1138
        return p2Repos;
1139
    }
1140

    
1141
    /**
1142
     * enables/disables nested composite. <br>
1143
     *
1144
     * @param ctrl - Composite to be en-/disabeld
1145
     * @param enabled - boolean
1146
     */
1147
    public static void recursiveSetEnabled(Control ctrl, boolean enabled) {
1148
        if (ctrl instanceof Composite) {
1149
            Composite comp = (Composite) ctrl;
1150
            for (Control c : comp.getChildren()) {
1151
                recursiveSetEnabled(c, enabled);
1152
            }
1153
        } else {
1154
            ctrl.setEnabled(enabled);
1155
        }
1156
    }
1157

    
1158
    public static void setSortNodes(NavigatorOrderEnum nodesOrder) {
1159
        if (nodesOrder == null){
1160
            setStringValue(PreferencePredicate.TaxonNodeOrder.getKey(), null);
1161
        }else{
1162
            setStringValue(PreferencePredicate.TaxonNodeOrder.getKey(), nodesOrder.key);
1163
        }
1164
    }
1165

    
1166
    public static NavigatorOrderEnum getSortNodes() {
1167
        return NavigatorOrderEnum.valueOf(getStringValue(PreferencePredicate.TaxonNodeOrder.getKey()));
1168
    }
1169

    
1170
    public static boolean isNodesSortedNaturally() {
1171
        NavigatorOrderEnum value = NavigatorOrderEnum.valueOf(getStringValue(PreferencePredicate.TaxonNodeOrder.getKey()));
1172
        return value.equals(NavigatorOrderEnum.NaturalOrder);
1173
    }
1174

    
1175
    public static boolean isNodesSortedByName() {
1176
        NavigatorOrderEnum value = NavigatorOrderEnum.valueOf(getStringValue(PreferencePredicate.TaxonNodeOrder.getKey()));
1177
        return value.equals(NavigatorOrderEnum.AlphabeticalOrder);
1178
    }
1179

    
1180
    public static boolean isNodesSortedByNameAndRank() {
1181
        NavigatorOrderEnum value = NavigatorOrderEnum.valueOf(getStringValue(PreferencePredicate.TaxonNodeOrder.getKey()));
1182
        return value.equals(NavigatorOrderEnum.RankAndNameOrder);
1183
    }
1184

    
1185
    public static boolean isStoreNavigatorState() {
1186
        return getBooleanValue(RESTORE_NAVIGATOR_STATE);
1187
    }
1188

    
1189
    public static void setStoreNavigatorState(boolean selection) {
1190
        setBooleanValue(RESTORE_NAVIGATOR_STATE, selection);
1191
    }
1192

    
1193
    public static boolean isShowUpWidgetIsDisposedMessages() {
1194
       return getBooleanValue(IS_SHOW_UP_WIDGET_IS_DISPOSED);
1195
    }
1196

    
1197
    public static void setShowUpWidgetIsDisposedMessages(boolean selection) {
1198
        setBooleanValue(IS_SHOW_UP_WIDGET_IS_DISPOSED, selection);
1199
    }
1200

    
1201
    public static boolean isShowIdInVocabularyInChecklistEditor() {
1202
        String area_display = getStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey());
1203
        if (area_display.equals(TermDisplayEnum.IdInVocabulary.getKey())) {
1204
            return true;
1205
        }else{
1206
            return false;
1207
        }
1208
    }
1209
    public static boolean isShowSymbol1InChecklistEditor() {
1210
        String area_display = getStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey());
1211
        if (area_display.equals(TermDisplayEnum.Symbol1.getKey())) {
1212
            return true;
1213
        }else{
1214
            return false;
1215
        }
1216
    }
1217
    public static boolean isShowSymbol2InChecklistEditor() {
1218
        String area_display = getStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey());
1219
        if (area_display.equals(TermDisplayEnum.Symbol2.getKey())) {
1220
            return true;
1221
        }else{
1222
            return false;
1223
        }
1224
    }
1225

    
1226
    public static void setAreaDisplayInChecklistEditor(String selection) {
1227
        setStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey(), selection);
1228
    }
1229

    
1230
    public static void setOwnDescriptionForChecklistEditor(boolean selection) {
1231
        setBooleanValue(PreferencePredicate.OwnDescriptionForDistributionEditor.getKey(), selection);
1232
    }
1233

    
1234
    public static boolean isOwnDescriptionForChecklistEditor() {
1235
        return getBooleanValue(PreferencePredicate.OwnDescriptionForDistributionEditor.getKey());
1236
    }
1237

    
1238
    public static TermDisplayEnum displayAreaInChecklistEditor() {
1239
        TermDisplayEnum result;
1240
        try{
1241
            result = TermDisplayEnum.byKey(getStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey()));
1242
        }catch (IllegalArgumentException e){
1243
           result = ((TermDisplayEnum) PreferencePredicate.DisplayOfAreasInDistributionEditor.getDefaultValue());
1244
        }
1245
       return result;
1246
    }
1247

    
1248
    public static TermDisplayEnum displayStatusInChecklistEditor() {
1249
        TermDisplayEnum result;
1250
        try{
1251
            result = TermDisplayEnum.byKey(getStringValue(PreferencePredicate.DisplayOfStatus.getKey()));
1252
        }catch (IllegalArgumentException e){
1253
           result = ((TermDisplayEnum) PreferencePredicate.DisplayOfStatus.getDefaultValue());
1254
        }
1255
       return result;
1256
    }
1257

    
1258
    public static void setDisplayStatusInChecklistEditor(String selection) {
1259
        setStringValue(PreferencePredicate.DisplayOfStatus.getKey(), selection);
1260
    }
1261

    
1262
    public static boolean isShowRankInChecklistEditor() {
1263
        return getBooleanValue(PreferencePredicate.ShowRankInDistributionEditor.getKey());
1264
    }
1265

    
1266
    public static void setShowRankInChecklistEditor(boolean selection) {
1267
       setBooleanValue(PreferencePredicate.ShowRankInDistributionEditor.getKey(), selection);
1268
    }
1269

    
1270
    public static NameDetailsConfigurator getPreferredNameDetailsConfiguration( boolean local) {
1271
        NameDetailsConfigurator config = new NameDetailsConfigurator();
1272
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1273
        CdmPreference preference = null;
1274
        String value;
1275
        if (!local) {
1276
            PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.NameDetailsView);
1277
            preference =  getPreferenceFromDB(PreferencePredicate.NameDetailsView);
1278
            if (preference == null){
1279
                return null;
1280
            }
1281

    
1282
        //    setBooleanValue(ALLOW_OVERRIDE_NAME_DETAILS, preference.isAllowOverride());
1283
            value = preference.getValue();
1284
            config.setAllowOverride(preference.isAllowOverride());
1285
            //the preference value is build like this:
1286
            //<section1>:true;<section2>:false....
1287
        }else{
1288
            value = getStringValue(PreferencePredicate.NameDetailsView.getKey(), local);
1289
        }
1290
        if (value!= null){
1291
            fillNameDetailsConfigurator(config, value);
1292

    
1293

    
1294
        }else {
1295
            return null;
1296
        }
1297
        return config;
1298
    }
1299

    
1300
    public static void fillNameDetailsConfigurator(NameDetailsConfigurator config, String value) {
1301
        String [] sections = value.split(";");
1302
        Map<String, Boolean> sectionMap = new HashMap<>();
1303
        String[] sectionValues;
1304
        for (String sectionValue: sections){
1305
            if (sectionValue.contains(":")){
1306
                sectionValues = sectionValue.split(":");
1307
                sectionMap.put(sectionValues[0], Boolean.valueOf(sectionValues[1]));
1308
            }
1309
        }
1310
        for (Field field: config.getClass().getDeclaredFields()){
1311
            try {
1312
                config.getClass().getDeclaredField(field.getName()).set(config, getValue(sectionMap, field.getName()));
1313
            } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException
1314
                    | SecurityException e) {
1315
               logger.debug(e.getMessage());
1316
            }
1317
        }
1318
    }
1319

    
1320
    public static NameDetailsConfigurator getPreferredNameDetailsConfiguration() {
1321
        NameDetailsConfigurator config = new NameDetailsConfigurator();
1322

    
1323
        String value;
1324

    
1325
        value = getStringValue(PreferencePredicate.NameDetailsView.getKey(), false);
1326
        if (value != null){
1327
            fillNameDetailsConfigurator(config, value);
1328
        }else {
1329
            return null;
1330
        }
1331
        return config;
1332
    }
1333

    
1334
    public static void setPreferredNameDetailsConfiguration(NameDetailsConfigurator config, boolean local) {
1335
        CdmPreference preference = null;
1336

    
1337
        if (!local) {
1338
            preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.NameDetailsView, config.toString());
1339

    
1340
            setPreferenceToDB(preference);
1341
        }
1342
        else{
1343
            setStringValue(PreferencePredicate.NameDetailsView.getKey(), config.toString());
1344
        }
1345
    }
1346

    
1347
    private static Boolean getValue(Map<String, Boolean> sectionMap, String string) {
1348
        if (sectionMap.containsKey(string)){
1349
            return sectionMap.get(string);
1350
        }else{
1351
            return true;
1352
        }
1353
    }
1354

    
1355
    public static Abcd206ImportConfigurator getDBAbcdImportConfigurationPreference() {
1356

    
1357
        Abcd206ImportConfigurator config = Abcd206ImportConfigurator.NewInstance(null,null);
1358
        ICdmRepository controller;
1359
        controller = CdmStore.getCurrentApplicationConfiguration();
1360
        PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AbcdImportConfig);
1361
        CdmPreference preference = null;
1362
        if (controller == null){
1363
            return null;
1364
        }
1365
        preference = controller.getPreferenceService().find(key);
1366
        if (preference == null){
1367
            return config;
1368
         } else{
1369
             String configString = preference.getValue();
1370
             extractAbcdConfiguratorFromPreferenceString(config, configString);
1371
         }
1372
        return config;
1373
    }
1374

    
1375
    public static void extractAbcdConfiguratorFromPreferenceString(Abcd206ImportConfigurator config,
1376
            String configString) {
1377
        if(configString != null){
1378
             String[] configArray = configString.split(";");
1379

    
1380
             for (String configItem: configArray){
1381
                 String[] keyValue = configItem.split(":");
1382
                 String keyString = keyValue[0];
1383
                 String valueString = null;
1384
                 if (keyValue.length>1){
1385
                     valueString = keyValue[1];
1386
                     if (keyValue.length>2){
1387

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

    
1446
    public static Abcd206ImportConfigurator getLocalAbcdImportConfigurator(){
1447
        return getLocalAbcdImportConfigurator(true);
1448
    }
1449

    
1450
    public static Abcd206ImportConfigurator getLocalAbcdImportConfigurator(boolean skipCheckOverride){
1451
       Abcd206ImportConfigurator config = Abcd206ImportConfigurator.NewInstance(null,null);
1452
       CdmPreference pref = CdmPreferenceCache.instance().get(PreferencePredicate.AbcdImportConfig.getKey());
1453
       if (pref  == null || pref.isAllowOverride()){
1454
       String configString = PreferencesUtil.getStringValue(PreferencePredicate.AbcdImportConfig.getKey());
1455
           if (StringUtils.isBlank(configString)){
1456
               configString = getStringValue(PreferencePredicate.AbcdImportConfig.getKey(), skipCheckOverride);
1457
               extractAbcdConfiguratorFromPreferenceString(config, configString);
1458
               if (config.getNomenclaturalCode() == null){
1459
                   config.setNomenclaturalCode(getPreferredNomenclaturalCode());
1460
               }
1461
           }else{
1462
               config = Abcd206ImportConfigurator.NewInstance(null, null);
1463
               PreferencesUtil.extractAbcdConfiguratorFromPreferenceString(config, configString);
1464
           }
1465
       }else{
1466
           extractAbcdConfiguratorFromPreferenceString(config, pref.getValue());
1467
       }
1468

    
1469
       return config;
1470

    
1471
    }
1472

    
1473
    public static Abcd206ImportConfigurator getLastUsedAbcdImportConfigurator(){
1474
        Abcd206ImportConfigurator config = Abcd206ImportConfigurator.NewInstance(null,null);
1475

    
1476
       String configString = PreferencesUtil.getStringValue(IPreferenceKeys.LAST_USED_ABCD_CONFIG, true);
1477
       if (configString != null){
1478
           extractAbcdConfiguratorFromPreferenceString(config, configString);
1479
           if (config != null){
1480
               if (config.getNomenclaturalCode() == null){
1481
                   config.setNomenclaturalCode(getPreferredNomenclaturalCode());
1482
               }
1483
           }
1484
       }else{
1485
           config = PreferencesUtil.getLocalAbcdImportConfigurator(false);
1486
       }
1487

    
1488
        return config;
1489

    
1490
    }
1491

    
1492
    public static void updateAbcdImportConfigurationPreference() {
1493
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1494

    
1495
        CdmPreference pref = cache.findBestMatching(CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AbcdImportConfig));
1496

    
1497
        if (!getBooleanValue(prefOverrideKey(PreferencePredicate.AbcdImportConfig.getKey())) || !pref.isAllowOverride()){
1498
            resetToDBPreferenceAbcdCOnfigurator();
1499

    
1500
        }
1501
    }
1502

    
1503
    public static void resetToDBPreferenceAbcdCOnfigurator(){
1504
        Abcd206ImportConfigurator config = getDBAbcdImportConfigurationPreference();
1505
        setStringValue(PreferencePredicate.AbcdImportConfig.getKey(), config.toString());
1506
    }
1507

    
1508
    public static boolean isSortTaxaByRankAndName() {
1509
        return getBooleanValue(PreferencePredicate.SortTaxaByRankAndName.getKey());
1510
    }
1511

    
1512
    public static TermOrder getSortNamedAreasInDistributionEditor() {
1513
        TermOrder result;
1514
        try{
1515
            result = TermOrder.valueOf(getStringValue(PreferencePredicate.AreasSortedInDistributionEditor.getKey()));
1516
        }catch (IllegalArgumentException e){
1517
            result = (TermOrder)PreferencePredicate.AreasSortedInDistributionEditor.getDefaultValue();
1518
        }
1519
        return result;
1520
    }
1521

    
1522
    public static void setSortNamedAreasInDistributionEditor(String isSortByVocabularyOrder) {
1523
        setStringValue(PreferencePredicate.AreasSortedInDistributionEditor.getKey(), isSortByVocabularyOrder);
1524
    }
1525

    
1526
    public static void setLastSelectedReference(
1527
            List<String> lastSelectedReferences) {
1528

    
1529
        setStringValue(IPreferenceKeys.LAST_SELECTED_REFERENCES, lastSelectedReferences.toString());
1530
    }
1531

    
1532
    public static List<String> getLastSelectedReferences() {
1533

    
1534
        //IPreferenceStore preferenceStore = PreferencesUtil.getPreferenceStore();
1535
        String lastSelected = getStringValue(IPreferenceKeys.LAST_SELECTED_REFERENCES, true);
1536
        List<String> result = new ArrayList<>();
1537
        if (!StringUtils.isBlank(lastSelected)){
1538
            Collections.addAll(result, lastSelected.substring(1,lastSelected.length()-1).split(", "));
1539
        }
1540
        return result;
1541
    }
1542

    
1543
    public static void setPreferredNamedAreasForDistributionEditor(
1544
            String saveCheckedElements, String saveGrayedElements, boolean local) {
1545
        if (local){
1546
            setStringValue(PreferencePredicate.AvailableDistributionAreaTerms.getKey(), saveCheckedElements);
1547
        }
1548
        else{
1549
            CdmPreference preference = null;
1550

    
1551
            if (saveCheckedElements == null){
1552
                preference = getPreferenceFromDB(PreferencePredicate.AvailableDistributionAreaTerms);
1553

    
1554
                if (preference == null){
1555
                    return ;
1556
                } else{
1557
                    setStringValue(PreferencePredicate.AvailableDistributionAreaTerms.getKey(),
1558
                            saveCheckedElements);
1559
                    preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AvailableDistributionAreaTerms, saveCheckedElements);
1560
                    setPreferenceToDB(preference);
1561

    
1562
                }
1563
            } else{
1564
                preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AvailableDistributionAreaTerms, saveCheckedElements);
1565
                setPreferenceToDB(preference);
1566
                setStringValue(PreferencePredicate.AvailableDistributionAreaTerms.getKey(),
1567
                        saveCheckedElements);
1568

    
1569
            }
1570
        }
1571
    }
1572

    
1573
    public static void setPreferredVocabulariesForDistributionEditor(String saveCheckedElements,
1574
            boolean local, boolean isOverride) {
1575
        if (local){
1576
            setStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(), saveCheckedElements);
1577
            setBooleanValue(prefOverrideKey(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey()), isOverride);
1578
        }
1579
        else{
1580
            CdmPreference preference = null;
1581

    
1582
            if (saveCheckedElements == null){
1583
                preference = getPreferenceFromDB(PreferencePredicate.AvailableDistributionAreaVocabularies);
1584

    
1585
                if (preference == null){
1586
                    return ;
1587
                } else{
1588
                    setStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(),
1589
                            saveCheckedElements);
1590
                    preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AvailableDistributionAreaVocabularies, saveCheckedElements);
1591
                    preference.setAllowOverride(isOverride);
1592
                    setPreferenceToDB(preference);
1593
                }
1594
            } else{
1595
                preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AvailableDistributionAreaVocabularies, saveCheckedElements);
1596
                preference.setAllowOverride(isOverride);
1597
                setPreferenceToDB(preference);
1598
                setStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(),
1599
                        saveCheckedElements);
1600
            }
1601
        }
1602
    }
1603

    
1604
    public static String getPreferredVocabulariesForDistributionEditor(boolean local) {
1605
        if (local){
1606

    
1607
            String pref = getStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(), local);
1608
            return pref;
1609
        }
1610
        else{
1611
            CdmPreference preference = null;
1612
            preference = getPreferenceFromDB(PreferencePredicate.AvailableDistributionAreaVocabularies);
1613
            if (preference == null){
1614
                return null;
1615
            } else{
1616
                return preference.getValue();
1617
            }
1618
        }
1619
    }
1620

    
1621
    public static List<UUID> createUUIDListFromStringPref(String prefKey, boolean local) {
1622
        if (prefKey == null){
1623
            return null;
1624
        }
1625
        String prefValue = PreferencesUtil.getStringValue(prefKey, local);
1626
        if (prefValue == null){
1627
            return null;
1628
        }
1629
        List<UUID> uuidList = createUuidList(prefValue);
1630
        return uuidList;
1631
    }
1632

    
1633
    public static List<UUID> createUuidList(String prefValue) {
1634
        String[] stringArray = prefValue.split(";");
1635
        List<UUID> uuidList = new ArrayList<>();
1636
        for (String uuid: stringArray){
1637
            if (!StringUtils.isBlank(uuid)){
1638
                uuidList.add(UUID.fromString(uuid));
1639
            }
1640
        }
1641
        return uuidList;
1642
    }
1643

    
1644
    public static boolean getFilterCommonNameReferences(){
1645
        Boolean result = getBooleanValue(PreferencePredicate.CommonNameReferencesWithMarker.getKey());
1646
        if (result == null){
1647
            return false;
1648
        }
1649
        return result;
1650
    }
1651

    
1652
    public static void updateDBPreferences() {
1653

    
1654
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1655
        cache.getAllTaxEditorDBPreferences();
1656

    
1657
        //ABCD Configurator
1658

    
1659
        //updateAbcdImportConfigurationPreference();
1660

    
1661
        //Name Details
1662
        NameDetailsConfigurator config = getPreferredNameDetailsConfiguration(false);
1663
        //    if (config != null ){
1664
        //        if (!getBooleanValue(OVERRIDE_NAME_DETAILS) ||  !getBooleanValue(ALLOW_OVERRIDE_NAME_DETAILS)){
1665
        //            setPreferredNameDetailsConfiguration(config, false);
1666
        //        }
1667
        //    }
1668

    
1669
    }
1670

    
1671
    public static void setPreferencesToDB(List<CdmPreference> preferences) {
1672

    
1673
        ICdmRepository controller;
1674
        if(CdmStore.isActive()){
1675
            controller = CdmStore.getCurrentApplicationConfiguration();
1676
            for (CdmPreference preference: preferences){
1677
                if (preference.getValue() == null && preference.isAllowOverride()){
1678
                    controller.getPreferenceService().remove(preference.getKey());
1679

    
1680
                }else{
1681
                    controller.getPreferenceService().set(preference);
1682

    
1683
                }
1684

    
1685
            }
1686
            CdmPreferenceCache.instance().getAllTaxEditorDBPreferences();
1687
        }
1688
    }
1689

    
1690
    /**
1691
     * Returns whether the named preference is known.
1692
     * @param prefKey the key of the preference
1693
     * @return <code>true</code> if the preference is known, <code>false</code> otherwise
1694
     */
1695
    public static boolean contains(String prefKey){
1696
        return getPreferenceStore().contains(prefKey(prefKey));
1697
    }
1698

    
1699
    /**
1700
     *
1701
     */
1702
    public static TermTree<?> getPreferredFeatureTreeForNameDescription(boolean createNew) {
1703
        if(preferredNameFeatureTree != null && !createNew){
1704
            return preferredNameFeatureTree;
1705
        }
1706
        createPreferredFeatureTreeForNameDescription();
1707
        return preferredNameFeatureTree;
1708
    }
1709

    
1710
    public static void createPreferredFeatureTreeForNameDescription() {
1711

    
1712
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1713
        CdmPreference pref = cache.get(PreferencePredicate.NameFeatures.getKey());
1714
        List<Feature> terms = new ArrayList<>();
1715
        boolean override = PreferencesUtil.getOverrideForPreference(PreferencePredicate.NameFeatures.getKey());
1716

    
1717
        List<UUID> uuids = PreferencesUtil.createUUIDListFromStringPref(PreferencePredicate.NameFeatures.getKey(), false);
1718
        if (uuids != null && !uuids.isEmpty()){
1719
            terms = CdmStore.getTermManager().getTerms(uuids, Feature.class);
1720
        }
1721

    
1722
       if (terms.isEmpty()){
1723
           terms.addAll(TermStore.getTerms(CdmStore.getService(IVocabularyService.class).load(VocabularyEnum.NameFeature.getUuid()), null));
1724
        }
1725
        terms.remove(Feature.PROTOLOGUE());
1726
        if (terms.isEmpty()){
1727
            preferredNameFeatureTree = TermEditorInput.getDefaultNameFeatureTree();
1728
        }else{
1729
            preferredNameFeatureTree = TermTree.NewInstance(terms);
1730
        }
1731
    }
1732

    
1733
    public static void removeFromDB(List<CdmPreference> prefsToDelete) {
1734
        ICdmRepository controller;
1735
        //try{
1736
            if(CdmStore.isActive()){
1737
                controller = CdmStore.getCurrentApplicationConfiguration();
1738
                for (CdmPreference preference: prefsToDelete){
1739
                    controller.getPreferenceService().remove(preference.getKey());
1740
                }
1741
                CdmPreferenceCache.instance().getAllTaxEditorDBPreferences();
1742
            }
1743
    }
1744

    
1745
    public static void removeFromDB(CdmPreference prefToDelete) {
1746
        ICdmRepository controller;
1747

    
1748
        if(CdmStore.isActive()){
1749
            controller = CdmStore.getCurrentApplicationConfiguration();
1750
            controller.getPreferenceService().remove(prefToDelete.getKey());
1751

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

    
1756
    public static TermTree<?> getPreferredFeatureTreeForTaxonDescription(boolean createNew) {
1757
        if(preferredTaxonFeatureTree != null && !createNew){
1758
            return preferredTaxonFeatureTree;
1759
        }
1760
        createPreferredFeatureTreeForTaxonDescription();
1761
        return preferredTaxonFeatureTree;
1762
    }
1763

    
1764
    public static void createPreferredFeatureTreeForTaxonDescription() {
1765

    
1766
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1767
        CdmPreference pref = cache.get(PreferencePredicate.TaxonFeatures.getKey());
1768
        List<Feature> terms = null;
1769
        boolean override = PreferencesUtil.getOverrideForPreference(PreferencePredicate.TaxonFeatures.getKey());
1770
        List<UUID> uuids = PreferencesUtil.createUUIDListFromStringPref(PreferencePredicate.TaxonFeatures.getKey(), false);
1771
        if (uuids != null && !uuids.isEmpty()){
1772
            terms = CdmStore.getTermManager().getTerms(uuids, Feature.class);
1773
        }
1774
        if (terms == null || terms.isEmpty()){
1775
            terms= CdmStore.getTermManager().getPreferredTerms(TermType.Feature);
1776
            TermVocabulary nameVocabulary = CdmStore.getService(IVocabularyService.class).load(VocabularyEnum.NameFeature.getUuid());
1777
            Set<Feature> nameFeature = nameVocabulary.getTerms();
1778
            terms.removeAll(nameFeature);
1779

    
1780
        }
1781

    
1782
        if (terms.isEmpty()){
1783
            preferredTaxonFeatureTree = TermEditorInput.getDefaultFeatureTree();
1784
        }else{
1785
            preferredTaxonFeatureTree = TermTree.NewInstance(terms);
1786
        }
1787
    }
1788

    
1789
    public static void setLastSelectedBiocaseProvider(String lastAccessPoint) {
1790
        setStringValue(LAST_USED_BIOCASE_PROVIDER, lastAccessPoint);
1791
    }
1792

    
1793
    /**
1794
     * @return
1795
     */
1796
    public static boolean getLocalActive() {
1797
        // TODO: this needs to be adapted!!!
1798
        return true;
1799
    }
1800

    
1801
    /**
1802
     * @return
1803
     */
1804
    public static boolean showGfbioMetaData() {
1805
        //TODO: needs to be adapted!!!
1806
        return false;
1807
    }
1808
}
(43-43/60)