Project

General

Profile

Download (74.8 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.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

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

    
264

    
265

    
266
    }
267

    
268
    public static String getStringValue(String name){
269
        return getStringValue(name, false);
270
    }
271

    
272
    private static CdmPreference getDBPreferenceValue(String name) {
273
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
274
        CdmPreference pref = null;
275
        pref = cache.get(name);
276

    
277
        return pref;
278
    }
279

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

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

    
320
        }
321
        return result;
322

    
323
    }
324

    
325
    public static boolean getBooleanValue(String name) {
326
        Boolean result = getBooleanValue(name, false);
327
        if (result == null){
328
            return false;
329
        }else{
330
            return result;
331
        }
332

    
333
    }
334

    
335
    public static Boolean getBooleanValue(String name, boolean local) {
336
        if (CdmStore.isActive()){
337
            CdmPreference pref = getDBPreferenceValue(name);
338
            String overrideKey =  createPreferenceString(createOverridePreferenceString(name));
339
            boolean override = getPreferenceStore().getBoolean(overrideKey);
340

    
341
            if (local || (pref == null && override)|| (pref != null && pref.isAllowOverride() && override)){
342
                //local preference
343
                String dbSpecific = prefKey(name);
344
                return getPreferenceStore().getBoolean(dbSpecific);
345

    
346
             }else if (pref != null){
347
                 //db preference is available and override == false
348
                 if (pref.getValue() == null){
349
                     Object result = PreferencePredicate.getByKey(pref.getPredicate()).getDefaultValue();
350
                     if (result instanceof Boolean){
351
                         return (Boolean)result;
352
                     }else{
353
                         return Boolean.valueOf(result.toString());
354
                     }
355
                 }
356
                return Boolean.valueOf(pref.getValue());
357
            }
358
            //no override but default value
359
            IPreferencePredicate pred = PreferencePredicate.getByKey(name);
360
            if (pred != null){
361
                if (pred.getDefaultValue() instanceof Boolean){
362
                    return (Boolean)pred.getDefaultValue();
363
                }else if (pred.getDefaultValue() != null){
364
                    return Boolean.valueOf(pred.getDefaultValue().toString());
365
                }
366
            }
367
            return false;
368
        }else{
369
            // no connection to db, use local preference
370
            return getPreferenceStore().getBoolean(name);
371
        }
372

    
373
    }
374

    
375

    
376

    
377
    public static float getFloatValue(String name, boolean local) {
378
        CdmPreference pref = getDBPreferenceValue(name);
379
        String prefValue = null;
380
        if (pref != null){
381
            prefValue = pref.getValue();
382
        }
383
        Float result = null;
384
        try{
385
            if (prefValue != null){
386
                result = Float.parseFloat(prefValue);
387
            }
388
        }catch(NumberFormatException e){
389
            logger.debug("Preference value of " + name + " is not a number");
390
        }
391
        String overrideKey =  createPreferenceString(createOverridePreferenceString(name));
392
        boolean override = true;
393
        if (getPreferenceStore().contains(overrideKey)){
394
            override = getPreferenceStore().getBoolean(overrideKey);
395
        }
396
        if (local || pref == null || (pref != null && pref.isAllowOverride() && override)){
397
            String dbSpecific = prefKey(name);
398
            if (getPreferenceStore().contains(dbSpecific)){
399
                result = getPreferenceStore().getFloat(dbSpecific);
400
            }else{
401
                IPreferencePredicate pred = PreferencePredicate.getByKey(name);
402
                if (pred != null){
403
                    if (pred.getDefaultValue() instanceof Float){
404
                        return (float)pred.getDefaultValue();
405
                    }else if (pred.getDefaultValue() != null){
406
                        return Float.valueOf(pred.getDefaultValue().toString());
407
                    }
408
                }
409
                return 0;
410
            }
411
        }
412
        return result;
413

    
414
    }
415

    
416

    
417

    
418
    public static CdmPreference setPreferredNomenclaturalCode(
419
            String preferenceValue, boolean local) {
420
        if (local){
421
            setStringValue(PreferencePredicate.NomenclaturalCode.getKey(),
422
                    preferenceValue);
423
        }
424
        else{
425
            ICdmRepository controller;
426
            controller = CdmStore.getCurrentApplicationConfiguration();
427
            if (controller == null){
428
                return null;
429
            }
430
            PrefKey key = null;
431
            try{
432
                key = CdmPreference.NewKey(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.NomenclaturalCode);
433
            }catch (Exception e){
434
                System.out.println(e.getStackTrace());
435
            }
436
            CdmPreference preference = null;
437

    
438
            if (preferenceValue == null){
439
                preference = controller.getPreferenceService().find(key);
440
                if (preference == null){
441
                    return null;
442
                } else{
443
                    setStringValue(PreferencePredicate.NomenclaturalCode.getKey(),
444
                            preference.getValue());
445

    
446
                    return preference;
447
                }
448
            } else{
449
                preference = CdmPreference.NewInstance(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.NomenclaturalCode, preferenceValue);
450
                controller.getPreferenceService().set(preference);
451

    
452
            }
453
        }
454
        return null;
455

    
456

    
457

    
458
    }
459

    
460
    public static void setPreferredNomenclaturalCode(
461
        CdmPreference preference) {
462

    
463
        ICdmRepository controller;
464
        controller = CdmStore.getCurrentApplicationConfiguration();
465
        if (controller == null){
466
            return;
467
        }
468

    
469
        if (preference == null){
470
            PrefKey key = null;
471
              try{
472
                  key = CdmPreference.NewKey(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.NomenclaturalCode);
473
              }catch (Exception e){
474
                  System.out.println(e.getStackTrace());
475
              }
476
            controller.getPreferenceService().remove(key);
477
        }else{
478
            controller.getPreferenceService().set(preference);
479
        }
480

    
481
    }
482

    
483
    public static NomenclaturalCode getPreferredNomenclaturalCode() {
484

    
485
        CdmPreference pref = getPreferenceFromDB(PreferencePredicate.NomenclaturalCode);
486

    
487

    
488
        String preferredCode;
489
        if(pref == null || (pref.isAllowOverride() && getBooleanValue(prefOverrideKey(PreferencePredicate.NomenclaturalCode.getKey())))){
490
            preferredCode = getStringValue(
491
                    PreferencePredicate.NomenclaturalCode.getKey(), true);
492

    
493
        }else{
494
            preferredCode = pref.getValue();
495
        }
496
        if (StringUtils.isBlank(preferredCode)){
497
            preferredCode = getPreferenceKey((NomenclaturalCode)PreferencePredicate.NomenclaturalCode.getDefaultValue());
498
        }
499

    
500
        return getPreferredNomenclaturalCode(preferredCode);
501

    
502
    }
503

    
504
    public static NomenclaturalCode getPreferredNomenclaturalCode(String preferenceKeyNomenclaturalCode) {
505

    
506
        for (NomenclaturalCode code : NomenclaturalCodeHelper.getAllCodes()) {
507
            if (getPreferenceKey(code).equals(preferenceKeyNomenclaturalCode) || code.getKey().equals(preferenceKeyNomenclaturalCode)) {
508
                return code;
509
            }
510
        }
511
        return null;
512
    }
513

    
514
    public static boolean isShowTaxonAssociations(){
515
        boolean result = getBooleanValue(PreferencePredicate.ShowTaxonAssociations.getKey());
516
        return result;
517
    }
518

    
519
    public static boolean isShowLifeForm(){
520
        boolean result =  getBooleanValue(PreferencePredicate.ShowLifeForm.getKey());
521
        return result;
522
    }
523

    
524
    public static boolean isDeterminationOnlyForFieldUnits(){
525
        boolean result =  getBooleanValue(PreferencePredicate.DeterminationOnlyForFieldUnits.getKey());
526
        return result;
527
    }
