Project

General

Profile

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

    
10
package eu.etaxonomy.taxeditor.preference;
11

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

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

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

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

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

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

    
106
    private static TermTree<Feature> preferredNameFeatureTree;
107

    
108
    private static TermTree<Feature> preferredTaxonFeatureTree;
109

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

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

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

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

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

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

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

    
163
            }
164

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

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

    
189
    }
190

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

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

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

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

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

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

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

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

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

    
229
        CdmPreference pref = getDBPreferenceValue(name);
230
        String prefValue = null;
231
        String overrideKey =  createPreferenceString(createOverridePreferenceString(name));
232
        boolean override = getPreferenceStore().getBoolean(overrideKey);
233

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

    
261
    }
262

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

    
267
    private static CdmPreference getDBPreferenceValue(String name) {
268
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
269
        CdmPreference pref = null;
270
//
271
        pref = cache.get(name);
272
//        if (pref == null ){
273
//            //get default value for Predicate
274
//            IPreferencePredicate pred = PreferencePredicate.getByKey(name);
275
//            if (pred != null){
276
//                if (pred.getDefaultValue() != null){
277
//                    pref = CdmPreference.NewTaxEditorInstance(pred, pred.getDefaultValue().toString());
278
//                }else{
279
//                    pref = CdmPreference.NewTaxEditorInstance(pred, null);
280
//                }
281
//                pref.setAllowOverride(true);
282
//            }
283
//        }
284
        return pref;
285
    }
286

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

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

    
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

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

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

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

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

    
358
    }
359

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

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

    
392
    }
393

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

    
422
    }
423

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

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

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

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

    
482
            }
483
        }
484
        return null;
485

    
486

    
487

    
488
    }
489

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

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

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

    
511
    }
512

    
513
    public static NomenclaturalCode getPreferredNomenclaturalCode() {
514

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

    
517

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

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

    
530
        return getPreferredNomenclaturalCode(preferredCode);
531

    
532
    }
533

    
534
    public static NomenclaturalCode getPreferredNomenclaturalCode(String preferenceKeyNomenclaturalCode) {
535

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

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

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

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

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

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

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

    
578
        return pref;
579

    
580
    }
581

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

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

    
596
        return prefs;
597

    
598
    }
599

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

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

    
616

    
617

    
618
    }
619

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

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

    
633
        return pref;
634

    
635
    }
636

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

    
653
    }
654

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
795

    
796

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

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

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

    
832
        return configurator;
833
    }
834

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

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

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

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

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

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

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

    
894

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

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

    
902
        }
903

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

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

    
922

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

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

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

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

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

    
955
    }
956

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

    
963

    
964

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

    
980
        int index = StringUtils.lastIndexOf(preference.getValue(), ".");
981
        UUID uuid = UUID.fromString(preference.getValue().substring(index +1, preference.getValue().length()));
982
        NomenclaturalCode preferredCode = NomenclaturalCode.getByUuid(uuid);
983

    
984
        setStringValue(PreferencePredicate.NomenclaturalCode.getKey(),
985
                getPreferenceKey(preferredCode));
986

    
987
    }
988

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

    
1002
    public static String getMapServiceAccessPoint() {
1003
        return getStringValue(EDIT_MAP_SERVICE_ACCES_POINT);
1004
    }
1005

    
1006
    public static boolean shouldConnectAtStartUp() {
1007
        //FIXME :  force SHOULD_CONNECT_AT_STARTUP to false (ticket 3828) until resolution
1008
        //return getBooleanValue(SHOULD_CONNECT_AT_STARTUP);
1009
        return false;
1010
    }
1011

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

    
1021
        if (tree == null || tree.getId() == 0) {
1022
            return null;
1023
        }
1024
        return tree;
1025
    }
1026

    
1027
    public static TermTree getDefaultFeatureTreeForStructuredDescription() {
1028
        String uuidString = getStringValue(
1029
                FEATURE_TREE_DEFAULT_STRUCTURE);
1030
        return StringUtils.isBlank(uuidString) ? null : CdmStore.getService(
1031
                ITermTreeService.class).load(UUID.fromString(uuidString));
1032
    }
1033

    
1034
    public static void setSortRanksHierarchichally(boolean selection) {
1035
        setBooleanValue(SORT_RANKS_HIERARCHICHALLY, selection);
1036
    }
1037

    
1038
    public static boolean getSortRanksHierarchichally() {
1039
        return getBooleanValue(SORT_RANKS_HIERARCHICHALLY);
1040
    }
