Project

General

Profile

Download (73.7 KB) Statistics
| Branch: | Tag: | Revision:
1
/**
2
 * Copyright (C) 2007 EDIT
3
 * European Distributed Institute of Taxonomy
4
 * http://www.e-taxonomy.eu
5
 *
6
 * The contents of this file are subject to the Mozilla Public License Version 1.1
7
 * See LICENSE.TXT at the top of this package for the full license terms.
8
 */
9

    
10
package eu.etaxonomy.taxeditor.preference;
11

    
12
import java.io.File;
13
import java.io.FileInputStream;
14
import java.io.FileOutputStream;
15
import java.io.IOException;
16
import java.lang.reflect.Field;
17
import java.net.URI;
18
import java.net.URISyntaxException;
19
import java.util.ArrayList;
20
import java.util.Arrays;
21
import java.util.Collections;
22
import java.util.HashMap;
23
import java.util.List;
24
import java.util.Map;
25
import java.util.Properties;
26
import java.util.Set;
27
import java.util.StringTokenizer;
28
import java.util.UUID;
29

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

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

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

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

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

    
107
    private static TermTree<Feature> preferredNameFeatureTree;
108

    
109
    private static TermTree<Feature> preferredTaxonFeatureTree;
110

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

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

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

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

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

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

    
147
    public static List<CdmPreference> getPreference(PreferencePredicate prefPredicate){
148
        try {
149
            List<CdmPreference> prefs = new ArrayList();
150
            CdmPreference pref;
151
            PreferenceSubject subject;
152
            if(getEditorPreferences().nodeExists(prefPredicate.getKey())){
153
                Preferences predicateNode = getEditorPreferences().node(prefPredicate.getKey());
154
                for (String childName: predicateNode.childrenNames()){
155
                    Preferences child = predicateNode.node(childName);
156
                    String subjectString = "";
157
                    subjectString = createSubjectStringForChildNodes(childName, child);
158
                    String value = child.get(subjectString, "");
159
                    subject = PreferenceSubject.NewInstance(subjectString);
160
                    pref = CdmPreference.NewInstance(subject, prefPredicate, value);
161
                    prefs.add(pref);
162
                }
163

    
164
            }
165

    
166
        } catch (BackingStoreException e) {
167
            // TODO Auto-generated catch block
168
            e.printStackTrace();
169
        }
170
        return null;
171
    }