528

    
529
    public static boolean isCollectingAreaInGeneralSection(){
530
        boolean result =  getBooleanValue(PreferencePredicate.ShowCollectingAreasInGeneralSection.getKey());
531
        return result;
532
    }
533

    
534
    public static CdmPreference getPreferenceFromDB(IPreferencePredicate predicate){
535
        ICdmRepository controller;
536
        CdmPreference pref = null;
537

    
538
        try{
539
            if(CdmStore.isActive()){
540
                controller = CdmStore.getCurrentApplicationConfiguration();
541
                PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), predicate);
542
                pref = controller.getPreferenceService().find(key);
543
            }
544
        }catch(Exception e){
545
            e.printStackTrace();
546
        }
547

    
548
        return pref;
549

    
550
    }
551

    
552
    public static List<CdmPreference> getPreferencesFromDB(IPreferencePredicate predicate){
553
        ICdmRepository controller;
554
        List<CdmPreference> prefs = null;
555

    
556
        try{
557
            if(CdmStore.isActive()){
558
                controller = CdmStore.getCurrentApplicationConfiguration();
559
                PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), predicate);
560
                prefs = controller.getPreferenceService().list(predicate);
561
            }
562
        }catch(Exception e){
563
            e.printStackTrace();
564
        }
565

    
566
        return prefs;
567

    
568
    }
569

    
570
    public static void setPreferencesToDB(CdmPreference preference, boolean setDefault){
571
        ICdmRepository controller;
572
        try{
573
            if(CdmStore.isActive()){
574
                controller = CdmStore.getCurrentApplicationConfiguration();
575

    
576
                if (setDefault){
577
                    controller.getPreferenceService().remove(preference.getKey());
578
                }else{
579
                    controller.getPreferenceService().set(preference);
580
                }
581
            }
582
        }catch(Exception e){
583
            e.printStackTrace();
584
        }
585

    
586

    
587

    
588
    }
589

    
590
    public static CdmPreference getPreferenceFromDB(PrefKey key){
591
        ICdmRepository controller;
592
        CdmPreference pref = null;
593

    
594
        try{
595
            if(CdmStore.isActive()){
596
                controller = CdmStore.getCurrentApplicationConfiguration();
597
                pref = controller.getPreferenceService().find(key);
598
            }
599
        }catch(Exception e){
600
            e.printStackTrace();
601
        }
602

    
603
        return pref;
604

    
605
    }
606

    
607
    public static void setPreferenceToDB(CdmPreference preference){
608
        ICdmRepository controller;
609
        try{
610
            if(CdmStore.isActive()){
611
                controller = CdmStore.getCurrentApplicationConfiguration();
612
                if (preference.getValue() == null && preference.isAllowOverride()){
613
                    controller.getPreferenceService().remove(preference.getKey());
614
                }else{
615
                    controller.getPreferenceService().set(preference);
616
                }
617
                CdmPreferenceCache.instance().put(preference);
618
            }
619
        }catch(Exception e){
620
            e.printStackTrace();
621
        }
622

    
623
    }
624

    
625
    public static String getPreferredDefaultLangugae(){
626
        String preferredLanguage = getStringValue(DEFAULT_LANGUAGE_EDITOR, true);
627
        if(StringUtils.isNotEmpty(preferredLanguage) && StringUtils.isNotBlank(preferredLanguage)){
628
            return preferredLanguage;
629
        }
630
        return null;
631
    }
632

    
633
    public static boolean isShowMediaPreview(){
634
        boolean isShowMediaPreview = getBooleanValue(SHOW_MEDIA_PREVIEW, true);
635
        return isShowMediaPreview;
636
    }
637

    
638
    /**
639
     * Get the match strategy for the given class that was stored in preferences
640
     * or the default strategy if it was not stored in preferences
641
     *
642
     * @param clazz
643
     *            a {@link java.lang.Class} object.
644
     * @return a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy} object.
645
     */
646
    public static IMatchStrategy getMatchStrategy(Class<?> clazz) {
647
        String className = clazz.getName();
648
        if (getBooleanValue(MATCH_STRATEGY_PREFIX + className, true)) {
649
            IMatchStrategy matchStrategy = getDefaultMatchStrategy(clazz);
650

    
651
            //TODO CacheMatchers (or multiple field matchers in future) are missing here
652
            for (FieldMatcher fieldMatcher : matchStrategy.getMatching().getFieldMatchers(false)) {
653
                String fieldName = fieldMatcher.getPropertyName();
654
                String matchModeName = getStringValue(
655
                        getMatchStrategyFieldName(className, fieldName), true);
656
                MatchMode matchMode = MatchMode.valueOf(matchModeName);
657
                try {
658
                    matchStrategy.setMatchMode(fieldName, matchMode);
659
                } catch (MatchException e) {
660
                    MessagingUtils.error(PreferencesUtil.class, e);
661
                    throw new RuntimeException(e);
662
                }
663
            }
664

    
665
            return matchStrategy;
666
        }
667
        return getDefaultMatchStrategy(clazz);
668
    }
669

    
670
    /**
671
     * Stores a matchStrategy into the preference store.
672
     *
673
     * @param matchStrategy
674
     *            a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy}
675
     *            object.
676
     */
677
    public static void setMatchStrategy(IMatchStrategy matchStrategy) {
678
        String className = "ANY class"; //FIXME was: matchStrategy.getMatchClass().getName(); seems currently not in use
679
        setBooleanValue(MATCH_STRATEGY_PREFIX + className, true);
680

    
681
        List<FieldMatcher> fieldMatchers = matchStrategy.getMatching().getFieldMatchers(false);
682

    
683
        for (FieldMatcher fieldMatcher : fieldMatchers) {
684
            String fieldName = fieldMatcher.getPropertyName();
685
            setStringValue(
686
                    getMatchStrategyFieldName(className, fieldName),
687
                    fieldMatcher.getMatchMode().name());
688
        }
689
    }
690

    
691
    /**
692
     * Helper method to create the preference property for a match field.
693
     *
694
     * @param className
695
     * @param fieldName
696
     * @return
697
     */
698
    private static String getMatchStrategyFieldName(String className,
699
            String fieldName) {
700
        return MATCH_STRATEGY_PREFIX + className + "." + fieldName;
701
    }
702

    
703
    /**
704
     * Returns the default match strategy for a given class.
705
     *
706
     * @param clazz
707
     *            a {@link java.lang.Class} object.
708
     * @return a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy} object.
709
     */
710
    public static IMatchStrategy getDefaultMatchStrategy(Class clazz) {
711
        return DefaultMatchStrategy.NewInstance(clazz);
712
    }
713

    
714
    public static String getDateFormatPattern() {
715
        // TODO make this configurable in properties
716
        String pattern = "Y-M-d H:m";
717
        return pattern;
718
    }
719

    
720
    public static <T extends TermBase> void addTermToPreferredTerms(T term) {
721

    
722
        // VocabularyEnum vocabulary =
723
        // VocabularyEnum.getVocabularyEnum(term.getClass());
724
        //
725
        // getPreferenceStore().setValue(getPreferenceKey(term),
726
        // VocabularyStore.getTermVocabulary(vocabulary).getTerms().contains(term));
727
        //
728
        // firePreferencesChanged(term.getClass());
729
    }
730

    
731
    /**
732
     * Construct a unique key using the CdmBase object's uuid
733
     *
734
     * @param cdmBase
735
     * @return
736
     */
737
    private static String getPreferenceKey(ICdmBase cdmBase) {
738
        cdmBase = HibernateProxyHelper.deproxy(cdmBase);
739

    
740
        String key = cdmBase.getClass().getName().concat(".")
741
                .concat(cdmBase.getUuid().toString());
742
        if (key.contains("javassist")) {
743
            MessagingUtils.info("proxy");
744
        }
745
        return key;
746
    }
