Project

General

Profile

Download (78.5 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.api.service.config.SecundumForSubtreeConfigurator;
51
import eu.etaxonomy.cdm.common.CdmUtils;
52
import eu.etaxonomy.cdm.common.URI;
53
import eu.etaxonomy.cdm.hibernate.HibernateProxyHelper;
54
import eu.etaxonomy.cdm.io.specimen.abcd206.in.Abcd206ImportConfigurator;
55
import eu.etaxonomy.cdm.model.common.ICdmBase;
56
import eu.etaxonomy.cdm.model.common.Language;
57
import eu.etaxonomy.cdm.model.common.MarkerType;
58
import eu.etaxonomy.cdm.model.description.Feature;
59
import eu.etaxonomy.cdm.model.metadata.CdmPreference;
60
import eu.etaxonomy.cdm.model.metadata.CdmPreference.PrefKey;
61
import eu.etaxonomy.cdm.model.metadata.EnabledComputedDescription;
62
import eu.etaxonomy.cdm.model.metadata.IPreferencePredicate;
63
import eu.etaxonomy.cdm.model.metadata.PreferencePredicate;
64
import eu.etaxonomy.cdm.model.metadata.PreferenceSubject;
65
import eu.etaxonomy.cdm.model.metadata.SecReferenceHandlingEnum;
66
import eu.etaxonomy.cdm.model.metadata.TermDisplayEnum;
67
import eu.etaxonomy.cdm.model.metadata.TermOrder;
68
import eu.etaxonomy.cdm.model.name.NomenclaturalCode;
69
import eu.etaxonomy.cdm.model.term.IDefinedTerm;
70
import eu.etaxonomy.cdm.model.term.ISimpleTerm;
71
import eu.etaxonomy.cdm.model.term.TermBase;
72
import eu.etaxonomy.cdm.model.term.TermTree;
73
import eu.etaxonomy.cdm.model.term.TermType;
74
import eu.etaxonomy.cdm.model.term.TermVocabulary;
75
import eu.etaxonomy.cdm.model.term.VocabularyEnum;
76
import eu.etaxonomy.cdm.strategy.match.DefaultMatchStrategy;
77
import eu.etaxonomy.cdm.strategy.match.FieldMatcher;
78
import eu.etaxonomy.cdm.strategy.match.IMatchStrategy;
79
import eu.etaxonomy.cdm.strategy.match.MatchException;
80
import eu.etaxonomy.cdm.strategy.match.MatchMode;
81
import eu.etaxonomy.taxeditor.editor.definedterm.input.TermEditorInput;
82
import eu.etaxonomy.taxeditor.model.AbstractUtility;
83
import eu.etaxonomy.taxeditor.model.MessagingUtils;
84
import eu.etaxonomy.taxeditor.model.NomenclaturalCodeHelper;
85
import eu.etaxonomy.taxeditor.remoting.source.ICdmRemoteSource;
86
import eu.etaxonomy.taxeditor.store.CdmStore;
87
import eu.etaxonomy.taxeditor.store.TermStore;
88
import eu.etaxonomy.taxeditor.store.internal.TaxeditorStorePlugin;
89
import eu.etaxonomy.taxeditor.ui.dialog.DefaultLanguageDialog;
90

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

    
103
    public static final String PREFERRED_TERMS_CHANGE = "preferred_terms";
104

    
105
    public static final String P2_REPOSITORIES_DELIM = ",";
106
    public static final String P2_REPOSITORY_FIELDS_DELIM = ";";
107
    public static final String SUBJECT_DELIM = "/";
108

    
109
    private static TermTree<Feature> preferredNameFeatureTree;
110

    
111
    private static TermTree<Feature> preferredTaxonFeatureTree;
112

    
113

    
114

    
115
    private final static Logger logger = Logger.getLogger(PreferencesUtil.class);
116

    
117
    public static IPreferenceStore getPreferenceStore() {
118
       return TaxeditorStorePlugin.getDefault().getPreferenceStore();
119
    }
120

    
121
    public static String[] extractSubjectParts(String subject){
122
       String[] result = subject.split("/");
123
       return result;
124
    }
125

    
126
    public static IEclipsePreferences getEditorPreferences(){
127
        return ConfigurationScope.INSTANCE.getNode(EDITOR_PREFERENCES_NODE);
128
    }
129

    
130
    public static String getPreferenceValue(PrefKey prefKey){
131
        try {
132
            //check if there exist a node for the predicate
133
            if(getEditorPreferences().nodeExists(prefKey.getPredicate())){
134
                Preferences predicateNode = getEditorPreferences().node(prefKey.getPredicate());
135
                String[] splittedSubject = extractSubjectParts(prefKey.getSubject());
136
                //check if the predicate node contains a node for the subject, this should be the last part
137
                String value = predicateNode.get(splittedSubject[splittedSubject.length-1], PreferencePredicate.getByKey(prefKey.getPredicate()).getDefaultValue() != null? PreferencePredicate.getByKey(prefKey.getPredicate()).getDefaultValue().toString(): "");
138
                int index = splittedSubject.length -2;
139
                while (value != null && index >= 0){
140
                   value = predicateNode.get(splittedSubject[index], prefKey.getPredicate());
141
                   index--;
142
                }
143
                return value;
144
            }
145

    
146
        } catch (BackingStoreException e) {
147
            // TODO Auto-generated catch block
148
            e.printStackTrace();
149
        }
150
        return null;
151
    }
152

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

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

    
190
    }
191

    
192
    private static String prefKey(String name) {
193
        return name + "_"+  ((ICdmRemoteSource)CdmStore.getActiveCdmSource()).toString();
194
    }