1041

    
1042
    public static boolean isMultilanguageTextEditingCapability() {
1043
        return getBooleanValue(
1044
                MULTILANGUAGE_TEXT_EDITING_CAPABILITY);
1045
    }
1046

    
1047
    public static Language getGlobalLanguage() {
1048

    
1049

    
1050
        String languageUuidString = getStringValue(
1051
                GLOBAL_LANGUAGE_UUID);
1052

    
1053
        if(!CdmStore.isActive()) {
1054
            MessagingUtils.noDataSourceWarningDialog(languageUuidString);
1055
            return null;
1056
        }
1057

    
1058
        if (CdmUtils.isBlank(languageUuidString)) {
1059
            return Language.getDefaultLanguage();
1060
        }
1061

    
1062
        UUID languageUuid = UUID.fromString(languageUuidString);
1063
        return (Language) CdmStore.getService(ITermService.class).load(
1064
                languageUuid);
1065
    }
1066

    
1067
    public static void setGlobalLanguage(Language language) {
1068
        if(language != null) {
1069
            setStringValue(GLOBAL_LANGUAGE_UUID,language.getUuid().toString());
1070
            CdmStore.setDefaultLanguage(language);
1071
        }
1072

    
1073
    }
1074

    
1075
    public static Map<MarkerType, Boolean> getEditMarkerTypePreferences() {
1076
        List<MarkerType> markerTypes = CdmStore.getTermManager()
1077
                .getPreferredTerms(MarkerType.class);
1078

    
1079
        Map<MarkerType, Boolean> result = new HashMap<MarkerType, Boolean>();
1080

    
1081
        for (MarkerType markerType : markerTypes) {
1082
            String name = getMarkerTypeEditingPreferenceKey(markerType);
1083
            Boolean value = getBooleanValue(name);
1084

    
1085
            result.put(markerType, value);
1086
        }
1087

    
1088
        return result;
1089
    }
1090

    
1091
    public static void setEditMarkerTypePreferences(
1092
            Map<MarkerType, Boolean> markerTypeEditingMap) {
1093
        for (MarkerType markerType : markerTypeEditingMap.keySet()) {
1094
            String name = getMarkerTypeEditingPreferenceKey(markerType);
1095
            setBooleanValue(name,
1096
                    markerTypeEditingMap.get(markerType));
1097
        }
1098

    
1099
    }
1100

    
1101
    private static String getMarkerTypeEditingPreferenceKey(
1102
            MarkerType markerType) {
1103
        markerType = HibernateProxyHelper.deproxy(markerType);
1104
        return markerType.getClass().getName() + EDIT_MARKER_TYPE_PREFIX;
1105
    }
1106

    
1107
    public static void setEditMarkerTypePreference(MarkerType markerType,
1108
            boolean edit) {
1109
        setBooleanValue(
1110
                getMarkerTypeEditingPreferenceKey(markerType), edit);
1111
    }
1112

    
1113
    public static DerivedUnitFacadeConfigurator getDerivedUnitConfigurator() {
1114
        DerivedUnitFacadeConfigurator configurator = DerivedUnitFacadeConfigurator
1115
                .NewInstance();
1116
        configurator.setMoveDerivedUnitMediaToGallery(true);
1117
        configurator.setMoveFieldObjectMediaToGallery(true);
1118
        return configurator;
1119
    }
1120

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

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

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

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

    
1200

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

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

    
1232
        return p2Repos;
1233
    }
1234

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

    
1252
    public static void setSortNodes(NavigatorOrderEnum nodesOrder) {
1253
        if (nodesOrder == null){
1254
            setStringValue(PreferencePredicate.TaxonNodeOrder.getKey(), null);
1255
        }else{
1256
            setStringValue(PreferencePredicate.TaxonNodeOrder.getKey(), nodesOrder.key);
1257
        }
1258

    
1259
    }
1260

    
1261
    public static NavigatorOrderEnum getSortNodes() {
1262
        return NavigatorOrderEnum.valueOf(getStringValue(PreferencePredicate.TaxonNodeOrder.getKey()));
1263

    
1264
    }
1265

    
1266
    public static boolean isNodesSortedNaturally() {
1267
        NavigatorOrderEnum value = NavigatorOrderEnum.valueOf(getStringValue(PreferencePredicate.TaxonNodeOrder.getKey()));
1268
        return value.equals(NavigatorOrderEnum.NaturalOrder);
1269

    
1270
    }
1271

    
1272
    public static boolean isNodesSortedByName() {
1273
        NavigatorOrderEnum value = NavigatorOrderEnum.valueOf(getStringValue(PreferencePredicate.TaxonNodeOrder.getKey()));
1274
        return value.equals(NavigatorOrderEnum.AlphabeticalOrder);
1275

    
1276
    }
