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.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
            if (StringUtils.isBlank(prefValue) || (pref == null && !override)){
244
                IPreferencePredicate pred = PreferencePredicate.getByKey(name);
245
                if (pred != null){
246
                    if (pred.getDefaultValue() instanceof String){
247
                        return (String)pred.getDefaultValue();
248
                    }else if (pred.getDefaultValue() != null){
249
                        return pred.getDefaultValue().toString();
250
                    }
251
                }
252
                return null;
253
            }
254

    
255
       }else if (pref != null){
256
           if (pref.getValue() == null){
257
               Object result = PreferencePredicate.getByKey(pref.getPredicate()).getDefaultValue();
258
               if (result instanceof String){
259
                   return (String)result;
260
               }else{
261
                   if (result == null){
262
                       return null;
263
                   }
264
                   if (result instanceof IKeyLabel){
265
                       return ((IKeyLabel)result).getKey();
266
                   }
267
                   return result.toString();
268
               }
269
           }
270
           prefValue = pref.getValue();
271
       }
272
        return prefValue;
273

    
274
    }
275

    
276
    public static String getStringValue(String name){
277
        return getStringValue(name, false);
278
    }
279

    
280
    private static CdmPreference getDBPreferenceValue(String name) {
281
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
282
        CdmPreference pref = null;
283
//
284
        pref = cache.get(name);
285
//        if (pref == null ){
286
//            //get default value for Predicate
287
//            IPreferencePredicate pred = PreferencePredicate.getByKey(name);
288
//            if (pred != null){
289
//                if (pred.getDefaultValue() != null){
290
//                    pref = CdmPreference.NewTaxEditorInstance(pred, pred.getDefaultValue().toString());
291
//                }else{
292
//                    pref = CdmPreference.NewTaxEditorInstance(pred, null);
293
//                }
294
//                pref.setAllowOverride(true);
295
//            }
296
//        }
297
        return pref;
298
    }
299

    
300
    public static int getIntValue(String name, boolean local) {
301
        CdmPreference pref= getDBPreferenceValue(name);
302
        String prefValue = null;
303
        if (pref != null){
304
            prefValue = pref.getValue();
305
        }
306
        Integer result = null;
307
        try{
308
            result = Integer.parseInt(prefValue);
309
        }catch(NumberFormatException e){
310
            logger.debug("Preference value of " + name + " is not a number");
311
        }
312

    
313
        String overrideKey =  createPreferenceString(createOverridePreferenceString(name));
314
        boolean override = true;
315
        if (getPreferenceStore().contains(overrideKey)){
316
            override = getPreferenceStore().getBoolean(overrideKey);
317
        }
318
        if (local || pref == null || (pref != null && pref.isAllowOverride() && override)){
319
            String dbSpecific = prefKey(name);
320
            if (getPreferenceStore().contains(dbSpecific)){
321
                result = getPreferenceStore().getInt(dbSpecific);
322
            }else{
323
                if (result == null){
324
                    IPreferencePredicate pred = PreferencePredicate.getByKey(name);
325
                    if (pred != null){
326
                        if (pred.getDefaultValue() instanceof Integer){
327
                            return (Integer)pred.getDefaultValue();
328
                        }else if (pred.getDefaultValue() != null){
329
                            return Integer.valueOf(pred.getDefaultValue().toString());
330
                        }
331
                    }
332
                    return 0;
333
                }
334
            }
335
        }
336
        return result;
337

    
338
    }
339

    
340
    public static boolean getBooleanValue(String name) {
341
        Boolean result = getBooleanValue(name, false);
342
        if (result == null){
343
            return false;
344
        }else{
345
            return result;
346
        }
347

    
348
    }
349

    
350
    public static Boolean getBooleanValue(String name, boolean local) {
351
        if (CdmStore.isActive()){
352
            CdmPreference pref = getDBPreferenceValue(name);
353

    
354
            String overrideKey =  createPreferenceString(createOverridePreferenceString(name));
355
            boolean override = getPreferenceStore().getBoolean(overrideKey);
356

    
357
            if (local || pref == null || (pref != null && pref.isAllowOverride() && override)){
358
                String dbSpecific = prefKey(name);
359
                if (getPreferenceStore().contains(dbSpecific)){
360
                    return getPreferenceStore().getBoolean(dbSpecific);
361
                }else{
362
                    IPreferencePredicate pred = PreferencePredicate.getByKey(name);
363
                    if (pred != null){
364
                        if (pred.getDefaultValue() instanceof Boolean){
365
                            return (Boolean)pred.getDefaultValue();
366
                        }else if (pred.getDefaultValue() != null){
367
                            return Boolean.valueOf(pred.getDefaultValue().toString());
368
                        }
369
                    }
370
                    return null;
371
                }
372
             }else{
373
                 if (pref.getValue() == null){
374
                     Object result = PreferencePredicate.getByKey(pref.getPredicate()).getDefaultValue();
375
                     if (result instanceof Boolean){
376
                         return (Boolean)result;
377
                     }else{
378
                         return Boolean.valueOf(result.toString());
379
                     }
380
                 }
381
                return Boolean.valueOf(pref.getValue());
382
            }
383

    
384
        }else{
385
            return getPreferenceStore().getBoolean(name);
386
        }
387

    
388
    }
389

    
390
    public static double getDoubleValue(String name) {
391
        CdmPreference pref = getDBPreferenceValue(name);
392
        String prefValue = null;
393
        if (pref != null){
394
            prefValue = pref.getValue();
395
        }
396
        Double result = null;
397
        try{
398
            if (pref.getValue() == null){
399
                Object defaultValue = PreferencePredicate.getByKey(pref.getPredicate()).getDefaultValue();
400
                if (defaultValue instanceof Double){
401
                    return (Double)defaultValue;
402
                }else{
403
                    return Double.valueOf(defaultValue.toString());
404
                }
405
            }
406

    
407
            result = Double.parseDouble(prefValue);
408
        }catch(NumberFormatException e){
409
            logger.debug("Preference value of " + name + " is not a number");
410
        }
411
        if (result == null){
412
            String dbSpecific = prefKey(name);
413
            if (getPreferenceStore().contains(dbSpecific)){
414
                result = getPreferenceStore().getDouble(dbSpecific);
415
            }else{
416
                result =  getPreferenceStore().
417
                        getDouble(name);
418
            }
419
        }
420
        return result;
421

    
422
    }
423

    
424
    public static float getFloatValue(String name, boolean local) {
425
        CdmPreference pref = getDBPreferenceValue(name);
426
        String prefValue = null;
427
        if (pref != null){
428
            prefValue = pref.getValue();
429
        }
430
        Float result = null;
431
        try{
432
            result = Float.parseFloat(prefValue);
433
        }catch(NumberFormatException e){
434
            logger.debug("Preference value of " + name + " is not a number");
435
        }
436
        String overrideKey =  createPreferenceString(createOverridePreferenceString(name));
437
        boolean override = true;
438
        if (getPreferenceStore().contains(overrideKey)){
439
            override = getPreferenceStore().getBoolean(overrideKey);
440
        }
441
        if (local || pref == null || (pref != null && pref.isAllowOverride() && override)){
442
            String dbSpecific = prefKey(name);
443
            if (getPreferenceStore().contains(dbSpecific)){
444
                result = getPreferenceStore().getFloat(dbSpecific);
445
            }else{
446
                IPreferencePredicate pred = PreferencePredicate.getByKey(name);
447
                if (pred != null){
448
                    if (pred.getDefaultValue() instanceof Float){
449
                        return (float)pred.getDefaultValue();
450
                    }else if (pred.getDefaultValue() != null){
451
                        return Float.valueOf(pred.getDefaultValue().toString());
452
                    }
453
                }
454
                return 0;
455
            }
456
        }
457
        return result;
458

    
459
    }
460

    
461
    public static long getLongValue(String name) {
462
        CdmPreference pref = getDBPreferenceValue(name);
463
        String prefValue = null;
464
        if (pref != null){
465
            prefValue = pref.getValue();
466
        }
467
        Long result = null;
468
        try{
469
            result = Long.parseLong(prefValue);
470
        }catch(NumberFormatException e){
471
            logger.debug("Preference value of " + name + " is not a number");
472
        }
473
        if (result == null){
474
            String dbSpecific = prefKey(name);
475
            if (getPreferenceStore().contains(dbSpecific)){
476
                result = getPreferenceStore().getLong(dbSpecific);
477
            }else{
478
                result =  getPreferenceStore().
479
                        getLong(name);
480
            }
481
        }
482
        return result;
483
    }