172

    
173
    /**
174
     * @param childName
175
     * @param child
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 + "_"+  ((CdmRemoteSource)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
        String prefValue = null;
232
        String overrideKey =  createPreferenceString(createOverridePreferenceString(name));
233
        boolean override = getPreferenceStore().getBoolean(overrideKey);
234

    
235
        if (local || pref == null || (pref != null && pref.isAllowOverride() && override)){
236
            String dbSpecific = prefKey(name);
237
            if (getPreferenceStore().contains(dbSpecific)){
238
                prefValue = getPreferenceStore().getString(dbSpecific);
239
            }else{
240
                prefValue = getPreferenceStore().
241
                        getString(name);
242
            }
243
       }else if (pref != null){
244
           if (pref.getValue() == null){
245
               Object result = PreferencePredicate.getByKey(pref.getPredicate()).getDefaultValue();
246
               if (result instanceof String){
247
                   return (String)result;
248
               }else{
249
                   if (result == null){
250
                       return null;
251
                   }
252
                   if (result instanceof IKeyLabel){
253
                       return ((IKeyLabel)result).getKey();
254
                   }
255
                   return result.toString();
256
               }
257
           }
258
           prefValue = pref.getValue();
259
       }
260
        return prefValue;
261

    
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
//
272
        pref = cache.get(name);
273
//        if (pref == null ){
274
//            //get default value for Predicate
275
//            IPreferencePredicate pred = PreferencePredicate.getByKey(name);
276
//            if (pred != null){
277
//                if (pred.getDefaultValue() != null){
278
//                    pref = CdmPreference.NewTaxEditorInstance(pred, pred.getDefaultValue().toString());
279
//                }else{
280
//                    pref = CdmPreference.NewTaxEditorInstance(pred, null);
281
//                }
282
//                pref.setAllowOverride(true);
283
//            }
284
//        }
285
        return pref;
286
    }
287

    
288
    public static int getIntValue(String name, boolean local) {
289
        CdmPreference pref= getDBPreferenceValue(name);
290
        String prefValue = null;
291
        if (pref != null){
292
            prefValue = pref.getValue();
293
        }
294
        Integer result = null;
295
        try{
296
            result = Integer.parseInt(prefValue);
297
        }catch(NumberFormatException e){
298
            logger.debug("Preference value of " + name + " is not a number");
299
        }
300

    
301
        String overrideKey =  createPreferenceString(createOverridePreferenceString(name));
302
        boolean override = true;
303
        if (getPreferenceStore().contains(overrideKey)){
304
            override = getPreferenceStore().getBoolean(overrideKey);
305
        }
306
        if (local || pref == null || (pref != null && pref.isAllowOverride() && override)){
307
            String dbSpecific = prefKey(name);
308
            if (getPreferenceStore().contains(dbSpecific)){
309
                result = getPreferenceStore().getInt(dbSpecific);
310
            }else{
311
                result =  getPreferenceStore().
312
                        getInt(name);
313
            }
314
        }
315
        return result;
316

    
317
    }
318

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

    
327
    }
328

    
329
    public static Boolean getBooleanValue(String name, boolean local) {
330
        if (CdmStore.isActive()){
331
            CdmPreference pref = getDBPreferenceValue(name);
332

    
333
            String overrideKey =  createPreferenceString(createOverridePreferenceString(name));
334
            boolean override = getPreferenceStore().getBoolean(overrideKey);
335

    
336
            if (local || pref == null || (pref != null && pref.isAllowOverride() && override)){
337
                String dbSpecific = prefKey(name);
338
                if (getPreferenceStore().contains(dbSpecific)){
339
                    return getPreferenceStore().getBoolean(dbSpecific);
340
                }else{
341
                    return null;
342
                }
343
             }else{
344
                 if (pref.getValue() == null){
345
                     Object result = PreferencePredicate.getByKey(pref.getPredicate()).getDefaultValue();
346
                     if (result instanceof Boolean){
347
                         return (Boolean)result;
348
                     }else{
349
                         return Boolean.valueOf(result.toString());
350
                     }
351
                 }
352
                return Boolean.valueOf(pref.getValue());
353
            }
354

    
355
        }else{
356
            return getPreferenceStore().getBoolean(name);
357
        }
358

    
359
    }
360

    
361
    public static double getDoubleValue(String name) {
362
        CdmPreference pref = getDBPreferenceValue(name);
363
        String prefValue = null;
364
        if (pref != null){
365
            prefValue = pref.getValue();
366
        }
367
        Double result = null;
368
        try{
369
            if (pref.getValue() == null){
370
                Object defaultValue = PreferencePredicate.getByKey(pref.getPredicate()).getDefaultValue();
371
                if (defaultValue instanceof Double){
372
                    return (Double)defaultValue;
373
                }else{
374
                    return Double.valueOf(defaultValue.toString());
375
                }
376
            }
377

    
378
            result = Double.parseDouble(prefValue);
379
        }catch(NumberFormatException e){
380
            logger.debug("Preference value of " + name + " is not a number");
381
        }
382
        if (result == null){
383
            String dbSpecific = prefKey(name);
384
            if (getPreferenceStore().contains(dbSpecific)){
385
                result = getPreferenceStore().getDouble(dbSpecific);
386
            }else{
387
                result =  getPreferenceStore().
388
                        getDouble(name);
389
            }
390
        }
391
        return result;
392

    
393
    }
394

    
395
    public static float getFloatValue(String name, boolean local) {
396
        CdmPreference pref = getDBPreferenceValue(name);
397
        String prefValue = null;
398
        if (pref != null){
399
            prefValue = pref.getValue();
400
        }
401
        Float result = null;
402
        try{
403
            result = Float.parseFloat(prefValue);
404
        }catch(NumberFormatException e){
405
            logger.debug("Preference value of " + name + " is not a number");
406
        }
407
        String overrideKey =  createPreferenceString(createOverridePreferenceString(name));
408
        boolean override = true;
409
        if (getPreferenceStore().contains(overrideKey)){
410
            override = getPreferenceStore().getBoolean(overrideKey);
411
        }
412
        if (local || pref == null || (pref != null && pref.isAllowOverride() && override)){
413
            String dbSpecific = prefKey(name);
414
            if (getPreferenceStore().contains(dbSpecific)){
415
                result = getPreferenceStore().getFloat(dbSpecific);
416
            }else{
417
                result =  getPreferenceStore().
418
                        getFloat(name);
419
            }
420
        }
421
        return result;
422

    
423
    }
424

    
425
    public static long getLongValue(String name) {
426
        CdmPreference pref = getDBPreferenceValue(name);
427
        String prefValue = null;
428
        if (pref != null){
429
            prefValue = pref.getValue();
430
        }
431
        Long result = null;
432
        try{
433
            result = Long.parseLong(prefValue);
434
        }catch(NumberFormatException e){
435
            logger.debug("Preference value of " + name + " is not a number");
436
        }
437
        if (result == null){
438
            String dbSpecific = prefKey(name);
439
            if (getPreferenceStore().contains(dbSpecific)){
440
                result = getPreferenceStore().getLong(dbSpecific);
441
            }else{
442
                result =  getPreferenceStore().
443
                        getLong(name);
444
            }
445
        }
446
        return result;
447
    }
448

    
449
    public static CdmPreference setPreferredNomenclaturalCode(
450
            String preferenceValue, boolean local) {
451
        if (local){
452
            setStringValue(PreferencePredicate.NomenclaturalCode.getKey(),
453
                    preferenceValue);
454
        }
455
        else{
456
            ICdmRepository controller;
457
            controller = CdmStore.getCurrentApplicationConfiguration();
458
            if (controller == null){
459
                return null;
460
            }
461
            PrefKey key = null;
462
            try{
463
                key = CdmPreference.NewKey(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.NomenclaturalCode);
464
            }catch (Exception e){
465
                System.out.println(e.getStackTrace());
466
            }
467
            CdmPreference preference = null;
468

    
469
            if (preferenceValue == null){
470
                preference = controller.getPreferenceService().find(key);
471
                if (preference == null){
472
                    return null;
473
                } else{
474
                    setStringValue(PreferencePredicate.NomenclaturalCode.getKey(),
475
                            preference.getValue());
476

    
477
                    return preference;
478
                }
479
            } else{
480
                preference = CdmPreference.NewInstance(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.NomenclaturalCode, preferenceValue);
481
                controller.getPreferenceService().set(preference);
482

    
483
            }
484
        }
485
        return null;
486

    
487

    
488

    
489
    }
490

    
491
    public static void setPreferredNomenclaturalCode(
492
        CdmPreference preference) {
493

    
494
        ICdmRepository controller;
495
        controller = CdmStore.getCurrentApplicationConfiguration();
496
        if (controller == null){
497
            return;
498
        }
499

    
500
        if (preference == null){
501
            PrefKey key = null;
502
              try{
503
                  key = CdmPreference.NewKey(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.NomenclaturalCode);
504
              }catch (Exception e){
505
                  System.out.println(e.getStackTrace());
506
              }
507
            controller.getPreferenceService().remove(key);
508
        }else{
509
            controller.getPreferenceService().set(preference);
510
        }
511

    
512
    }
513

    
514
    public static NomenclaturalCode getPreferredNomenclaturalCode() {
515

    
516
        CdmPreference pref = getPreferenceFromDB(PreferencePredicate.NomenclaturalCode);
517

    
518

    
519
        String preferredCode;
520
        if(pref == null || (pref.isAllowOverride() && getBooleanValue(prefOverrideKey(PreferencePredicate.NomenclaturalCode.getKey())))){
521
            preferredCode = getStringValue(
522
                    PreferencePredicate.NomenclaturalCode.getKey());
523

    
524
        }else{
525
            preferredCode = pref.getValue();
526
        }
527
        if (StringUtils.isBlank(preferredCode)){
528
            preferredCode = getPreferenceKey((NomenclaturalCode)PreferencePredicate.NomenclaturalCode.getDefaultValue());
529
        }
530

    
531
        return getPreferredNomenclaturalCode(preferredCode);
532

    
533
    }
534

    
535
    public static NomenclaturalCode getPreferredNomenclaturalCode(String preferenceKeyNomenclaturalCode) {
536

    
537
        for (NomenclaturalCode code : NomenclaturalCodeHelper.getAllCodes()) {
538
            if (getPreferenceKey(code).equals(preferenceKeyNomenclaturalCode) || code.getKey().equals(preferenceKeyNomenclaturalCode)) {
539
                return code;
540
            }
541
        }
542
        return null;
543
    }
544

    
545
    public static boolean isShowTaxonAssociations(){
546
        boolean result = getBooleanValue(PreferencePredicate.ShowTaxonAssociations.getKey());
547
        return result;
548
    }
549

    
550
    public static boolean isShowLifeForm(){
551
        boolean result =  getBooleanValue(PreferencePredicate.ShowLifeForm.getKey());
552
        return result;
553
    }
554

    
555
    public static boolean isDeterminationOnlyForFieldUnits(){
556
        boolean result =  getBooleanValue(PreferencePredicate.DeterminationOnlyForFieldUnits.getKey());
557
        return result;
558
    }
559

    
560
    public static boolean isCollectingAreaInGeneralSection(){
561
        boolean result =  getBooleanValue(PreferencePredicate.ShowCollectingAreasInGeneralSection.getKey());
562
        return result;
563
    }
564

    
565
    public static CdmPreference getPreferenceFromDB(IPreferencePredicate predicate){
566
        ICdmRepository controller;
567
        CdmPreference pref = null;
568

    
569
        try{
570
            if(CdmStore.isActive()){
571
                controller = CdmStore.getCurrentApplicationConfiguration();
572
                PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), predicate);
573
                pref = controller.getPreferenceService().find(key);
574
            }
575
        }catch(Exception e){
576
            e.printStackTrace();
577
        }
578

    
579
        return pref;
580

    
581
    }
582

    
583
    public static List<CdmPreference> getPreferencesFromDB(IPreferencePredicate predicate){
584
        ICdmRepository controller;
585
        List<CdmPreference> prefs = null;
586

    
587
        try{
588
            if(CdmStore.isActive()){
589
                controller = CdmStore.getCurrentApplicationConfiguration();
590
                PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), predicate);
591
                prefs = controller.getPreferenceService().list(predicate);
592
            }
593
        }catch(Exception e){
594
            e.printStackTrace();
595
        }
596

    
597
        return prefs;
598

    
599
    }
600

    
601
    public static void setPreferencesToDB(CdmPreference preference, boolean setDefault){
602
        ICdmRepository controller;
603
        try{
604
            if(CdmStore.isActive()){
605
                controller = CdmStore.getCurrentApplicationConfiguration();
606

    
607
                if (setDefault){
608
                    controller.getPreferenceService().remove(preference.getKey());
609
                }else{
610
                    controller.getPreferenceService().set(preference);
611
                }
612
            }
613
        }catch(Exception e){
614
            e.printStackTrace();
615
        }
616

    
617

    
618

    
619
    }
620

    
621
    public static CdmPreference getPreferenceFromDB(PrefKey key){
622
        ICdmRepository controller;
623
        CdmPreference pref = null;
624

    
625
        try{
626
            if(CdmStore.isActive()){
627
                controller = CdmStore.getCurrentApplicationConfiguration();
628
                pref = controller.getPreferenceService().find(key);
629
            }
630
        }catch(Exception e){
631
            e.printStackTrace();
632
        }
633

    
634
        return pref;
635

    
636
    }
637

    
638
    public static void setPreferenceToDB(CdmPreference preference){
639
        ICdmRepository controller;
640
        try{
641
            if(CdmStore.isActive()){
642
                controller = CdmStore.getCurrentApplicationConfiguration();
643
                if (preference.getValue() == null && preference.isAllowOverride()){
644
                    controller.getPreferenceService().remove(preference.getKey());
645
                }else{
646
                    controller.getPreferenceService().set(preference);
647
                }
648
                CdmPreferenceCache.instance().put(preference);
649
            }
650
        }catch(Exception e){
651
            e.printStackTrace();
652
        }
653

    
654
    }
655

    
656
    public static String getPreferredDefaultLangugae(){
657
        String preferredLanguage = getStringValue(DEFAULT_LANGUAGE_EDITOR);
658
        if(StringUtils.isNotEmpty(preferredLanguage) && StringUtils.isNotBlank(preferredLanguage)){
659
            return preferredLanguage;
660
        }
661
        return null;
662
    }
663

    
664
    public static boolean isShowMediaPreview(){
665
        boolean isShowMediaPreview = getBooleanValue(SHOW_MEDIA_PREVIEW);
666
        return isShowMediaPreview;
667
    }
668

    
669
    /**
670
     * Get the match strategy for the given class that was stored in preferences
671
     * or the default strategy if it was not stored in preferences
672
     *
673
     * @param clazz
674
     *            a {@link java.lang.Class} object.
675
     * @return a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy} object.
676
     */