195

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

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

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

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

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

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

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

    
228
    public static String getStringValue(String name, boolean local) {
229

    
230
        CdmPreference pref = getDBPreferenceValue(name);
231

    
232
        boolean override = getOverrideForPreference(name);
233

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

    
264
    public static String getStringValue(String name){
265
        return getStringValue(name, false);
266
    }
267

    
268
    private static CdmPreference getDBPreferenceValue(String name) {
269
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
270
        CdmPreference pref = null;
271
        pref = cache.get(name);
272

    
273
        return pref;
274
    }
275

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

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

    
318
    public static boolean getBooleanValue(String name) {
319
        Boolean result = getBooleanValue(name, false);
320
        if (result == null){
321
            return false;
322
        }else{
323
            return result;
324
        }
325
    }
326

    
327
    public static Boolean getBooleanValue(String name, boolean local) {
328
        if (CdmStore.isActive()){
329
            CdmPreference pref = getDBPreferenceValue(name);
330
            String overrideKey =  createPreferenceString(createOverridePreferenceString(name));
331
            boolean override = getPreferenceStore().getBoolean(overrideKey);
332
            if (local || (pref == null && override)|| (pref != null && pref.isAllowOverride() && override)){
333
                //local preference
334
                String dbSpecific = prefKey(name);
335
                return getPreferenceStore().getBoolean(dbSpecific);
336

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

    
365
    public static float getFloatValue(String name, boolean local) {
366
        CdmPreference pref = getDBPreferenceValue(name);
367
        String prefValue = null;
368
        if (pref != null){
369
            prefValue = pref.getValue();
370
        }
371
        Float result = null;
372
        try{
373
            if (prefValue != null){
374
                result = Float.parseFloat(prefValue);
375
            }
376
        }catch(NumberFormatException e){
377
            logger.debug("Preference value of " + name + " is not a float");
378
        }
379

    
380
        boolean override = getOverrideForPreference(name);
381

    
382
        if (local || pref == null || (pref.isAllowOverride() && override)){
383
            String dbSpecific = prefKey(name);
384
            if (getPreferenceStore().contains(dbSpecific)){
385
                result = getPreferenceStore().getFloat(dbSpecific);
386
            }else{
387
                IPreferencePredicate<?> pred = PreferencePredicate.getByKey(name);
388
                if (pred != null){
389
                    if (pred.getDefaultValue() instanceof Float){
390
                        return (float)pred.getDefaultValue();
391
                    }else if (pred.getDefaultValue() != null){
392
                        return Float.valueOf(pred.getDefaultValue().toString());
393
                    }
394
                }
395
                return 0;
396
            }
397
        }
398
        return result;
399
    }
400

    
401
    public static CdmPreference setPreferredNomenclaturalCode(
402
            String preferenceValue, boolean local) {
403
        if (local){
404
            setStringValue(PreferencePredicate.NomenclaturalCode.getKey(),
405
                    preferenceValue);
406
        }
407
        else{
408
            ICdmRepository controller;
409
            controller = CdmStore.getCurrentApplicationConfiguration();
410
            if (controller == null){
411
                return null;
412
            }
413
            PrefKey key = null;
414
            try{
415
                key = CdmPreference.NewKey(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.NomenclaturalCode);
416
            }catch (Exception e){
417
                System.out.println(e.getStackTrace());
418
            }
419
            CdmPreference preference = null;
420

    
421
            if (preferenceValue == null){
422
                preference = controller.getPreferenceService().find(key);
423
                if (preference == null){
424
                    return null;
425
                } else{
426
                    setStringValue(PreferencePredicate.NomenclaturalCode.getKey(),
427
                            preference.getValue());
428

    
429
                    return preference;
430
                }
431
            } else{
432
                preference = CdmPreference.NewInstance(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.NomenclaturalCode, preferenceValue);
433
                controller.getPreferenceService().set(preference);
434

    
435
            }
436
        }
437
        return null;
438
    }
439

    
440
    public static void setPreferredNomenclaturalCode(
441
        CdmPreference preference) {
442

    
443
        ICdmRepository controller;
444
        controller = CdmStore.getCurrentApplicationConfiguration();
445
        if (controller == null){
446
            return;
447
        }
448

    
449
        if (preference == null){
450
            PrefKey key = null;
451
              try{
452
                  key = CdmPreference.NewKey(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.NomenclaturalCode);
453
              }catch (Exception e){
454
                  System.out.println(e.getStackTrace());
455
              }
456
            controller.getPreferenceService().remove(key);
457
        }else{
458
            controller.getPreferenceService().set(preference);
459
        }
460
    }
461

    
462
    public static NomenclaturalCode getPreferredNomenclaturalCode() {
463

    
464
        String nomString = getStringValue(PreferencePredicate.NomenclaturalCode.getKey());
465
        return getPreferredNomenclaturalCode(nomString);
466
    }
467

    
468
    public static NomenclaturalCode getPreferredNomenclaturalCode(String preferenceKeyNomenclaturalCode) {
469

    
470
        for (NomenclaturalCode code : NomenclaturalCodeHelper.getAllCodes()) {
471
            if (getPreferenceKey(code).equals(preferenceKeyNomenclaturalCode) || code.getKey().equals(preferenceKeyNomenclaturalCode)) {
472
                return code;
473
            }
474
        }
475
        return null;
476
    }
477

    
478
    public static boolean isShowTaxonAssociations(){
479
        boolean result = getBooleanValue(PreferencePredicate.ShowTaxonAssociations.getKey());
480
        return result;
481
    }
482

    
483
    public static boolean isShowLifeForm(){
484
        boolean result =  getBooleanValue(PreferencePredicate.ShowLifeForm.getKey());
485
        return result;
486
    }
487

    
488
    public static boolean isDeterminationOnlyForFieldUnits(){
489
        boolean result =  getBooleanValue(PreferencePredicate.DeterminationOnlyForFieldUnits.getKey());
490
        return result;
491
    }
492

    
493
    public static boolean isCollectingAreaInGeneralSection(){
494
        boolean result =  getBooleanValue(PreferencePredicate.ShowCollectingAreasInGeneralSection.getKey());
495
        return result;
496
    }
497

    
498
    public static CdmPreference getPreferenceFromDB(IPreferencePredicate<?> predicate){
499
        ICdmRepository controller;
500
        CdmPreference pref = null;
501

    
502
        try{
503
            if(CdmStore.isActive()){
504
                controller = CdmStore.getCurrentApplicationConfiguration();
505
                PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), predicate);
506
                pref = controller.getPreferenceService().find(key);
507
            }
508
        }catch(Exception e){
509
            e.printStackTrace();
510
        }
511

    
512
        return pref;
513
    }
514

    
515
    public static List<CdmPreference> getPreferencesFromDB(IPreferencePredicate<?> predicate){
516
        ICdmRepository controller;
517
        List<CdmPreference> prefs = null;
518

    
519
        try{
520
            if(CdmStore.isActive()){
521
                controller = CdmStore.getCurrentApplicationConfiguration();
522
                PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), predicate);
523
                prefs = controller.getPreferenceService().list(predicate);
524
            }
525
        }catch(Exception e){
526
            e.printStackTrace();
527
        }
528

    
529
        return prefs;
530

    
531
    }