484

    
485
    public static CdmPreference setPreferredNomenclaturalCode(
486
            String preferenceValue, boolean local) {
487
        if (local){
488
            setStringValue(PreferencePredicate.NomenclaturalCode.getKey(),
489
                    preferenceValue);
490
        }
491
        else{
492
            ICdmRepository controller;
493
            controller = CdmStore.getCurrentApplicationConfiguration();
494
            if (controller == null){
495
                return null;
496
            }
497
            PrefKey key = null;
498
            try{
499
                key = CdmPreference.NewKey(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.NomenclaturalCode);
500
            }catch (Exception e){
501
                System.out.println(e.getStackTrace());
502
            }
503
            CdmPreference preference = null;
504

    
505
            if (preferenceValue == null){
506
                preference = controller.getPreferenceService().find(key);
507
                if (preference == null){
508
                    return null;
509
                } else{
510
                    setStringValue(PreferencePredicate.NomenclaturalCode.getKey(),
511
                            preference.getValue());
512

    
513
                    return preference;
514
                }
515
            } else{
516
                preference = CdmPreference.NewInstance(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.NomenclaturalCode, preferenceValue);
517
                controller.getPreferenceService().set(preference);
518

    
519
            }
520
        }
521
        return null;
522

    
523

    
524

    
525
    }
526

    
527
    public static void setPreferredNomenclaturalCode(
528
        CdmPreference preference) {
529

    
530
        ICdmRepository controller;
531
        controller = CdmStore.getCurrentApplicationConfiguration();
532
        if (controller == null){
533
            return;
534
        }
535

    
536
        if (preference == null){
537
            PrefKey key = null;
538
              try{
539
                  key = CdmPreference.NewKey(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.NomenclaturalCode);
540
              }catch (Exception e){
541
                  System.out.println(e.getStackTrace());
542
              }
543
            controller.getPreferenceService().remove(key);
544
        }else{
545
            controller.getPreferenceService().set(preference);
546
        }
547

    
548
    }
549

    
550
    public static NomenclaturalCode getPreferredNomenclaturalCode() {
551

    
552
        CdmPreference pref = getPreferenceFromDB(PreferencePredicate.NomenclaturalCode);
553

    
554

    
555
        String preferredCode;
556
        if(pref == null || (pref.isAllowOverride() && getBooleanValue(prefOverrideKey(PreferencePredicate.NomenclaturalCode.getKey())))){
557
            preferredCode = getStringValue(
558
                    PreferencePredicate.NomenclaturalCode.getKey());
559

    
560
        }else{
561
            preferredCode = pref.getValue();
562
        }
563
        if (StringUtils.isBlank(preferredCode)){
564
            preferredCode = getPreferenceKey((NomenclaturalCode)PreferencePredicate.NomenclaturalCode.getDefaultValue());
565
        }
566

    
567
        return getPreferredNomenclaturalCode(preferredCode);
568

    
569
    }
570

    
571
    public static NomenclaturalCode getPreferredNomenclaturalCode(String preferenceKeyNomenclaturalCode) {
572

    
573
        for (NomenclaturalCode code : NomenclaturalCodeHelper.getAllCodes()) {
574
            if (getPreferenceKey(code).equals(preferenceKeyNomenclaturalCode) || code.getKey().equals(preferenceKeyNomenclaturalCode)) {
575
                return code;
576
            }
577
        }
578
        return null;
579
    }
580

    
581
    public static boolean isShowTaxonAssociations(){
582
        boolean result = getBooleanValue(PreferencePredicate.ShowTaxonAssociations.getKey());
583
        return result;
584
    }
585

    
586
    public static boolean isShowLifeForm(){
587
        boolean result =  getBooleanValue(PreferencePredicate.ShowLifeForm.getKey());
588
        return result;
589
    }
590

    
591
    public static boolean isDeterminationOnlyForFieldUnits(){
592
        boolean result =  getBooleanValue(PreferencePredicate.DeterminationOnlyForFieldUnits.getKey());
593
        return result;
594
    }
595

    
596
    public static boolean isCollectingAreaInGeneralSection(){
597
        boolean result =  getBooleanValue(PreferencePredicate.ShowCollectingAreasInGeneralSection.getKey());
598
        return result;
599
    }
600

    
601
    public static CdmPreference getPreferenceFromDB(IPreferencePredicate predicate){
602
        ICdmRepository controller;
603
        CdmPreference pref = null;
604

    
605
        try{
606
            if(CdmStore.isActive()){
607
                controller = CdmStore.getCurrentApplicationConfiguration();
608
                PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), predicate);
609
                pref = controller.getPreferenceService().find(key);
610
            }
611
        }catch(Exception e){
612
            e.printStackTrace();
613
        }
614

    
615
        return pref;
616

    
617
    }
618

    
619
    public static List<CdmPreference> getPreferencesFromDB(IPreferencePredicate predicate){
620
        ICdmRepository controller;
621
        List<CdmPreference> prefs = null;
622

    
623
        try{
624
            if(CdmStore.isActive()){
625
                controller = CdmStore.getCurrentApplicationConfiguration();
626
                PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), predicate);
627
                prefs = controller.getPreferenceService().list(predicate);
628
            }
629
        }catch(Exception e){
630
            e.printStackTrace();
631
        }
632

    
633
        return prefs;
634

    
635
    }
636

    
637
    public static void setPreferencesToDB(CdmPreference preference, boolean setDefault){
638
        ICdmRepository controller;
639
        try{
640
            if(CdmStore.isActive()){
641
                controller = CdmStore.getCurrentApplicationConfiguration();
642

    
643
                if (setDefault){
644
                    controller.getPreferenceService().remove(preference.getKey());
645
                }else{
646
                    controller.getPreferenceService().set(preference);
647
                }
648
            }
649
        }catch(Exception e){
650
            e.printStackTrace();
651
        }
652

    
653

    
654

    
655
    }
656

    
657
    public static CdmPreference getPreferenceFromDB(PrefKey key){
658
        ICdmRepository controller;
659
        CdmPreference pref = null;
660

    
661
        try{
662
            if(CdmStore.isActive()){
663
                controller = CdmStore.getCurrentApplicationConfiguration();
664
                pref = controller.getPreferenceService().find(key);
665
            }
666
        }catch(Exception e){
667
            e.printStackTrace();
668
        }
669

    
670
        return pref;
671

    
672
    }
673

    
674
    public static void setPreferenceToDB(CdmPreference preference){
675
        ICdmRepository controller;
676
        try{
677
            if(CdmStore.isActive()){
678
                controller = CdmStore.getCurrentApplicationConfiguration();
679
                if (preference.getValue() == null && preference.isAllowOverride()){
680
                    controller.getPreferenceService().remove(preference.getKey());
681
                }else{
682
                    controller.getPreferenceService().set(preference);
683
                }
684
                CdmPreferenceCache.instance().put(preference);
685
            }
686
        }catch(Exception e){
687
            e.printStackTrace();
688
        }
689

    
690
    }
691

    
692
    public static String getPreferredDefaultLangugae(){
693
        String preferredLanguage = getStringValue(DEFAULT_LANGUAGE_EDITOR);
694
        if(StringUtils.isNotEmpty(preferredLanguage) && StringUtils.isNotBlank(preferredLanguage)){
695
            return preferredLanguage;
696
        }
697
        return null;
698
    }
699

    
700
    public static boolean isShowMediaPreview(){
701
        boolean isShowMediaPreview = getBooleanValue(SHOW_MEDIA_PREVIEW);
702
        return isShowMediaPreview;
703
    }
704

    
705
    /**
706
     * Get the match strategy for the given class that was stored in preferences
707
     * or the default strategy if it was not stored in preferences
708
     *
709
     * @param clazz
710
     *            a {@link java.lang.Class} object.
711
     * @return a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy} object.
712
     */