677
    public static IMatchStrategy getMatchStrategy(Class<?> clazz) {
678
        String className = clazz.getName();
679
        if (getBooleanValue(MATCH_STRATEGY_PREFIX + className)) {
680
            IMatchStrategy matchStrategy = getDefaultMatchStrategy(clazz);
681

    
682
            //TODO CacheMatchers (or multiple field matchers in future) are missing here
683
            for (FieldMatcher fieldMatcher : matchStrategy.getMatching().getFieldMatchers(false)) {
684
                String fieldName = fieldMatcher.getPropertyName();
685
                String matchModeName = getStringValue(
686
                        getMatchStrategyFieldName(className, fieldName));
687
                MatchMode matchMode = MatchMode.valueOf(matchModeName);
688
                try {
689
                    matchStrategy.setMatchMode(fieldName, matchMode);
690
                } catch (MatchException e) {
691
                    MessagingUtils.error(PreferencesUtil.class, e);
692
                    throw new RuntimeException(e);
693
                }
694
            }
695

    
696
            return matchStrategy;
697
        }
698
        return getDefaultMatchStrategy(clazz);
699
    }
700

    
701
    /**
702
     * Stores a matchStrategy into the preference store.
703
     *
704
     * @param matchStrategy
705
     *            a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy}
706
     *            object.
707
     */
708
    public static void setMatchStrategy(IMatchStrategy matchStrategy) {
709
        String className = "ANY class"; //FIXME was: matchStrategy.getMatchClass().getName(); seems currently not in use
710
        setBooleanValue(MATCH_STRATEGY_PREFIX + className, true);
711

    
712
        List<FieldMatcher> fieldMatchers = matchStrategy.getMatching().getFieldMatchers(false);
713

    
714
        for (FieldMatcher fieldMatcher : fieldMatchers) {
715
            String fieldName = fieldMatcher.getPropertyName();
716
            setStringValue(
717
                    getMatchStrategyFieldName(className, fieldName),
718
                    fieldMatcher.getMatchMode().name());
719
        }
720
    }
721

    
722
    /**
723
     * Helper method to create the preference property for a match field.
724
     *
725
     * @param className
726
     * @param fieldName
727
     * @return
728
     */
729
    private static String getMatchStrategyFieldName(String className,
730
            String fieldName) {
731
        return MATCH_STRATEGY_PREFIX + className + "." + fieldName;
732
    }
733

    
734
    /**
735
     * Returns the default match strategy for a given class.
736
     *
737
     * @param clazz
738
     *            a {@link java.lang.Class} object.
739
     * @return a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy} object.
740
     */
741
    public static IMatchStrategy getDefaultMatchStrategy(Class clazz) {
742
        return DefaultMatchStrategy.NewInstance(clazz);
743
    }
744

    
745
    public static String getDateFormatPattern() {
746
        // TODO make this configurable in properties
747
        String pattern = "Y-M-d H:m";
748
        return pattern;
749
    }
750

    
751
    public static <T extends TermBase> void addTermToPreferredTerms(T term) {
752

    
753
        // VocabularyEnum vocabulary =
754
        // VocabularyEnum.getVocabularyEnum(term.getClass());
755
        //
756
        // getPreferenceStore().setValue(getPreferenceKey(term),
757
        // VocabularyStore.getTermVocabulary(vocabulary).getTerms().contains(term));
758
        //
759
        // firePreferencesChanged(term.getClass());
760
    }
761

    
762
    /**
763
     * Construct a unique key using the CdmBase object's uuid
764
     *
765
     * @param cdmBase
766
     * @return
767
     */
768
    private static String getPreferenceKey(ICdmBase cdmBase) {
769
        cdmBase = HibernateProxyHelper.deproxy(cdmBase);
770

    
771
        String key = cdmBase.getClass().getName().concat(".")
772
                .concat(cdmBase.getUuid().toString());
773
        if (key.contains("javassist")) {
774
            MessagingUtils.info("proxy");
775
        }
776
        return key;
777
    }
778

    
779
    /**
780
     * Construct a unique key using the CdmBase object's uuid
781
     *
782
     * @param cdmBase
783
     * @return
784
     */
785
    public static String getPreferenceKey(ISimpleTerm simpleTerm) {
786
        simpleTerm = HibernateProxyHelper.deproxy(simpleTerm);
787
        String key = simpleTerm.getClass().getName().concat(".")
788
                .concat(simpleTerm.getUuid().toString());
789
        if (key.contains("javassist")) {
790
            MessagingUtils.warn(PreferencesUtil.class,
791
                    "Trying to persist a preference based on a proxy class.");
792
        }
793
        return key;
794
    }
795

    
796

    
797

    
798
    /**
799
     * Construct a unique key using the CdmBase object's uuid
800
     *
801
     * @param cdmBase
802
     * @return
803
     */
804
    public static String getPreferenceKey(IDefinedTerm definedTerm) {
805
        definedTerm = HibernateProxyHelper.deproxy(definedTerm);
806
        String key = definedTerm.getClass().getName().concat(".")
807
                .concat(definedTerm.getUuid().toString());
808
        if (key.contains("javassist")) {
809
            MessagingUtils.warn(PreferencesUtil.class,
810
                    "Trying to persist a preference based on a proxy class.");
811
        }
812
        return key;
813
    }
814

    
815
    /**
816
     * Retrieves search preferences from the preference store
817
     *
818
     * @return an {@link ITaxonServiceConfigurator} to pass to search methods
819
     */
820
    public static IFindTaxaAndNamesConfigurator getSearchConfigurator() {
821
        IFindTaxaAndNamesConfigurator configurator = initializeSearchConfigurator();
822

    
823
        configurator.setDoTaxa(PreferencesUtil.getPreferenceStore().contains(IPreferenceKeys.TAXON_SERVICE_CONFIGURATOR_TAXA)? PreferencesUtil.getPreferenceStore().getBoolean(
824
                IPreferenceKeys.TAXON_SERVICE_CONFIGURATOR_TAXA): true);
825
        configurator.setDoSynonyms(PreferencesUtil.getPreferenceStore().contains(IPreferenceKeys.TAXON_SERVICE_CONFIGURATOR_SYNONYMS)? PreferencesUtil.getPreferenceStore().getBoolean(
826
                IPreferenceKeys.TAXON_SERVICE_CONFIGURATOR_SYNONYMS): true);
827
        configurator.setDoNamesWithoutTaxa(PreferencesUtil.getPreferenceStore().contains(IPreferenceKeys.TAXON_SERVICE_CONFIGURATOR_NAMES)? PreferencesUtil.getPreferenceStore().getBoolean(
828
                IPreferenceKeys.TAXON_SERVICE_CONFIGURATOR_NAMES): true);
829
        configurator.setDoTaxaByCommonNames(PreferencesUtil.getPreferenceStore().contains(IPreferenceKeys.TAXON_SERVICE_CONFIGURATOR_COMMON_NAMES)? PreferencesUtil.getPreferenceStore().getBoolean(
830
                IPreferenceKeys.TAXON_SERVICE_CONFIGURATOR_COMMON_NAMES): true);
831
        //configurator.setMatchMode(eu.etaxonomy.cdm.persistence.query.MatchMode.valueOf(getStringValue(TAXON_SERVICE_CONFIGURATOR_MATCH_MODE)));
832

    
833
        return configurator;
834
    }