532

    
533
    public static void setPreferencesToDB(CdmPreference preference, boolean setDefault){
534
        ICdmRepository controller;
535
        try{
536
            if(CdmStore.isActive()){
537
                controller = CdmStore.getCurrentApplicationConfiguration();
538

    
539
                if (setDefault){
540
                    controller.getPreferenceService().remove(preference.getKey());
541
                }else{
542
                    controller.getPreferenceService().set(preference);
543
                }
544
            }
545
        }catch(Exception e){
546
            e.printStackTrace();
547
        }
548
    }
549

    
550
    public static CdmPreference getPreferenceFromDB(PrefKey key){
551
        ICdmRepository controller;
552
        CdmPreference pref = null;
553

    
554
        try{
555
            if(CdmStore.isActive()){
556
                controller = CdmStore.getCurrentApplicationConfiguration();
557
                pref = controller.getPreferenceService().find(key);
558
            }
559
        }catch(Exception e){
560
            e.printStackTrace();
561
        }
562

    
563
        return pref;
564

    
565
    }
566

    
567
    public static void setPreferenceToDB(CdmPreference preference){
568
        ICdmRepository controller;
569
        try{
570
            if(CdmStore.isActive()){
571
                controller = CdmStore.getCurrentApplicationConfiguration();
572
                if (preference.getValue() == null && preference.isAllowOverride()){
573
                    controller.getPreferenceService().remove(preference.getKey());
574
                }else{
575
                    controller.getPreferenceService().set(preference);
576
                }
577
                CdmPreferenceCache.instance().put(preference);
578
            }
579
        }catch(Exception e){
580
            e.printStackTrace();
581
        }
582
    }
583

    
584
    public static String getPreferredDefaultLangugae(){
585
        String preferredLanguage = getStringValue(DEFAULT_LANGUAGE_EDITOR, true);
586
        if(StringUtils.isNotEmpty(preferredLanguage) && StringUtils.isNotBlank(preferredLanguage)){
587
            return preferredLanguage;
588
        }
589
        return null;
590
    }
591

    
592
    public static boolean isShowMediaPreview(){
593
        boolean isShowMediaPreview = getBooleanValue(SHOW_MEDIA_PREVIEW, true);
594
        return isShowMediaPreview;
595
    }
596

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

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

    
624
            return matchStrategy;
625
        }
626
        return getDefaultMatchStrategy(clazz);
627
    }
628

    
629
    /**
630
     * Stores a matchStrategy into the preference store.
631
     *
632
     * @param matchStrategy
633
     *            a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy}
634
     *            object.
635
     */
636
    public static void setMatchStrategy(IMatchStrategy matchStrategy) {
637
        String className = "ANY class"; //FIXME was: matchStrategy.getMatchClass().getName(); seems currently not in use
638
        setBooleanValue(MATCH_STRATEGY_PREFIX + className, true);
639

    
640
        List<FieldMatcher> fieldMatchers = matchStrategy.getMatching().getFieldMatchers(false);
641

    
642
        for (FieldMatcher fieldMatcher : fieldMatchers) {
643
            String fieldName = fieldMatcher.getPropertyName();
644
            setStringValue(
645
                    getMatchStrategyFieldName(className, fieldName),
646
                    fieldMatcher.getMatchMode().name());
647
        }
648
    }
649

    
650
    /**
651
     * Helper method to create the preference property for a match field.
652
     *
653
     * @param className
654
     * @param fieldName
655
     * @return
656
     */
657
    private static String getMatchStrategyFieldName(String className,
658
            String fieldName) {
659
        return MATCH_STRATEGY_PREFIX + className + "." + fieldName;
660
    }
661

    
662
    /**
663
     * Returns the default match strategy for a given class.
664
     *
665
     * @param clazz
666
     *            a {@link java.lang.Class} object.
667
     * @return a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy} object.
668
     */
669
    public static IMatchStrategy getDefaultMatchStrategy(Class clazz) {
670
        return DefaultMatchStrategy.NewInstance(clazz);
671
    }
672

    
673
    public static String getDateFormatPattern() {
674
        // TODO make this configurable in properties
675
        String pattern = "Y-M-d H:m";
676
        return pattern;
677
    }
678

    
679
    public static <T extends TermBase> void addTermToPreferredTerms(T term) {
680

    
681
        // VocabularyEnum vocabulary =
682
        // VocabularyEnum.getVocabularyEnum(term.getClass());
683
        //
684
        // getPreferenceStore().setValue(getPreferenceKey(term),
685
        // VocabularyStore.getTermVocabulary(vocabulary).getTerms().contains(term));
686
        //
687
        // firePreferencesChanged(term.getClass());
688
    }
689

    
690
    /**
691
     * Construct a unique key using the CdmBase object's uuid
692
     *
693
     * @param cdmBase
694
     * @return
695
     */
696
    private static String getPreferenceKey(ICdmBase cdmBase) {
697
        cdmBase = HibernateProxyHelper.deproxy(cdmBase);
698

    
699
        String key = cdmBase.getClass().getName().concat(".")
700
                .concat(cdmBase.getUuid().toString());
701
        if (key.contains("javassist")) {
702
            MessagingUtils.info("proxy");
703
        }
704
        return key;
705
    }
706

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

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

    
738
    /**
739
     * Retrieves search preferences from the preference store
740
     *
741
     * @return an {@link ITaxonServiceConfigurator} to pass to search methods
742
     */