747

    
748
    /**
749
     * Construct a unique key using the CdmBase object's uuid
750
     *
751
     * @param cdmBase
752
     * @return
753
     */
754
    public static String getPreferenceKey(ISimpleTerm simpleTerm) {
755
        simpleTerm = HibernateProxyHelper.deproxy(simpleTerm);
756
        String key = simpleTerm.getClass().getName().concat(".")
757
                .concat(simpleTerm.getUuid().toString());
758
        if (key.contains("javassist")) {
759
            MessagingUtils.warn(PreferencesUtil.class,
760
                    "Trying to persist a preference based on a proxy class.");
761
        }
762
        return key;
763
    }
764

    
765

    
766

    
767
    /**
768
     * Construct a unique key using the CdmBase object's uuid
769
     *
770
     * @param cdmBase
771
     * @return
772
     */
773
    public static String getPreferenceKey(IDefinedTerm definedTerm) {
774
        definedTerm = HibernateProxyHelper.deproxy(definedTerm);
775
        String key = definedTerm.getClass().getName().concat(".")
776
                .concat(definedTerm.getUuid().toString());
777
        if (key.contains("javassist")) {
778
            MessagingUtils.warn(PreferencesUtil.class,
779
                    "Trying to persist a preference based on a proxy class.");
780
        }
781
        return key;
782
    }
783

    
784
    /**
785
     * Retrieves search preferences from the preference store
786
     *
787
     * @return an {@link ITaxonServiceConfigurator} to pass to search methods
788
     */
789
    public static IFindTaxaAndNamesConfigurator getSearchConfigurator() {
790
        IFindTaxaAndNamesConfigurator configurator = initializeSearchConfigurator();
791

    
792
        configurator.setDoTaxa(PreferencesUtil.getPreferenceStore().contains(IPreferenceKeys.TAXON_SERVICE_CONFIGURATOR_TAXA)? PreferencesUtil.getPreferenceStore().getBoolean(
793
                IPreferenceKeys.TAXON_SERVICE_CONFIGURATOR_TAXA): true);
794
        configurator.setDoSynonyms(PreferencesUtil.getPreferenceStore().contains(IPreferenceKeys.TAXON_SERVICE_CONFIGURATOR_SYNONYMS)? PreferencesUtil.getPreferenceStore().getBoolean(
795
                IPreferenceKeys.TAXON_SERVICE_CONFIGURATOR_SYNONYMS): true);
796
        configurator.setDoNamesWithoutTaxa(PreferencesUtil.getPreferenceStore().contains(IPreferenceKeys.TAXON_SERVICE_CONFIGURATOR_NAMES)? PreferencesUtil.getPreferenceStore().getBoolean(
797
                IPreferenceKeys.TAXON_SERVICE_CONFIGURATOR_NAMES): true);
798
        configurator.setDoTaxaByCommonNames(PreferencesUtil.getPreferenceStore().contains(IPreferenceKeys.TAXON_SERVICE_CONFIGURATOR_COMMON_NAMES)? PreferencesUtil.getPreferenceStore().getBoolean(
799
                IPreferenceKeys.TAXON_SERVICE_CONFIGURATOR_COMMON_NAMES): true);
800
        //configurator.setMatchMode(eu.etaxonomy.cdm.persistence.query.MatchMode.valueOf(getStringValue(TAXON_SERVICE_CONFIGURATOR_MATCH_MODE)));
801

    
802
        return configurator;
803
    }
804

    
805
    /**
806
     * create new preferences, setting all search options to true
807
     *
808
     * @return a
809
     *         {@link eu.etaxonomy.cdm.api.service.config.ITaxonServiceConfigurator}
810
     *         object.
811
     */
812
    public static IFindTaxaAndNamesConfigurator initializeSearchConfigurator() {
813
        IFindTaxaAndNamesConfigurator configurator = FindTaxaAndNamesConfiguratorImpl.NewInstance();
814

    
815
        configurator.setDoTaxa(true);
816
        configurator.setDoSynonyms(true);
817
        configurator.setDoNamesWithoutTaxa(true);
818
        configurator.setDoTaxaByCommonNames(true);
819

    
820
        configurator.setTaxonPropertyPath(Arrays.asList("$", "titleCache",
821
                "name", "name.$", "relationsFromThisTaxon.$"));
822

    
823
        configurator.setSynonymPropertyPath(Arrays.asList("$", "titleCache",
824
                "name", "name.$", "synonyms.relatedTo.*"));
825

    
826
        // DEFAULT VALUES
827
        // match mode is a simple like, actually all other match modes are kind
828
        // of bogus
829
        configurator
830
                .setMatchMode(eu.etaxonomy.cdm.persistence.query.MatchMode.ANYWHERE);
831
        // we set page number and size here as this should always be unlimited
832
        configurator.setPageNumber(0);
833
        // TODO currently limit results to 10000
834
        configurator.setPageSize(10000);
835
        //setSearchConfigurator(configurator) ;
836
        return configurator;
837
    }
838

    
839
    /**
840
     * Store search preferences
841
     *
842
     * @param configurator
843
     *            a
844
     *            {@link eu.etaxonomy.cdm.api.service.config.ITaxonServiceConfigurator}
845
     *            object.
846
     */
847
    public static void setSearchConfigurator(
848
            IFindTaxaAndNamesConfigurator configurator) {
849
        getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_TAXA,
850
                configurator.isDoTaxa());
851
        getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_SYNONYMS,
852
                configurator.isDoSynonyms());
853
        getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_NAMES,
854
                configurator.isDoNamesWithoutTaxa());
855
        getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_COMMON_NAMES,
856
                configurator.isDoTaxaByCommonNames());
857
    }
858

    
859
    public static void firePreferencesChanged(Class clazz) {
860
        getPreferenceStore().firePropertyChangeEvent(PREFERRED_TERMS_CHANGE,
861
                null, clazz);
862
    }
863

    
864

    
865
    public static String createPreferenceString(String property){
866
       return prefKey(property);
867

    
868
    }
869
    public static String createOverridePreferenceString(String property){
870
           return prefOverrideKey(property);
871

    
872
        }
873

    
874
    /**
875
     * Set default values for preferences
876
     */
877
    public static void setDefaults() {
878

    
879
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.EditMapServiceAccessPoint.getKey()),
880
                "http://edit.africamuseum.be/edit_wp5/v1.2/rest_gen.php");
881
        //FIXME : changed default for SHOULD_CONNECT_AT_STARTUP to false (ticket 3828) until resolution
882
        getPreferenceStore().setDefault(createPreferenceString(SHOULD_CONNECT_AT_STARTUP), false);
883
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.MobotOpenUrlServiceAccessPoint.getKey()),
884
                "http://www.biodiversitylibrary.org/openurl");
885
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.MobotOpenUrlServiceMaxWidth.getKey()), "1000");
886
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.MobotOpenUrlServiceMaxHeight.getKey()), "1000");
887
        getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_TAXA, true);
888
        getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_SYNONYMS, true);
889
        getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_NAMES, true);
890
        getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_COMMON_NAMES, true);
891

    
892

    
893
        //Name Details
894
       // getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.NameDetailsView.getKey()), new NameDetailsConfigurator(false).toString());
895

    
896
        //Navigator preferences
897
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.TaxonNodeOrder.getKey()), NavigatorOrderEnum.RankAndNameOrder.getKey());
898

    
899
        //getPreferenceStore().setDefault(createPreferenceString(Prefe), true);
900

    
901
        getPreferenceStore().setDefault(createPreferenceString(SHOW_ADVANCED_MEDIA_SECTION), false);