835

    
836
    /**
837
     * create new preferences, setting all search options to true
838
     *
839
     * @return a
840
     *         {@link eu.etaxonomy.cdm.api.service.config.ITaxonServiceConfigurator}
841
     *         object.
842
     */
843
    public static IFindTaxaAndNamesConfigurator initializeSearchConfigurator() {
844
        IFindTaxaAndNamesConfigurator configurator = FindTaxaAndNamesConfiguratorImpl.NewInstance();
845

    
846
        configurator.setDoTaxa(true);
847
        configurator.setDoSynonyms(true);
848
        configurator.setDoNamesWithoutTaxa(true);
849
        configurator.setDoTaxaByCommonNames(true);
850

    
851
        configurator.setTaxonPropertyPath(Arrays.asList("$", "titleCache",
852
                "name", "name.$", "relationsFromThisTaxon.$"));
853

    
854
        configurator.setSynonymPropertyPath(Arrays.asList("$", "titleCache",
855
                "name", "name.$", "synonyms.relatedTo.*"));
856

    
857
        // DEFAULT VALUES
858
        // match mode is a simple like, actually all other match modes are kind
859
        // of bogus
860
        configurator
861
                .setMatchMode(eu.etaxonomy.cdm.persistence.query.MatchMode.ANYWHERE);
862
        // we set page number and size here as this should always be unlimited
863
        configurator.setPageNumber(0);
864
        // TODO currently limit results to 10000
865
        configurator.setPageSize(10000);
866
        //setSearchConfigurator(configurator) ;
867
        return configurator;
868
    }
869

    
870
    /**
871
     * Store search preferences
872
     *
873
     * @param configurator
874
     *            a
875
     *            {@link eu.etaxonomy.cdm.api.service.config.ITaxonServiceConfigurator}
876
     *            object.
877
     */
878
    public static void setSearchConfigurator(
879
            IFindTaxaAndNamesConfigurator configurator) {
880
        getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_TAXA,
881
                configurator.isDoTaxa());
882
        getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_SYNONYMS,
883
                configurator.isDoSynonyms());
884
        getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_NAMES,
885
                configurator.isDoNamesWithoutTaxa());
886
        getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_COMMON_NAMES,
887
                configurator.isDoTaxaByCommonNames());
888
    }
889

    
890
    public static void firePreferencesChanged(Class clazz) {
891
        getPreferenceStore().firePropertyChangeEvent(PREFERRED_TERMS_CHANGE,
892
                null, clazz);
893
    }
894

    
895

    
896
    public static String createPreferenceString(String property){
897
       return prefKey(property);
898

    
899
    }
900
    public static String createOverridePreferenceString(String property){
901
           return prefOverrideKey(property);
902

    
903
        }
904

    
905
    /**
906
     * Set default values for preferences
907
     */
908
    public static void setDefaults() {
909

    
910
        getPreferenceStore().setDefault(createPreferenceString(EDIT_MAP_SERVICE_ACCES_POINT),
911
                "http://edit.africamuseum.be/edit_wp5/v1.2/rest_gen.php");
912
        //FIXME : changed default for SHOULD_CONNECT_AT_STARTUP to false (ticket 3828) until resolution
913
        getPreferenceStore().setDefault(createPreferenceString(SHOULD_CONNECT_AT_STARTUP), false);
914
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.MobotOpenUrlServiceAccessPoint.getKey()),
915
                "http://www.biodiversitylibrary.org/openurl");
916
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.MobotOpenUrlServiceMaxWidth.getKey()), "1000");
917
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.MobotOpenUrlServiceMaxHeight.getKey()), "1000");
918
        getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_TAXA, true);
919
        getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_SYNONYMS, true);
920
        getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_NAMES, true);
921
        getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_COMMON_NAMES, true);
922

    
923

    
924
        //Name Details
925
       // getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.NameDetailsView.getKey()), new NameDetailsConfigurator(false).toString());
926

    
927
        //Navigator preferences
928
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.TaxonNodeOrder.getKey()), NavigatorOrderEnum.RankAndNameOrder.getKey());
929

    
930
        //getPreferenceStore().setDefault(createPreferenceString(Prefe), true);
931

    
932
        getPreferenceStore().setDefault(createPreferenceString(SHOW_ADVANCED_MEDIA_SECTION), false);
933

    
934
        getPreferenceStore().setDefault(createPreferenceString(SHOW_MEDIA_PREVIEW), false);
935
        //override db preferences
936
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.AbcdImportConfig.getKey())), false);
937
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.NameDetailsView.getKey())), false);
938
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.CommonNameAreaVocabularies.getKey())), false);
939
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.CommonNameReferencesWithMarker.getKey()), false);
940
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowTaxonNodeWizard.getKey()), Boolean.valueOf(PreferencePredicate.ShowTaxonNodeWizard.getDefaultValue().toString()));
941
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowNamespaceInSource.getKey()), Boolean.valueOf(PreferencePredicate.ShowNamespaceInSource.getDefaultValue().toString()));
942
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowIdInSource.getKey()), Boolean.valueOf(PreferencePredicate.ShowIdInSource.getDefaultValue().toString()));
943
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.DisableMultiClassification.getKey()), Boolean.valueOf(PreferencePredicate.DisableMultiClassification.getDefaultValue().toString()));
944
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowImportExportMenu.getKey()), Boolean.valueOf(PreferencePredicate.ShowImportExportMenu.getDefaultValue().toString()));
945
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowSpecimen.getKey()), Boolean.valueOf(PreferencePredicate.ShowSpecimen.getDefaultValue().toString()));
946
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.SearchForIdentifierAndTitleCache.getKey()), Boolean.valueOf(PreferencePredicate.SearchForIdentifierAndTitleCache.getDefaultValue().toString()));
947
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.SearchForIdentifierAndTitleCache.getKey())), false);
948
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.SearchForIdentifierAsDefault.getKey()), Boolean.valueOf(PreferencePredicate.SearchForIdentifierAsDefault.getDefaultValue().toString()));
949
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.SearchForIdentifierAsDefault.getKey())), false);
950

    
951
    }
952

    
953
    public static void checkNomenclaturalCode() {
954
        // First time Editor is opened, no nomenclatural code has been set
955
        if (PreferencesUtil.getPreferredNomenclaturalCode() == null) {
956
            PreferencesUtil.setPreferredNomenclaturalCode(getPreferenceKey(NomenclaturalCode.ICNAFP), true);
957
        }
958

    
959

    
960

    
961
    }
962
    public static void setNomenclaturalCodePreferences(){
963
        ICdmRepository controller;
964
        controller = CdmStore.getCurrentApplicationConfiguration();
965
        PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.NomenclaturalCode);
966
        CdmPreference preference = null;
967
        if (controller == null){
968
            return ;
969
        }
970
        preference = controller.getPreferenceService().find(key);
971
        if (preference == null){
972
            return;
973
        }
974
//        setBooleanValue(ALLOW_OVERRIDE_NOMENCLATURAL_CODE_KEY, preference.isAllowOverride());
975

    
976
        int index = StringUtils.lastIndexOf(preference.getValue(), ".");
977
        UUID uuid = UUID.fromString(preference.getValue().substring(index +1, preference.getValue().length()));
978
        NomenclaturalCode preferredCode = NomenclaturalCode.getByUuid(uuid);
979

    
980
        setStringValue(PreferencePredicate.NomenclaturalCode.getKey(),
981
                getPreferenceKey(preferredCode));
982

    
983
    }
984

    
985
    public static void checkDefaultLanguage(){
986
        if(PreferencesUtil.getPreferredDefaultLangugae() == null){
987
           Shell shell = AbstractUtility.getShell();
988
           int open = new DefaultLanguageDialog(shell).open();
989
           if(open == Window.OK){
990
               PlatformUI.getWorkbench().restart();
991
           }
992
        }else{
993
            //TODO:In case of a reinstall, the config.ini will be overwritten
994
            //     here you create config.ini with the stored key from preferences
995
        }
996
    }
997

    
998
    public static String getMapServiceAccessPoint() {
999
        return getStringValue(EDIT_MAP_SERVICE_ACCES_POINT);
1000
    }
1001

    
1002
    public static boolean shouldConnectAtStartUp() {
1003
        //FIXME :  force SHOULD_CONNECT_AT_STARTUP to false (ticket 3828) until resolution
1004
        //return getBooleanValue(SHOULD_CONNECT_AT_STARTUP);
1005
        return false;
1006
    }