713
    public static IMatchStrategy getMatchStrategy(Class<?> clazz) {
714
        String className = clazz.getName();
715
        if (getBooleanValue(MATCH_STRATEGY_PREFIX + className)) {
716
            IMatchStrategy matchStrategy = getDefaultMatchStrategy(clazz);
717

    
718
            //TODO CacheMatchers (or multiple field matchers in future) are missing here
719
            for (FieldMatcher fieldMatcher : matchStrategy.getMatching().getFieldMatchers(false)) {
720
                String fieldName = fieldMatcher.getPropertyName();
721
                String matchModeName = getStringValue(
722
                        getMatchStrategyFieldName(className, fieldName));
723
                MatchMode matchMode = MatchMode.valueOf(matchModeName);
724
                try {
725
                    matchStrategy.setMatchMode(fieldName, matchMode);
726
                } catch (MatchException e) {
727
                    MessagingUtils.error(PreferencesUtil.class, e);
728
                    throw new RuntimeException(e);
729
                }
730
            }
731

    
732
            return matchStrategy;
733
        }
734
        return getDefaultMatchStrategy(clazz);
735
    }
736

    
737
    /**
738
     * Stores a matchStrategy into the preference store.
739
     *
740
     * @param matchStrategy
741
     *            a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy}
742
     *            object.
743
     */
744
    public static void setMatchStrategy(IMatchStrategy matchStrategy) {
745
        String className = "ANY class"; //FIXME was: matchStrategy.getMatchClass().getName(); seems currently not in use
746
        setBooleanValue(MATCH_STRATEGY_PREFIX + className, true);
747

    
748
        List<FieldMatcher> fieldMatchers = matchStrategy.getMatching().getFieldMatchers(false);
749

    
750
        for (FieldMatcher fieldMatcher : fieldMatchers) {
751
            String fieldName = fieldMatcher.getPropertyName();
752
            setStringValue(
753
                    getMatchStrategyFieldName(className, fieldName),
754
                    fieldMatcher.getMatchMode().name());
755
        }
756
    }
757

    
758
    /**
759
     * Helper method to create the preference property for a match field.
760
     *
761
     * @param className
762
     * @param fieldName
763
     * @return
764
     */
765
    private static String getMatchStrategyFieldName(String className,
766
            String fieldName) {
767
        return MATCH_STRATEGY_PREFIX + className + "." + fieldName;
768
    }
769

    
770
    /**
771
     * Returns the default match strategy for a given class.
772
     *
773
     * @param clazz
774
     *            a {@link java.lang.Class} object.
775
     * @return a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy} object.
776
     */
777
    public static IMatchStrategy getDefaultMatchStrategy(Class clazz) {
778
        return DefaultMatchStrategy.NewInstance(clazz);
779
    }
780

    
781
    public static String getDateFormatPattern() {
782
        // TODO make this configurable in properties
783
        String pattern = "Y-M-d H:m";
784
        return pattern;
785
    }
786

    
787
    public static <T extends TermBase> void addTermToPreferredTerms(T term) {
788

    
789
        // VocabularyEnum vocabulary =
790
        // VocabularyEnum.getVocabularyEnum(term.getClass());
791
        //
792
        // getPreferenceStore().setValue(getPreferenceKey(term),
793
        // VocabularyStore.getTermVocabulary(vocabulary).getTerms().contains(term));
794
        //
795
        // firePreferencesChanged(term.getClass());
796
    }
797

    
798
    /**
799
     * Construct a unique key using the CdmBase object's uuid
800
     *
801
     * @param cdmBase
802
     * @return
803
     */
804
    private static String getPreferenceKey(ICdmBase cdmBase) {
805
        cdmBase = HibernateProxyHelper.deproxy(cdmBase);
806

    
807
        String key = cdmBase.getClass().getName().concat(".")
808
                .concat(cdmBase.getUuid().toString());
809
        if (key.contains("javassist")) {
810
            MessagingUtils.info("proxy");
811
        }
812
        return key;
813
    }
814

    
815
    /**
816
     * Construct a unique key using the CdmBase object's uuid
817
     *
818
     * @param cdmBase
819
     * @return
820
     */
821
    public static String getPreferenceKey(ISimpleTerm simpleTerm) {
822
        simpleTerm = HibernateProxyHelper.deproxy(simpleTerm);
823
        String key = simpleTerm.getClass().getName().concat(".")
824
                .concat(simpleTerm.getUuid().toString());
825
        if (key.contains("javassist")) {
826
            MessagingUtils.warn(PreferencesUtil.class,
827
                    "Trying to persist a preference based on a proxy class.");
828
        }
829
        return key;
830
    }
831

    
832

    
833

    
834
    /**
835
     * Construct a unique key using the CdmBase object's uuid
836
     *
837
     * @param cdmBase
838
     * @return
839
     */
840
    public static String getPreferenceKey(IDefinedTerm definedTerm) {
841
        definedTerm = HibernateProxyHelper.deproxy(definedTerm);
842
        String key = definedTerm.getClass().getName().concat(".")
843
                .concat(definedTerm.getUuid().toString());
844
        if (key.contains("javassist")) {
845
            MessagingUtils.warn(PreferencesUtil.class,
846
                    "Trying to persist a preference based on a proxy class.");
847
        }
848
        return key;
849
    }
850

    
851
    /**
852
     * Retrieves search preferences from the preference store
853
     *
854
     * @return an {@link ITaxonServiceConfigurator} to pass to search methods
855
     */
856
    public static IFindTaxaAndNamesConfigurator getSearchConfigurator() {
857
        IFindTaxaAndNamesConfigurator configurator = initializeSearchConfigurator();
858

    
859
        configurator.setDoTaxa(PreferencesUtil.getPreferenceStore().contains(IPreferenceKeys.TAXON_SERVICE_CONFIGURATOR_TAXA)? PreferencesUtil.getPreferenceStore().getBoolean(
860
                IPreferenceKeys.TAXON_SERVICE_CONFIGURATOR_TAXA): true);
861
        configurator.setDoSynonyms(PreferencesUtil.getPreferenceStore().contains(IPreferenceKeys.TAXON_SERVICE_CONFIGURATOR_SYNONYMS)? PreferencesUtil.getPreferenceStore().getBoolean(
862
                IPreferenceKeys.TAXON_SERVICE_CONFIGURATOR_SYNONYMS): true);
863
        configurator.setDoNamesWithoutTaxa(PreferencesUtil.getPreferenceStore().contains(IPreferenceKeys.TAXON_SERVICE_CONFIGURATOR_NAMES)? PreferencesUtil.getPreferenceStore().getBoolean(
864
                IPreferenceKeys.TAXON_SERVICE_CONFIGURATOR_NAMES): true);
865
        configurator.setDoTaxaByCommonNames(PreferencesUtil.getPreferenceStore().contains(IPreferenceKeys.TAXON_SERVICE_CONFIGURATOR_COMMON_NAMES)? PreferencesUtil.getPreferenceStore().getBoolean(
866
                IPreferenceKeys.TAXON_SERVICE_CONFIGURATOR_COMMON_NAMES): true);
867
        //configurator.setMatchMode(eu.etaxonomy.cdm.persistence.query.MatchMode.valueOf(getStringValue(TAXON_SERVICE_CONFIGURATOR_MATCH_MODE)));
868

    
869
        return configurator;
870
    }
871

    
872
    /**
873
     * create new preferences, setting all search options to true
874
     *
875
     * @return a
876
     *         {@link eu.etaxonomy.cdm.api.service.config.ITaxonServiceConfigurator}
877
     *         object.
878
     */
879
    public static IFindTaxaAndNamesConfigurator initializeSearchConfigurator() {
880
        IFindTaxaAndNamesConfigurator configurator = FindTaxaAndNamesConfiguratorImpl.NewInstance();
881

    
882
        configurator.setDoTaxa(true);
883
        configurator.setDoSynonyms(true);
884
        configurator.setDoNamesWithoutTaxa(true);
885
        configurator.setDoTaxaByCommonNames(true);
886

    
887
        configurator.setTaxonPropertyPath(Arrays.asList("$", "titleCache",
888
                "name", "name.$", "relationsFromThisTaxon.$"));
889

    
890
        configurator.setSynonymPropertyPath(Arrays.asList("$", "titleCache",
891
                "name", "name.$", "synonyms.relatedTo.*"));
892

    
893
        // DEFAULT VALUES
894
        // match mode is a simple like, actually all other match modes are kind
895
        // of bogus
896
        configurator
897
                .setMatchMode(eu.etaxonomy.cdm.persistence.query.MatchMode.ANYWHERE);
898
        // we set page number and size here as this should always be unlimited
899
        configurator.setPageNumber(0);
900
        // TODO currently limit results to 10000
901
        configurator.setPageSize(10000);
902
        //setSearchConfigurator(configurator) ;
903
        return configurator;
904
    }