902

    
903
        getPreferenceStore().setDefault(createPreferenceString(SHOW_MEDIA_PREVIEW), false);
904
        //override db preferences
905
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.AbcdImportConfig.getKey())), false);
906
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.NameDetailsView.getKey())), false);
907
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.CommonNameAreaVocabularies.getKey())), false);
908
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.CommonNameReferencesWithMarker.getKey()), false);
909
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowTaxonNodeWizard.getKey()), Boolean.valueOf(PreferencePredicate.ShowTaxonNodeWizard.getDefaultValue().toString()));
910
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowNamespaceInSource.getKey()), Boolean.valueOf(PreferencePredicate.ShowNamespaceInSource.getDefaultValue().toString()));
911
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowIdInSource.getKey()), Boolean.valueOf(PreferencePredicate.ShowIdInSource.getDefaultValue().toString()));
912
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.DisableMultiClassification.getKey()), Boolean.valueOf(PreferencePredicate.DisableMultiClassification.getDefaultValue().toString()));
913
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowImportExportMenu.getKey()), Boolean.valueOf(PreferencePredicate.ShowImportExportMenu.getDefaultValue().toString()));
914
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowSpecimen.getKey()), Boolean.valueOf(PreferencePredicate.ShowSpecimen.getDefaultValue().toString()));
915
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.SearchForIdentifierAndTitleCache.getKey()), Boolean.valueOf(PreferencePredicate.SearchForIdentifierAndTitleCache.getDefaultValue().toString()));
916
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.SearchForIdentifierAndTitleCache.getKey())), false);
917
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.SearchForIdentifierAsDefault.getKey()), Boolean.valueOf(PreferencePredicate.SearchForIdentifierAsDefault.getDefaultValue().toString()));
918
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.SearchForIdentifierAsDefault.getKey())), false);
919
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.ShowModifierFreeText.getKey())), false);
920
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.ShowModifier.getKey())), false);
921
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.DistributionEditorActivated.getKey())), false);
922

    
923
    }
924

    
925
    public static void checkNomenclaturalCode() {
926
        // First time Editor is opened, no nomenclatural code has been set
927
        if (PreferencesUtil.getPreferredNomenclaturalCode() == null) {
928
            PreferencesUtil.setPreferredNomenclaturalCode(getPreferenceKey(NomenclaturalCode.ICNAFP), true);
929
        }
930

    
931

    
932

    
933
    }
934
    public static void setNomenclaturalCodePreferences(){
935
        ICdmRepository controller;
936
        controller = CdmStore.getCurrentApplicationConfiguration();
937
        PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.NomenclaturalCode);
938
        CdmPreference preference = null;
939
        if (controller == null){
940
            return ;
941
        }
942
        preference = controller.getPreferenceService().find(key);
943
        if (preference == null){
944
            return;
945
        }
946
//        setBooleanValue(ALLOW_OVERRIDE_NOMENCLATURAL_CODE_KEY, preference.isAllowOverride());
947

    
948
        int index = StringUtils.lastIndexOf(preference.getValue(), ".");
949
        UUID uuid = UUID.fromString(preference.getValue().substring(index +1, preference.getValue().length()));
950
        NomenclaturalCode preferredCode = NomenclaturalCode.getByUuid(uuid);
951

    
952
        setStringValue(PreferencePredicate.NomenclaturalCode.getKey(),
953
                getPreferenceKey(preferredCode));
954

    
955
    }
956

    
957
    public static void checkDefaultLanguage(){
958
        if(PreferencesUtil.getPreferredDefaultLangugae() == null){
959
           Shell shell = AbstractUtility.getShell();
960
           int open = new DefaultLanguageDialog(shell).open();
961
           if(open == Window.OK){
962
               PlatformUI.getWorkbench().restart();
963
           }
964
        }else{
965
            //TODO:In case of a reinstall, the config.ini will be overwritten
966
            //     here you create config.ini with the stored key from preferences
967
        }
968
    }
969

    
970
    public static String getMapServiceAccessPoint() {
971
        return getStringValue(PreferencePredicate.EditMapServiceAccessPoint.getKey());
972
    }
973

    
974
    public static boolean shouldConnectAtStartUp() {
975
        //FIXME :  force SHOULD_CONNECT_AT_STARTUP to false (ticket 3828) until resolution
976
        //return getBooleanValue(SHOULD_CONNECT_AT_STARTUP);
977
        return false;
978
    }
979

    
980
    public static TermTree getDefaultFeatureTreeForTextualDescription() {
981
        String uuidString = getStringValue(
982
                FEATURE_TREE_DEFAULT_TEXT, true);
983
        if (StringUtils.isBlank(uuidString)) {
984
            return null;
985
        }
986
        TermTree tree = CdmStore.getService(
987
                ITermTreeService.class).load(UUID.fromString(uuidString));
988

    
989
        if (tree == null || tree.getId() == 0) {
990
            return null;
991
        }
992
        return tree;
993
    }
994

    
995
    public static TermTree getDefaultFeatureTreeForStructuredDescription() {
996
        String uuidString = getStringValue(
997
                FEATURE_TREE_DEFAULT_STRUCTURE, true);
998
        return StringUtils.isBlank(uuidString) ? null : CdmStore.getService(
999
                ITermTreeService.class).load(UUID.fromString(uuidString));
1000
    }
1001

    
1002
    public static void setSortRanksHierarchichally(boolean selection) {
1003
        setBooleanValue(PreferencePredicate.SortRanksHierarchichally.getKey(), selection);
1004
    }
1005

    
1006
    public static boolean getSortRanksHierarchichally() {
1007
        return getBooleanValue(PreferencePredicate.SortRanksHierarchichally.getKey());
1008
    }
1009

    
1010
    public static boolean isMultilanguageTextEditingCapability() {
1011
        return getBooleanValue(
1012
                PreferencePredicate.MultiLanguageTextEditing.getKey());
1013
    }
1014

    
1015
    public static Language getGlobalLanguage() {
1016

    
1017

    
1018
        String languageUuidString = getStringValue(
1019
                GLOBAL_LANGUAGE_UUID, true);
1020

    
1021
        if(!CdmStore.isActive()) {
1022
            MessagingUtils.noDataSourceWarningDialog(languageUuidString);
1023
            return null;
1024
        }
1025

    
1026
        if (CdmUtils.isBlank(languageUuidString)) {
1027
            return Language.getDefaultLanguage();
1028
        }
1029

    
1030
        UUID languageUuid = UUID.fromString(languageUuidString);
1031
        return (Language) CdmStore.getService(ITermService.class).load(
1032
                languageUuid);
1033
    }
1034

    
1035
    public static void setGlobalLanguage(Language language) {
1036
        if(language != null) {
1037
            setStringValue(GLOBAL_LANGUAGE_UUID,language.getUuid().toString());
1038
            CdmStore.setDefaultLanguage(language);
1039
        }
1040

    
1041
    }
1042

    
1043
    public static Map<MarkerType, Boolean> getEditMarkerTypePreferences() {
1044
        List<MarkerType> markerTypes = CdmStore.getTermManager()
1045
                .getPreferredTerms(MarkerType.class);
1046

    
1047
        Map<MarkerType, Boolean> result = new HashMap<MarkerType, Boolean>();
1048

    
1049
        for (MarkerType markerType : markerTypes) {
1050
            String name = getMarkerTypeEditingPreferenceKey(markerType);
1051
            Boolean value = getBooleanValue(name);
1052

    
1053
            result.put(markerType, value);
1054
        }
1055

    
1056
        return result;
1057
    }