1007

    
1008
    public static TermTree getDefaultFeatureTreeForTextualDescription() {
1009
        String uuidString = getStringValue(
1010
                FEATURE_TREE_DEFAULT_TEXT);
1011
        if (StringUtils.isBlank(uuidString)) {
1012
            return null;
1013
        }
1014
        TermTree tree = CdmStore.getService(
1015
                ITermTreeService.class).load(UUID.fromString(uuidString));
1016

    
1017
        if (tree == null || tree.getId() == 0) {
1018
            return null;
1019
        }
1020
        return tree;
1021
    }
1022

    
1023
    public static TermTree getDefaultFeatureTreeForStructuredDescription() {
1024
        String uuidString = getStringValue(
1025
                FEATURE_TREE_DEFAULT_STRUCTURE);
1026
        return StringUtils.isBlank(uuidString) ? null : CdmStore.getService(
1027
                ITermTreeService.class).load(UUID.fromString(uuidString));
1028
    }
1029

    
1030
    public static void setSortRanksHierarchichally(boolean selection) {
1031
        setBooleanValue(SORT_RANKS_HIERARCHICHALLY, selection);
1032
    }
1033

    
1034
    public static boolean getSortRanksHierarchichally() {
1035
        return getBooleanValue(SORT_RANKS_HIERARCHICHALLY);
1036
    }
1037

    
1038
    public static boolean isMultilanguageTextEditingCapability() {
1039
        return getBooleanValue(
1040
                MULTILANGUAGE_TEXT_EDITING_CAPABILITY);
1041
    }
1042

    
1043
    public static Language getGlobalLanguage() {
1044

    
1045

    
1046
        String languageUuidString = getStringValue(
1047
                GLOBAL_LANGUAGE_UUID);
1048

    
1049
        if(!CdmStore.isActive()) {
1050
            MessagingUtils.noDataSourceWarningDialog(languageUuidString);
1051
            return null;
1052
        }
1053

    
1054
        if (CdmUtils.isBlank(languageUuidString)) {
1055
            return Language.getDefaultLanguage();
1056
        }
1057

    
1058
        UUID languageUuid = UUID.fromString(languageUuidString);
1059
        return (Language) CdmStore.getService(ITermService.class).load(
1060
                languageUuid);
1061
    }
1062

    
1063
    public static void setGlobalLanguage(Language language) {
1064
        if(language != null) {
1065
            setStringValue(GLOBAL_LANGUAGE_UUID,language.getUuid().toString());
1066
            CdmStore.setDefaultLanguage(language);
1067
        }
1068

    
1069
    }
1070

    
1071
    public static Map<MarkerType, Boolean> getEditMarkerTypePreferences() {
1072
        List<MarkerType> markerTypes = CdmStore.getTermManager()
1073
                .getPreferredTerms(MarkerType.class);
1074

    
1075
        Map<MarkerType, Boolean> result = new HashMap<MarkerType, Boolean>();
1076

    
1077
        for (MarkerType markerType : markerTypes) {
1078
            String name = getMarkerTypeEditingPreferenceKey(markerType);
1079
            Boolean value = getBooleanValue(name);
1080

    
1081
            result.put(markerType, value);
1082
        }
1083

    
1084
        return result;
1085
    }
1086

    
1087
    public static void setEditMarkerTypePreferences(
1088
            Map<MarkerType, Boolean> markerTypeEditingMap) {
1089
        for (MarkerType markerType : markerTypeEditingMap.keySet()) {
1090
            String name = getMarkerTypeEditingPreferenceKey(markerType);
1091
            setBooleanValue(name,
1092
                    markerTypeEditingMap.get(markerType));
1093
        }
1094

    
1095
    }
1096

    
1097
    private static String getMarkerTypeEditingPreferenceKey(
1098
            MarkerType markerType) {
1099
        markerType = HibernateProxyHelper.deproxy(markerType);
1100
        return markerType.getClass().getName() + EDIT_MARKER_TYPE_PREFIX;
1101
    }
1102

    
1103
    public static void setEditMarkerTypePreference(MarkerType markerType,
1104
            boolean edit) {
1105
        setBooleanValue(
1106
                getMarkerTypeEditingPreferenceKey(markerType), edit);
1107
    }
1108

    
1109
    public static DerivedUnitFacadeConfigurator getDerivedUnitConfigurator() {
1110
        DerivedUnitFacadeConfigurator configurator = DerivedUnitFacadeConfigurator
1111
                .NewInstance();
1112
        configurator.setMoveDerivedUnitMediaToGallery(true);
1113
        configurator.setMoveFieldObjectMediaToGallery(true);
1114
        return configurator;
1115
    }
1116

    
1117
    /**
1118
     * This method will write language properties to the config.ini located in the configuration folder
1119
     * of the Taxonomic Ediitor. <b>This method is only used to set the default language for Taxonomic Editor.</b>
1120
     *
1121
     * @param setLanguage 0 is for german and 1 for english.
1122
     * @throws IOException
1123
     */
1124
    public void writePropertyToConfigFile(int setLanguage) throws IOException {
1125
        File file = org.eclipse.core.runtime.preferences.ConfigurationScope.INSTANCE.getLocation().toFile();
1126
        //give warning to user if the directory has no write access
1127
        if(file == null){
1128
            throw new IOException();
1129
        }
1130
        Properties properties = load(file.getAbsolutePath()+"/config.ini");
1131
        switch(setLanguage){
1132
        case 0:
1133
            properties.setProperty("osgi.nl", "de");
1134
            setStringValue(IPreferenceKeys.DEFAULT_LANGUAGE_EDITOR, "de");
1135
            break;
1136
        case 1:
1137
            properties.setProperty("osgi.nl", "en");
1138
            setStringValue(IPreferenceKeys.DEFAULT_LANGUAGE_EDITOR, "en");
1139
            break;
1140
        default:
1141
            break;
1142
        }
1143
        save(file+"/config.ini", properties);
1144
    }
1145

    
1146
    /**
1147
     * This method loads a property from a given file and returns it.
1148
     *
1149
     * @param filename
1150
     * @return
1151
     * @throws IOException
1152
     */
1153
    private Properties load(String filename) throws IOException {
1154
        FileInputStream in = new FileInputStream(filename);
1155
        Properties prop = new Properties();
1156
        prop.load(in);
1157
        in.close();
1158
        return prop;
1159
    }
1160

    
1161
    /**
1162
     * This method saves a property to the specified file.
1163
     *
1164
     * @param filename
1165
     * @param properties
1166
     * @throws IOException
1167
     */
1168
    private void save(String filename, Properties properties) throws IOException{
1169
        FileOutputStream fos =  new FileOutputStream(filename);
1170
        properties.store(fos, "");
1171
        fos.close();
1172
    }
1173

    
1174
    /**
1175
     * Saves a list of P2 Metadata Repositories as string with specified delimiters
1176
     *
1177
     * @param p2Repos
1178
     */
1179
    public static void setP2Repositories(List<MetadataRepositoryElement> p2Repos) {
1180
        StringBuilder sb = new StringBuilder();
1181
        for(MetadataRepositoryElement p2Repo : p2Repos) {
1182
            sb.append(P2_REPOSITORIES_DELIM);
1183
            if(p2Repo.getName() == null || p2Repo.getName().isEmpty()) {
1184
                sb.append("-");
1185
            } else {
1186
                sb.append(p2Repo.getName());
1187
            }
1188
            sb.append(P2_REPOSITORY_FIELDS_DELIM);
1189
            sb.append(p2Repo.getLocation().toString());
1190
            sb.append(P2_REPOSITORY_FIELDS_DELIM);
1191
            sb.append(String.valueOf(p2Repo.isEnabled()));
1192
        }
1193
        getPreferenceStore().setValue(P2_REPOSITORY_LIST, sb.toString());
1194
    }
1195

    
1196

    
1197
    /**
1198
     * Retrieves a list of previously saved P2 repositories
1199
     *
1200
     * @return
1201
     */