905

    
906
    /**
907
     * Store search preferences
908
     *
909
     * @param configurator
910
     *            a
911
     *            {@link eu.etaxonomy.cdm.api.service.config.ITaxonServiceConfigurator}
912
     *            object.
913
     */
914
    public static void setSearchConfigurator(
915
            IFindTaxaAndNamesConfigurator configurator) {
916
        getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_TAXA,
917
                configurator.isDoTaxa());
918
        getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_SYNONYMS,
919
                configurator.isDoSynonyms());
920
        getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_NAMES,
921
                configurator.isDoNamesWithoutTaxa());
922
        getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_COMMON_NAMES,
923
                configurator.isDoTaxaByCommonNames());
924
    }
925

    
926
    public static void firePreferencesChanged(Class clazz) {
927
        getPreferenceStore().firePropertyChangeEvent(PREFERRED_TERMS_CHANGE,
928
                null, clazz);
929
    }
930

    
931

    
932
    public static String createPreferenceString(String property){
933
       return prefKey(property);
934

    
935
    }
936
    public static String createOverridePreferenceString(String property){
937
           return prefOverrideKey(property);
938

    
939
        }
940

    
941
    /**
942
     * Set default values for preferences
943
     */
944
    public static void setDefaults() {
945

    
946
        getPreferenceStore().setDefault(createPreferenceString(EDIT_MAP_SERVICE_ACCES_POINT),
947
                "http://edit.africamuseum.be/edit_wp5/v1.2/rest_gen.php");
948
        //FIXME : changed default for SHOULD_CONNECT_AT_STARTUP to false (ticket 3828) until resolution
949
        getPreferenceStore().setDefault(createPreferenceString(SHOULD_CONNECT_AT_STARTUP), false);
950
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.MobotOpenUrlServiceAccessPoint.getKey()),
951
                "http://www.biodiversitylibrary.org/openurl");
952
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.MobotOpenUrlServiceMaxWidth.getKey()), "1000");
953
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.MobotOpenUrlServiceMaxHeight.getKey()), "1000");
954
        getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_TAXA, true);
955
        getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_SYNONYMS, true);
956
        getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_NAMES, true);
957
        getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_COMMON_NAMES, true);
958

    
959

    
960
        //Name Details
961
       // getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.NameDetailsView.getKey()), new NameDetailsConfigurator(false).toString());
962

    
963
        //Navigator preferences
964
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.TaxonNodeOrder.getKey()), NavigatorOrderEnum.RankAndNameOrder.getKey());
965

    
966
        //getPreferenceStore().setDefault(createPreferenceString(Prefe), true);
967

    
968
        getPreferenceStore().setDefault(createPreferenceString(SHOW_ADVANCED_MEDIA_SECTION), false);
969

    
970
        getPreferenceStore().setDefault(createPreferenceString(SHOW_MEDIA_PREVIEW), false);
971
        //override db preferences
972
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.AbcdImportConfig.getKey())), false);
973
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.NameDetailsView.getKey())), false);
974
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.CommonNameAreaVocabularies.getKey())), false);
975
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.CommonNameReferencesWithMarker.getKey()), false);
976
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowTaxonNodeWizard.getKey()), Boolean.valueOf(PreferencePredicate.ShowTaxonNodeWizard.getDefaultValue().toString()));
977
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowNamespaceInSource.getKey()), Boolean.valueOf(PreferencePredicate.ShowNamespaceInSource.getDefaultValue().toString()));
978
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowIdInSource.getKey()), Boolean.valueOf(PreferencePredicate.ShowIdInSource.getDefaultValue().toString()));
979
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.DisableMultiClassification.getKey()), Boolean.valueOf(PreferencePredicate.DisableMultiClassification.getDefaultValue().toString()));
980
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowImportExportMenu.getKey()), Boolean.valueOf(PreferencePredicate.ShowImportExportMenu.getDefaultValue().toString()));
981
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowSpecimen.getKey()), Boolean.valueOf(PreferencePredicate.ShowSpecimen.getDefaultValue().toString()));
982
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.SearchForIdentifierAndTitleCache.getKey()), Boolean.valueOf(PreferencePredicate.SearchForIdentifierAndTitleCache.getDefaultValue().toString()));
983
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.SearchForIdentifierAndTitleCache.getKey())), false);
984
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.SearchForIdentifierAsDefault.getKey()), Boolean.valueOf(PreferencePredicate.SearchForIdentifierAsDefault.getDefaultValue().toString()));
985
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.SearchForIdentifierAsDefault.getKey())), false);
986
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.ShowModifierFreeText.getKey())), false);
987
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.ShowModifier.getKey())), false);
988
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.DistributionEditorActivated.getKey())), false);
989

    
990
    }
991

    
992
    public static void checkNomenclaturalCode() {
993
        // First time Editor is opened, no nomenclatural code has been set
994
        if (PreferencesUtil.getPreferredNomenclaturalCode() == null) {
995
            PreferencesUtil.setPreferredNomenclaturalCode(getPreferenceKey(NomenclaturalCode.ICNAFP), true);
996
        }
997

    
998

    
999

    
1000
    }
1001
    public static void setNomenclaturalCodePreferences(){
1002
        ICdmRepository controller;
1003
        controller = CdmStore.getCurrentApplicationConfiguration();
1004
        PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.NomenclaturalCode);
1005
        CdmPreference preference = null;
1006
        if (controller == null){
1007
            return ;
1008
        }
1009
        preference = controller.getPreferenceService().find(key);
1010
        if (preference == null){
1011
            return;
1012
        }
1013
//        setBooleanValue(ALLOW_OVERRIDE_NOMENCLATURAL_CODE_KEY, preference.isAllowOverride());
1014

    
1015
        int index = StringUtils.lastIndexOf(preference.getValue(), ".");
1016
        UUID uuid = UUID.fromString(preference.getValue().substring(index +1, preference.getValue().length()));
1017
        NomenclaturalCode preferredCode = NomenclaturalCode.getByUuid(uuid);
1018

    
1019
        setStringValue(PreferencePredicate.NomenclaturalCode.getKey(),
1020
                getPreferenceKey(preferredCode));
1021

    
1022
    }
1023

    
1024
    public static void checkDefaultLanguage(){
1025
        if(PreferencesUtil.getPreferredDefaultLangugae() == null){
1026
           Shell shell = AbstractUtility.getShell();
1027
           int open = new DefaultLanguageDialog(shell).open();
1028
           if(open == Window.OK){
1029
               PlatformUI.getWorkbench().restart();
1030
           }
1031
        }else{
1032
            //TODO:In case of a reinstall, the config.ini will be overwritten
1033
            //     here you create config.ini with the stored key from preferences
1034
        }
1035
    }
1036

    
1037
    public static String getMapServiceAccessPoint() {
1038
        return getStringValue(EDIT_MAP_SERVICE_ACCES_POINT);
1039
    }
1040

    
1041
    public static boolean shouldConnectAtStartUp() {
1042
        //FIXME :  force SHOULD_CONNECT_AT_STARTUP to false (ticket 3828) until resolution
1043
        //return getBooleanValue(SHOULD_CONNECT_AT_STARTUP);
1044
        return false;
1045
    }
1046

    
1047
    public static TermTree getDefaultFeatureTreeForTextualDescription() {
1048
        String uuidString = getStringValue(
1049
                FEATURE_TREE_DEFAULT_TEXT);
1050
        if (StringUtils.isBlank(uuidString)) {
1051
            return null;
1052
        }
1053
        TermTree tree = CdmStore.getService(
1054
                ITermTreeService.class).load(UUID.fromString(uuidString));
1055

    
1056
        if (tree == null || tree.getId() == 0) {
1057
            return null;
1058
        }
1059
        return tree;
1060
    }