1058

    
1059
    public static void setEditMarkerTypePreferences(
1060
            Map<MarkerType, Boolean> markerTypeEditingMap) {
1061
        for (MarkerType markerType : markerTypeEditingMap.keySet()) {
1062
            String name = getMarkerTypeEditingPreferenceKey(markerType);
1063
            setBooleanValue(name,
1064
                    markerTypeEditingMap.get(markerType));
1065
        }
1066

    
1067
    }
1068

    
1069
    private static String getMarkerTypeEditingPreferenceKey(
1070
            MarkerType markerType) {
1071
        markerType = HibernateProxyHelper.deproxy(markerType);
1072
        return markerType.getClass().getName() + EDIT_MARKER_TYPE_PREFIX;
1073
    }
1074

    
1075
    public static void setEditMarkerTypePreference(MarkerType markerType,
1076
            boolean edit) {
1077
        setBooleanValue(
1078
                getMarkerTypeEditingPreferenceKey(markerType), edit);
1079
    }
1080

    
1081
    public static DerivedUnitFacadeConfigurator getDerivedUnitConfigurator() {
1082
        DerivedUnitFacadeConfigurator configurator = DerivedUnitFacadeConfigurator
1083
                .NewInstance();
1084
        configurator.setMoveDerivedUnitMediaToGallery(true);
1085
        configurator.setMoveFieldObjectMediaToGallery(true);
1086
        return configurator;
1087
    }
1088

    
1089
    /**
1090
     * This method will write language properties to the config.ini located in the configuration folder
1091
     * of the Taxonomic Ediitor. <b>This method is only used to set the default language for Taxonomic Editor.</b>
1092
     *
1093
     * @param setLanguage 0 is for german and 1 for english.
1094
     * @throws IOException
1095
     */
1096
    public void writePropertyToConfigFile(int setLanguage) throws IOException {
1097
        File file = org.eclipse.core.runtime.preferences.ConfigurationScope.INSTANCE.getLocation().toFile();
1098
        //give warning to user if the directory has no write access
1099
        if(file == null){
1100
            throw new IOException();
1101
        }
1102
        Properties properties = load(file.getAbsolutePath()+"/config.ini");
1103
        switch(setLanguage){
1104
        case 0:
1105
            properties.setProperty("osgi.nl", "de");
1106
            setStringValue(IPreferenceKeys.DEFAULT_LANGUAGE_EDITOR, "de");
1107
            break;
1108
        case 1:
1109
            properties.setProperty("osgi.nl", "en");
1110
            setStringValue(IPreferenceKeys.DEFAULT_LANGUAGE_EDITOR, "en");
1111
            break;
1112
        default:
1113
            break;
1114
        }
1115
        save(file+"/config.ini", properties);
1116
    }
1117

    
1118
    /**
1119
     * This method loads a property from a given file and returns it.
1120
     *
1121
     * @param filename
1122
     * @return
1123
     * @throws IOException
1124
     */
1125
    private Properties load(String filename) throws IOException {
1126
        FileInputStream in = new FileInputStream(filename);
1127
        Properties prop = new Properties();
1128
        prop.load(in);
1129
        in.close();
1130
        return prop;
1131
    }
1132

    
1133
    /**
1134
     * This method saves a property to the specified file.
1135
     *
1136
     * @param filename
1137
     * @param properties
1138
     * @throws IOException
1139
     */
1140
    private void save(String filename, Properties properties) throws IOException{
1141
        FileOutputStream fos =  new FileOutputStream(filename);
1142
        properties.store(fos, "");
1143
        fos.close();
1144
    }
1145

    
1146
    /**
1147
     * Saves a list of P2 Metadata Repositories as string with specified delimiters
1148
     *
1149
     * @param p2Repos
1150
     */
1151
    public static void setP2Repositories(List<MetadataRepositoryElement> p2Repos) {
1152
        StringBuilder sb = new StringBuilder();
1153
        for(MetadataRepositoryElement p2Repo : p2Repos) {
1154
            sb.append(P2_REPOSITORIES_DELIM);
1155
            if(p2Repo.getName() == null || p2Repo.getName().isEmpty()) {
1156
                sb.append("-");
1157
            } else {
1158
                sb.append(p2Repo.getName());
1159
            }
1160
            sb.append(P2_REPOSITORY_FIELDS_DELIM);
1161
            sb.append(p2Repo.getLocation().toString());
1162
            sb.append(P2_REPOSITORY_FIELDS_DELIM);
1163
            sb.append(String.valueOf(p2Repo.isEnabled()));
1164
        }
1165
        getPreferenceStore().setValue(P2_REPOSITORY_LIST, sb.toString());
1166
    }
1167

    
1168

    
1169
    /**
1170
     * Retrieves a list of previously saved P2 repositories
1171
     *
1172
     * @return
1173
     */
1174
    public static List<MetadataRepositoryElement> getP2Repositories() {
1175
        List<MetadataRepositoryElement> p2Repos = new ArrayList<MetadataRepositoryElement>();
1176
        String p2ReposPref =  getStringValue(P2_REPOSITORY_LIST, true);
1177
        if(p2ReposPref != null && !p2ReposPref.isEmpty()) {
1178
            StringTokenizer p2ReposPrefST = new StringTokenizer(p2ReposPref,P2_REPOSITORIES_DELIM);
1179

    
1180
            while(p2ReposPrefST.hasMoreTokens()) {
1181
                String p2RepoStr = p2ReposPrefST.nextToken();
1182
                StringTokenizer p2ReposStrST = new StringTokenizer(p2RepoStr,P2_REPOSITORY_FIELDS_DELIM);
1183
                if(p2ReposStrST.countTokens()==3) {
1184
                    String nickname = p2ReposStrST.nextToken();
1185
                    URI uri = null;
1186
                    try {
1187
                        uri = new URI(p2ReposStrST.nextToken());
1188
                    } catch (URISyntaxException e) {
1189
                        continue;
1190
                    }
1191
                    boolean enabled = Boolean.parseBoolean(p2ReposStrST.nextToken());
1192
                    MetadataRepositoryElement mre = new MetadataRepositoryElement(null, uri, true);
1193
                    mre.setNickname(nickname);
1194
                    mre.setEnabled(enabled);
1195
                    p2Repos.add(mre);
1196
                }
1197
            }
1198
        }
1199

    
1200
        return p2Repos;
1201
    }
1202

    
1203
    /**
1204
     * enables/disables nested composite. <br>
1205
     *
1206
     * @param ctrl - Composite to be en-/disabeld
1207
     * @param enabled - boolean
1208
     */
1209
    public static void recursiveSetEnabled(Control ctrl, boolean enabled) {
1210
        if (ctrl instanceof Composite) {
1211
            Composite comp = (Composite) ctrl;
1212
            for (Control c : comp.getChildren()) {
1213
                recursiveSetEnabled(c, enabled);
1214
            }
1215
        } else {
1216
            ctrl.setEnabled(enabled);
1217
        }
1218
    }
1219

    
1220
    public static void setSortNodes(NavigatorOrderEnum nodesOrder) {
1221
        if (nodesOrder == null){
1222
            setStringValue(PreferencePredicate.TaxonNodeOrder.getKey(), null);
1223
        }else{
1224
            setStringValue(PreferencePredicate.TaxonNodeOrder.getKey(), nodesOrder.key);
1225
        }
1226

    
1227
    }
1228

    
1229
    public static NavigatorOrderEnum getSortNodes() {
1230
        return NavigatorOrderEnum.valueOf(getStringValue(PreferencePredicate.TaxonNodeOrder.getKey()));
1231

    
1232
    }
1233

    
1234
    public static boolean isNodesSortedNaturally() {
1235
        NavigatorOrderEnum value = NavigatorOrderEnum.valueOf(getStringValue(PreferencePredicate.TaxonNodeOrder.getKey()));
1236
        return value.equals(NavigatorOrderEnum.NaturalOrder);
1237

    
1238
    }