1202
    public static List<MetadataRepositoryElement> getP2Repositories() {
1203
        List<MetadataRepositoryElement> p2Repos = new ArrayList<MetadataRepositoryElement>();
1204
        String p2ReposPref =  getStringValue(P2_REPOSITORY_LIST);
1205
        if(p2ReposPref != null && !p2ReposPref.isEmpty()) {
1206
            StringTokenizer p2ReposPrefST = new StringTokenizer(p2ReposPref,P2_REPOSITORIES_DELIM);
1207

    
1208
            while(p2ReposPrefST.hasMoreTokens()) {
1209
                String p2RepoStr = p2ReposPrefST.nextToken();
1210
                StringTokenizer p2ReposStrST = new StringTokenizer(p2RepoStr,P2_REPOSITORY_FIELDS_DELIM);
1211
                if(p2ReposStrST.countTokens()==3) {
1212
                    String nickname = p2ReposStrST.nextToken();
1213
                    URI uri = null;
1214
                    try {
1215
                        uri = new URI(p2ReposStrST.nextToken());
1216
                    } catch (URISyntaxException e) {
1217
                        continue;
1218
                    }
1219
                    boolean enabled = Boolean.parseBoolean(p2ReposStrST.nextToken());
1220
                    MetadataRepositoryElement mre = new MetadataRepositoryElement(null, uri, true);
1221
                    mre.setNickname(nickname);
1222
                    mre.setEnabled(enabled);
1223
                    p2Repos.add(mre);
1224
                }
1225
            }
1226
        }
1227

    
1228
        return p2Repos;
1229
    }
1230

    
1231
    /**
1232
     * enables/disables nested composite. <br>
1233
     *
1234
     * @param ctrl - Composite to be en-/disabeld
1235
     * @param enabled - boolean
1236
     */
1237
    public static void recursiveSetEnabled(Control ctrl, boolean enabled) {
1238
        if (ctrl instanceof Composite) {
1239
            Composite comp = (Composite) ctrl;
1240
            for (Control c : comp.getChildren()) {
1241
                recursiveSetEnabled(c, enabled);
1242
            }
1243
        } else {
1244
            ctrl.setEnabled(enabled);
1245
        }
1246
    }
1247

    
1248
    public static void setSortNodes(NavigatorOrderEnum nodesOrder) {
1249
        if (nodesOrder == null){
1250
            setStringValue(PreferencePredicate.TaxonNodeOrder.getKey(), null);
1251
        }else{
1252
            setStringValue(PreferencePredicate.TaxonNodeOrder.getKey(), nodesOrder.key);
1253
        }
1254

    
1255
    }
1256

    
1257
    public static NavigatorOrderEnum getSortNodes() {
1258
        return NavigatorOrderEnum.valueOf(getStringValue(PreferencePredicate.TaxonNodeOrder.getKey()));
1259

    
1260
    }
1261

    
1262
    public static boolean isNodesSortedNaturally() {
1263
        NavigatorOrderEnum value = NavigatorOrderEnum.valueOf(getStringValue(PreferencePredicate.TaxonNodeOrder.getKey()));
1264
        return value.equals(NavigatorOrderEnum.NaturalOrder);
1265

    
1266
    }
1267

    
1268
    public static boolean isNodesSortedByName() {
1269
        NavigatorOrderEnum value = NavigatorOrderEnum.valueOf(getStringValue(PreferencePredicate.TaxonNodeOrder.getKey()));
1270
        return value.equals(NavigatorOrderEnum.AlphabeticalOrder);
1271

    
1272
    }
1273

    
1274
    public static boolean isNodesSortedByNameAndRank() {
1275
        NavigatorOrderEnum value = NavigatorOrderEnum.valueOf(getStringValue(PreferencePredicate.TaxonNodeOrder.getKey()));
1276
        return value.equals(NavigatorOrderEnum.RankAndNameOrder);
1277

    
1278
    }
1279

    
1280
    public static boolean isStoreNavigatorState() {
1281
        return getBooleanValue(RESTORE_NAVIGATOR_STATE);
1282

    
1283
    }
1284

    
1285
    public static void setStoreNavigatorState(boolean selection) {
1286
        setBooleanValue(RESTORE_NAVIGATOR_STATE, selection);
1287

    
1288
    }
1289

    
1290
    public static boolean isShowUpWidgetIsDisposedMessages() {
1291
       return getBooleanValue(IS_SHOW_UP_WIDGET_IS_DISPOSED);
1292
    }
1293
    public static void setShowUpWidgetIsDisposedMessages(boolean selection) {
1294
        setBooleanValue(IS_SHOW_UP_WIDGET_IS_DISPOSED, selection);
1295
    }
1296

    
1297
    public static boolean isShowIdInVocabularyInChecklistEditor() {
1298
        String area_display = getStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey());
1299
        if (area_display.equals(TermDisplayEnum.IdInVocabulary.getKey())) {
1300
            return true;
1301
        }else{
1302
            return false;
1303
        }
1304
    }
1305
    public static boolean isShowSymbol1InChecklistEditor() {
1306
        String area_display = getStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey());
1307
        if (area_display.equals(TermDisplayEnum.Symbol1.getKey())) {
1308
            return true;
1309
        }else{
1310
            return false;
1311
        }
1312
     }
1313
    public static boolean isShowSymbol2InChecklistEditor() {
1314
        String area_display = getStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey());
1315
        if (area_display.equals(TermDisplayEnum.Symbol2.getKey())) {
1316
            return true;
1317
        }else{
1318
            return false;
1319
        }
1320
     }
1321
    public static void setAreaDisplayInChecklistEditor(String selection) {
1322
        setStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey(), selection);
1323
    }
1324

    
1325
    public static void setOwnDescriptionForChecklistEditor(boolean selection) {
1326
        setBooleanValue(PreferencePredicate.OwnDescriptionForDistributionEditor.getKey(), selection);
1327
    }
1328

    
1329
    public static boolean isOwnDescriptionForChecklistEditor() {
1330
        return getBooleanValue(PreferencePredicate.OwnDescriptionForDistributionEditor.getKey());
1331
    }
1332

    
1333
    public static TermDisplayEnum displayAreaInChecklistEditor() {
1334
        TermDisplayEnum result;
1335
        try{
1336
            result = TermDisplayEnum.byKey(getStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey()));
1337
        }catch (IllegalArgumentException e){
1338
           result = ((TermDisplayEnum) PreferencePredicate.DisplayOfAreasInDistributionEditor.getDefaultValue());
1339
        }
1340
       return result;
1341
    }
1342

    
1343
    public static TermDisplayEnum displayStatusInChecklistEditor() {
1344
        TermDisplayEnum result;
1345
        try{
1346
            result = TermDisplayEnum.byKey(getStringValue(PreferencePredicate.DisplayOfStatus.getKey()));
1347
        }catch (IllegalArgumentException e){
1348
           result = ((TermDisplayEnum) PreferencePredicate.DisplayOfStatus.getDefaultValue());
1349
        }
1350
       return result;
1351
    }
1352
    public static void setDisplayStatusInChecklistEditor(String selection) {
1353
        setStringValue(PreferencePredicate.DisplayOfStatus.getKey(), selection);
1354

    
1355
    }
1356

    
1357
    public static boolean isShowRankInChecklistEditor() {
1358
        return getBooleanValue(PreferencePredicate.ShowRankInDistributionEditor.getKey());
1359
    }
1360
    public static void setShowRankInChecklistEditor(boolean selection) {
1361
       setBooleanValue(PreferencePredicate.ShowRankInDistributionEditor.getKey(), selection);
1362
    }
1363

    
1364
    public static NameDetailsConfigurator getPreferredNameDetailsConfiguration( boolean local) {
1365
        NameDetailsConfigurator config = new NameDetailsConfigurator(true);
1366
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1367
        CdmPreference preference = null;
1368
        String value;
1369
        if (!local) {
1370
            PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.NameDetailsView);
1371
            preference =  getPreferenceFromDB(PreferencePredicate.NameDetailsView);
1372
            if (preference == null){
1373
                return null;
1374
            }
1375

    
1376
        //    setBooleanValue(ALLOW_OVERRIDE_NAME_DETAILS, preference.isAllowOverride());
1377
            value = preference.getValue();
1378
            config.setAllowOverride(preference.isAllowOverride());
1379
            //the preference value is build like this:
1380
            //<section1>:true;<section2>:false....
1381
        }else{
1382
            value = getStringValue(PreferencePredicate.NameDetailsView.getKey(), local);
1383
        }