1277

    
1278
    public static boolean isNodesSortedByNameAndRank() {
1279
        NavigatorOrderEnum value = NavigatorOrderEnum.valueOf(getStringValue(PreferencePredicate.TaxonNodeOrder.getKey()));
1280
        return value.equals(NavigatorOrderEnum.RankAndNameOrder);
1281

    
1282
    }
1283

    
1284
    public static boolean isStoreNavigatorState() {
1285
        return getBooleanValue(RESTORE_NAVIGATOR_STATE);
1286

    
1287
    }
1288

    
1289
    public static void setStoreNavigatorState(boolean selection) {
1290
        setBooleanValue(RESTORE_NAVIGATOR_STATE, selection);
1291

    
1292
    }
1293

    
1294
    public static boolean isShowUpWidgetIsDisposedMessages() {
1295
       return getBooleanValue(IS_SHOW_UP_WIDGET_IS_DISPOSED);
1296
    }
1297
    public static void setShowUpWidgetIsDisposedMessages(boolean selection) {
1298
        setBooleanValue(IS_SHOW_UP_WIDGET_IS_DISPOSED, selection);
1299
    }
1300

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

    
1329
    public static void setOwnDescriptionForChecklistEditor(boolean selection) {
1330
        setBooleanValue(PreferencePredicate.OwnDescriptionForDistributionEditor.getKey(), selection);
1331
    }
1332

    
1333
    public static boolean isOwnDescriptionForChecklistEditor() {
1334
        return getBooleanValue(PreferencePredicate.OwnDescriptionForDistributionEditor.getKey());
1335
    }
1336

    
1337
    public static TermDisplayEnum displayAreaInChecklistEditor() {
1338
        TermDisplayEnum result;
1339
        try{
1340
            result = TermDisplayEnum.byKey(getStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey()));
1341
        }catch (IllegalArgumentException e){
1342
           result = ((TermDisplayEnum) PreferencePredicate.DisplayOfAreasInDistributionEditor.getDefaultValue());
1343
        }
1344
       return result;
1345
    }
1346

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

    
1359
    }
1360

    
1361
    public static boolean isShowRankInChecklistEditor() {
1362
        return getBooleanValue(PreferencePredicate.ShowRankInDistributionEditor.getKey());
1363
    }
1364
    public static void setShowRankInChecklistEditor(boolean selection) {
1365
       setBooleanValue(PreferencePredicate.ShowRankInDistributionEditor.getKey(), selection);
1366
    }
1367

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

    
1380
        //    setBooleanValue(ALLOW_OVERRIDE_NAME_DETAILS, preference.isAllowOverride());
1381
            value = preference.getValue();
1382
            config.setAllowOverride(preference.isAllowOverride());
1383
            //the preference value is build like this:
1384
            //<section1>:true;<section2>:false....
1385
        }else{
1386
            value = getStringValue(PreferencePredicate.NameDetailsView.getKey(), local);
1387
        }
1388
        if (value!= null){
1389
            String [] sections = value.split(";");
1390
            Map<String, Boolean> sectionMap = new HashMap<String, Boolean>();
1391
            String[] sectionValues;
1392
            for (String sectionValue: sections){
1393
                sectionValues = sectionValue.split(":");
1394
                sectionMap.put(sectionValues[0], Boolean.valueOf(sectionValues[1]));
1395
            }
1396
            config.setSimpleDetailsViewActivated(getValue(sectionMap, "simpleViewActivated"));
1397
            config.setTaxonSectionActivated(getValue(sectionMap, "taxon"));
1398
            config.setSecDetailsActivated(getValue(sectionMap, "taxon.SecDetails"));
1399
            config.setSecEnabled(getValue(sectionMap, "taxon.SecEnabled"));
1400
            config.setLSIDActivated(getValue(sectionMap, "lsid"));
1401
            config.setNomenclaturalCodeActived(getValue(sectionMap, "nc"));
1402
            config.setAppendedPhraseActivated(getValue(sectionMap, "ap"));
1403
            config.setRankActivated(getValue(sectionMap, "rank"));
1404
            config.setNameCacheActivated(getValue(sectionMap, "nameCache"));
1405
            config.setAtomisedEpithetsActivated(getValue(sectionMap, "atomisedEpithets"));
1406
            config.setAuthorshipSectionActivated(getValue(sectionMap,"author"));
1407
            config.setAuthorCacheActivated(getValue(sectionMap, "authorCache"));
1408
            config.setNomenclaturalReferenceSectionActivated(sectionMap.get("nomRef"));
1409
            config.setNomenclaturalStatusSectionActivated(getValue(sectionMap, "nomStat"));
1410
            config.setProtologueActivated(getValue(sectionMap,"protologue"));
1411
            config.setTypeDesignationSectionActivated(getValue(sectionMap,"typeDes"));
1412
            config.setNameRelationsSectionActivated(getValue(sectionMap,"nameRelation"));
1413
            config.setHybridActivated(getValue(sectionMap,"hybrid"));
1414
            config.setNameApprobiationActivated(getValue(sectionMap, "nameApproviation"));
1415
        }else {
1416
            return null;
1417
        }