743
    public static IFindTaxaAndNamesConfigurator getSearchConfigurator() {
744
        IFindTaxaAndNamesConfigurator configurator = initializeSearchConfigurator();
745

    
746
        configurator.setDoTaxa(PreferencesUtil.getPreferenceStore().contains(IPreferenceKeys.TAXON_SERVICE_CONFIGURATOR_TAXA)? PreferencesUtil.getPreferenceStore().getBoolean(
747
                IPreferenceKeys.TAXON_SERVICE_CONFIGURATOR_TAXA): true);
748
        configurator.setDoSynonyms(PreferencesUtil.getPreferenceStore().contains(IPreferenceKeys.TAXON_SERVICE_CONFIGURATOR_SYNONYMS)? PreferencesUtil.getPreferenceStore().getBoolean(
749
                IPreferenceKeys.TAXON_SERVICE_CONFIGURATOR_SYNONYMS): true);
750
        configurator.setDoNamesWithoutTaxa(PreferencesUtil.getPreferenceStore().contains(IPreferenceKeys.TAXON_SERVICE_CONFIGURATOR_NAMES)? PreferencesUtil.getPreferenceStore().getBoolean(
751
                IPreferenceKeys.TAXON_SERVICE_CONFIGURATOR_NAMES): true);
752
        configurator.setDoTaxaByCommonNames(PreferencesUtil.getPreferenceStore().contains(IPreferenceKeys.TAXON_SERVICE_CONFIGURATOR_COMMON_NAMES)? PreferencesUtil.getPreferenceStore().getBoolean(
753
                IPreferenceKeys.TAXON_SERVICE_CONFIGURATOR_COMMON_NAMES): true);
754
        configurator.setDoIncludeAuthors(PreferencesUtil.getPreferenceStore().contains(IPreferenceKeys.TAXON_SERVICE_CONFIGURATOR_WITH_AUTHORS)? PreferencesUtil.getPreferenceStore().getBoolean(
755
                IPreferenceKeys.TAXON_SERVICE_CONFIGURATOR_WITH_AUTHORS): false);
756
        configurator.setIncludeUnpublished(PreferencesUtil.getPreferenceStore().contains(IPreferenceKeys.TAXON_SERVICE_CONFIGURATOR_UNPUBLISHED)? PreferencesUtil.getPreferenceStore().getBoolean(
757
                IPreferenceKeys.TAXON_SERVICE_CONFIGURATOR_UNPUBLISHED): true);
758
        //configurator.setMatchMode(eu.etaxonomy.cdm.persistence.query.MatchMode.valueOf(getStringValue(TAXON_SERVICE_CONFIGURATOR_MATCH_MODE)));
759

    
760
        return configurator;
761
    }
762

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

    
773
        configurator.setDoTaxa(true);
774
        configurator.setDoSynonyms(true);
775
        configurator.setDoNamesWithoutTaxa(true);
776
        configurator.setDoTaxaByCommonNames(true);
777
        configurator.setIncludeUnpublished(true);
778
        configurator.setDoIncludeAuthors(false);
779
        configurator.setTaxonPropertyPath(Arrays.asList("$", "titleCache",
780
                "name", "name.$", "relationsFromThisTaxon.$"));
781

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

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

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

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

    
827

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

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

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

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

    
858
        //Name Details
859
       // getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.NameDetailsView.getKey()), new NameDetailsConfigurator(false).toString());
860

    
861
        //Navigator preferences
862
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.TaxonNodeOrder.getKey()), NavigatorOrderEnum.RankAndNameOrder.getKey());
863

    
864
        //getPreferenceStore().setDefault(createPreferenceString(Prefe), true);
865

    
866
        getPreferenceStore().setDefault(createPreferenceString(SHOW_ADVANCED_MEDIA_SECTION), false);
867

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

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

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

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

    
914
        setStringValue(PreferencePredicate.NomenclaturalCode.getKey(),
915
                getPreferenceKey(preferredCode));
916
    }
917

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

    
931
    public static String getMapServiceAccessPoint() {
932
        return getStringValue(PreferencePredicate.EditMapServiceAccessPoint.getKey());
933
    }
934

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

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

    
950
        if (tree == null || tree.getId() == 0) {
951
            return null;
952
        }
953
        return tree;
954
    }
955

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

    
963
    public static void setSortRanksHierarchichally(boolean selection) {
964
        setBooleanValue(PreferencePredicate.SortRanksHierarchichally.getKey(), selection);
965
    }
966

    
967
    public static boolean getSortRanksHierarchichally() {
968
        return getBooleanValue(PreferencePredicate.SortRanksHierarchichally.getKey());
969
    }
970

    
971
    public static boolean isMultilanguageTextEditingCapability() {
972
        return getBooleanValue(
973
                PreferencePredicate.MultiLanguageTextEditing.getKey());
974
    }
975

    
976
    public static Language getGlobalLanguage() {
977

    
978
        String languageUuidString = getStringValue(
979
                GLOBAL_LANGUAGE_UUID, true);
980

    
981
        if(!CdmStore.isActive()) {
982
            MessagingUtils.noDataSourceWarningDialog(languageUuidString);
983
            return null;
984
        }
985

    
986
        if (CdmUtils.isBlank(languageUuidString)) {
987
            return Language.getDefaultLanguage();
988
        }
989

    
990
        UUID languageUuid = UUID.fromString(languageUuidString);
991
        return (Language) CdmStore.getService(ITermService.class).load(
992
                languageUuid);
993
    }
994

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

    
1002
    public static Map<MarkerType, Boolean> getEditMarkerTypePreferences() {
1003
        List<MarkerType> markerTypes = CdmStore.getTermManager()
1004
                .getPreferredTerms(MarkerType.class);
1005

    
1006
        Map<MarkerType, Boolean> result = new HashMap<>();
1007

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

    
1014
        return result;
1015
    }
1016

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

    
1026
    private static String getMarkerTypeEditingPreferenceKey(
1027
            MarkerType markerType) {
1028
        markerType = HibernateProxyHelper.deproxy(markerType);
1029
        return markerType.getClass().getName() + EDIT_MARKER_TYPE_PREFIX;
1030
    }
1031

    
1032
    public static void setEditMarkerTypePreference(MarkerType markerType,
1033
            boolean edit) {
1034
        setBooleanValue(
1035
                getMarkerTypeEditingPreferenceKey(markerType), edit);
1036
    }
1037

    
1038
    public static DerivedUnitFacadeConfigurator getDerivedUnitConfigurator() {
1039
        DerivedUnitFacadeConfigurator configurator = DerivedUnitFacadeConfigurator
1040
                .NewInstance();
1041
        configurator.setMoveDerivedUnitMediaToGallery(true);
1042
        configurator.setMoveFieldObjectMediaToGallery(true);
1043
        return configurator;
1044
    }
1045

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

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

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

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

    
1125

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

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

    
1155
        return p2Repos;
1156
    }