1384
        if (value!= null){
1385
            fillNameDetailsConfigurator(config, value);
1386

    
1387

    
1388
        }else {
1389
            return null;
1390
        }
1391
        return config;
1392
    }
1393

    
1394
    public static void fillNameDetailsConfigurator(NameDetailsConfigurator config, String value) {
1395
        String [] sections = value.split(";");
1396
        Map<String, Boolean> sectionMap = new HashMap<>();
1397
        String[] sectionValues;
1398
        for (String sectionValue: sections){
1399
            if (sectionValue.contains(":")){
1400
                sectionValues = sectionValue.split(":");
1401
                sectionMap.put(sectionValues[0], Boolean.valueOf(sectionValues[1]));
1402
            }
1403
        }
1404
        for (Field field: config.getClass().getDeclaredFields()){
1405
            try {
1406
                config.getClass().getDeclaredField(field.getName()).set(config, getValue(sectionMap, field.getName()));
1407
            } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException
1408
                    | SecurityException e) {
1409
               logger.debug(e.getMessage());
1410
            }
1411
        }
1412
    }
1413

    
1414
    public static NameDetailsConfigurator getPreferredNameDetailsConfiguration() {
1415
        NameDetailsConfigurator config = new NameDetailsConfigurator(true);
1416

    
1417
        String value;
1418

    
1419
        value = getStringValue(PreferencePredicate.NameDetailsView.getKey(), false);
1420
        if (value != null){
1421
            fillNameDetailsConfigurator(config, value);
1422
        }
1423
        return config;
1424
    }
1425

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

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

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

    
1438

    
1439
    }
1440

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

    
1448
    }
1449

    
1450
    public static Abcd206ImportConfigurator getDBAbcdImportConfigurationPreference() {
1451

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

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

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

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

    
1534

    
1535
             }
1536
         }
1537
    }
1538
    public static Abcd206ImportConfigurator getLocalAbcdImportConfigurator(){
1539
        return getLocalAbcdImportConfigurator(true);
1540
    }
1541
    public static Abcd206ImportConfigurator getLocalAbcdImportConfigurator(boolean skipCheckOverride){
1542
       Abcd206ImportConfigurator config = Abcd206ImportConfigurator.NewInstance(null,null);
1543
       CdmPreference pref = CdmPreferenceCache.instance().get(PreferencePredicate.AbcdImportConfig.getKey());
1544
       if (pref.isAllowOverride()){
1545
       String configString = PreferencesUtil.getStringValue(IPreferenceKeys.LAST_USED_ABCD_CONFIG);
1546
           if (StringUtils.isBlank(configString)){
1547
               configString = getStringValue(PreferencePredicate.AbcdImportConfig.getKey(), skipCheckOverride);
1548
               extractAbcdConfiguratorFromPreferenceString(config, configString);
1549
               if (config.getNomenclaturalCode() == null){
1550
                   config.setNomenclaturalCode(getPreferredNomenclaturalCode());
1551
               }
1552
           }else{
1553
               config = Abcd206ImportConfigurator.NewInstance(null, null);
1554
               PreferencesUtil.extractAbcdConfiguratorFromPreferenceString(config, configString);
1555
           }
1556
       }else{
1557
           extractAbcdConfiguratorFromPreferenceString(config, pref.getValue());
1558
       }
1559

    
1560
       return config;
1561

    
1562
    }
1563

    
1564
    public static void updateAbcdImportConfigurationPreference() {
1565
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1566

    
1567
        CdmPreference pref = cache.findBestMatching(CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AbcdImportConfig));
1568

    
1569
        if (!getBooleanValue(prefOverrideKey(PreferencePredicate.AbcdImportConfig.getKey())) || !pref.isAllowOverride()){
1570
            resetToDBPreferenceAbcdCOnfigurator();
1571

    
1572
        }
1573
    }
1574

    
1575
    public static void resetToDBPreferenceAbcdCOnfigurator(){
1576
        Abcd206ImportConfigurator config = getDBAbcdImportConfigurationPreference();
1577
        setStringValue(PreferencePredicate.AbcdImportConfig.getKey(), config.toString());
1578

    
1579
    }
1580

    
1581
    public static boolean isSortTaxaByRankAndName() {
1582

    
1583
        return getBooleanValue(PreferencePredicate.SortTaxaByRankAndName.getKey());
1584
    }
1585

    
1586
    public static TermOrder getSortNamedAreasInDistributionEditor() {
1587
        TermOrder result;
1588
        try{
1589
            result = TermOrder.valueOf(getStringValue(PreferencePredicate.AreasSortedInDistributionEditor.getKey()));
1590
        }catch (IllegalArgumentException e){
1591
            result = (TermOrder)PreferencePredicate.AreasSortedInDistributionEditor.getDefaultValue();
1592
        }
1593
        return result;
1594
    }
1595

    
1596
    public static void setSortNamedAreasInDistributionEditor(String isSortByVocabularyOrder) {
1597
        setStringValue(PreferencePredicate.AreasSortedInDistributionEditor.getKey(), isSortByVocabularyOrder);
1598

    
1599
    }
1600

    
1601
    public static void setLastSelectedReference(
1602
            List<String> lastSelectedReferences) {
1603

    
1604
        setStringValue(PreferencesUtil.LAST_SELECTED_REFERENCES, lastSelectedReferences.toString());
1605
    }
1606

    
1607
    public static List<String> getLastSelectedReferences() {
1608

    
1609
        //IPreferenceStore preferenceStore = PreferencesUtil.getPreferenceStore();
1610
        String lastSelected = getStringValue(PreferencesUtil.LAST_SELECTED_REFERENCES);
1611
        List<String> result = new ArrayList<>();
1612
        if (!StringUtils.isBlank(lastSelected)){
1613
            Collections.addAll(result, lastSelected.substring(1,lastSelected.length()-1).split(", "));
1614
        }
1615
        return result;
1616
    }
1617

    
1618
    public static void setPreferredNamedAreasForDistributionEditor(
1619
            String saveCheckedElements, String saveGrayedElements, boolean local) {
1620
        if (local){
1621
            setStringValue(PreferencePredicate.AvailableDistributionAreaTerms.getKey(), saveCheckedElements);
1622

    
1623
        }
1624
        else{
1625
            CdmPreference preference = null;
1626

    
1627
            if (saveCheckedElements == null){
1628
                preference = getPreferenceFromDB(PreferencePredicate.AvailableDistributionAreaTerms);
1629

    
1630
                if (preference == null){
1631
                    return ;
1632
                } else{
1633
                    setStringValue(PreferencePredicate.AvailableDistributionAreaTerms.getKey(),
1634
                            saveCheckedElements);
1635
                    preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AvailableDistributionAreaTerms, saveCheckedElements);
1636
                    setPreferenceToDB(preference);
1637

    
1638
                }
1639
            } else{
1640
                preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AvailableDistributionAreaTerms, saveCheckedElements);
1641
                setPreferenceToDB(preference);
1642
                setStringValue(PreferencePredicate.AvailableDistributionAreaTerms.getKey(),
1643
                        saveCheckedElements);
1644

    
1645
            }
1646
        }
1647

    
1648
    }
1649

    
1650
    public static void setPreferredVocabulariesForDistributionEditor(String saveCheckedElements,
1651
            boolean local, boolean isOverride) {
1652
        if (local){
1653
            setStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(), saveCheckedElements);
1654
            setBooleanValue(prefOverrideKey(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey()), isOverride);
1655
        }
1656
        else{
1657
            ICdmRepository controller;
1658
            CdmPreference preference = null;
1659

    
1660
            if (saveCheckedElements == null){
1661
                preference = getPreferenceFromDB(PreferencePredicate.AvailableDistributionAreaVocabularies);
1662

    
1663
                if (preference == null){
1664
                    return ;
1665
                } else{
1666
                    setStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(),
1667
                            saveCheckedElements);
1668
                    preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AvailableDistributionAreaVocabularies, saveCheckedElements);
1669
                    preference.setAllowOverride(isOverride);
1670
                    setPreferenceToDB(preference);
1671
                }