1418
        return config;
1419
    }
1420

    
1421
    public static NameDetailsConfigurator getPreferredNameDetailsConfiguration() {
1422
        NameDetailsConfigurator config = new NameDetailsConfigurator(true);
1423

    
1424
        String value;
1425

    
1426
        value = getStringValue(PreferencePredicate.NameDetailsView.getKey(), false);
1427
        if (value != null){
1428
            String [] sections = value.split(";");
1429
            Map<String, Boolean> sectionMap = new HashMap<String, Boolean>();
1430
            String[] sectionValues;
1431
            for (String sectionValue: sections){
1432
                sectionValues = sectionValue.split(":");
1433
                sectionMap.put(sectionValues[0], Boolean.valueOf(sectionValues[1]));
1434
            }
1435

    
1436
            config.setSimpleDetailsViewActivated(getValue(sectionMap, "simpleViewActivated"));
1437

    
1438
            config.setTaxonSectionActivated(getValue(sectionMap, "taxon"));
1439

    
1440
            config.setSecDetailsActivated(getValue(sectionMap, "taxon.SecDetails"));
1441
            config.setSecEnabled(getValue(sectionMap, "taxon.SecEnabled"));
1442

    
1443
            config.setLSIDActivated(getValue(sectionMap, "lsid"));
1444

    
1445
            config.setNomenclaturalCodeActived(getValue(sectionMap, "nc"));
1446

    
1447
            config.setAppendedPhraseActivated(getValue(sectionMap, "ap"));
1448

    
1449
            config.setRankActivated(getValue(sectionMap, "rank"));
1450

    
1451
            config.setAtomisedEpithetsActivated(getValue(sectionMap, "atomisedEpithets"));
1452

    
1453
            config.setAuthorshipSectionActivated(getValue(sectionMap,"author"));
1454

    
1455
            config.setNomenclaturalReferenceSectionActivated(sectionMap.get("nomRef"));
1456

    
1457
            config.setNomenclaturalStatusSectionActivated(getValue(sectionMap, "nomStat"));
1458

    
1459
            config.setProtologueActivated(getValue(sectionMap,"protologue"));
1460

    
1461
            config.setTypeDesignationSectionActivated(getValue(sectionMap,"typeDes"));
1462

    
1463
            config.setNameRelationsSectionActivated(getValue(sectionMap,"nameRelation"));
1464

    
1465
                config.setHybridActivated(getValue(sectionMap,"hybrid"));
1466
        }
1467
        return config;
1468
    }
1469

    
1470
    public static void setPreferredNameDetailsConfiguration(NameDetailsConfigurator config, boolean local) {
1471
        CdmPreference preference = null;
1472

    
1473
        if (!local) {
1474
            preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.NameDetailsView, config.toString());
1475

    
1476
            setPreferenceToDB(preference);
1477
        }
1478
        else{
1479
            setStringValue(PreferencePredicate.NameDetailsView.getKey(), config.toString());
1480
        }
1481

    
1482

    
1483
    }
1484

    
1485
    private static Boolean getValue(Map<String, Boolean> sectionMap, String string) {
1486
        if (sectionMap.containsKey(string)){
1487
            return sectionMap.get(string);
1488
        }else{
1489
            return true;
1490
        }
1491

    
1492
    }
1493

    
1494
    public static Abcd206ImportConfigurator getDBAbcdImportConfigurationPreference() {
1495

    
1496
        Abcd206ImportConfigurator config = Abcd206ImportConfigurator.NewInstance(null,null);
1497
        ICdmRepository controller;
1498
        controller = CdmStore.getCurrentApplicationConfiguration();
1499
        PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AbcdImportConfig);
1500
        CdmPreference preference = null;
1501
        if (controller == null){
1502
            return null;
1503
        }
1504
        preference = controller.getPreferenceService().find(key);