1157

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

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

    
1183
    public static NavigatorOrderEnum getSortNodes() {
1184
        return NavigatorOrderEnum.valueOf(getStringValue(PreferencePredicate.TaxonNodeOrder.getKey()));
1185
    }
1186

    
1187
    public static boolean isNodesSortedNaturally() {
1188
        NavigatorOrderEnum value = NavigatorOrderEnum.valueOf(getStringValue(PreferencePredicate.TaxonNodeOrder.getKey()));
1189
        return value.equals(NavigatorOrderEnum.NaturalOrder);
1190
    }
1191

    
1192
    public static boolean isNodesSortedByName() {
1193
        NavigatorOrderEnum value = NavigatorOrderEnum.valueOf(getStringValue(PreferencePredicate.TaxonNodeOrder.getKey()));
1194
        return value.equals(NavigatorOrderEnum.AlphabeticalOrder);
1195
    }
1196

    
1197
    public static boolean isNodesSortedByNameAndRank() {
1198
        NavigatorOrderEnum value = NavigatorOrderEnum.valueOf(getStringValue(PreferencePredicate.TaxonNodeOrder.getKey()));
1199
        return value.equals(NavigatorOrderEnum.RankAndNameOrder);
1200
    }
1201

    
1202
    public static boolean isStoreNavigatorState() {
1203
        return getBooleanValue(RESTORE_NAVIGATOR_STATE);
1204
    }
1205

    
1206
    public static void setStoreNavigatorState(boolean selection) {
1207
        setBooleanValue(RESTORE_NAVIGATOR_STATE, selection);
1208
    }
1209

    
1210
    public static boolean isShowUpWidgetIsDisposedMessages() {
1211
       return getBooleanValue(IS_SHOW_UP_WIDGET_IS_DISPOSED);
1212
    }
1213

    
1214
    public static void setShowUpWidgetIsDisposedMessages(boolean selection) {
1215
        setBooleanValue(IS_SHOW_UP_WIDGET_IS_DISPOSED, selection);
1216
    }
1217

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

    
1243
    public static void setAreaDisplayInChecklistEditor(String selection) {
1244
        setStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey(), selection);
1245
    }
1246

    
1247
    public static void setOwnDescriptionForChecklistEditor(boolean selection) {
1248
        setBooleanValue(PreferencePredicate.OwnDescriptionForDistributionEditor.getKey(), selection);
1249
    }
1250

    
1251
    public static boolean isOwnDescriptionForChecklistEditor() {
1252
        return getBooleanValue(PreferencePredicate.OwnDescriptionForDistributionEditor.getKey());
1253
    }
1254

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

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

    
1275
    public static void setDisplayStatusInChecklistEditor(String selection) {
1276
        setStringValue(PreferencePredicate.DisplayOfStatus.getKey(), selection);
1277
    }
1278

    
1279
    public static boolean isShowRankInChecklistEditor() {
1280
        return getBooleanValue(PreferencePredicate.ShowRankInDistributionEditor.getKey());
1281
    }
1282

    
1283
    public static void setShowRankInChecklistEditor(boolean selection) {
1284
       setBooleanValue(PreferencePredicate.ShowRankInDistributionEditor.getKey(), selection);
1285
    }
1286

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

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

    
1310

    
1311
        }else {
1312
            return null;
1313
        }
1314
        return config;
1315
    }
1316

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

    
1337
    public static NameDetailsConfigurator getPreferredNameDetailsConfiguration() {
1338
        NameDetailsConfigurator config = new NameDetailsConfigurator();
1339

    
1340
        String value;
1341

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

    
1351
    public static void setPreferredNameDetailsConfiguration(NameDetailsConfigurator config, boolean local) {
1352
        CdmPreference preference = null;
1353

    
1354
        if (!local) {
1355
            preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.NameDetailsView, config.toString());
1356

    
1357
            setPreferenceToDB(preference);
1358
        }
1359
        else{
1360
            setStringValue(PreferencePredicate.NameDetailsView.getKey(), config.toString());
1361
        }
1362
    }
1363

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

    
1372
    public static void extractSecundumForSubtreeConfiguratorFromPreferenceString(SecundumForSubtreeConfigurator config,
1373
            String configString) {
1374
        if(configString != null){
1375
             String[] configArray = configString.split(";");
1376

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

    
1385
                         for (int index = 2; index< keyValue.length; index++){
1386
                             valueString += ":"+ keyValue[index];
1387
                         }
1388
                     }
1389
                 }
1390
                 if (keyString.equals("includeAcceptedTaxa")){
1391
                     config.setIncludeAcceptedTaxa(Boolean.valueOf(valueString));
1392
                 }else if (keyString.equals("includeSynonyms")){
1393
                     config.setIncludeSynonyms(Boolean.valueOf(valueString));
1394
                 }else if (keyString.equals("includeSharedTaxa")){
1395
                     config.setIncludeSharedTaxa(Boolean.valueOf(valueString));
1396
                 }else if (keyString.equals("includeProParteSynonyms")){
1397
                     config.setIncludeProParteSynonyms(Boolean.valueOf(valueString));
1398
                 }else if (keyString.equals("includeMisapplications")){
1399
                     config.setIncludeMisapplications(Boolean.valueOf(valueString));
1400
                 }else if (keyString.equals("overwriteExisting")){
1401
                     config.setOverwriteExisting(Boolean.valueOf(valueString));
1402
                 }else if (keyString.equals("emptySecundumDetail")){
1403
                     config.setEmptySecundumDetail(Boolean.valueOf(valueString));
1404
                 }else{
1405
                     logger.debug("This key of the set secundum configurator needs to be added to the transformer: " + keyString);
1406
                 }
1407
             }
1408
         }
1409
    }
1410

    
1411
    public static Abcd206ImportConfigurator getDBAbcdImportConfigurationPreference() {
1412

    
1413
        Abcd206ImportConfigurator config = Abcd206ImportConfigurator.NewInstance(null,null);
1414
        ICdmRepository controller;
1415
        controller = CdmStore.getCurrentApplicationConfiguration();
1416
        PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AbcdImportConfig);
1417
        CdmPreference preference = null;
1418
        if (controller == null){
1419
            return null;
1420
        }
1421
        preference = controller.getPreferenceService().find(key);
1422
        if (preference == null){
1423
            return config;
1424
         } else{
1425
             String configString = preference.getValue();
1426
             extractAbcdConfiguratorFromPreferenceString(config, configString);
1427
         }