1672
            } else{
1673
                preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AvailableDistributionAreaVocabularies, saveCheckedElements);
1674
                preference.setAllowOverride(isOverride);
1675
                setPreferenceToDB(preference);
1676
                setStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(),
1677
                        saveCheckedElements);
1678

    
1679
            }
1680
        }
1681
    }
1682

    
1683
    public static String getPreferredVocabulariesForDistributionEditor(boolean local) {
1684
        if (local){
1685

    
1686
            String pref = getStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(), local);
1687
            return pref;
1688
        }
1689
        else{
1690
            CdmPreference preference = null;
1691
            preference = getPreferenceFromDB(PreferencePredicate.AvailableDistributionAreaVocabularies);
1692
            if (preference == null){
1693
                return null;
1694
            } else{
1695
                return preference.getValue();
1696
            }
1697

    
1698
        }
1699
    }
1700

    
1701
    public static List<UUID> createUUIDListFromStringPref(String prefKey, boolean local) {
1702
        if (prefKey == null){
1703
            return null;
1704
        }
1705
        String prefValue = PreferencesUtil.getStringValue(prefKey, local);
1706
        if (prefValue == null){
1707
            return null;
1708
        }
1709
        List<UUID> uuidList = createUuidList(prefValue);
1710
        return uuidList;
1711
    }
1712

    
1713
    public static List<UUID> createUuidList(String prefValue) {
1714
        String[] stringArray = prefValue.split(";");
1715
        List<UUID> uuidList = new ArrayList();
1716
        for (String uuid: stringArray){
1717
            if (!StringUtils.isBlank(uuid)){
1718
                uuidList.add(UUID.fromString(uuid));
1719
            }
1720
        }
1721
        return uuidList;
1722
    }
1723

    
1724
    public static boolean getFilterCommonNameReferences(){
1725
        Boolean result = getBooleanValue(PreferencesUtil.FILTER_COMMON_NAME_REFERENCES);
1726
        if (result == null){
1727
            return false;
1728
        }
1729
        return result;
1730
    }
1731

    
1732
    public static void updateDBPreferences() {
1733

    
1734

    
1735
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1736
        cache.getAllTaxEditorDBPreferences();
1737

    
1738
        //ABCD Configurator
1739

    
1740
        //updateAbcdImportConfigurationPreference();
1741

    
1742
        //Name Details
1743
        NameDetailsConfigurator config = getPreferredNameDetailsConfiguration(false);
1744
        //    if (config != null ){
1745
        //        if (!getBooleanValue(OVERRIDE_NAME_DETAILS) ||  !getBooleanValue(ALLOW_OVERRIDE_NAME_DETAILS)){
1746
        //            setPreferredNameDetailsConfiguration(config, false);
1747
        //        }
1748
        //    }
1749

    
1750
    }
1751

    
1752
    public static void setPreferencesToDB(List<CdmPreference> preferences) {
1753

    
1754
        ICdmRepository controller;
1755
        //try{
1756
            if(CdmStore.isActive()){
1757
                controller = CdmStore.getCurrentApplicationConfiguration();
1758
                for (CdmPreference preference: preferences){
1759
                    if (preference.getValue() == null && preference.isAllowOverride()){
1760
                        controller.getPreferenceService().remove(preference.getKey());
1761

    
1762
                    }else{
1763
                        controller.getPreferenceService().set(preference);
1764

    
1765
                    }
1766

    
1767
                }
1768
                CdmPreferenceCache.instance().getAllTaxEditorDBPreferences();
1769

    
1770
            }
1771
        /*}catch(Exception e){
1772
            e.printStackTrace();
1773
        }*/
1774
    }
1775

    
1776
    /**
1777
     * Returns whether the named preference is known.
1778
     * @param prefKey the key of the preference
1779
     * @return <code>true</code> if the preference is known, <code>false</code> otherwise
1780
     */
1781
    public static boolean contains(String prefKey){
1782
        return getPreferenceStore().contains(prefKey(prefKey));
1783
    }
1784

    
1785
    /**
1786
     *
1787
     */
1788
    public static TermTree getPreferredFeatureTreeForNameDescription(boolean createNew) {
1789
        if(preferredNameFeatureTree != null && !createNew){
1790
            return preferredNameFeatureTree;
1791
        }
1792
        createPreferredFeatureTreeForNameDescription();
1793
        return preferredNameFeatureTree;
1794

    
1795
    }
1796

    
1797
    public static void createPreferredFeatureTreeForNameDescription() {
1798

    
1799
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1800
        CdmPreference pref = cache.get(PreferencePredicate.NameFeatures.getKey());
1801
        List<Feature> terms = new ArrayList();
1802
        boolean override = PreferencesUtil.getBooleanValue(PreferencesUtil.createOverridePreferenceString(PreferencePredicate.NameFeatures.getKey()));
1803

    
1804
        List<UUID> uuids = PreferencesUtil.createUUIDListFromStringPref(PreferencePredicate.NameFeatures.getKey(), false);
1805
        if (uuids != null && !uuids.isEmpty()){
1806
            terms = CdmStore.getTermManager().getTerms(uuids, Feature.class);
1807
        }
1808

    
1809

    
1810

    
1811

    
1812
       if (terms.isEmpty()){
1813
           terms.addAll(TermStore.getTerms(CdmStore.getService(IVocabularyService.class).load(VocabularyEnum.NameFeature.getUuid()), null));
1814

    
1815
        }
1816
        terms.remove(Feature.PROTOLOGUE());
1817
        if (terms.isEmpty()){
1818
            preferredNameFeatureTree = TermEditorInput.getDefaultNameFeatureTree();
1819
        }else{
1820
            preferredNameFeatureTree = TermTree.NewInstance(terms);
1821
        }
1822

    
1823

    
1824
    }
1825

    
1826
    /**
1827
     * @param prefsToDelete
1828
     */
1829
    public static void removeFromDB(List<CdmPreference> prefsToDelete) {
1830
        ICdmRepository controller;
1831
        //try{
1832
            if(CdmStore.isActive()){
1833
                controller = CdmStore.getCurrentApplicationConfiguration();
1834
                for (CdmPreference preference: prefsToDelete){
1835
                    controller.getPreferenceService().remove(preference.getKey());
1836
                }
1837
                CdmPreferenceCache.instance().getAllTaxEditorDBPreferences();
1838
            }
1839

    
1840
    }
1841

    
1842
    /**
1843
     * @return
1844
     */
1845
    public static TermTree<?> getPreferredFeatureTreeForTaxonDescription(boolean createNew) {
1846
        if(preferredTaxonFeatureTree != null && !createNew){
1847
            return preferredTaxonFeatureTree;
1848
        }
1849
        createPreferredFeatureTreeForTaxonDescription();
1850
        return preferredTaxonFeatureTree;
1851

    
1852
    }
1853

    
1854
    public static void createPreferredFeatureTreeForTaxonDescription() {
1855

    
1856
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1857
        CdmPreference pref = cache.get(PreferencePredicate.TaxonFeatures.getKey());
1858
        List<Feature> terms;
1859
        boolean override = PreferencesUtil.getBooleanValue(PreferencesUtil.createOverridePreferenceString(PreferencePredicate.TaxonFeatures.getKey()));
1860
        List<UUID> uuids = PreferencesUtil.createUUIDListFromStringPref(PreferencePredicate.TaxonFeatures.getKey(), false);
1861
        terms = CdmStore.getTermManager().getTerms(uuids, Feature.class);
1862
        if (terms == null || terms.isEmpty()){
1863
            terms= CdmStore.getTermManager().getPreferredTerms(TermType.Feature);
1864
            TermVocabulary nameVocabulary = CdmStore.getService(IVocabularyService.class).load(VocabularyEnum.NameFeature.getUuid());
1865
            Set<Feature> nameFeature = nameVocabulary.getTerms();
1866
            terms.removeAll(nameFeature);
1867

    
1868
        }
1869

    
1870
        if (terms.isEmpty()){
1871
            preferredTaxonFeatureTree = TermEditorInput.getDefaultFeatureTree();
1872
        }else{
1873
            preferredTaxonFeatureTree = TermTree.NewInstance(terms);
1874
        }
1875

    
1876

    
1877
    }
1878

    
1879

    
1880

    
1881

    
1882
}
(39-39/55)