1239

    
1240
    public static boolean isNodesSortedByName() {
1241
        NavigatorOrderEnum value = NavigatorOrderEnum.valueOf(getStringValue(PreferencePredicate.TaxonNodeOrder.getKey()));
1242
        return value.equals(NavigatorOrderEnum.AlphabeticalOrder);
1243

    
1244
    }
1245

    
1246
    public static boolean isNodesSortedByNameAndRank() {
1247
        NavigatorOrderEnum value = NavigatorOrderEnum.valueOf(getStringValue(PreferencePredicate.TaxonNodeOrder.getKey()));
1248
        return value.equals(NavigatorOrderEnum.RankAndNameOrder);
1249

    
1250
    }
1251

    
1252
    public static boolean isStoreNavigatorState() {
1253
        return getBooleanValue(RESTORE_NAVIGATOR_STATE);
1254

    
1255
    }
1256

    
1257
    public static void setStoreNavigatorState(boolean selection) {
1258
        setBooleanValue(RESTORE_NAVIGATOR_STATE, selection);
1259

    
1260
    }
1261

    
1262
    public static boolean isShowUpWidgetIsDisposedMessages() {
1263
       return getBooleanValue(IS_SHOW_UP_WIDGET_IS_DISPOSED);
1264
    }
1265
    public static void setShowUpWidgetIsDisposedMessages(boolean selection) {
1266
        setBooleanValue(IS_SHOW_UP_WIDGET_IS_DISPOSED, selection);
1267
    }
1268

    
1269
    public static boolean isShowIdInVocabularyInChecklistEditor() {
1270
        String area_display = getStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey());
1271
        if (area_display.equals(TermDisplayEnum.IdInVocabulary.getKey())) {
1272
            return true;
1273
        }else{
1274
            return false;
1275
        }
1276
    }
1277
    public static boolean isShowSymbol1InChecklistEditor() {
1278
        String area_display = getStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey());
1279
        if (area_display.equals(TermDisplayEnum.Symbol1.getKey())) {
1280
            return true;
1281
        }else{
1282
            return false;
1283
        }
1284
     }
1285
    public static boolean isShowSymbol2InChecklistEditor() {
1286
        String area_display = getStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey());
1287
        if (area_display.equals(TermDisplayEnum.Symbol2.getKey())) {
1288
            return true;
1289
        }else{
1290
            return false;
1291
        }
1292
     }
1293
    public static void setAreaDisplayInChecklistEditor(String selection) {
1294
        setStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey(), selection);
1295
    }
1296

    
1297
    public static void setOwnDescriptionForChecklistEditor(boolean selection) {
1298
        setBooleanValue(PreferencePredicate.OwnDescriptionForDistributionEditor.getKey(), selection);
1299
    }
1300

    
1301
    public static boolean isOwnDescriptionForChecklistEditor() {
1302
        return getBooleanValue(PreferencePredicate.OwnDescriptionForDistributionEditor.getKey());
1303
    }
1304

    
1305
    public static TermDisplayEnum displayAreaInChecklistEditor() {
1306
        TermDisplayEnum result;
1307
        try{
1308
            result = TermDisplayEnum.byKey(getStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey()));
1309
        }catch (IllegalArgumentException e){
1310
           result = ((TermDisplayEnum) PreferencePredicate.DisplayOfAreasInDistributionEditor.getDefaultValue());
1311
        }
1312
       return result;
1313
    }
1314

    
1315
    public static TermDisplayEnum displayStatusInChecklistEditor() {
1316
        TermDisplayEnum result;
1317
        try{
1318
            result = TermDisplayEnum.byKey(getStringValue(PreferencePredicate.DisplayOfStatus.getKey()));
1319
        }catch (IllegalArgumentException e){
1320
           result = ((TermDisplayEnum) PreferencePredicate.DisplayOfStatus.getDefaultValue());
1321
        }
1322
       return result;
1323
    }
1324
    public static void setDisplayStatusInChecklistEditor(String selection) {
1325
        setStringValue(PreferencePredicate.DisplayOfStatus.getKey(), selection);
1326

    
1327
    }
1328

    
1329
    public static boolean isShowRankInChecklistEditor() {
1330
        return getBooleanValue(PreferencePredicate.ShowRankInDistributionEditor.getKey());
1331
    }
1332
    public static void setShowRankInChecklistEditor(boolean selection) {
1333
       setBooleanValue(PreferencePredicate.ShowRankInDistributionEditor.getKey(), selection);
1334
    }
1335

    
1336
    public static NameDetailsConfigurator getPreferredNameDetailsConfiguration( boolean local) {
1337
        NameDetailsConfigurator config = new NameDetailsConfigurator();
1338
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1339
        CdmPreference preference = null;
1340
        String value;
1341
        if (!local) {
1342
            PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.NameDetailsView);
1343
            preference =  getPreferenceFromDB(PreferencePredicate.NameDetailsView);
1344
            if (preference == null){
1345
                return null;
1346
            }
1347

    
1348
        //    setBooleanValue(ALLOW_OVERRIDE_NAME_DETAILS, preference.isAllowOverride());
1349
            value = preference.getValue();
1350
            config.setAllowOverride(preference.isAllowOverride());
1351
            //the preference value is build like this:
1352
            //<section1>:true;<section2>:false....
1353
        }else{
1354
            value = getStringValue(PreferencePredicate.NameDetailsView.getKey(), local);
1355
        }
1356
        if (value!= null){
1357
            fillNameDetailsConfigurator(config, value);
1358

    
1359

    
1360
        }else {
1361
            return null;
1362
        }
1363
        return config;
1364
    }
1365

    
1366
    public static void fillNameDetailsConfigurator(NameDetailsConfigurator config, String value) {
1367
        String [] sections = value.split(";");
1368
        Map<String, Boolean> sectionMap = new HashMap<>();
1369
        String[] sectionValues;
1370
        for (String sectionValue: sections){
1371
            if (sectionValue.contains(":")){
1372
                sectionValues = sectionValue.split(":");
1373
                sectionMap.put(sectionValues[0], Boolean.valueOf(sectionValues[1]));
1374
            }
1375
        }
1376
        for (Field field: config.getClass().getDeclaredFields()){
1377
            try {
1378
                config.getClass().getDeclaredField(field.getName()).set(config, getValue(sectionMap, field.getName()));
1379
            } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException
1380
                    | SecurityException e) {
1381
               logger.debug(e.getMessage());
1382
            }
1383
        }
1384
    }
1385

    
1386
    public static NameDetailsConfigurator getPreferredNameDetailsConfiguration() {
1387
        NameDetailsConfigurator config = new NameDetailsConfigurator();
1388

    
1389
        String value;
1390

    
1391
        value = getStringValue(PreferencePredicate.NameDetailsView.getKey(), false);
1392
        if (value != null){
1393
            fillNameDetailsConfigurator(config, value);
1394
        }else {
1395
            return null;
1396
        }
1397
        return config;
1398
    }
1399

    
1400
    public static void setPreferredNameDetailsConfiguration(NameDetailsConfigurator config, boolean local) {
1401
        CdmPreference preference = null;
1402

    
1403
        if (!local) {
1404
            preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.NameDetailsView, config.toString());
1405

    
1406
            setPreferenceToDB(preference);
1407
        }
1408
        else{
1409
            setStringValue(PreferencePredicate.NameDetailsView.getKey(), config.toString());
1410
        }
1411

    
1412

    
1413
    }
1414

    
1415
    private static Boolean getValue(Map<String, Boolean> sectionMap, String string) {
1416
        if (sectionMap.containsKey(string)){
1417
            return sectionMap.get(string);
1418
        }else{
1419
            return true;
1420
        }
1421

    
1422
    }