1428
        return config;
1429
    }
1430

    
1431
    public static void extractAbcdConfiguratorFromPreferenceString(Abcd206ImportConfigurator config,
1432
            String configString) {
1433
        if(configString != null){
1434
             String[] configArray = configString.split(";");
1435

    
1436
             for (String configItem: configArray){
1437
                 String[] keyValue = configItem.split(":");
1438
                 String keyString = keyValue[0];
1439
                 String valueString = null;
1440
                 if (keyValue.length>1){
1441
                     valueString = keyValue[1];
1442
                     if (keyValue.length>2){
1443

    
1444
                         for (int index = 2; index< keyValue.length; index++){
1445
                             valueString += ":"+ keyValue[index];
1446
                         }
1447
                     }
1448
                 }
1449
                 if (keyString.equals("ignoreImportOfExistingSpecimen")){
1450
                     config.setIgnoreImportOfExistingSpecimen(Boolean.valueOf(valueString));
1451
                 }else if (keyString.equals("addIndividualsAssociationsSuchAsSpecimenAndObservations")){
1452
                     config.setAddIndividualsAssociationsSuchAsSpecimenAndObservations(Boolean.valueOf(valueString));
1453
                 }else if (keyString.equals("reuseExistingTaxaWhenPossible")){
1454
                     config.setReuseExistingTaxaWhenPossible(Boolean.valueOf(valueString));
1455
                 }else if (keyString.equals("ignoreAuthorship")){
1456
                     config.setIgnoreAuthorship(Boolean.valueOf(valueString));
1457
                 }else if (keyString.equals("addMediaAsMediaSpecimen")){
1458
                     config.setAddMediaAsMediaSpecimen(Boolean.valueOf(valueString));
1459
                 }else if (keyString.equals("reuseExistingMetaData")){
1460
                     config.setReuseExistingMetaData(Boolean.valueOf(valueString));
1461
                 }else if (keyString.equals("reuseExistingDescriptiveGroups")){
1462
                     config.setReuseExistingDescriptiveGroups(Boolean.valueOf(valueString));
1463
                 }else if (keyString.equals("allowReuseOtherClassifications")){
1464
                     config.setAllowReuseOtherClassifications(Boolean.valueOf(valueString));
1465
                 }else if (keyString.equals("deduplicateReferences")){
1466
                     config.setDeduplicateReferences(Boolean.valueOf(valueString));
1467
                 }else if (keyString.equals("deduplicateClassifications")){
1468
                     config.setDeduplicateClassifications(Boolean.valueOf(valueString));
1469
                 }else if (keyString.equals("moveNewTaxaToDefaultClassification")){
1470
                     config.setMoveNewTaxaToDefaultClassification(Boolean.valueOf(valueString));
1471
                 }else if (keyString.equals("mapUnitIdToCatalogNumber")){
1472
                     config.setMapUnitIdToCatalogNumber(Boolean.valueOf(valueString));
1473
                 }else if (keyString.equals("mapUnitIdToAccessionNumber")){
1474
                     config.setMapUnitIdToAccessionNumber(Boolean.valueOf(valueString));
1475
                 }else if (keyString.equals("mapUnitIdToBarcode")){
1476
                     config.setMapUnitIdToBarcode(Boolean.valueOf(valueString));
1477
                 }else if (keyString.equals("overwriteExistingSpecimens")){
1478
                     config.setOverwriteExistingSpecimens(Boolean.valueOf(valueString));
1479
                 }else if (keyString.equals("nomenclaturalCode")){
1480
                     config.setNomenclaturalCode(NomenclaturalCode.fromString(valueString));
1481
                 }else if (keyString.equals("removeCountryFromLocalityText")){
1482
                     config.setRemoveCountryFromLocalityText(Boolean.valueOf(valueString));
1483
                 }else if (keyString.equals("getSiblings")){
1484
                     config.setGetSiblings(Boolean.valueOf(valueString));
1485
                 }else if (keyString.equals("classificationUUID")){
1486
                     if (valueString != null){
1487
                         config.setClassificationUuid(UUID.fromString(valueString));
1488
                     }
1489
                 }else if (keyString.equals("classificationName")){
1490
                     config.setClassificationName(valueString);
1491
                 }else if (keyString.equals("dnaSource")){
1492
                     try{
1493
                         if (StringUtils.isNotBlank(valueString)){
1494
                             config.setDnaSoure(URI.create(valueString));
1495
                         }
1496
                     }catch(Exception e){
1497
                         config.setDnaSoure(null);
1498
                     }
1499
                 }else{
1500
                     logger.debug("This key of the abcd configurator needs to be added to the transformer: " + keyString);
1501
                 }
1502
             }
1503
         }
1504
    }
1505

    
1506
    public static Abcd206ImportConfigurator getLocalAbcdImportConfigurator(){
1507
        return getLocalAbcdImportConfigurator(true);
1508
    }
1509

    
1510
    public static Abcd206ImportConfigurator getLocalAbcdImportConfigurator(boolean skipCheckOverride){
1511
       Abcd206ImportConfigurator config = Abcd206ImportConfigurator.NewInstance(null,null);
1512
       CdmPreference pref = CdmPreferenceCache.instance().get(PreferencePredicate.AbcdImportConfig.getKey());
1513
       if (pref  == null || pref.isAllowOverride()){
1514
       String configString = PreferencesUtil.getStringValue(PreferencePredicate.AbcdImportConfig.getKey());
1515
           if (StringUtils.isBlank(configString)){
1516
               configString = getStringValue(PreferencePredicate.AbcdImportConfig.getKey(), skipCheckOverride);
1517
               extractAbcdConfiguratorFromPreferenceString(config, configString);
1518
               if (config.getNomenclaturalCode() == null){
1519
                   config.setNomenclaturalCode(getPreferredNomenclaturalCode());
1520
               }
1521
           }else{
1522
               config = Abcd206ImportConfigurator.NewInstance(null, null);
1523
               PreferencesUtil.extractAbcdConfiguratorFromPreferenceString(config, configString);
1524
           }
1525
       }else{
1526
           extractAbcdConfiguratorFromPreferenceString(config, pref.getValue());
1527
       }
1528

    
1529
       return config;
1530

    
1531
    }