1505
        if (preference == null){
1506
            return config;
1507
         } else{
1508
             String configString = preference.getValue();
1509
             extractAbcdConfiguratorFromPreferenceString(config, configString);
1510
         }
1511
        return config;
1512
    }
1513

    
1514
    public static void extractAbcdConfiguratorFromPreferenceString(Abcd206ImportConfigurator config,
1515
            String configString) {
1516
        if(configString!=null){
1517
             String[] configArray = configString.split(";");
1518

    
1519
             for (String configItem: configArray){
1520
                 String[] keyValue = configItem.split(":");
1521
                 String keyString = keyValue[0];
1522
                 String valueString = null;
1523
                 if (keyValue.length>1){
1524
                     valueString = keyValue[1];
1525
                     if (keyValue.length>2){
1526

    
1527
                         for (int index = 2; index< keyValue.length; index++){
1528
                             valueString += ":"+ keyValue[index];
1529
                         }
1530
                     }
1531
                 }
1532
                 if (keyString.equals("ignoreImportOfExistingSpecimen")){
1533
                     config.setIgnoreImportOfExistingSpecimen(Boolean.valueOf(valueString));
1534
                 }else if (keyString.equals("addIndividualsAssociationsSuchAsSpecimenAndObservations")){
1535
                     config.setAddIndividualsAssociationsSuchAsSpecimenAndObservations(Boolean.valueOf(valueString));
1536
                 }else if (keyString.equals("reuseExistingTaxaWhenPossible")){
1537
                     config.setReuseExistingTaxaWhenPossible(Boolean.valueOf(valueString));
1538
                 }else if (keyString.equals("ignoreAuthorship")){
1539
                     config.setIgnoreAuthorship(Boolean.valueOf(valueString));
1540
                 }else if (keyString.equals("addMediaAsMediaSpecimen")){
1541
                     config.setAddMediaAsMediaSpecimen(Boolean.valueOf(valueString));
1542
                 }else if (keyString.equals("reuseExistingMetaData")){
1543
                     config.setReuseExistingMetaData(Boolean.valueOf(valueString));
1544
                 }else if (keyString.equals("reuseExistingDescriptiveGroups")){
1545
                     config.setReuseExistingDescriptiveGroups(Boolean.valueOf(valueString));
1546
                 }else if (keyString.equals("allowReuseOtherClassifications")){
1547
                     config.setAllowReuseOtherClassifications(Boolean.valueOf(valueString));
1548
                 }else if (keyString.equals("deduplicateReferences")){
1549
                     config.setDeduplicateReferences(Boolean.valueOf(valueString));
1550
                 }else if (keyString.equals("deduplicateClassifications")){
1551
                     config.setDeduplicateClassifications(Boolean.valueOf(valueString));
1552
                 }else if (keyString.equals("moveNewTaxaToDefaultClassification")){
1553
                     config.setMoveNewTaxaToDefaultClassification(Boolean.valueOf(valueString));
1554
                 }else if (keyString.equals("mapUnitIdToCatalogNumber")){
1555
                     config.setMapUnitIdToCatalogNumber(Boolean.valueOf(valueString));
1556
                 }else if (keyString.equals("mapUnitIdToAccessionNumber")){
1557
                     config.setMapUnitIdToAccessionNumber(Boolean.valueOf(valueString));
1558
                 }else if (keyString.equals("mapUnitIdToBarcode")){
1559
                     config.setMapUnitIdToBarcode(Boolean.valueOf(valueString));
1560
                 }else if (keyString.equals("overwriteExistingSpecimens")){
1561
                     config.setOverwriteExistingSpecimens(Boolean.valueOf(valueString));
1562
                 }else if (keyString.equals("nomenclaturalCode")){
1563
                     config.setNomenclaturalCode(NomenclaturalCode.fromString(valueString));
1564
                 }else if (keyString.equals("removeCountryFromLocalityText")){
1565
                     config.setRemoveCountryFromLocalityText(Boolean.valueOf(valueString));
1566
                 }else if (keyString.equals("getSiblings")){
1567
                     config.setGetSiblings(Boolean.valueOf(valueString));
1568
                 }else if (keyString.equals("dnaSource")){
1569
                     try{
1570
                         config.setDnaSoure(URI.create(valueString));
1571
                     }catch(Exception e){
1572
                         config.setDnaSoure(null);
1573
                     }
1574
                 }else{
1575
                     logger.debug("This key of the abcd configurator needs to be added to the transformer: " + keyString);
1576
                 }
1577

    
1578

    
1579
             }
1580
         }
1581
    }