1061

    
1062
    public static TermTree getDefaultFeatureTreeForStructuredDescription() {
1063
        String uuidString = getStringValue(
1064
                FEATURE_TREE_DEFAULT_STRUCTURE);
1065
        return StringUtils.isBlank(uuidString) ? null : CdmStore.getService(
1066
                ITermTreeService.class).load(UUID.fromString(uuidString));
1067
    }
1068

    
1069
    public static void setSortRanksHierarchichally(boolean selection) {
1070
        setBooleanValue(SORT_RANKS_HIERARCHICHALLY, selection);
1071
    }
1072

    
1073
    public static boolean getSortRanksHierarchichally() {
1074
        return getBooleanValue(SORT_RANKS_HIERARCHICHALLY);
1075
    }
1076

    
1077
    public static boolean isMultilanguageTextEditingCapability() {
1078
        return getBooleanValue(
1079
                MULTILANGUAGE_TEXT_EDITING_CAPABILITY);
1080
    }
1081

    
1082
    public static Language getGlobalLanguage() {
1083

    
1084

    
1085
        String languageUuidString = getStringValue(
1086
                GLOBAL_LANGUAGE_UUID);
1087

    
1088
        if(!CdmStore.isActive()) {
1089
            MessagingUtils.noDataSourceWarningDialog(languageUuidString);
1090
            return null;
1091
        }
1092

    
1093
        if (CdmUtils.isBlank(languageUuidString)) {
1094
            return Language.getDefaultLanguage();
1095
        }
1096

    
1097
        UUID languageUuid = UUID.fromString(languageUuidString);
1098
        return (Language) CdmStore.getService(ITermService.class).load(
1099
                languageUuid);
1100
    }
1101

    
1102
    public static void setGlobalLanguage(Language language) {
1103
        if(language != null) {
1104
            setStringValue(GLOBAL_LANGUAGE_UUID,language.getUuid().toString());
1105
            CdmStore.setDefaultLanguage(language);
1106
        }
1107

    
1108
    }
1109

    
1110
    public static Map<MarkerType, Boolean> getEditMarkerTypePreferences() {
1111
        List<MarkerType> markerTypes = CdmStore.getTermManager()
1112
                .getPreferredTerms(MarkerType.class);
1113

    
1114
        Map<MarkerType, Boolean> result = new HashMap<MarkerType, Boolean>();
1115

    
1116
        for (MarkerType markerType : markerTypes) {
1117
            String name = getMarkerTypeEditingPreferenceKey(markerType);
1118
            Boolean value = getBooleanValue(name);
1119

    
1120
            result.put(markerType, value);
1121
        }
1122

    
1123
        return result;
1124
    }
1125

    
1126
    public static void setEditMarkerTypePreferences(
1127
            Map<MarkerType, Boolean> markerTypeEditingMap) {
1128
        for (MarkerType markerType : markerTypeEditingMap.keySet()) {
1129
            String name = getMarkerTypeEditingPreferenceKey(markerType);
1130
            setBooleanValue(name,
1131
                    markerTypeEditingMap.get(markerType));
1132
        }
1133

    
1134
    }
1135

    
1136
    private static String getMarkerTypeEditingPreferenceKey(
1137
            MarkerType markerType) {
1138
        markerType = HibernateProxyHelper.deproxy(markerType);
1139
        return markerType.getClass().getName() + EDIT_MARKER_TYPE_PREFIX;
1140
    }
1141

    
1142
    public static void setEditMarkerTypePreference(MarkerType markerType,
1143
            boolean edit) {
1144
        setBooleanValue(
1145
                getMarkerTypeEditingPreferenceKey(markerType), edit);
1146
    }
1147

    
1148
    public static DerivedUnitFacadeConfigurator getDerivedUnitConfigurator() {
1149
        DerivedUnitFacadeConfigurator configurator = DerivedUnitFacadeConfigurator
1150
                .NewInstance();
1151
        configurator.setMoveDerivedUnitMediaToGallery(true);
1152
        configurator.setMoveFieldObjectMediaToGallery(true);
1153
        return configurator;
1154
    }
1155

    
1156
    /**
1157
     * This method will write language properties to the config.ini located in the configuration folder
1158
     * of the Taxonomic Ediitor. <b>This method is only used to set the default language for Taxonomic Editor.</b>
1159
     *
1160
     * @param setLanguage 0 is for german and 1 for english.
1161
     * @throws IOException
1162
     */
1163
    public void writePropertyToConfigFile(int setLanguage) throws IOException {
1164
        File file = org.eclipse.core.runtime.preferences.ConfigurationScope.INSTANCE.getLocation().toFile();
1165
        //give warning to user if the directory has no write access
1166
        if(file == null){
1167
            throw new IOException();
1168
        }
1169
        Properties properties = load(file.getAbsolutePath()+"/config.ini");
1170
        switch(setLanguage){
1171
        case 0:
1172
            properties.setProperty("osgi.nl", "de");
1173
            setStringValue(IPreferenceKeys.DEFAULT_LANGUAGE_EDITOR, "de");
1174
            break;
1175
        case 1:
1176
            properties.setProperty("osgi.nl", "en");
1177
            setStringValue(IPreferenceKeys.DEFAULT_LANGUAGE_EDITOR, "en");
1178
            break;
1179
        default:
1180
            break;
1181
        }
1182
        save(file+"/config.ini", properties);
1183
    }
1184

    
1185
    /**
1186
     * This method loads a property from a given file and returns it.
1187
     *
1188
     * @param filename
1189
     * @return
1190
     * @throws IOException
1191
     */
1192
    private Properties load(String filename) throws IOException {
1193
        FileInputStream in = new FileInputStream(filename);
1194
        Properties prop = new Properties();
1195
        prop.load(in);
1196
        in.close();
1197
        return prop;
1198
    }
1199

    
1200
    /**
1201
     * This method saves a property to the specified file.
1202
     *
1203
     * @param filename
1204
     * @param properties
1205
     * @throws IOException
1206
     */
1207
    private void save(String filename, Properties properties) throws IOException{
1208
        FileOutputStream fos =  new FileOutputStream(filename);
1209
        properties.store(fos, "");
1210
        fos.close();
1211
    }
1212

    
1213
    /**
1214
     * Saves a list of P2 Metadata Repositories as string with specified delimiters
1215
     *
1216
     * @param p2Repos
1217
     */
1218
    public static void setP2Repositories(List<MetadataRepositoryElement> p2Repos) {
1219
        StringBuilder sb = new StringBuilder();
1220
        for(MetadataRepositoryElement p2Repo : p2Repos) {
1221
            sb.append(P2_REPOSITORIES_DELIM);
1222
            if(p2Repo.getName() == null || p2Repo.getName().isEmpty()) {
1223
                sb.append("-");
1224
            } else {
1225
                sb.append(p2Repo.getName());
1226
            }
1227
            sb.append(P2_REPOSITORY_FIELDS_DELIM);
1228
            sb.append(p2Repo.getLocation().toString());
1229
            sb.append(P2_REPOSITORY_FIELDS_DELIM);
1230
            sb.append(String.valueOf(p2Repo.isEnabled()));
1231
        }
1232
        getPreferenceStore().setValue(P2_REPOSITORY_LIST, sb.toString());
1233
    }
1234

    
1235

    
1236
    /**
1237
     * Retrieves a list of previously saved P2 repositories
1238
     *
1239
     * @return
1240
     */