1532

    
1533
    public static Abcd206ImportConfigurator getLastUsedAbcdImportConfigurator(){
1534
        Abcd206ImportConfigurator config = Abcd206ImportConfigurator.NewInstance(null,null);
1535

    
1536
       String configString = PreferencesUtil.getStringValue(IPreferenceKeys.LAST_USED_ABCD_CONFIG, true);
1537
       if (configString != null){
1538
           extractAbcdConfiguratorFromPreferenceString(config, configString);
1539
           if (config != null){
1540
               if (config.getNomenclaturalCode() == null){
1541
                   config.setNomenclaturalCode(getPreferredNomenclaturalCode());
1542
               }
1543
           }
1544
       }else{
1545
           config = PreferencesUtil.getLocalAbcdImportConfigurator(false);
1546
       }
1547

    
1548
        return config;
1549

    
1550
    }
1551

    
1552
    public static void updateAbcdImportConfigurationPreference() {
1553
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1554

    
1555
        CdmPreference pref = cache.findBestMatching(CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AbcdImportConfig));
1556

    
1557
        if (!getBooleanValue(prefOverrideKey(PreferencePredicate.AbcdImportConfig.getKey())) || !pref.isAllowOverride()){
1558
            resetToDBPreferenceAbcdCOnfigurator();
1559

    
1560
        }
1561
    }
1562

    
1563
    public static void resetToDBPreferenceAbcdCOnfigurator(){
1564
        Abcd206ImportConfigurator config = getDBAbcdImportConfigurationPreference();
1565
        setStringValue(PreferencePredicate.AbcdImportConfig.getKey(), config.toString());
1566
    }
1567

    
1568
    public static boolean isSortTaxaByRankAndName() {
1569
        return getBooleanValue(PreferencePredicate.SortTaxaByRankAndName.getKey());
1570
    }
1571

    
1572
    public static TermOrder getSortNamedAreasInDistributionEditor() {
1573
        TermOrder result;
1574
        try{
1575
            result = TermOrder.valueOf(getStringValue(PreferencePredicate.AreasSortedInDistributionEditor.getKey()));
1576
        }catch (IllegalArgumentException e){
1577
            result = (TermOrder)PreferencePredicate.AreasSortedInDistributionEditor.getDefaultValue();
1578
        }
1579
        return result;
1580
    }
1581

    
1582
    public static void setSortNamedAreasInDistributionEditor(String isSortByVocabularyOrder) {
1583
        setStringValue(PreferencePredicate.AreasSortedInDistributionEditor.getKey(), isSortByVocabularyOrder);
1584
    }
1585

    
1586
    public static void setLastSelectedReference(
1587
            List<String> lastSelectedReferences) {
1588

    
1589
        setStringValue(IPreferenceKeys.LAST_SELECTED_REFERENCES, lastSelectedReferences.toString());
1590
    }