1582

    
1583
    public static Abcd206ImportConfigurator getLocalAbcdImportConfigurator(){
1584
       Abcd206ImportConfigurator config = Abcd206ImportConfigurator.NewInstance(null,null);
1585
       String configString = getStringValue(PreferencePredicate.AbcdImportConfig.getKey(), true);
1586
       extractAbcdConfiguratorFromPreferenceString(config, configString);
1587
       return config;
1588

    
1589
    }
1590

    
1591
    public static void updateAbcdImportConfigurationPreference() {
1592
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1593

    
1594
        CdmPreference pref = cache.findBestMatching(CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AbcdImportConfig));
1595

    
1596
        if (!getBooleanValue(prefOverrideKey(PreferencePredicate.AbcdImportConfig.getKey())) || !pref.isAllowOverride()){
1597
            resetToDBPreferenceAbcdCOnfigurator();
1598

    
1599
        }
1600
    }
1601

    
1602
    public static void resetToDBPreferenceAbcdCOnfigurator(){
1603
        Abcd206ImportConfigurator config = getDBAbcdImportConfigurationPreference();
1604
        setStringValue(PreferencePredicate.AbcdImportConfig.getKey(), config.toString());
1605

    
1606
    }
1607

    
1608
    public static boolean isSortTaxaByRankAndName() {
1609

    
1610
        return getBooleanValue(PreferencePredicate.SortTaxaByRankAndName.getKey());
1611
    }
1612

    
1613
    public static TermOrder getSortNamedAreasInDistributionEditor() {
1614
        TermOrder result;
1615
        try{
1616
            result = TermOrder.valueOf(getStringValue(PreferencePredicate.AreasSortedInDistributionEditor.getKey()));
1617
        }catch (IllegalArgumentException e){
1618
            result = (TermOrder)PreferencePredicate.AreasSortedInDistributionEditor.getDefaultValue();
1619
        }
1620
        return result;
1621
    }
1622

    
1623
    public static void setSortNamedAreasInDistributionEditor(String isSortByVocabularyOrder) {
1624
        setStringValue(PreferencePredicate.AreasSortedInDistributionEditor.getKey(), isSortByVocabularyOrder);
1625

    
1626
    }
1627

    
1628
    public static void setLastSelectedReference(
1629
            List<String> lastSelectedReferences) {
1630

    
1631
        setStringValue(PreferencesUtil.LAST_SELECTED_REFERENCES, lastSelectedReferences.toString());
1632
    }
1633

    
1634
    public static List<String> getLastSelectedReferences() {
1635

    
1636
        //IPreferenceStore preferenceStore = PreferencesUtil.getPreferenceStore();
1637
        String lastSelected = getStringValue(PreferencesUtil.LAST_SELECTED_REFERENCES);
1638
        List<String> result = new ArrayList<>();
1639
        if (!StringUtils.isBlank(lastSelected)){
1640
            Collections.addAll(result, lastSelected.substring(1,lastSelected.length()-1).split(", "));
1641
        }
1642
        return result;
1643
    }
1644

    
1645
    public static void setPreferredNamedAreasForDistributionEditor(
1646
            String saveCheckedElements, String saveGrayedElements, boolean local) {
1647
        if (local){
1648
            setStringValue(PreferencePredicate.AvailableDistributionAreaTerms.getKey(), saveCheckedElements);
1649

    
1650
        }
1651
        else{
1652
            CdmPreference preference = null;
1653

    
1654
            if (saveCheckedElements == null){
1655
                preference = getPreferenceFromDB(PreferencePredicate.AvailableDistributionAreaTerms);
1656

    
1657
                if (preference == null){
1658
                    return ;
1659
                } else{
1660
                    setStringValue(PreferencePredicate.AvailableDistributionAreaTerms.getKey(),
1661
                            saveCheckedElements);
1662
                    preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AvailableDistributionAreaTerms, saveCheckedElements);
1663
                    setPreferenceToDB(preference);
1664

    
1665
                }
1666
            } else{
1667
                preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AvailableDistributionAreaTerms, saveCheckedElements);
1668
                setPreferenceToDB(preference);
1669
                setStringValue(PreferencePredicate.AvailableDistributionAreaTerms.getKey(),
1670
                        saveCheckedElements);
1671

    
1672
            }
1673
        }
1674

    
1675
    }
1676

    
1677
    public static void setPreferredVocabulariesForDistributionEditor(String saveCheckedElements,
1678
            boolean local, boolean isOverride) {
1679
        if (local){
1680
            setStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(), saveCheckedElements);
1681
            setBooleanValue(prefOverrideKey(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey()), isOverride);
1682
        }