1241
    public static List<MetadataRepositoryElement> getP2Repositories() {
1242
        List<MetadataRepositoryElement> p2Repos = new ArrayList<MetadataRepositoryElement>();
1243
        String p2ReposPref =  getStringValue(P2_REPOSITORY_LIST);
1244
        if(p2ReposPref != null && !p2ReposPref.isEmpty()) {
1245
            StringTokenizer p2ReposPrefST = new StringTokenizer(p2ReposPref,P2_REPOSITORIES_DELIM);
1246

    
1247
            while(p2ReposPrefST.hasMoreTokens()) {
1248
                String p2RepoStr = p2ReposPrefST.nextToken();
1249
                StringTokenizer p2ReposStrST = new StringTokenizer(p2RepoStr,P2_REPOSITORY_FIELDS_DELIM);
1250
                if(p2ReposStrST.countTokens()==3) {
1251
                    String nickname = p2ReposStrST.nextToken();
1252
                    URI uri = null;
1253
                    try {
1254
                        uri = new URI(p2ReposStrST.nextToken());
1255
                    } catch (URISyntaxException e) {
1256
                        continue;
1257
                    }
1258
                    boolean enabled = Boolean.parseBoolean(p2ReposStrST.nextToken());
1259
                    MetadataRepositoryElement mre = new MetadataRepositoryElement(null, uri, true);
1260
                    mre.setNickname(nickname);
1261
                    mre.setEnabled(enabled);
1262
                    p2Repos.add(mre);
1263
                }
1264
            }
1265
        }
1266

    
1267
        return p2Repos;
1268
    }
1269

    
1270
    /**
1271
     * enables/disables nested composite. <br>
1272
     *
1273
     * @param ctrl - Composite to be en-/disabeld
1274
     * @param enabled - boolean
1275
     */
1276
    public static void recursiveSetEnabled(Control ctrl, boolean enabled) {
1277
        if (ctrl instanceof Composite) {
1278
            Composite comp = (Composite) ctrl;
1279
            for (Control c : comp.getChildren()) {
1280
                recursiveSetEnabled(c, enabled);
1281
            }
1282
        } else {
1283
            ctrl.setEnabled(enabled);
1284
        }
1285
    }
1286

    
1287
    public static void setSortNodes(NavigatorOrderEnum nodesOrder) {
1288
        if (nodesOrder == null){
1289
            setStringValue(PreferencePredicate.TaxonNodeOrder.getKey(), null);
1290
        }else{
1291
            setStringValue(PreferencePredicate.TaxonNodeOrder.getKey(), nodesOrder.key);
1292
        }
1293

    
1294
    }
1295

    
1296
    public static NavigatorOrderEnum getSortNodes() {
1297
        return NavigatorOrderEnum.valueOf(getStringValue(PreferencePredicate.TaxonNodeOrder.getKey()));
1298

    
1299
    }
1300

    
1301
    public static boolean isNodesSortedNaturally() {
1302
        NavigatorOrderEnum value = NavigatorOrderEnum.valueOf(getStringValue(PreferencePredicate.TaxonNodeOrder.getKey()));
1303
        return value.equals(NavigatorOrderEnum.NaturalOrder);
1304

    
1305
    }
1306

    
1307
    public static boolean isNodesSortedByName() {
1308
        NavigatorOrderEnum value = NavigatorOrderEnum.valueOf(getStringValue(PreferencePredicate.TaxonNodeOrder.getKey()));
1309
        return value.equals(NavigatorOrderEnum.AlphabeticalOrder);
1310

    
1311
    }
1312

    
1313
    public static boolean isNodesSortedByNameAndRank() {
1314
        NavigatorOrderEnum value = NavigatorOrderEnum.valueOf(getStringValue(PreferencePredicate.TaxonNodeOrder.getKey()));
1315
        return value.equals(NavigatorOrderEnum.RankAndNameOrder);
1316

    
1317
    }
1318

    
1319
    public static boolean isStoreNavigatorState() {
1320
        return getBooleanValue(RESTORE_NAVIGATOR_STATE);
1321

    
1322
    }
1323

    
1324
    public static void setStoreNavigatorState(boolean selection) {
1325
        setBooleanValue(RESTORE_NAVIGATOR_STATE, selection);
1326

    
1327
    }
1328

    
1329
    public static boolean isShowUpWidgetIsDisposedMessages() {
1330
       return getBooleanValue(IS_SHOW_UP_WIDGET_IS_DISPOSED);
1331
    }
1332
    public static void setShowUpWidgetIsDisposedMessages(boolean selection) {
1333
        setBooleanValue(IS_SHOW_UP_WIDGET_IS_DISPOSED, selection);
1334
    }
1335

    
1336
    public static boolean isShowIdInVocabularyInChecklistEditor() {
1337
        String area_display = getStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey());
1338
        if (area_display.equals(TermDisplayEnum.IdInVocabulary.getKey())) {
1339
            return true;
1340
        }else{
1341
            return false;
1342
        }
1343
    }
1344
    public static boolean isShowSymbol1InChecklistEditor() {
1345
        String area_display = getStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey());
1346
        if (area_display.equals(TermDisplayEnum.Symbol1.getKey())) {
1347
            return true;
1348
        }else{
1349
            return false;
1350
        }
1351
     }
1352
    public static boolean isShowSymbol2InChecklistEditor() {
1353
        String area_display = getStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey());
1354
        if (area_display.equals(TermDisplayEnum.Symbol2.getKey())) {
1355
            return true;
1356
        }else{
1357
            return false;
1358
        }
1359
     }
1360
    public static void setAreaDisplayInChecklistEditor(String selection) {
1361
        setStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey(), selection);
1362
    }
1363

    
1364
    public static void setOwnDescriptionForChecklistEditor(boolean selection) {
1365
        setBooleanValue(PreferencePredicate.OwnDescriptionForDistributionEditor.getKey(), selection);
1366
    }
1367

    
1368
    public static boolean isOwnDescriptionForChecklistEditor() {
1369
        return getBooleanValue(PreferencePredicate.OwnDescriptionForDistributionEditor.getKey());
1370
    }
1371

    
1372
    public static TermDisplayEnum displayAreaInChecklistEditor() {
1373
        TermDisplayEnum result;
1374
        try{
1375
            result = TermDisplayEnum.byKey(getStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey()));
1376
        }catch (IllegalArgumentException e){
1377
           result = ((TermDisplayEnum) PreferencePredicate.DisplayOfAreasInDistributionEditor.getDefaultValue());
1378
        }
1379
       return result;
1380
    }
1381

    
1382
    public static TermDisplayEnum displayStatusInChecklistEditor() {
1383
        TermDisplayEnum result;
1384
        try{
1385
            result = TermDisplayEnum.byKey(getStringValue(PreferencePredicate.DisplayOfStatus.getKey()));
1386
        }catch (IllegalArgumentException e){
1387
           result = ((TermDisplayEnum) PreferencePredicate.DisplayOfStatus.getDefaultValue());
1388
        }
1389
       return result;
1390
    }
1391
    public static void setDisplayStatusInChecklistEditor(String selection) {
1392
        setStringValue(PreferencePredicate.DisplayOfStatus.getKey(), selection);
1393

    
1394
    }
1395

    
1396
    public static boolean isShowRankInChecklistEditor() {
1397
        return getBooleanValue(PreferencePredicate.ShowRankInDistributionEditor.getKey());
1398
    }
1399
    public static void setShowRankInChecklistEditor(boolean selection) {
1400
       setBooleanValue(PreferencePredicate.ShowRankInDistributionEditor.getKey(), selection);
1401
    }
1402

    
1403
    public static NameDetailsConfigurator getPreferredNameDetailsConfiguration( boolean local) {
1404
        NameDetailsConfigurator config = new NameDetailsConfigurator();
1405
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1406
        CdmPreference preference = null;
1407
        String value;
1408
        if (!local) {
1409
            PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.NameDetailsView);
1410
            preference =  getPreferenceFromDB(PreferencePredicate.NameDetailsView);
1411
            if (preference == null){
1412
                return null;
1413
            }
1414

    
1415
        //    setBooleanValue(ALLOW_OVERRIDE_NAME_DETAILS, preference.isAllowOverride());
1416
            value = preference.getValue();
1417
            config.setAllowOverride(preference.isAllowOverride());
1418
            //the preference value is build like this:
1419
            //<section1>:true;<section2>:false....
1420
        }else{
1421
            value = getStringValue(PreferencePredicate.NameDetailsView.getKey(), local);
1422
        }
1423
        if (value!= null){
1424
            fillNameDetailsConfigurator(config, value);
1425

    
1426

    
1427
        }else {
1428
            return null;
1429
        }
1430
        return config;
1431
    }