1423

    
1424
    public static Abcd206ImportConfigurator getDBAbcdImportConfigurationPreference() {
1425

    
1426
        Abcd206ImportConfigurator config = Abcd206ImportConfigurator.NewInstance(null,null);
1427
        ICdmRepository controller;
1428
        controller = CdmStore.getCurrentApplicationConfiguration();
1429
        PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AbcdImportConfig);
1430
        CdmPreference preference = null;
1431
        if (controller == null){
1432
            return null;
1433
        }
1434
        preference = controller.getPreferenceService().find(key);
1435
        if (preference == null){
1436
            return config;
1437
         } else{
1438
             String configString = preference.getValue();
1439
             extractAbcdConfiguratorFromPreferenceString(config, configString);
1440
         }
1441
        return config;
1442
    }
1443

    
1444
    public static void extractAbcdConfiguratorFromPreferenceString(Abcd206ImportConfigurator config,
1445
            String configString) {
1446
        if(configString != null){
1447
             String[] configArray = configString.split(";");
1448

    
1449
             for (String configItem: configArray){
1450
                 String[] keyValue = configItem.split(":");
1451
                 String keyString = keyValue[0];
1452
                 String valueString = null;
1453
                 if (keyValue.length>1){
1454
                     valueString = keyValue[1];
1455
                     if (keyValue.length>2){
1456

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

    
1508

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

    
1534
       return config;
1535

    
1536
    }
1537

    
1538
    public static Abcd206ImportConfigurator getLastUsedAbcdImportConfigurator(){
1539
        Abcd206ImportConfigurator config = Abcd206ImportConfigurator.NewInstance(null,null);
1540

    
1541
       String configString = PreferencesUtil.getStringValue(IPreferenceKeys.LAST_USED_ABCD_CONFIG, true);
1542
       if (configString != null){
1543
           extractAbcdConfiguratorFromPreferenceString(config, configString);
1544
           if (config != null){
1545
               if (config.getNomenclaturalCode() == null){
1546
                   config.setNomenclaturalCode(getPreferredNomenclaturalCode());
1547
               }
1548
           }
1549
       }else{
1550
           config = PreferencesUtil.getLocalAbcdImportConfigurator(false);
1551
       }
1552

    
1553
        return config;
1554

    
1555
     }
1556

    
1557
    public static void updateAbcdImportConfigurationPreference() {
1558
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1559

    
1560
        CdmPreference pref = cache.findBestMatching(CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AbcdImportConfig));
1561

    
1562
        if (!getBooleanValue(prefOverrideKey(PreferencePredicate.AbcdImportConfig.getKey())) || !pref.isAllowOverride()){
1563
            resetToDBPreferenceAbcdCOnfigurator();
1564

    
1565
        }
1566
    }
1567

    
1568
    public static void resetToDBPreferenceAbcdCOnfigurator(){
1569
        Abcd206ImportConfigurator config = getDBAbcdImportConfigurationPreference();
1570
        setStringValue(PreferencePredicate.AbcdImportConfig.getKey(), config.toString());
1571

    
1572
    }
1573

    
1574
    public static boolean isSortTaxaByRankAndName() {
1575

    
1576
        return getBooleanValue(PreferencePredicate.SortTaxaByRankAndName.getKey());
1577
    }
1578

    
1579
    public static TermOrder getSortNamedAreasInDistributionEditor() {
1580
        TermOrder result;
1581
        try{
1582
            result = TermOrder.valueOf(getStringValue(PreferencePredicate.AreasSortedInDistributionEditor.getKey()));
1583
        }catch (IllegalArgumentException e){
1584
            result = (TermOrder)PreferencePredicate.AreasSortedInDistributionEditor.getDefaultValue();
1585
        }
1586
        return result;
1587
    }
1588

    
1589
    public static void setSortNamedAreasInDistributionEditor(String isSortByVocabularyOrder) {
1590
        setStringValue(PreferencePredicate.AreasSortedInDistributionEditor.getKey(), isSortByVocabularyOrder);
1591

    
1592
    }
1593

    
1594
    public static void setLastSelectedReference(
1595
            List<String> lastSelectedReferences) {
1596

    
1597
        setStringValue(PreferencesUtil.LAST_SELECTED_REFERENCES, lastSelectedReferences.toString());
1598
    }
1599

    
1600
    public static List<String> getLastSelectedReferences() {
1601

    
1602
        //IPreferenceStore preferenceStore = PreferencesUtil.getPreferenceStore();
1603
        String lastSelected = getStringValue(PreferencesUtil.LAST_SELECTED_REFERENCES, true);
1604
        List<String> result = new ArrayList<>();
1605
        if (!StringUtils.isBlank(lastSelected)){
1606
            Collections.addAll(result, lastSelected.substring(1,lastSelected.length()-1).split(", "));
1607
        }
1608
        return result;
1609
    }
1610

    
1611
    public static void setPreferredNamedAreasForDistributionEditor(
1612
            String saveCheckedElements, String saveGrayedElements, boolean local) {
1613
        if (local){
1614
            setStringValue(PreferencePredicate.AvailableDistributionAreaTerms.getKey(), saveCheckedElements);
1615

    
1616
        }
1617
        else{
1618
            CdmPreference preference = null;
1619

    
1620
            if (saveCheckedElements == null){
1621
                preference = getPreferenceFromDB(PreferencePredicate.AvailableDistributionAreaTerms);
1622

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

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

    
1638
            }
1639
        }
1640

    
1641
    }
1642

    
1643
    public static void setPreferredVocabulariesForDistributionEditor(String saveCheckedElements,
1644
            boolean local, boolean isOverride) {
1645
        if (local){
1646
            setStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(), saveCheckedElements);
1647
            setBooleanValue(prefOverrideKey(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey()), isOverride);
1648
        }
1649
        else{
1650
            ICdmRepository controller;
1651
            CdmPreference preference = null;
1652

    
1653
            if (saveCheckedElements == null){
1654
                preference = getPreferenceFromDB(PreferencePredicate.AvailableDistributionAreaVocabularies);
1655

    
1656
                if (preference == null){
1657
                    return ;
1658
                } else{
1659
                    setStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(),
1660
                            saveCheckedElements);
1661
                    preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AvailableDistributionAreaVocabularies, saveCheckedElements);
1662
                    preference.setAllowOverride(isOverride);
1663
                    setPreferenceToDB(preference);
1664
                }
1665
            } else{
1666
                preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AvailableDistributionAreaVocabularies, saveCheckedElements);
1667
                preference.setAllowOverride(isOverride);
1668
                setPreferenceToDB(preference);
1669
                setStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(),
1670
                        saveCheckedElements);
1671

    
1672
            }
1673
        }
1674
    }
1675

    
1676
    public static String getPreferredVocabulariesForDistributionEditor(boolean local) {
1677
        if (local){
1678

    
1679
            String pref = getStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(), local);
1680
            return pref;
1681
        }
1682
        else{
1683
            CdmPreference preference = null;
1684
            preference = getPreferenceFromDB(PreferencePredicate.AvailableDistributionAreaVocabularies);
1685
            if (preference == null){
1686
                return null;
1687
            } else{
1688
                return preference.getValue();
1689
            }
1690

    
1691
        }
1692
    }
1693

    
1694
    public static List<UUID> createUUIDListFromStringPref(String prefKey, boolean local) {
1695
        if (prefKey == null){
1696
            return null;
1697
        }
1698
        String prefValue = PreferencesUtil.getStringValue(prefKey, local);
1699
        if (prefValue == null){
1700
            return null;
1701
        }
1702
        List<UUID> uuidList = createUuidList(prefValue);
1703
        return uuidList;
1704
    }