1591

    
1592
    public static List<String> getLastSelectedReferences() {
1593

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

    
1603
    public static void setPreferredNamedAreasForDistributionEditor(
1604
            String saveCheckedElements, String saveGrayedElements, boolean local) {
1605
        if (local){
1606
            setStringValue(PreferencePredicate.AvailableDistributionAreaTerms.getKey(), saveCheckedElements);
1607
        }
1608
        else{
1609
            CdmPreference preference = null;
1610

    
1611
            if (saveCheckedElements == null){
1612
                preference = getPreferenceFromDB(PreferencePredicate.AvailableDistributionAreaTerms);
1613

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

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

    
1629
            }
1630
        }
1631
    }
1632

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

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

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

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

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

    
1681
    public static List<UUID> createUUIDListFromStringPref(String prefKey, boolean local) {
1682
        if (prefKey == null){
1683
            return null;
1684
        }
1685
        String prefValue = PreferencesUtil.getStringValue(prefKey, local);
1686
        if (prefValue == null){
1687
            return null;
1688
        }
1689
        List<UUID> uuidList = createUuidList(prefValue);
1690
        return uuidList;
1691
    }
1692

    
1693
    public static List<UUID> createUuidList(String prefValue) {
1694
        String[] stringArray = prefValue.split(";");
1695
        List<UUID> uuidList = new ArrayList<>();
1696
        for (String uuid: stringArray){
1697
            if (!StringUtils.isBlank(uuid)){
1698
                uuidList.add(UUID.fromString(uuid));
1699
            }
1700
        }
1701
        return uuidList;
1702
    }
1703

    
1704
    public static boolean getFilterCommonNameReferences(){
1705
        Boolean result = getBooleanValue(PreferencePredicate.CommonNameReferencesWithMarker.getKey());
1706
        if (result == null){
1707
            return false;
1708
        }
1709
        return result;
1710
    }
1711

    
1712
    public static void updateDBPreferences() {
1713

    
1714
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1715
        cache.getAllTaxEditorDBPreferences();
1716

    
1717
        //Name Details
1718
        NameDetailsConfigurator config = getPreferredNameDetailsConfiguration(false);
1719

    
1720
    }
1721

    
1722
    public static void setPreferencesToDB(List<CdmPreference> preferences) {
1723

    
1724
        ICdmRepository controller;
1725
        if(CdmStore.isActive()){
1726
            controller = CdmStore.getCurrentApplicationConfiguration();
1727
            for (CdmPreference preference: preferences){
1728
                if (preference.getValue() == null && preference.isAllowOverride()){
1729
                    controller.getPreferenceService().remove(preference.getKey());
1730

    
1731
                }else{
1732
                    controller.getPreferenceService().set(preference);
1733

    
1734
                }
1735

    
1736
            }
1737
            CdmPreferenceCache.instance().getAllTaxEditorDBPreferences();
1738
        }
1739
    }
1740

    
1741
    /**
1742
     * Returns whether the named preference is known.
1743
     * @param prefKey the key of the preference
1744
     * @return <code>true</code> if the preference is known, <code>false</code> otherwise
1745
     */
1746
    public static boolean contains(String prefKey){
1747
        return getPreferenceStore().contains(prefKey(prefKey));
1748
    }
1749

    
1750
    /**
1751
     *
1752
     */
1753
    public static TermTree<?> getPreferredFeatureTreeForNameDescription(boolean createNew) {
1754
        if(preferredNameFeatureTree != null && !createNew){
1755
            return preferredNameFeatureTree;
1756
        }
1757
        createPreferredFeatureTreeForNameDescription();
1758
        return preferredNameFeatureTree;
1759
    }
1760

    
1761
    public static void createPreferredFeatureTreeForNameDescription() {
1762

    
1763
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1764
        CdmPreference pref = cache.get(PreferencePredicate.NameFeatures.getKey());
1765
        List<Feature> terms = new ArrayList<>();
1766
        boolean override = PreferencesUtil.getOverrideForPreference(PreferencePredicate.NameFeatures.getKey());
1767

    
1768
        List<UUID> uuids = PreferencesUtil.createUUIDListFromStringPref(PreferencePredicate.NameFeatures.getKey(), false);
1769
        if (uuids != null && !uuids.isEmpty()){
1770
            terms = CdmStore.getTermManager().getTerms(uuids, Feature.class);
1771
        }
1772

    
1773
       if (terms.isEmpty()){
1774
           terms.addAll(TermStore.getTerms(CdmStore.getService(IVocabularyService.class).load(VocabularyEnum.NameFeature.getUuid()), null));
1775
        }
1776
        terms.remove(Feature.PROTOLOGUE());
1777
        if (terms.isEmpty()){
1778
            preferredNameFeatureTree = TermEditorInput.getDefaultNameFeatureTree();
1779
        }else{
1780
            preferredNameFeatureTree = TermTree.NewInstance(terms);
1781
        }
1782
    }
1783

    
1784
    public static void removeFromDB(List<CdmPreference> prefsToDelete) {
1785
        ICdmRepository controller;
1786
        //try{
1787
            if(CdmStore.isActive()){
1788
                controller = CdmStore.getCurrentApplicationConfiguration();
1789
                for (CdmPreference preference: prefsToDelete){
1790
                    controller.getPreferenceService().remove(preference.getKey());
1791
                }
1792
                CdmPreferenceCache.instance().getAllTaxEditorDBPreferences();
1793
            }
1794
    }
1795

    
1796
    public static void removeFromDB(CdmPreference prefToDelete) {
1797
        ICdmRepository controller;
1798

    
1799
        if(CdmStore.isActive()){
1800
            controller = CdmStore.getCurrentApplicationConfiguration();
1801
            controller.getPreferenceService().remove(prefToDelete.getKey());
1802

    
1803
            CdmPreferenceCache.instance().getAllTaxEditorDBPreferences();
1804
        }
1805
    }
1806

    
1807
    public static TermTree<?> getPreferredFeatureTreeForTaxonDescription(boolean createNew) {
1808
        if(preferredTaxonFeatureTree != null && !createNew){
1809
            return preferredTaxonFeatureTree;
1810
        }
1811
        createPreferredFeatureTreeForTaxonDescription();
1812
        return preferredTaxonFeatureTree;
1813
    }
1814

    
1815
    public static void createPreferredFeatureTreeForTaxonDescription() {
1816

    
1817
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1818
        CdmPreference pref = cache.get(PreferencePredicate.TaxonFeatures.getKey());
1819
        List<Feature> terms = null;
1820
        boolean override = PreferencesUtil.getOverrideForPreference(PreferencePredicate.TaxonFeatures.getKey());
1821
        List<UUID> uuids = PreferencesUtil.createUUIDListFromStringPref(PreferencePredicate.TaxonFeatures.getKey(), false);
1822
        if (uuids != null && !uuids.isEmpty()){
1823
            terms = CdmStore.getTermManager().getTerms(uuids, Feature.class);
1824
        }
1825
        if (terms == null || terms.isEmpty()){
1826
            terms= CdmStore.getTermManager().getPreferredTerms(TermType.Feature);
1827
            TermVocabulary nameVocabulary = CdmStore.getService(IVocabularyService.class).load(VocabularyEnum.NameFeature.getUuid());
1828
            Set<Feature> nameFeature = nameVocabulary.getTerms();
1829
            terms.removeAll(nameFeature);
1830

    
1831
        }
1832

    
1833
        if (terms.isEmpty()){
1834
            preferredTaxonFeatureTree = TermEditorInput.getDefaultFeatureTree();
1835
        }else{
1836
            preferredTaxonFeatureTree = TermTree.NewInstance(terms);
1837
        }
1838
    }
1839

    
1840
    public static void setLastSelectedBiocaseProvider(String lastAccessPoint) {
1841
        setStringValue(LAST_USED_BIOCASE_PROVIDER, lastAccessPoint);
1842
    }
1843

    
1844
    /**
1845
     * @return
1846
     */
1847
    public static boolean getLocalActive() {
1848
        // TODO: this needs to be adapted!!!
1849
        return true;
1850
    }
1851

    
1852
    /**
1853
     * @return
1854
     */
1855
    public static boolean showGfbioMetaData() {
1856
        //TODO: needs to be adapted!!!
1857
        return false;
1858
    }
1859

    
1860
    public static SecReferenceHandlingEnum getSecReferenceHandlingPreference(){
1861
        String defaultBehaviour = getStringValue(PreferencePredicate.DefaultBehaviourForSecundum.getKey());
1862
        SecReferenceHandlingEnum handling = SecReferenceHandlingEnum.valueOf(defaultBehaviour);
1863
        return handling;
1864

    
1865
    }
1866

    
1867
    public static EnabledComputedDescription getComputedDesciptionHandlingPreference(){
1868
        String defaultBehaviour= getStringValue(PreferencePredicate.EnableComputedDescription.getKey());
1869
        EnabledComputedDescription computedDescriptionsEnabled = (EnabledComputedDescription)PreferencePredicate.EnableComputedDescription.getDefaultValue();
1870
        if (StringUtils.isNotBlank(defaultBehaviour)){
1871
            computedDescriptionsEnabled = EnabledComputedDescription.byKey(defaultBehaviour);
1872
        }
1873
        return computedDescriptionsEnabled;
1874

    
1875
    }
1876

    
1877
    public static boolean isComputedDesciptionHandlingDisabled(){
1878
        String defaultBehaviour= getStringValue(PreferencePredicate.EnableComputedDescription.getKey());
1879
        EnabledComputedDescription computedDescriptionsEnabled = EnabledComputedDescription.byKey(defaultBehaviour);
1880
        return computedDescriptionsEnabled.equals(EnabledComputedDescription.Disabled);
1881

    
1882
    }
1883

    
1884
}
(44-44/62)