1432

    
1433
    public static void fillNameDetailsConfigurator(NameDetailsConfigurator config, String value) {
1434
        String [] sections = value.split(";");
1435
        Map<String, Boolean> sectionMap = new HashMap<>();
1436
        String[] sectionValues;
1437
        for (String sectionValue: sections){
1438
            if (sectionValue.contains(":")){
1439
                sectionValues = sectionValue.split(":");
1440
                sectionMap.put(sectionValues[0], Boolean.valueOf(sectionValues[1]));
1441
            }
1442
        }
1443
        for (Field field: config.getClass().getDeclaredFields()){
1444
            try {
1445
                config.getClass().getDeclaredField(field.getName()).set(config, getValue(sectionMap, field.getName()));
1446
            } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException
1447
                    | SecurityException e) {
1448
               logger.debug(e.getMessage());
1449
            }
1450
        }
1451
    }
1452

    
1453
    public static NameDetailsConfigurator getPreferredNameDetailsConfiguration() {
1454
        NameDetailsConfigurator config = new NameDetailsConfigurator();
1455

    
1456
        String value;
1457

    
1458
        value = getStringValue(PreferencePredicate.NameDetailsView.getKey(), false);
1459
        if (value != null){
1460
            fillNameDetailsConfigurator(config, value);
1461
        }else {
1462
            return null;
1463
        }
1464
        return config;
1465
    }
1466

    
1467
    public static void setPreferredNameDetailsConfiguration(NameDetailsConfigurator config, boolean local) {
1468
        CdmPreference preference = null;
1469

    
1470
        if (!local) {
1471
            preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.NameDetailsView, config.toString());
1472

    
1473
            setPreferenceToDB(preference);
1474
        }
1475
        else{
1476
            setStringValue(PreferencePredicate.NameDetailsView.getKey(), config.toString());
1477
        }
1478

    
1479

    
1480
    }
1481

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

    
1489
    }
1490

    
1491
    public static Abcd206ImportConfigurator getDBAbcdImportConfigurationPreference() {
1492

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

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

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

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

    
1575

    
1576
             }
1577
         }
1578
    }
1579
    public static Abcd206ImportConfigurator getLocalAbcdImportConfigurator(){
1580
        return getLocalAbcdImportConfigurator(true);
1581
    }
1582
    public static Abcd206ImportConfigurator getLocalAbcdImportConfigurator(boolean skipCheckOverride){
1583
       Abcd206ImportConfigurator config = Abcd206ImportConfigurator.NewInstance(null,null);
1584
       CdmPreference pref = CdmPreferenceCache.instance().get(PreferencePredicate.AbcdImportConfig.getKey());
1585
       if (pref  == null || pref.isAllowOverride()){
1586
       String configString = PreferencesUtil.getStringValue(IPreferenceKeys.LAST_USED_ABCD_CONFIG);
1587
           if (StringUtils.isBlank(configString)){
1588
               configString = getStringValue(PreferencePredicate.AbcdImportConfig.getKey(), skipCheckOverride);
1589
               extractAbcdConfiguratorFromPreferenceString(config, configString);
1590
               if (config.getNomenclaturalCode() == null){
1591
                   config.setNomenclaturalCode(getPreferredNomenclaturalCode());
1592
               }
1593
           }else{
1594
               config = Abcd206ImportConfigurator.NewInstance(null, null);
1595
               PreferencesUtil.extractAbcdConfiguratorFromPreferenceString(config, configString);
1596
           }
1597
       }else{
1598
           extractAbcdConfiguratorFromPreferenceString(config, pref.getValue());
1599
       }
1600

    
1601
       return config;
1602

    
1603
    }
1604

    
1605
    public static void updateAbcdImportConfigurationPreference() {
1606
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1607

    
1608
        CdmPreference pref = cache.findBestMatching(CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AbcdImportConfig));
1609

    
1610
        if (!getBooleanValue(prefOverrideKey(PreferencePredicate.AbcdImportConfig.getKey())) || !pref.isAllowOverride()){
1611
            resetToDBPreferenceAbcdCOnfigurator();
1612

    
1613
        }
1614
    }
1615

    
1616
    public static void resetToDBPreferenceAbcdCOnfigurator(){
1617
        Abcd206ImportConfigurator config = getDBAbcdImportConfigurationPreference();
1618
        setStringValue(PreferencePredicate.AbcdImportConfig.getKey(), config.toString());
1619

    
1620
    }
1621

    
1622
    public static boolean isSortTaxaByRankAndName() {
1623

    
1624
        return getBooleanValue(PreferencePredicate.SortTaxaByRankAndName.getKey());
1625
    }
1626

    
1627
    public static TermOrder getSortNamedAreasInDistributionEditor() {
1628
        TermOrder result;
1629
        try{
1630
            result = TermOrder.valueOf(getStringValue(PreferencePredicate.AreasSortedInDistributionEditor.getKey()));
1631
        }catch (IllegalArgumentException e){
1632
            result = (TermOrder)PreferencePredicate.AreasSortedInDistributionEditor.getDefaultValue();
1633
        }
1634
        return result;
1635
    }
1636

    
1637
    public static void setSortNamedAreasInDistributionEditor(String isSortByVocabularyOrder) {
1638
        setStringValue(PreferencePredicate.AreasSortedInDistributionEditor.getKey(), isSortByVocabularyOrder);
1639

    
1640
    }
1641

    
1642
    public static void setLastSelectedReference(
1643
            List<String> lastSelectedReferences) {
1644

    
1645
        setStringValue(PreferencesUtil.LAST_SELECTED_REFERENCES, lastSelectedReferences.toString());
1646
    }
1647

    
1648
    public static List<String> getLastSelectedReferences() {
1649

    
1650
        //IPreferenceStore preferenceStore = PreferencesUtil.getPreferenceStore();
1651
        String lastSelected = getStringValue(PreferencesUtil.LAST_SELECTED_REFERENCES);
1652
        List<String> result = new ArrayList<>();
1653
        if (!StringUtils.isBlank(lastSelected)){
1654
            Collections.addAll(result, lastSelected.substring(1,lastSelected.length()-1).split(", "));
1655
        }
1656
        return result;
1657
    }
1658

    
1659
    public static void setPreferredNamedAreasForDistributionEditor(
1660
            String saveCheckedElements, String saveGrayedElements, boolean local) {
1661
        if (local){
1662
            setStringValue(PreferencePredicate.AvailableDistributionAreaTerms.getKey(), saveCheckedElements);
1663

    
1664
        }
1665
        else{
1666
            CdmPreference preference = null;
1667

    
1668
            if (saveCheckedElements == null){
1669
                preference = getPreferenceFromDB(PreferencePredicate.AvailableDistributionAreaTerms);
1670

    
1671
                if (preference == null){
1672
                    return ;
1673
                } else{
1674
                    setStringValue(PreferencePredicate.AvailableDistributionAreaTerms.getKey(),
1675
                            saveCheckedElements);
1676
                    preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AvailableDistributionAreaTerms, saveCheckedElements);
1677
                    setPreferenceToDB(preference);
1678

    
1679
                }
1680
            } else{
1681
                preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AvailableDistributionAreaTerms, saveCheckedElements);
1682
                setPreferenceToDB(preference);
1683
                setStringValue(PreferencePredicate.AvailableDistributionAreaTerms.getKey(),
1684
                        saveCheckedElements);
1685

    
1686
            }
1687
        }
1688

    
1689
    }
1690

    
1691
    public static void setPreferredVocabulariesForDistributionEditor(String saveCheckedElements,
1692
            boolean local, boolean isOverride) {
1693
        if (local){
1694
            setStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(), saveCheckedElements);
1695
            setBooleanValue(prefOverrideKey(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey()), isOverride);
1696
        }
1697
        else{
1698
            ICdmRepository controller;
1699
            CdmPreference preference = null;
1700

    
1701
            if (saveCheckedElements == null){
1702
                preference = getPreferenceFromDB(PreferencePredicate.AvailableDistributionAreaVocabularies);
1703

    
1704
                if (preference == null){
1705
                    return ;
1706
                } else{
1707
                    setStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(),
1708
                            saveCheckedElements);
1709
                    preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AvailableDistributionAreaVocabularies, saveCheckedElements);
1710
                    preference.setAllowOverride(isOverride);
1711
                    setPreferenceToDB(preference);
1712
                }
1713
            } else{
1714
                preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AvailableDistributionAreaVocabularies, saveCheckedElements);