1705

    
1706
    public static List<UUID> createUuidList(String prefValue) {
1707
        String[] stringArray = prefValue.split(";");
1708
        List<UUID> uuidList = new ArrayList();
1709
        for (String uuid: stringArray){
1710
            if (!StringUtils.isBlank(uuid)){
1711
                uuidList.add(UUID.fromString(uuid));
1712
            }
1713
        }
1714
        return uuidList;
1715
    }
1716

    
1717
    public static boolean getFilterCommonNameReferences(){
1718
        Boolean result = getBooleanValue(PreferencesUtil.FILTER_COMMON_NAME_REFERENCES);
1719
        if (result == null){
1720
            return false;
1721
        }
1722
        return result;
1723
    }
1724

    
1725
    public static void updateDBPreferences() {
1726

    
1727

    
1728
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1729
        cache.getAllTaxEditorDBPreferences();
1730

    
1731
        //ABCD Configurator
1732

    
1733
        //updateAbcdImportConfigurationPreference();
1734

    
1735
        //Name Details
1736
        NameDetailsConfigurator config = getPreferredNameDetailsConfiguration(false);
1737
        //    if (config != null ){
1738
        //        if (!getBooleanValue(OVERRIDE_NAME_DETAILS) ||  !getBooleanValue(ALLOW_OVERRIDE_NAME_DETAILS)){
1739
        //            setPreferredNameDetailsConfiguration(config, false);
1740
        //        }
1741
        //    }
1742

    
1743
    }
1744

    
1745
    public static void setPreferencesToDB(List<CdmPreference> preferences) {
1746

    
1747
        ICdmRepository controller;
1748
        //try{
1749
            if(CdmStore.isActive()){
1750
                controller = CdmStore.getCurrentApplicationConfiguration();
1751
                for (CdmPreference preference: preferences){
1752
                    if (preference.getValue() == null && preference.isAllowOverride()){
1753
                        controller.getPreferenceService().remove(preference.getKey());
1754

    
1755
                    }else{
1756
                        controller.getPreferenceService().set(preference);
1757

    
1758
                    }
1759

    
1760
                }
1761
                CdmPreferenceCache.instance().getAllTaxEditorDBPreferences();
1762

    
1763
            }
1764
        /*}catch(Exception e){
1765
            e.printStackTrace();
1766
        }*/
1767
    }
1768

    
1769
    /**
1770
     * Returns whether the named preference is known.
1771
     * @param prefKey the key of the preference
1772
     * @return <code>true</code> if the preference is known, <code>false</code> otherwise
1773
     */
1774
    public static boolean contains(String prefKey){
1775
        return getPreferenceStore().contains(prefKey(prefKey));
1776
    }
1777

    
1778
    /**
1779
     *
1780
     */
1781
    public static TermTree getPreferredFeatureTreeForNameDescription(boolean createNew) {
1782
        if(preferredNameFeatureTree != null && !createNew){
1783
            return preferredNameFeatureTree;
1784
        }
1785
        createPreferredFeatureTreeForNameDescription();
1786
        return preferredNameFeatureTree;
1787

    
1788
    }
1789

    
1790
    public static void createPreferredFeatureTreeForNameDescription() {
1791

    
1792
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1793
        CdmPreference pref = cache.get(PreferencePredicate.NameFeatures.getKey());
1794
        List<Feature> terms = new ArrayList();
1795
        boolean override = PreferencesUtil.getBooleanValue(PreferencesUtil.createOverridePreferenceString(PreferencePredicate.NameFeatures.getKey()));
1796

    
1797
        List<UUID> uuids = PreferencesUtil.createUUIDListFromStringPref(PreferencePredicate.NameFeatures.getKey(), false);
1798
        if (uuids != null && !uuids.isEmpty()){
1799
            terms = CdmStore.getTermManager().getTerms(uuids, Feature.class);
1800
        }
1801

    
1802

    
1803

    
1804

    
1805
       if (terms.isEmpty()){
1806
           terms.addAll(TermStore.getTerms(CdmStore.getService(IVocabularyService.class).load(VocabularyEnum.NameFeature.getUuid()), null));
1807

    
1808
        }
1809
        terms.remove(Feature.PROTOLOGUE());
1810
        if (terms.isEmpty()){
1811
            preferredNameFeatureTree = TermEditorInput.getDefaultNameFeatureTree();
1812
        }else{
1813
            preferredNameFeatureTree = TermTree.NewInstance(terms);
1814
        }
1815

    
1816

    
1817
    }
1818

    
1819
    /**
1820
     * @param prefsToDelete
1821
     */
1822
    public static void removeFromDB(List<CdmPreference> prefsToDelete) {
1823
        ICdmRepository controller;
1824
        //try{
1825
            if(CdmStore.isActive()){
1826
                controller = CdmStore.getCurrentApplicationConfiguration();
1827
                for (CdmPreference preference: prefsToDelete){
1828
                    controller.getPreferenceService().remove(preference.getKey());
1829
                }
1830
                CdmPreferenceCache.instance().getAllTaxEditorDBPreferences();
1831
            }
1832

    
1833
    }
1834

    
1835

    
1836
    public static void removeFromDB(CdmPreference prefToDelete) {
1837
        ICdmRepository controller;
1838

    
1839
        if(CdmStore.isActive()){
1840
            controller = CdmStore.getCurrentApplicationConfiguration();
1841
            controller.getPreferenceService().remove(prefToDelete.getKey());
1842

    
1843
            CdmPreferenceCache.instance().getAllTaxEditorDBPreferences();
1844
        }
1845

    
1846
    }
1847
    /**
1848
     * @return
1849
     */
1850
    public static TermTree<?> getPreferredFeatureTreeForTaxonDescription(boolean createNew) {
1851
        if(preferredTaxonFeatureTree != null && !createNew){
1852
            return preferredTaxonFeatureTree;
1853
        }
1854
        createPreferredFeatureTreeForTaxonDescription();
1855
        return preferredTaxonFeatureTree;
1856

    
1857
    }
1858

    
1859
    public static void createPreferredFeatureTreeForTaxonDescription() {
1860

    
1861
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1862
        CdmPreference pref = cache.get(PreferencePredicate.TaxonFeatures.getKey());
1863
        List<Feature> terms = null;
1864
        boolean override = PreferencesUtil.getBooleanValue(PreferencesUtil.createOverridePreferenceString(PreferencePredicate.TaxonFeatures.getKey()));
1865
        List<UUID> uuids = PreferencesUtil.createUUIDListFromStringPref(PreferencePredicate.TaxonFeatures.getKey(), false);
1866
        if (uuids != null && !uuids.isEmpty()){
1867
            terms = CdmStore.getTermManager().getTerms(uuids, Feature.class);
1868
        }
1869
        if (terms == null || terms.isEmpty()){
1870
            terms= CdmStore.getTermManager().getPreferredTerms(TermType.Feature);
1871
            TermVocabulary nameVocabulary = CdmStore.getService(IVocabularyService.class).load(VocabularyEnum.NameFeature.getUuid());
1872
            Set<Feature> nameFeature = nameVocabulary.getTerms();
1873
            terms.removeAll(nameFeature);
1874

    
1875
        }
1876

    
1877
        if (terms.isEmpty()){
1878
            preferredTaxonFeatureTree = TermEditorInput.getDefaultFeatureTree();
1879
        }else{
1880
            preferredTaxonFeatureTree = TermTree.NewInstance(terms);
1881
        }
1882

    
1883

    
1884
    }
1885

    
1886
    /**
1887
     * @param lastAccessPoint
1888
     */
1889
    public static void setLastSelectedBiocaseProvider(String lastAccessPoint) {
1890
        setStringValue(LAST_USED_BIOCASE_PROVIDER, lastAccessPoint);
1891
    }
1892

    
1893

    
1894

    
1895

    
1896
}
(40-40/56)