1683
        else{
1684
            ICdmRepository controller;
1685
            CdmPreference preference = null;
1686

    
1687
            if (saveCheckedElements == null){
1688
                preference = getPreferenceFromDB(PreferencePredicate.AvailableDistributionAreaVocabularies);
1689

    
1690
                if (preference == null){
1691
                    return ;
1692
                } else{
1693
                    setStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(),
1694
                            saveCheckedElements);
1695
                    preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AvailableDistributionAreaVocabularies, saveCheckedElements);
1696
                    preference.setAllowOverride(isOverride);
1697
                    setPreferenceToDB(preference);
1698
                }
1699
            } else{
1700
                preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AvailableDistributionAreaVocabularies, saveCheckedElements);
1701
                preference.setAllowOverride(isOverride);
1702
                setPreferenceToDB(preference);
1703
                setStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(),
1704
                        saveCheckedElements);
1705

    
1706
            }
1707
        }
1708
    }
1709

    
1710
    public static String getPreferredVocabulariesForDistributionEditor(boolean local) {
1711
        if (local){
1712

    
1713
            String pref = getStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(), local);
1714
            return pref;
1715
        }
1716
        else{
1717
            CdmPreference preference = null;
1718
            preference = getPreferenceFromDB(PreferencePredicate.AvailableDistributionAreaVocabularies);
1719
            if (preference == null){
1720
                return null;
1721
            } else{
1722
                return preference.getValue();
1723
            }
1724

    
1725
        }
1726
    }
1727

    
1728
    public static List<UUID> createUUIDListFromStringPref(String prefKey, boolean local) {
1729
        if (prefKey == null){
1730
            return null;
1731
        }
1732
        String prefValue = PreferencesUtil.getStringValue(prefKey, local);
1733
        if (prefValue == null){
1734
            return null;
1735
        }
1736
        List<UUID> uuidList = createUuidList(prefValue);
1737
        return uuidList;
1738
    }
1739

    
1740
    public static List<UUID> createUuidList(String prefValue) {
1741
        String[] stringArray = prefValue.split(";");
1742
        List<UUID> uuidList = new ArrayList();
1743
        for (String uuid: stringArray){
1744
            if (!StringUtils.isBlank(uuid)){
1745
                uuidList.add(UUID.fromString(uuid));
1746
            }
1747
        }
1748
        return uuidList;
1749
    }
1750

    
1751
    public static boolean getFilterCommonNameReferences(){
1752
        Boolean result = getBooleanValue(PreferencesUtil.FILTER_COMMON_NAME_REFERENCES);
1753
        if (result == null){
1754
            return false;
1755
        }
1756
        return result;
1757
    }
1758

    
1759
    public static void updateDBPreferences() {
1760

    
1761

    
1762
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1763
        cache.getAllTaxEditorDBPreferences();
1764

    
1765
        //ABCD Configurator
1766

    
1767
        //updateAbcdImportConfigurationPreference();
1768

    
1769
        //Name Details
1770
        NameDetailsConfigurator config = getPreferredNameDetailsConfiguration(false);
1771
        //    if (config != null ){
1772
        //        if (!getBooleanValue(OVERRIDE_NAME_DETAILS) ||  !getBooleanValue(ALLOW_OVERRIDE_NAME_DETAILS)){
1773
        //            setPreferredNameDetailsConfiguration(config, false);
1774
        //        }
1775
        //    }
1776

    
1777
    }
1778

    
1779
    public static void setPreferencesToDB(List<CdmPreference> preferences) {
1780

    
1781
        ICdmRepository controller;
1782
        //try{
1783
            if(CdmStore.isActive()){
1784
                controller = CdmStore.getCurrentApplicationConfiguration();
1785
                for (CdmPreference preference: preferences){
1786
                    if (preference.getValue() == null && preference.isAllowOverride()){
1787
                        controller.getPreferenceService().remove(preference.getKey());
1788

    
1789
                    }else{
1790
                        controller.getPreferenceService().set(preference);
1791

    
1792
                    }
1793

    
1794
                }
1795
                CdmPreferenceCache.instance().getAllTaxEditorDBPreferences();
1796

    
1797
            }
1798
        /*}catch(Exception e){
1799
            e.printStackTrace();
1800
        }*/
1801
    }
1802

    
1803
    /**
1804
     * Returns whether the named preference is known.
1805
     * @param prefKey the key of the preference
1806
     * @return <code>true</code> if the preference is known, <code>false</code> otherwise
1807
     */