1715
                preference.setAllowOverride(isOverride);
1716
                setPreferenceToDB(preference);
1717
                setStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(),
1718
                        saveCheckedElements);
1719

    
1720
            }
1721
        }
1722
    }
1723

    
1724
    public static String getPreferredVocabulariesForDistributionEditor(boolean local) {
1725
        if (local){
1726

    
1727
            String pref = getStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(), local);
1728
            return pref;
1729
        }
1730
        else{
1731
            CdmPreference preference = null;
1732
            preference = getPreferenceFromDB(PreferencePredicate.AvailableDistributionAreaVocabularies);
1733
            if (preference == null){
1734
                return null;
1735
            } else{
1736
                return preference.getValue();
1737
            }
1738

    
1739
        }
1740
    }
1741

    
1742
    public static List<UUID> createUUIDListFromStringPref(String prefKey, boolean local) {
1743
        if (prefKey == null){
1744
            return null;
1745
        }
1746
        String prefValue = PreferencesUtil.getStringValue(prefKey, local);
1747
        if (prefValue == null){
1748
            return null;
1749
        }
1750
        List<UUID> uuidList = createUuidList(prefValue);
1751
        return uuidList;
1752
    }
1753

    
1754
    public static List<UUID> createUuidList(String prefValue) {
1755
        String[] stringArray = prefValue.split(";");
1756
        List<UUID> uuidList = new ArrayList();
1757
        for (String uuid: stringArray){
1758
            if (!StringUtils.isBlank(uuid)){
1759
                uuidList.add(UUID.fromString(uuid));
1760
            }
1761
        }
1762
        return uuidList;
1763
    }
1764

    
1765
    public static boolean getFilterCommonNameReferences(){
1766
        Boolean result = getBooleanValue(PreferencesUtil.FILTER_COMMON_NAME_REFERENCES);
1767
        if (result == null){
1768
            return false;
1769
        }
1770
        return result;
1771
    }
1772

    
1773
    public static void updateDBPreferences() {
1774

    
1775

    
1776
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1777
        cache.getAllTaxEditorDBPreferences();
1778

    
1779
        //ABCD Configurator
1780

    
1781
        //updateAbcdImportConfigurationPreference();
1782

    
1783
        //Name Details
1784
        NameDetailsConfigurator config = getPreferredNameDetailsConfiguration(false);
1785
        //    if (config != null ){
1786
        //        if (!getBooleanValue(OVERRIDE_NAME_DETAILS) ||  !getBooleanValue(ALLOW_OVERRIDE_NAME_DETAILS)){
1787
        //            setPreferredNameDetailsConfiguration(config, false);
1788
        //        }
1789
        //    }
1790

    
1791
    }
1792

    
1793
    public static void setPreferencesToDB(List<CdmPreference> preferences) {
1794

    
1795
        ICdmRepository controller;
1796
        //try{
1797
            if(CdmStore.isActive()){
1798
                controller = CdmStore.getCurrentApplicationConfiguration();
1799
                for (CdmPreference preference: preferences){
1800
                    if (preference.getValue() == null && preference.isAllowOverride()){
1801
                        controller.getPreferenceService().remove(preference.getKey());
1802

    
1803
                    }else{
1804
                        controller.getPreferenceService().set(preference);
1805

    
1806
                    }
1807

    
1808
                }
1809
                CdmPreferenceCache.instance().getAllTaxEditorDBPreferences();
1810

    
1811
            }
1812
        /*}catch(Exception e){
1813
            e.printStackTrace();
1814
        }*/
1815
    }
1816

    
1817
    /**
1818
     * Returns whether the named preference is known.
1819
     * @param prefKey the key of the preference
1820
     * @return <code>true</code> if the preference is known, <code>false</code> otherwise
1821
     */
1822
    public static boolean contains(String prefKey){
1823
        return getPreferenceStore().contains(prefKey(prefKey));
1824
    }
1825

    
1826
    /**
1827
     *
1828
     */
1829
    public static TermTree getPreferredFeatureTreeForNameDescription(boolean createNew) {
1830
        if(preferredNameFeatureTree != null && !createNew){
1831
            return preferredNameFeatureTree;
1832
        }
1833
        createPreferredFeatureTreeForNameDescription();
1834
        return preferredNameFeatureTree;
1835

    
1836
    }
1837

    
1838
    public static void createPreferredFeatureTreeForNameDescription() {
1839

    
1840
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1841
        CdmPreference pref = cache.get(PreferencePredicate.NameFeatures.getKey());
1842
        List<Feature> terms = new ArrayList();
1843
        boolean override = PreferencesUtil.getBooleanValue(PreferencesUtil.createOverridePreferenceString(PreferencePredicate.NameFeatures.getKey()));
1844

    
1845
        List<UUID> uuids = PreferencesUtil.createUUIDListFromStringPref(PreferencePredicate.NameFeatures.getKey(), false);
1846
        if (uuids != null && !uuids.isEmpty()){
1847
            terms = CdmStore.getTermManager().getTerms(uuids, Feature.class);
1848
        }
1849

    
1850

    
1851

    
1852

    
1853
       if (terms.isEmpty()){
1854
           terms.addAll(TermStore.getTerms(CdmStore.getService(IVocabularyService.class).load(VocabularyEnum.NameFeature.getUuid()), null));
1855

    
1856
        }
1857
        terms.remove(Feature.PROTOLOGUE());
1858
        if (terms.isEmpty()){
1859
            preferredNameFeatureTree = TermEditorInput.getDefaultNameFeatureTree();
1860
        }else{
1861
            preferredNameFeatureTree = TermTree.NewInstance(terms);
1862
        }
1863

    
1864

    
1865
    }
1866

    
1867
    /**
1868
     * @param prefsToDelete
1869
     */
1870
    public static void removeFromDB(List<CdmPreference> prefsToDelete) {
1871
        ICdmRepository controller;
1872
        //try{
1873
            if(CdmStore.isActive()){
1874
                controller = CdmStore.getCurrentApplicationConfiguration();
1875
                for (CdmPreference preference: prefsToDelete){
1876
                    controller.getPreferenceService().remove(preference.getKey());
1877
                }
1878
                CdmPreferenceCache.instance().getAllTaxEditorDBPreferences();
1879
            }
1880

    
1881
    }
1882

    
1883
    /**
1884
     * @return
1885
     */
1886
    public static TermTree<?> getPreferredFeatureTreeForTaxonDescription(boolean createNew) {
1887
        if(preferredTaxonFeatureTree != null && !createNew){
1888
            return preferredTaxonFeatureTree;
1889
        }
1890
        createPreferredFeatureTreeForTaxonDescription();
1891
        return preferredTaxonFeatureTree;
1892

    
1893
    }
1894

    
1895
    public static void createPreferredFeatureTreeForTaxonDescription() {
1896

    
1897
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1898
        CdmPreference pref = cache.get(PreferencePredicate.TaxonFeatures.getKey());
1899
        List<Feature> terms;
1900
        boolean override = PreferencesUtil.getBooleanValue(PreferencesUtil.createOverridePreferenceString(PreferencePredicate.TaxonFeatures.getKey()));
1901
        List<UUID> uuids = PreferencesUtil.createUUIDListFromStringPref(PreferencePredicate.TaxonFeatures.getKey(), false);
1902
        terms = CdmStore.getTermManager().getTerms(uuids, Feature.class);
1903
        if (terms == null || terms.isEmpty()){
1904
            terms= CdmStore.getTermManager().getPreferredTerms(TermType.Feature);
1905
            TermVocabulary nameVocabulary = CdmStore.getService(IVocabularyService.class).load(VocabularyEnum.NameFeature.getUuid());
1906
            Set<Feature> nameFeature = nameVocabulary.getTerms();
1907
            terms.removeAll(nameFeature);
1908

    
1909
        }
1910

    
1911
        if (terms.isEmpty()){
1912
            preferredTaxonFeatureTree = TermEditorInput.getDefaultFeatureTree();
1913
        }else{
1914
            preferredTaxonFeatureTree = TermTree.NewInstance(terms);
1915
        }
1916

    
1917

    
1918
    }
1919

    
1920

    
1921

    
1922

    
1923
}
(39-39/55)