1808
    public static boolean contains(String prefKey){
1809
        return getPreferenceStore().contains(prefKey(prefKey));
1810
    }
1811

    
1812
    /**
1813
     *
1814
     */
1815
    public static TermTree getPreferredFeatureTreeForNameDescription(boolean createNew) {
1816
        if(preferredNameFeatureTree != null && !createNew){
1817
            return preferredNameFeatureTree;
1818
        }
1819
        createPreferredFeatureTreeForNameDescription();
1820
        return preferredNameFeatureTree;
1821

    
1822
    }
1823

    
1824
    public static void createPreferredFeatureTreeForNameDescription() {
1825

    
1826
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1827
        CdmPreference pref = cache.get(PreferencePredicate.NameFeatures.getKey());
1828
        List<Feature> terms = new ArrayList();
1829
        boolean override = PreferencesUtil.getBooleanValue(PreferencesUtil.createOverridePreferenceString(PreferencePredicate.NameFeatures.getKey()));
1830

    
1831
        List<UUID> uuids = PreferencesUtil.createUUIDListFromStringPref(PreferencePredicate.NameFeatures.getKey(), false);
1832
        if (uuids != null && !uuids.isEmpty()){
1833
            terms = CdmStore.getTermManager().getTerms(uuids, Feature.class);
1834
        }
1835

    
1836

    
1837

    
1838

    
1839
       if (terms.isEmpty()){
1840
           terms.addAll(TermStore.getTerms(CdmStore.getService(IVocabularyService.class).load(VocabularyEnum.NameFeature.getUuid()), null));
1841

    
1842
        }
1843
        terms.remove(Feature.PROTOLOGUE());
1844
        if (terms.isEmpty()){
1845
            preferredNameFeatureTree = TermEditorInput.getDefaultNameFeatureTree();
1846
        }else{
1847
            preferredNameFeatureTree = TermTree.NewInstance(terms);
1848
        }
1849

    
1850

    
1851
    }
1852

    
1853
    /**
1854
     * @param prefsToDelete
1855
     */
1856
    public static void removeFromDB(List<CdmPreference> prefsToDelete) {
1857
        ICdmRepository controller;
1858
        //try{
1859
            if(CdmStore.isActive()){
1860
                controller = CdmStore.getCurrentApplicationConfiguration();
1861
                for (CdmPreference preference: prefsToDelete){
1862
                    controller.getPreferenceService().remove(preference.getKey());
1863
                }
1864
                CdmPreferenceCache.instance().getAllTaxEditorDBPreferences();
1865
            }
1866

    
1867
    }
1868

    
1869
    /**
1870
     * @return
1871
     */
1872
    public static TermTree<?> getPreferredFeatureTreeForTaxonDescription(boolean createNew) {
1873
        if(preferredTaxonFeatureTree != null && !createNew){
1874
            return preferredTaxonFeatureTree;
1875
        }
1876
        createPreferredFeatureTreeForTaxonDescription();
1877
        return preferredTaxonFeatureTree;
1878

    
1879
    }
1880

    
1881
    public static void createPreferredFeatureTreeForTaxonDescription() {
1882

    
1883
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1884
        CdmPreference pref = cache.get(PreferencePredicate.TaxonFeatures.getKey());
1885
        List<Feature> terms;
1886
        boolean override = PreferencesUtil.getBooleanValue(PreferencesUtil.createOverridePreferenceString(PreferencePredicate.TaxonFeatures.getKey()));
1887
        List<UUID> uuids = PreferencesUtil.createUUIDListFromStringPref(PreferencePredicate.TaxonFeatures.getKey(), false);
1888
        terms = CdmStore.getTermManager().getTerms(uuids, Feature.class);
1889
        if (terms == null || terms.isEmpty()){
1890
            terms= CdmStore.getTermManager().getPreferredTerms(TermType.Feature);
1891
            TermVocabulary nameVocabulary = CdmStore.getService(IVocabularyService.class).load(VocabularyEnum.NameFeature.getUuid());
1892
            Set<Feature> nameFeature = nameVocabulary.getTerms();
1893
            terms.removeAll(nameFeature);
1894

    
1895
        }
1896

    
1897
        if (terms.isEmpty()){
1898
            preferredTaxonFeatureTree = TermEditorInput.getDefaultFeatureTree();
1899
        }else{
1900
            preferredTaxonFeatureTree = TermTree.NewInstance(terms);
1901
        }
1902

    
1903

    
1904
    }
1905

    
1906

    
1907

    
1908

    
1909
}
(38-38/54)