Project

General

Profile

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

    
10
package eu.etaxonomy.taxeditor.preference;
11

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

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

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

    
78
/**
79
 * <p>
80
 * PreferencesUtil class.
81
 * </p>
82
 *
83
 * @author p.ciardelli
84
 * @author n.hoffmann
85
 * @created 05.12.2008
86
 */
87
public class PreferencesUtil implements IPreferenceKeys {
88
    private final static String EDITOR_PREFERENCES_NODE = "eu.etaxonomy.taxeditor";
89

    
90
    public static final String PREFERRED_TERMS_CHANGE = "preferred_terms";
91

    
92
    public static final String P2_REPOSITORIES_DELIM = ",";
93
    public static final String P2_REPOSITORY_FIELDS_DELIM = ";";
94
    public static final String SUBJECT_DELIM = "/";
95
    private final static Logger logger = Logger.getLogger(PreferencesUtil.class);
96

    
97
    public static IPreferenceStore getPreferenceStore() {
98
       return TaxeditorStorePlugin.getDefault().getPreferenceStore();
99
    }
100

    
101
    public static String[] extractSubjectParts(String subject){
102
       String[] result = subject.split("/");
103
       return result;
104
    }
105

    
106
    public static IEclipsePreferences getEditorPreferences(){
107
        return ConfigurationScope.INSTANCE.getNode(EDITOR_PREFERENCES_NODE);
108
    }
109

    
110
    public static String getPreferenceValue(PrefKey prefKey){
111
        try {
112
            if(getEditorPreferences().nodeExists(prefKey.getPredicate())){
113
                Preferences predicateNode = getEditorPreferences().node(prefKey.getPredicate());
114
                String[] splittedSubject = extractSubjectParts(prefKey.getSubject());
115
                String value = predicateNode.get(splittedSubject[splittedSubject.length-1], PreferencePredicate.getByKey(prefKey.getPredicate()).getDefaultValue() != null? PreferencePredicate.getByKey(prefKey.getPredicate()).getDefaultValue().toString(): "");
116
                int index = splittedSubject.length -2;
117
                while (value != null && index >= 0){
118
                   value = predicateNode.get(splittedSubject[index], prefKey.getPredicate());
119
                   index--;
120
                }
121
                return value;
122
            }
123

    
124
        } catch (BackingStoreException e) {
125
            // TODO Auto-generated catch block
126
            e.printStackTrace();
127
        }
128
        return null;
129
    }
130

    
131
    public static List<CdmPreference> getPreference(PreferencePredicate prefPredicate){
132
        try {
133
            List<CdmPreference> prefs = new ArrayList();
134
            CdmPreference pref;
135
            PreferenceSubject subject;
136
            if(getEditorPreferences().nodeExists(prefPredicate.getKey())){
137
                Preferences predicateNode = getEditorPreferences().node(prefPredicate.getKey());
138
                for (String childName: predicateNode.childrenNames()){
139
                    Preferences child = predicateNode.node(childName);
140
                    String subjectString = "";
141
                    subjectString = createSubjectStringForChildNodes(childName, child);
142
                    String value = child.get(subjectString, "");
143
                    subject = PreferenceSubject.NewInstance(subjectString);
144
                    pref = CdmPreference.NewInstance(subject, prefPredicate, value);
145
                    prefs.add(pref);
146
                }
147

    
148
            }
149

    
150
        } catch (BackingStoreException e) {
151
            // TODO Auto-generated catch block
152
            e.printStackTrace();
153
        }
154
        return null;
155
    }
156

    
157
    /**
158
     * @param childName
159
     * @param child
160
     */
161
    private static String createSubjectStringForChildNodes(String subject, Preferences parent) {
162
        try {
163
            for (String childName: parent.childrenNames()){
164
                subject = childName+SUBJECT_DELIM+subject;
165
                Preferences child = parent.node(childName);
166
                createSubjectStringForChildNodes(subject, child);
167
            }
168
        } catch (BackingStoreException e) {
169
            // TODO Auto-generated catch block
170
            e.printStackTrace();
171
        }
172
        return subject;
173

    
174
    }
175

    
176
    private static String prefKey(String name) {
177
        return name + "_"+  ((CdmRemoteSource)CdmStore.getActiveCdmSource()).toString();
178
    }
179

    
180
    public static String prefOverrideKey(String name) {
181
        return name + "_OVERRIDE_";
182
    }
183

    
184
    public static void setStringValue(String name, String value) {
185
        if (value != null){
186
            getPreferenceStore().setValue(prefKey(name), value);
187
        }else{
188
            getPreferenceStore().setToDefault(name);
189
        }
190
    }
191

    
192
    public static void setIntValue(String name, int value) {
193
        getPreferenceStore().setValue(prefKey(name), value);
194
    }
195

    
196
    public static void setBooleanValue(String name, boolean value) {
197
        getPreferenceStore().setValue(prefKey(name), value);
198
    }
199

    
200
    public static void setDoubleValue(String name, double value) {
201
        getPreferenceStore().setValue(prefKey(name), value);
202
    }
203

    
204
    public static void setFloatValue(String name, float value) {
205
        getPreferenceStore().setValue(prefKey(name), value);
206
    }
207

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

    
212
    public static String getStringValue(String name, boolean local) {
213

    
214
        CdmPreference pref = getDBPreferenceValue(name);
215
        String prefValue = null;
216
        String overrideKey =  createPreferenceString(createOverridePreferenceString(name));
217
        boolean override = getPreferenceStore().getBoolean(overrideKey);
218

    
219
        if (local || pref == null || (pref != null && pref.isAllowOverride() && override)){
220
            String dbSpecific = prefKey(name);
221
            if (getPreferenceStore().contains(dbSpecific)){
222
                prefValue = getPreferenceStore().getString(dbSpecific);
223
            }else{
224
                prefValue = getPreferenceStore().
225
                        getString(name);
226
            }
227
       }else if (pref != null){
228
           prefValue = pref.getValue();
229
       }
230
        return prefValue;
231

    
232
    }
233

    
234
    public static String getStringValue(String name){
235
        return getStringValue(name, false);
236
    }
237

    
238
    private static CdmPreference getDBPreferenceValue(String name) {
239
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
240
        CdmPreference pref = null;
241
//
242
        pref = cache.get(name);
243
        if (pref == null ){
244
            //get default value for Predicate
245
            IPreferencePredicate pred = PreferencePredicate.getByKey(name);
246
            if (pred != null){
247
                if (pred.getDefaultValue() != null){
248
                    pref = CdmPreference.NewTaxEditorInstance(pred, pred.getDefaultValue().toString());
249
                }else{
250
                    pref = CdmPreference.NewTaxEditorInstance(pred, null);
251
                }
252
                pref.setAllowOverride(true);
253
            }
254
        }
255
        return pref;
256
    }
257

    
258
    public static int getIntValue(String name, boolean local) {
259
        CdmPreference pref= getDBPreferenceValue(name);
260
        String prefValue = null;
261
        if (pref != null){
262
            prefValue = pref.getValue();
263
        }
264
        Integer result = null;
265
        try{
266
            result = Integer.parseInt(prefValue);
267
        }catch(NumberFormatException e){
268
            logger.debug("Preference value of " + name + " is not a number");
269
        }
270

    
271
        String overrideKey =  createPreferenceString(createOverridePreferenceString(name));
272
        boolean override = true;
273
        if (getPreferenceStore().contains(overrideKey)){
274
            override = getPreferenceStore().getBoolean(overrideKey);
275
        }
276
        if (local || pref == null || (pref != null && pref.isAllowOverride() && override)){
277
            String dbSpecific = prefKey(name);
278
            if (getPreferenceStore().contains(dbSpecific)){
279
                result = getPreferenceStore().getInt(dbSpecific);
280
            }else{
281
                result =  getPreferenceStore().
282
                        getInt(name);
283
            }
284
        }
285
        return result;
286

    
287
    }
288

    
289
    public static boolean getBooleanValue(String name) {
290
        Boolean result = getBooleanValue(name, false);
291
        if (result == null){
292
            return false;
293
        }else{
294
            return result;
295
        }
296

    
297
    }
298

    
299
    public static Boolean getBooleanValue(String name, boolean local) {
300
        if (CdmStore.isActive()){
301
            CdmPreference pref = getDBPreferenceValue(name);
302

    
303
            String overrideKey =  createPreferenceString(createOverridePreferenceString(name));
304
            boolean override = getPreferenceStore().getBoolean(overrideKey);
305

    
306
            if (local || pref == null || (pref != null && pref.isAllowOverride() && override)){
307
                String dbSpecific = prefKey(name);
308
                if (getPreferenceStore().contains(dbSpecific)){
309
                    return getPreferenceStore().getBoolean(dbSpecific);
310
                }else{
311
                    return null;
312
                }
313
             }else{
314
                return Boolean.valueOf(pref.getValue());
315
            }
316

    
317
        }else{
318
            return getPreferenceStore().getBoolean(name);
319
        }
320

    
321
    }
322

    
323
    public static double getDoubleValue(String name) {
324
        CdmPreference pref = getDBPreferenceValue(name);
325
        String prefValue = null;
326
        if (pref != null){
327
            prefValue = pref.getValue();
328
        }
329
        Double result = null;
330
        try{
331
            result = Double.parseDouble(prefValue);
332
        }catch(NumberFormatException e){
333
            logger.debug("Preference value of " + name + " is not a number");
334
        }
335
        if (result == null){
336
            String dbSpecific = prefKey(name);
337
            if (getPreferenceStore().contains(dbSpecific)){
338
                result = getPreferenceStore().getDouble(dbSpecific);
339
            }else{
340
                result =  getPreferenceStore().
341
                        getDouble(name);
342
            }
343
        }
344
        return result;
345

    
346
    }
347

    
348
    public static float getFloatValue(String name, boolean local) {
349
        CdmPreference pref = getDBPreferenceValue(name);
350
        String prefValue = null;
351
        if (pref != null){
352
            prefValue = pref.getValue();
353
        }
354
        Float result = null;
355
        try{
356
            result = Float.parseFloat(prefValue);
357
        }catch(NumberFormatException e){
358
            logger.debug("Preference value of " + name + " is not a number");
359
        }
360
        String overrideKey =  createPreferenceString(createOverridePreferenceString(name));
361
        boolean override = true;
362
        if (getPreferenceStore().contains(overrideKey)){
363
            override = getPreferenceStore().getBoolean(overrideKey);
364
        }
365
        if (local || pref == null || (pref != null && pref.isAllowOverride() && override)){
366
            String dbSpecific = prefKey(name);
367
            if (getPreferenceStore().contains(dbSpecific)){
368
                result = getPreferenceStore().getFloat(dbSpecific);
369
            }else{
370
                result =  getPreferenceStore().
371
                        getFloat(name);
372
            }
373
        }
374
        return result;
375

    
376
    }
377

    
378
    public static long getLongValue(String name) {
379
        CdmPreference pref = getDBPreferenceValue(name);
380
        String prefValue = null;
381
        if (pref != null){
382
            prefValue = pref.getValue();
383
        }
384
        Long result = null;
385
        try{
386
            result = Long.parseLong(prefValue);
387
        }catch(NumberFormatException e){
388
            logger.debug("Preference value of " + name + " is not a number");
389
        }
390
        if (result == null){
391
            String dbSpecific = prefKey(name);
392
            if (getPreferenceStore().contains(dbSpecific)){
393
                result = getPreferenceStore().getLong(dbSpecific);
394
            }else{
395
                result =  getPreferenceStore().
396
                        getLong(name);
397
            }
398
        }
399
        return result;
400
    }
401

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

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

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

    
436
            }
437
        }
438
        return null;
439

    
440

    
441

    
442
    }
443

    
444
    public static void setPreferredNomenclaturalCode(
445
        CdmPreference preference) {
446

    
447
        ICdmRepository controller;
448
        controller = CdmStore.getCurrentApplicationConfiguration();
449
        if (controller == null){
450
            return;
451
        }
452
        PrefKey key = null;
453
        try{
454
            key = CdmPreference.NewKey(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.NomenclaturalCode);
455
        }catch (Exception e){
456
            System.out.println(e.getStackTrace());
457
        }
458

    
459
        controller.getPreferenceService().set(preference);
460

    
461
    }
462

    
463
    public static NomenclaturalCode getPreferredNomenclaturalCode() {
464

    
465
        CdmPreference pref = getPreferenceFromDB(PreferencePredicate.NomenclaturalCode);
466

    
467

    
468
        String preferredCode;
469
        if(pref == null || (pref.isAllowOverride() && getBooleanValue(prefOverrideKey(PreferencePredicate.NomenclaturalCode.getKey())))){
470
            preferredCode = getStringValue(
471
                    PreferencePredicate.NomenclaturalCode.getKey(), true);
472

    
473
        }else{
474
            preferredCode = pref.getValue();
475
        }
476
        if (StringUtils.isBlank(preferredCode)){
477
            preferredCode = getPreferenceKey((NomenclaturalCode)PreferencePredicate.NomenclaturalCode.getDefaultValue());
478
        }
479

    
480
        return getPreferredNomenclaturalCode(preferredCode);
481

    
482
    }
483

    
484
    public static NomenclaturalCode getPreferredNomenclaturalCode(String preferenceKeyNomenclaturalCode) {
485

    
486
        for (NomenclaturalCode code : NomenclaturalCodeHelper.getAllCodes()) {
487
            if (getPreferenceKey(code).equals(preferenceKeyNomenclaturalCode)) {
488
                return code;
489
            }
490
        }
491
        return null;
492
    }
493

    
494
    public static boolean isShowTaxonAssociations(){
495
        boolean result = getBooleanValue(PreferencePredicate.ShowTaxonAssociations.getKey());
496
        return result;
497
    }
498

    
499
    public static boolean isShowLifeForm(){
500
        boolean result =  getBooleanValue(PreferencePredicate.ShowLifeForm.getKey());
501
        return result;
502
    }
503

    
504
    public static boolean isDeterminationOnlyForFieldUnits(){
505
        boolean result =  getBooleanValue(PreferencePredicate.DeterminationOnlyForFieldUnits.getKey());
506
        return result;
507
    }
508

    
509
    public static boolean isCollectingAreaInGeneralSection(){
510
        boolean result =  getBooleanValue(PreferencePredicate.ShowCollectingAreasInGeneralSection.getKey());
511
        return result;
512
    }
513

    
514
    public static CdmPreference getPreferenceFromDB(IPreferencePredicate predicate){
515
        ICdmRepository controller;
516
        CdmPreference pref = null;
517

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

    
528
        return pref;
529

    
530
    }
531

    
532
    public static List<CdmPreference> getPreferencesFromDB(IPreferencePredicate predicate){
533
        ICdmRepository controller;
534
        List<CdmPreference> prefs = null;
535

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

    
546
        return prefs;
547

    
548
    }
549

    
550
    public static void setPreferencesToDB(CdmPreference preference, boolean setDefault){
551
        ICdmRepository controller;
552
        try{
553
            if(CdmStore.isActive()){
554
                controller = CdmStore.getCurrentApplicationConfiguration();
555

    
556
                if (setDefault){
557
                    controller.getPreferenceService().remove(preference.getKey());
558
                }else{
559
                    controller.getPreferenceService().set(preference);
560
                }
561
            }
562
        }catch(Exception e){
563
            e.printStackTrace();
564
        }
565

    
566

    
567

    
568
    }
569

    
570
    public static CdmPreference getPreferenceFromDB(PrefKey key){
571
        ICdmRepository controller;
572
        CdmPreference pref = null;
573

    
574
        try{
575
            if(CdmStore.isActive()){
576
                controller = CdmStore.getCurrentApplicationConfiguration();
577
                pref = controller.getPreferenceService().find(key);
578
            }
579
        }catch(Exception e){
580
            e.printStackTrace();
581
        }
582

    
583
        return pref;
584

    
585
    }
586

    
587
    public static void setPreferenceToDB(CdmPreference preference){
588
        ICdmRepository controller;
589
        try{
590
            if(CdmStore.isActive()){
591
                controller = CdmStore.getCurrentApplicationConfiguration();
592
                if (preference.getValue() == null && preference.isAllowOverride()){
593
                    controller.getPreferenceService().remove(preference.getKey());
594
                }else{
595
                    controller.getPreferenceService().set(preference);
596
                }
597
                CdmPreferenceCache.instance().put(preference);
598
            }
599
        }catch(Exception e){
600
            e.printStackTrace();
601
        }
602

    
603
    }
604

    
605
    public static String getPreferredDefaultLangugae(){
606
        String preferredLanguage = getStringValue(DEFAULT_LANGUAGE_EDITOR);
607
        if(StringUtils.isNotEmpty(preferredLanguage) && StringUtils.isNotBlank(preferredLanguage)){
608
            return preferredLanguage;
609
        }
610
        return null;
611
    }
612

    
613
    public static boolean isShowMediaPreview(){
614
        boolean isShowMediaPreview = getBooleanValue(SHOW_MEDIA_PREVIEW);
615
        return isShowMediaPreview;
616
    }
617

    
618
    /**
619
     * Get the match strategy for the given class that was stored in preferences
620
     * or the default strategy if it was not stored in preferences
621
     *
622
     * @param clazz
623
     *            a {@link java.lang.Class} object.
624
     * @return a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy} object.
625
     */
626
    public static IMatchStrategy getMatchStrategy(Class<?> clazz) {
627
        String className = clazz.getName();
628
        if (getBooleanValue(MATCH_STRATEGY_PREFIX + className)) {
629
            IMatchStrategy matchStrategy = getDefaultMatchStrategy(clazz);
630

    
631
            //TODO CacheMatchers (or multiple field matchers in future) are missing here
632
            for (FieldMatcher fieldMatcher : matchStrategy.getMatching().getFieldMatchers(false)) {
633
                String fieldName = fieldMatcher.getPropertyName();
634
                String matchModeName = getStringValue(
635
                        getMatchStrategyFieldName(className, fieldName));
636
                MatchMode matchMode = MatchMode.valueOf(matchModeName);
637
                try {
638
                    matchStrategy.setMatchMode(fieldName, matchMode);
639
                } catch (MatchException e) {
640
                    MessagingUtils.error(PreferencesUtil.class, e);
641
                    throw new RuntimeException(e);
642
                }
643
            }
644

    
645
            return matchStrategy;
646
        }
647
        return getDefaultMatchStrategy(clazz);
648
    }
649

    
650
    /**
651
     * Stores a matchStrategy into the preference store.
652
     *
653
     * @param matchStrategy
654
     *            a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy}
655
     *            object.
656
     */
657
    public static void setMatchStrategy(IMatchStrategy matchStrategy) {
658
        String className = "ANY class"; //FIXME was: matchStrategy.getMatchClass().getName(); seems currently not in use
659
        setBooleanValue(MATCH_STRATEGY_PREFIX + className, true);
660

    
661
        List<FieldMatcher> fieldMatchers = matchStrategy.getMatching().getFieldMatchers(false);
662

    
663
        for (FieldMatcher fieldMatcher : fieldMatchers) {
664
            String fieldName = fieldMatcher.getPropertyName();
665
            setStringValue(
666
                    getMatchStrategyFieldName(className, fieldName),
667
                    fieldMatcher.getMatchMode().name());
668
        }
669
    }
670

    
671
    /**
672
     * Helper method to create the preference property for a match field.
673
     *
674
     * @param className
675
     * @param fieldName
676
     * @return
677
     */
678
    private static String getMatchStrategyFieldName(String className,
679
            String fieldName) {
680
        return MATCH_STRATEGY_PREFIX + className + "." + fieldName;
681
    }
682

    
683
    /**
684
     * Returns the default match strategy for a given class.
685
     *
686
     * @param clazz
687
     *            a {@link java.lang.Class} object.
688
     * @return a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy} object.
689
     */
690
    public static IMatchStrategy getDefaultMatchStrategy(Class clazz) {
691
        return DefaultMatchStrategy.NewInstance(clazz);
692
    }
693

    
694
    public static String getDateFormatPattern() {
695
        // TODO make this configurable in properties
696
        String pattern = "Y-M-d H:m";
697
        return pattern;
698
    }
699

    
700
    public static <T extends TermBase> void addTermToPreferredTerms(T term) {
701

    
702
        // VocabularyEnum vocabulary =
703
        // VocabularyEnum.getVocabularyEnum(term.getClass());
704
        //
705
        // getPreferenceStore().setValue(getPreferenceKey(term),
706
        // VocabularyStore.getTermVocabulary(vocabulary).getTerms().contains(term));
707
        //
708
        // firePreferencesChanged(term.getClass());
709
    }
710

    
711
    /**
712
     * Construct a unique key using the CdmBase object's uuid
713
     *
714
     * @param cdmBase
715
     * @return
716
     */
717
    private static String getPreferenceKey(ICdmBase cdmBase) {
718
        cdmBase = HibernateProxyHelper.deproxy(cdmBase);
719

    
720
        String key = cdmBase.getClass().getName().concat(".")
721
                .concat(cdmBase.getUuid().toString());
722
        if (key.contains("javassist")) {
723
            MessagingUtils.info("proxy");
724
        }
725
        return key;
726
    }
727

    
728
    /**
729
     * Construct a unique key using the CdmBase object's uuid
730
     *
731
     * @param cdmBase
732
     * @return
733
     */
734
    public static String getPreferenceKey(ISimpleTerm simpleTerm) {
735
        simpleTerm = HibernateProxyHelper.deproxy(simpleTerm);
736
        String key = simpleTerm.getClass().getName().concat(".")
737
                .concat(simpleTerm.getUuid().toString());
738
        if (key.contains("javassist")) {
739
            MessagingUtils.warn(PreferencesUtil.class,
740
                    "Trying to persist a preference based on a proxy class.");
741
        }
742
        return key;
743
    }
744

    
745

    
746

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

    
764
    /**
765
     * Retrieves search preferences from the preference store
766
     *
767
     * @return an {@link ITaxonServiceConfigurator} to pass to search methods
768
     */
769
    public static IFindTaxaAndNamesConfigurator getSearchConfigurator() {
770
        IFindTaxaAndNamesConfigurator configurator = initializeSearchConfigurator();
771

    
772
        configurator.setDoTaxa(getBooleanValue(
773
                TAXON_SERVICE_CONFIGURATOR_TAXA));
774
        configurator.setDoSynonyms(getBooleanValue(
775
                TAXON_SERVICE_CONFIGURATOR_SYNONYMS));
776
        configurator.setDoNamesWithoutTaxa(getBooleanValue(
777
                TAXON_SERVICE_CONFIGURATOR_NAMES));
778
        configurator.setDoTaxaByCommonNames(getBooleanValue(
779
                TAXON_SERVICE_CONFIGURATOR_COMMON_NAMES));
780
        //configurator.setMatchMode(eu.etaxonomy.cdm.persistence.query.MatchMode.valueOf(getStringValue(TAXON_SERVICE_CONFIGURATOR_MATCH_MODE)));
781

    
782
        return configurator;
783
    }
784

    
785
    /**
786
     * create new preferences, setting all search options to true
787
     *
788
     * @return a
789
     *         {@link eu.etaxonomy.cdm.api.service.config.ITaxonServiceConfigurator}
790
     *         object.
791
     */
792
    public static IFindTaxaAndNamesConfigurator initializeSearchConfigurator() {
793
        IFindTaxaAndNamesConfigurator configurator = FindTaxaAndNamesConfiguratorImpl.NewInstance();
794

    
795
        configurator.setDoTaxa(true);
796
        configurator.setDoSynonyms(true);
797
        configurator.setDoNamesWithoutTaxa(true);
798
        configurator.setDoTaxaByCommonNames(true);
799

    
800
        configurator.setTaxonPropertyPath(Arrays.asList("$", "titleCache",
801
                "name", "name.$", "relationsFromThisTaxon.$"));
802

    
803
        configurator.setSynonymPropertyPath(Arrays.asList("$", "titleCache",
804
                "name", "name.$", "synonyms.relatedTo.*"));
805

    
806
        // DEFAULT VALUES
807
        // match mode is a simple like, actually all other match modes are kind
808
        // of bogus
809
        configurator
810
                .setMatchMode(eu.etaxonomy.cdm.persistence.query.MatchMode.ANYWHERE);
811
        // we set page number and size here as this should always be unlimited
812
        configurator.setPageNumber(0);
813
        // TODO currently limit results to 10000
814
        configurator.setPageSize(10000);
815
        //setSearchConfigurator(configurator) ;
816
        return configurator;
817
    }
818

    
819
    /**
820
     * Store search preferences
821
     *
822
     * @param configurator
823
     *            a
824
     *            {@link eu.etaxonomy.cdm.api.service.config.ITaxonServiceConfigurator}
825
     *            object.
826
     */
827
    public static void setSearchConfigurator(
828
            IFindTaxaAndNamesConfigurator configurator) {
829
        getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_TAXA,
830
                configurator.isDoTaxa());
831
        getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_SYNONYMS,
832
                configurator.isDoSynonyms());
833
        getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_NAMES,
834
                configurator.isDoNamesWithoutTaxa());
835
        getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_COMMON_NAMES,
836
                configurator.isDoTaxaByCommonNames());
837
    }
838

    
839
    public static void firePreferencesChanged(Class clazz) {
840
        getPreferenceStore().firePropertyChangeEvent(PREFERRED_TERMS_CHANGE,
841
                null, clazz);
842
    }
843

    
844

    
845
    public static String createPreferenceString(String property){
846
       return prefKey(property);
847

    
848
    }
849
    public static String createOverridePreferenceString(String property){
850
           return prefOverrideKey(property);
851

    
852
        }
853

    
854
    /**
855
     * Set default values for preferences
856
     */
857
    public static void setDefaults() {
858
        getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_TAXA, true);
859
        getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_SYNONYMS,
860
                true);
861
        getPreferenceStore().setDefault(createPreferenceString(EDIT_MAP_SERVICE_ACCES_POINT),
862
                "http://edit.africamuseum.be/edit_wp5/v1.2/rest_gen.php");
863
        //FIXME : changed default for SHOULD_CONNECT_AT_STARTUP to false (ticket 3828) until resolution
864
        getPreferenceStore().setDefault(createPreferenceString(SHOULD_CONNECT_AT_STARTUP), false);
865
        getPreferenceStore().setDefault(createPreferenceString(OPENURL_ACCESS_POINT),
866
                "http://www.biodiversitylibrary.org/openurl");
867
        getPreferenceStore().setDefault(createPreferenceString(OPENURL_IMAGE_MAX_WIDTH), "1000");
868
        getPreferenceStore().setDefault(createPreferenceString(OPENURL_IMAGE_MAX_HEIGHT), "1000");
869
        getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_TAXA, true);
870
        getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_SYNONYMS, true);
871
        getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_NAMES, true);
872
        getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_COMMON_NAMES, true);
873

    
874
        //Distribution Editor:
875
//      getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.DistributionEditorActivated.getKey()), Boolean.valueOf(PreferencePredicate.DistributionEditorActivated.getDefaultValue().toString()));
876
//      getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey()), PreferencePredicate.DisplayOfAreasInDistributionEditor.getDefaultValue().toString());
877
//      getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.DisplayOfStatus.getKey()), PreferencePredicate.DisplayOfStatus.getDefaultValue().toString());
878

    
879

    
880
        //Name Details
881
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.NameDetailsView.getKey()), new NameDetailsConfigurator(false).toString());
882

    
883
        //Navigator preferences
884
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.TaxonNodeOrder.getKey()), NavigatorOrderEnum.RankAndNameOrder.getKey());
885

    
886
        //getPreferenceStore().setDefault(createPreferenceString(Prefe), true);
887

    
888
        getPreferenceStore().setDefault(createPreferenceString(SHOW_ADVANCED_MEDIA_SECTION), false);
889

    
890
        getPreferenceStore().setDefault(createPreferenceString(SHOW_MEDIA_PREVIEW), false);
891
        //override db preferences
892
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.AbcdImportConfig.getKey())), false);
893
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.ShowSpecimen.getKey())), true);
894
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.NameDetailsView.getKey())), false);
895
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.DistributionEditorActivated.getKey())), true);
896
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.AvailableDistributionStatus.getKey())), true);
897
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.AvailableDistributionAreaTerms.getKey())), true);
898
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey())), true);
899
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.CommonNameAreaVocabularies.getKey())), false);
900
        getPreferenceStore().setDefault(createPreferenceString(FILTER_COMMON_NAME_REFERENCES), false);
901
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowTaxonNodeWizard.getKey()), Boolean.valueOf(PreferencePredicate.ShowTaxonNodeWizard.getDefaultValue().toString()));
902
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowNamespaceInSource.getKey()), Boolean.valueOf(PreferencePredicate.ShowNamespaceInSource.getDefaultValue().toString()));
903
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowIdInSource.getKey()), Boolean.valueOf(PreferencePredicate.ShowIdInSource.getDefaultValue().toString()));
904
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.DisableMultiClassification.getKey()), Boolean.valueOf(PreferencePredicate.DisableMultiClassification.getDefaultValue().toString()));
905
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowImportExportMenu.getKey()), Boolean.valueOf(PreferencePredicate.ShowImportExportMenu.getDefaultValue().toString()));
906
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowSpecimen.getKey()), Boolean.valueOf(PreferencePredicate.ShowSpecimen.getDefaultValue().toString()));
907

    
908
    }
909

    
910
    public static void checkNomenclaturalCode() {
911
        // First time Editor is opened, no nomenclatural code has been set
912
        if (PreferencesUtil.getPreferredNomenclaturalCode() == null) {
913
            PreferencesUtil.setPreferredNomenclaturalCode(getPreferenceKey(NomenclaturalCode.ICNAFP), true);
914
        }
915

    
916

    
917

    
918
    }
919
    public static void setNomenclaturalCodePreferences(){
920
        ICdmRepository controller;
921
        controller = CdmStore.getCurrentApplicationConfiguration();
922
        PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.NomenclaturalCode);
923
        CdmPreference preference = null;
924
        if (controller == null){
925
            return ;
926
        }
927
        preference = controller.getPreferenceService().find(key);
928
        if (preference == null){
929
            return;
930
        }
931
//        setBooleanValue(ALLOW_OVERRIDE_NOMENCLATURAL_CODE_KEY, preference.isAllowOverride());
932

    
933
        int index = StringUtils.lastIndexOf(preference.getValue(), ".");
934
        UUID uuid = UUID.fromString(preference.getValue().substring(index +1, preference.getValue().length()));
935
        NomenclaturalCode preferredCode = NomenclaturalCode.getByUuid(uuid);
936

    
937
        setStringValue(PREFERRED_NOMENCLATURAL_CODE_KEY,
938
                getPreferenceKey(preferredCode));
939

    
940
    }
941

    
942
    public static void checkDefaultLanguage(){
943
        if(PreferencesUtil.getPreferredDefaultLangugae() == null){
944
           Shell shell = AbstractUtility.getShell();
945
           int open = new DefaultLanguageDialog(shell).open();
946
           if(open == Window.OK){
947
               PlatformUI.getWorkbench().restart();
948
           }
949
        }else{
950
            //TODO:In case of a reinstall, the config.ini will be overwritten
951
            //     here you create config.ini with the stored key from preferences
952
        }
953
    }
954

    
955
    public static String getMapServiceAccessPoint() {
956
        return getStringValue(EDIT_MAP_SERVICE_ACCES_POINT);
957
    }
958

    
959
    public static boolean shouldConnectAtStartUp() {
960
        //FIXME :  force SHOULD_CONNECT_AT_STARTUP to false (ticket 3828) until resolution
961
        //return getBooleanValue(SHOULD_CONNECT_AT_STARTUP);
962
        return false;
963
    }
964

    
965
    public static TermTree getDefaultFeatureTreeForTextualDescription() {
966
        String uuidString = getStringValue(
967
                FEATURE_TREE_DEFAULT_TEXT);
968
        if (StringUtils.isBlank(uuidString)) {
969
            return null;
970
        }
971
        TermTree tree = CdmStore.getService(
972
                ITermTreeService.class).load(UUID.fromString(uuidString));
973
        if (tree.getId() == 0) {
974
            return null;
975
        }
976
        return tree;
977
    }
978

    
979
    public static TermTree getDefaultFeatureTreeForStructuredDescription() {
980
        String uuidString = getStringValue(
981
                FEATURE_TREE_DEFAULT_STRUCTURE);
982
        return StringUtils.isBlank(uuidString) ? null : CdmStore.getService(
983
                ITermTreeService.class).load(UUID.fromString(uuidString));
984
    }
985

    
986
    public static void setSortRanksHierarchichally(boolean selection) {
987
        setBooleanValue(SORT_RANKS_HIERARCHICHALLY, selection);
988
    }
989

    
990
    public static boolean getSortRanksHierarchichally() {
991
        return getBooleanValue(SORT_RANKS_HIERARCHICHALLY);
992
    }
993

    
994
    public static boolean isMultilanguageTextEditingCapability() {
995
        return getBooleanValue(
996
                MULTILANGUAGE_TEXT_EDITING_CAPABILITY);
997
    }
998

    
999
    public static Language getGlobalLanguage() {
1000

    
1001

    
1002
        String languageUuidString = getStringValue(
1003
                GLOBAL_LANGUAGE_UUID);
1004

    
1005
        if(!CdmStore.isActive()) {
1006
            MessagingUtils.noDataSourceWarningDialog(languageUuidString);
1007
            return null;
1008
        }
1009

    
1010
        if (CdmUtils.isBlank(languageUuidString)) {
1011
            return Language.getDefaultLanguage();
1012
        }
1013

    
1014
        UUID languageUuid = UUID.fromString(languageUuidString);
1015
        return (Language) CdmStore.getService(ITermService.class).load(
1016
                languageUuid);
1017
    }
1018

    
1019
    public static void setGlobalLanguage(Language language) {
1020
        if(language != null) {
1021
            setStringValue(GLOBAL_LANGUAGE_UUID,language.getUuid().toString());
1022
            CdmStore.setDefaultLanguage(language);
1023
        }
1024

    
1025
    }
1026

    
1027
    public static Map<MarkerType, Boolean> getEditMarkerTypePreferences() {
1028
        List<MarkerType> markerTypes = CdmStore.getTermManager()
1029
                .getPreferredTerms(MarkerType.class);
1030

    
1031
        Map<MarkerType, Boolean> result = new HashMap<MarkerType, Boolean>();
1032

    
1033
        for (MarkerType markerType : markerTypes) {
1034
            String name = getMarkerTypeEditingPreferenceKey(markerType);
1035
            Boolean value = getBooleanValue(name);
1036

    
1037
            result.put(markerType, value);
1038
        }
1039

    
1040
        return result;
1041
    }
1042

    
1043
    public static void setEditMarkerTypePreferences(
1044
            Map<MarkerType, Boolean> markerTypeEditingMap) {
1045
        for (MarkerType markerType : markerTypeEditingMap.keySet()) {
1046
            String name = getMarkerTypeEditingPreferenceKey(markerType);
1047
            setBooleanValue(name,
1048
                    markerTypeEditingMap.get(markerType));
1049
        }
1050

    
1051
    }
1052

    
1053
    private static String getMarkerTypeEditingPreferenceKey(
1054
            MarkerType markerType) {
1055
        markerType = HibernateProxyHelper.deproxy(markerType);
1056
        return markerType.getClass().getName() + EDIT_MARKER_TYPE_PREFIX;
1057
    }
1058

    
1059
    public static void setEditMarkerTypePreference(MarkerType markerType,
1060
            boolean edit) {
1061
        setBooleanValue(
1062
                getMarkerTypeEditingPreferenceKey(markerType), edit);
1063
    }
1064

    
1065
    public static DerivedUnitFacadeConfigurator getDerivedUnitConfigurator() {
1066
        DerivedUnitFacadeConfigurator configurator = DerivedUnitFacadeConfigurator
1067
                .NewInstance();
1068
        configurator.setMoveDerivedUnitMediaToGallery(true);
1069
        configurator.setMoveFieldObjectMediaToGallery(true);
1070
        return configurator;
1071
    }
1072

    
1073
    /**
1074
     * This method will write language properties to the config.ini located in the configuration folder
1075
     * of the Taxonomic Ediitor. <b>This method is only used to set the default language for Taxonomic Editor.</b>
1076
     *
1077
     * @param setLanguage 0 is for german and 1 for english.
1078
     * @throws IOException
1079
     */
1080
    public void writePropertyToConfigFile(int setLanguage) throws IOException {
1081
        File file = org.eclipse.core.runtime.preferences.ConfigurationScope.INSTANCE.getLocation().toFile();
1082
        //give warning to user if the directory has no write access
1083
        if(file == null){
1084
            throw new IOException();
1085
        }
1086
        Properties properties = load(file.getAbsolutePath()+"/config.ini");
1087
        switch(setLanguage){
1088
        case 0:
1089
            properties.setProperty("osgi.nl", "de");
1090
            setStringValue(IPreferenceKeys.DEFAULT_LANGUAGE_EDITOR, "de");
1091
            break;
1092
        case 1:
1093
            properties.setProperty("osgi.nl", "en");
1094
            setStringValue(IPreferenceKeys.DEFAULT_LANGUAGE_EDITOR, "en");
1095
            break;
1096
        default:
1097
            break;
1098
        }
1099
        save(file+"/config.ini", properties);
1100
    }
1101

    
1102
    /**
1103
     * This method loads a property from a given file and returns it.
1104
     *
1105
     * @param filename
1106
     * @return
1107
     * @throws IOException
1108
     */
1109
    private Properties load(String filename) throws IOException {
1110
        FileInputStream in = new FileInputStream(filename);
1111
        Properties prop = new Properties();
1112
        prop.load(in);
1113
        in.close();
1114
        return prop;
1115
    }
1116

    
1117
    /**
1118
     * This method saves a property to the specified file.
1119
     *
1120
     * @param filename
1121
     * @param properties
1122
     * @throws IOException
1123
     */
1124
    private void save(String filename, Properties properties) throws IOException{
1125
        FileOutputStream fos =  new FileOutputStream(filename);
1126
        properties.store(fos, "");
1127
        fos.close();
1128
    }
1129

    
1130
    /**
1131
     * Saves a list of P2 Metadata Repositories as string with specified delimiters
1132
     *
1133
     * @param p2Repos
1134
     */
1135
    public static void setP2Repositories(List<MetadataRepositoryElement> p2Repos) {
1136
        StringBuilder sb = new StringBuilder();
1137
        for(MetadataRepositoryElement p2Repo : p2Repos) {
1138
            sb.append(P2_REPOSITORIES_DELIM);
1139
            if(p2Repo.getName() == null || p2Repo.getName().isEmpty()) {
1140
                sb.append("-");
1141
            } else {
1142
                sb.append(p2Repo.getName());
1143
            }
1144
            sb.append(P2_REPOSITORY_FIELDS_DELIM);
1145
            sb.append(p2Repo.getLocation().toString());
1146
            sb.append(P2_REPOSITORY_FIELDS_DELIM);
1147
            sb.append(String.valueOf(p2Repo.isEnabled()));
1148
        }
1149
        getPreferenceStore().setValue(P2_REPOSITORY_LIST, sb.toString());
1150
    }
1151

    
1152

    
1153
    /**
1154
     * Retrieves a list of previously saved P2 repositories
1155
     *
1156
     * @return
1157
     */
1158
    public static List<MetadataRepositoryElement> getP2Repositories() {
1159
        List<MetadataRepositoryElement> p2Repos = new ArrayList<MetadataRepositoryElement>();
1160
        String p2ReposPref =  getStringValue(P2_REPOSITORY_LIST);
1161
        if(p2ReposPref != null && !p2ReposPref.isEmpty()) {
1162
            StringTokenizer p2ReposPrefST = new StringTokenizer(p2ReposPref,P2_REPOSITORIES_DELIM);
1163

    
1164
            while(p2ReposPrefST.hasMoreTokens()) {
1165
                String p2RepoStr = p2ReposPrefST.nextToken();
1166
                StringTokenizer p2ReposStrST = new StringTokenizer(p2RepoStr,P2_REPOSITORY_FIELDS_DELIM);
1167
                if(p2ReposStrST.countTokens()==3) {
1168
                    String nickname = p2ReposStrST.nextToken();
1169
                    URI uri = null;
1170
                    try {
1171
                        uri = new URI(p2ReposStrST.nextToken());
1172
                    } catch (URISyntaxException e) {
1173
                        continue;
1174
                    }
1175
                    boolean enabled = Boolean.parseBoolean(p2ReposStrST.nextToken());
1176
                    MetadataRepositoryElement mre = new MetadataRepositoryElement(null, uri, true);
1177
                    mre.setNickname(nickname);
1178
                    mre.setEnabled(enabled);
1179
                    p2Repos.add(mre);
1180
                }
1181
            }
1182
        }
1183

    
1184
        return p2Repos;
1185
    }
1186

    
1187
    /**
1188
     * enables/disables nested composite. <br>
1189
     *
1190
     * @param ctrl - Composite to be en-/disabeld
1191
     * @param enabled - boolean
1192
     */
1193
    public static void recursiveSetEnabled(Control ctrl, boolean enabled) {
1194
        if (ctrl instanceof Composite) {
1195
            Composite comp = (Composite) ctrl;
1196
            for (Control c : comp.getChildren()) {
1197
                recursiveSetEnabled(c, enabled);
1198
            }
1199
        } else {
1200
            ctrl.setEnabled(enabled);
1201
        }
1202
    }
1203

    
1204
    public static void setSortNodes(NavigatorOrderEnum nodesOrder) {
1205
        setStringValue(PreferencePredicate.TaxonNodeOrder.getKey(), nodesOrder.key);
1206

    
1207
    }
1208

    
1209
    public static NavigatorOrderEnum getSortNodes() {
1210
        return NavigatorOrderEnum.valueOf(getStringValue(PreferencePredicate.TaxonNodeOrder.getKey()));
1211

    
1212
    }
1213

    
1214
    public static boolean isNodesSortedNaturally() {
1215
        NavigatorOrderEnum value = NavigatorOrderEnum.valueOf(getStringValue(PreferencePredicate.TaxonNodeOrder.getKey()));
1216
        return value.equals(NavigatorOrderEnum.NaturalOrder);
1217

    
1218
    }
1219

    
1220
    public static boolean isNodesSortedByName() {
1221
        NavigatorOrderEnum value = NavigatorOrderEnum.valueOf(getStringValue(PreferencePredicate.TaxonNodeOrder.getKey()));
1222
        return value.equals(NavigatorOrderEnum.AlphabeticalOrder);
1223

    
1224
    }
1225

    
1226
    public static boolean isNodesSortedByNameAndRank() {
1227
        NavigatorOrderEnum value = NavigatorOrderEnum.valueOf(getStringValue(PreferencePredicate.TaxonNodeOrder.getKey()));
1228
        return value.equals(NavigatorOrderEnum.RankAndNameOrder);
1229

    
1230
    }
1231

    
1232
    public static boolean isStoreNavigatorState() {
1233
        return getBooleanValue(RESTORE_NAVIGATOR_STATE);
1234

    
1235
    }
1236

    
1237
    public static void setStoreNavigatorState(boolean selection) {
1238
        setBooleanValue(RESTORE_NAVIGATOR_STATE, selection);
1239

    
1240
    }
1241

    
1242
    public static boolean isShowUpWidgetIsDisposedMessages() {
1243
       return getBooleanValue(IS_SHOW_UP_WIDGET_IS_DISPOSED);
1244
    }
1245
    public static void setShowUpWidgetIsDisposedMessages(boolean selection) {
1246
        setBooleanValue(IS_SHOW_UP_WIDGET_IS_DISPOSED, selection);
1247
    }
1248

    
1249
    public static boolean isShowIdInVocabularyInChecklistEditor() {
1250
        String area_display = getStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey());
1251
        if (area_display.equals(TermDisplayEnum.IdInVocabulary.getKey())) {
1252
            return true;
1253
        }else{
1254
            return false;
1255
        }
1256
    }
1257
    public static boolean isShowSymbol1InChecklistEditor() {
1258
        String area_display = getStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey());
1259
        if (area_display.equals(TermDisplayEnum.Symbol1.getKey())) {
1260
            return true;
1261
        }else{
1262
            return false;
1263
        }
1264
     }
1265
    public static boolean isShowSymbol2InChecklistEditor() {
1266
        String area_display = getStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey());
1267
        if (area_display.equals(TermDisplayEnum.Symbol2.getKey())) {
1268
            return true;
1269
        }else{
1270
            return false;
1271
        }
1272
     }
1273
    public static void setAreaDisplayInChecklistEditor(String selection) {
1274
        setStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey(), selection);
1275
    }
1276

    
1277
    public static void setOwnDescriptionForChecklistEditor(boolean selection) {
1278
        setBooleanValue(PreferencePredicate.OwnDescriptionForDistributionEditor.getKey(), selection);
1279
    }
1280

    
1281
    public static boolean isOwnDescriptionForChecklistEditor() {
1282
        return getBooleanValue(PreferencePredicate.OwnDescriptionForDistributionEditor.getKey());
1283
    }
1284

    
1285
    public static String displayAreaInChecklistEditor() {
1286
        String result = getStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey());
1287
        if (StringUtils.isBlank(result)){
1288
            return ((TermDisplayEnum) PreferencePredicate.DisplayOfAreasInDistributionEditor.getDefaultValue()).getKey();
1289
        }
1290
       return result;
1291
    }
1292

    
1293
    public static String displayStatusInChecklistEditor() {
1294
        String result = getStringValue(PreferencePredicate.DisplayOfStatus.getKey());
1295
        if (StringUtils.isBlank(result)){
1296
            return((TermDisplayEnum) PreferencePredicate.DisplayOfStatus.getDefaultValue()).getKey();
1297
        }
1298
       return result;
1299
    }
1300
    public static void setDisplayStatusInChecklistEditor(String selection) {
1301
        setStringValue(PreferencePredicate.DisplayOfStatus.getKey(), selection);
1302

    
1303
    }
1304

    
1305
    public static boolean isShowRankInChecklistEditor() {
1306
        return getBooleanValue(PreferencePredicate.ShowRankInDistributionEditor.getKey());
1307
    }
1308
    public static void setShowRankInChecklistEditor(boolean selection) {
1309
       setBooleanValue(PreferencePredicate.ShowRankInDistributionEditor.getKey(), selection);
1310
    }
1311

    
1312
    public static NameDetailsConfigurator getPreferredNameDetailsConfiguration( boolean local) {
1313
        NameDetailsConfigurator config = new NameDetailsConfigurator(true);
1314
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1315
        CdmPreference preference = null;
1316
        String value;
1317
        if (!local) {
1318
            PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.NameDetailsView);
1319
            preference =  getPreferenceFromDB(PreferencePredicate.NameDetailsView);
1320
            if (preference == null){
1321
                return null;
1322
            }
1323

    
1324
        //    setBooleanValue(ALLOW_OVERRIDE_NAME_DETAILS, preference.isAllowOverride());
1325
            value = preference.getValue();
1326
            config.setAllowOverride(preference.isAllowOverride());
1327
            //the preference value is build like this:
1328
            //<section1>:true;<section2>:false....
1329
        }else{
1330
            value = getStringValue(PreferencePredicate.NameDetailsView.getKey(), local);
1331
        }
1332
        if (value!= null){
1333
            String [] sections = value.split(";");
1334
            Map<String, Boolean> sectionMap = new HashMap<String, Boolean>();
1335
            String[] sectionValues;
1336
            for (String sectionValue: sections){
1337
                sectionValues = sectionValue.split(":");
1338
                sectionMap.put(sectionValues[0], Boolean.valueOf(sectionValues[1]));
1339
            }
1340
            config.setSimpleDetailsViewActivated(getValue(sectionMap, "simpleViewActivated"));
1341
            config.setTaxonSectionActivated(getValue(sectionMap, "taxon"));
1342
            config.setSecDetailsActivated(getValue(sectionMap, "taxon.SecDetails"));
1343
            config.setSecEnabled(getValue(sectionMap, "taxon.SecEnabled"));
1344
            config.setLSIDActivated(getValue(sectionMap, "lsid"));
1345
            config.setNomenclaturalCodeActived(getValue(sectionMap, "nc"));
1346
            config.setAppendedPhraseActivated(getValue(sectionMap, "ap"));
1347
            config.setRankActivated(getValue(sectionMap, "rank"));
1348
            config.setAtomisedEpithetsActivated(getValue(sectionMap, "atomisedEpithets"));
1349
            config.setAuthorshipSectionActivated(getValue(sectionMap,"author"));
1350
            config.setNomenclaturalReferenceSectionActivated(sectionMap.get("nomRef"));
1351
            config.setNomenclaturalStatusSectionActivated(getValue(sectionMap, "nomStat"));
1352
            config.setProtologueActivated(getValue(sectionMap,"protologue"));
1353
            config.setTypeDesignationSectionActivated(getValue(sectionMap,"typeDes"));
1354
            config.setNameRelationsSectionActivated(getValue(sectionMap,"nameRelation"));
1355
            config.setHybridActivated(getValue(sectionMap,"hybrid"));
1356
        }
1357
        return config;
1358
    }
1359

    
1360
    public static NameDetailsConfigurator getPreferredNameDetailsConfiguration() {
1361
        NameDetailsConfigurator config = new NameDetailsConfigurator(true);
1362

    
1363
        String value;
1364

    
1365
        value = getStringValue(PreferencePredicate.NameDetailsView.getKey(), false);
1366
        if (value != null){
1367
            String [] sections = value.split(";");
1368
            Map<String, Boolean> sectionMap = new HashMap<String, Boolean>();
1369
            String[] sectionValues;
1370
            for (String sectionValue: sections){
1371
                sectionValues = sectionValue.split(":");
1372
                sectionMap.put(sectionValues[0], Boolean.valueOf(sectionValues[1]));
1373
            }
1374

    
1375
            config.setSimpleDetailsViewActivated(getValue(sectionMap, "simpleViewActivated"));
1376

    
1377
            config.setTaxonSectionActivated(getValue(sectionMap, "taxon"));
1378

    
1379
            config.setSecDetailsActivated(getValue(sectionMap, "taxon.SecDetails"));
1380
            config.setSecEnabled(getValue(sectionMap, "taxon.SecEnabled"));
1381

    
1382
            config.setLSIDActivated(getValue(sectionMap, "lsid"));
1383

    
1384
            config.setNomenclaturalCodeActived(getValue(sectionMap, "nc"));
1385

    
1386
            config.setAppendedPhraseActivated(getValue(sectionMap, "ap"));
1387

    
1388
            config.setRankActivated(getValue(sectionMap, "rank"));
1389

    
1390
            config.setAtomisedEpithetsActivated(getValue(sectionMap, "atomisedEpithets"));
1391

    
1392
            config.setAuthorshipSectionActivated(getValue(sectionMap,"author"));
1393

    
1394
            config.setNomenclaturalReferenceSectionActivated(sectionMap.get("nomRef"));
1395

    
1396
            config.setNomenclaturalStatusSectionActivated(getValue(sectionMap, "nomStat"));
1397

    
1398
            config.setProtologueActivated(getValue(sectionMap,"protologue"));
1399

    
1400
            config.setTypeDesignationSectionActivated(getValue(sectionMap,"typeDes"));
1401

    
1402
            config.setNameRelationsSectionActivated(getValue(sectionMap,"nameRelation"));
1403

    
1404
                config.setHybridActivated(getValue(sectionMap,"hybrid"));
1405
        }
1406
        return config;
1407
    }
1408

    
1409
    public static void setPreferredNameDetailsConfiguration(NameDetailsConfigurator config, boolean local) {
1410
        CdmPreference preference = null;
1411

    
1412
        if (!local) {
1413
            preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.NameDetailsView, config.toString());
1414

    
1415
            setPreferenceToDB(preference);
1416
        }
1417
        else{
1418
            setStringValue(PreferencePredicate.NameDetailsView.getKey(), config.toString());
1419
        }
1420

    
1421

    
1422
    }
1423

    
1424
    private static Boolean getValue(Map<String, Boolean> sectionMap, String string) {
1425
        if (sectionMap.containsKey(string)){
1426
            return sectionMap.get(string);
1427
        }else{
1428
            return true;
1429
        }
1430

    
1431
    }
1432

    
1433
    public static Abcd206ImportConfigurator getDBAbcdImportConfigurationPreference() {
1434

    
1435
        Abcd206ImportConfigurator config = Abcd206ImportConfigurator.NewInstance(null,null);
1436
        ICdmRepository controller;
1437
        controller = CdmStore.getCurrentApplicationConfiguration();
1438
        PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AbcdImportConfig);
1439
        CdmPreference preference = null;
1440
        if (controller == null){
1441
            return null;
1442
        }
1443
        preference = controller.getPreferenceService().find(key);
1444
        if (preference == null){
1445
            return config;
1446
         } else{
1447
             String configString = preference.getValue();
1448
             if(configString!=null){
1449
                 String[] configArray = configString.split(";");
1450

    
1451
                 for (String configItem: configArray){
1452
                     String[] keyValue = configItem.split(":");
1453
                     String keyString = keyValue[0];
1454
                     String valueString = null;
1455
                     if (keyValue.length>1){
1456
                         valueString = keyValue[1];
1457
                     }
1458
                     if (keyString.equals("ignoreImportOfExistingSpecimen")){
1459
                         config.setIgnoreImportOfExistingSpecimen(Boolean.valueOf(valueString));
1460
                     }else if (keyString.equals("addIndividualsAssociationsSuchAsSpecimenAndObservations")){
1461
                         config.setAddIndividualsAssociationsSuchAsSpecimenAndObservations(Boolean.valueOf(valueString));
1462
                     }else if (keyString.equals("reuseExistingTaxaWhenPossible")){
1463
                         config.setReuseExistingTaxaWhenPossible(Boolean.valueOf(valueString));
1464
                     }else if (keyString.equals("ignoreAuthorship")){
1465
                         config.setIgnoreAuthorship(Boolean.valueOf(valueString));
1466
                     }else if (keyString.equals("addMediaAsMediaSpecimen")){
1467
                         config.setAddMediaAsMediaSpecimen(Boolean.valueOf(valueString));
1468
                     }else if (keyString.equals("reuseExistingMetaData")){
1469
                         config.setReuseExistingMetaData(Boolean.valueOf(valueString));
1470
                     }else if (keyString.equals("reuseExistingDescriptiveGroups")){
1471
                         config.setReuseExistingDescriptiveGroups(Boolean.valueOf(valueString));
1472
                     }else if (keyString.equals("allowReuseOtherClassifications")){
1473
                         config.setAllowReuseOtherClassifications(Boolean.valueOf(valueString));
1474
                     }else if (keyString.equals("deduplicateReferences")){
1475
                         config.setDeduplicateReferences(Boolean.valueOf(valueString));
1476
                     }else if (keyString.equals("deduplicateClassifications")){
1477
                         config.setDeduplicateClassifications(Boolean.valueOf(valueString));
1478
                     }else if (keyString.equals("moveNewTaxaToDefaultClassification")){
1479
                         config.setMoveNewTaxaToDefaultClassification(Boolean.valueOf(valueString));
1480
                     }else if (keyString.equals("mapUnitIdToCatalogNumber")){
1481
                         config.setMapUnitIdToCatalogNumber(Boolean.valueOf(valueString));
1482
                     }else if (keyString.equals("mapUnitIdToAccessionNumber")){
1483
                         config.setMapUnitIdToAccessionNumber(Boolean.valueOf(valueString));
1484
                     }else if (keyString.equals("mapUnitIdToBarcode")){
1485
                         config.setMapUnitIdToBarcode(Boolean.valueOf(valueString));
1486
                     }else if (keyString.equals("overwriteExistingSpecimens")){
1487
                         config.setOverwriteExistingSpecimens(Boolean.valueOf(valueString));
1488
                     }else if (keyString.equals("nomenclaturalCode")){
1489
                         config.setNomenclaturalCode(NomenclaturalCode.fromString(valueString));
1490
                     }else{
1491
                         logger.debug("This key of the abcd configurator needs to be added to the transformer: " + keyString);
1492
                     }
1493
                 }
1494
             }
1495
         }
1496
        return config;
1497
    }
1498

    
1499
    public static Abcd206ImportConfigurator getLocalAbcdImportConfigurator(){
1500
       Abcd206ImportConfigurator config = Abcd206ImportConfigurator.NewInstance(null,null);
1501

    
1502
        config.setAddIndividualsAssociationsSuchAsSpecimenAndObservations(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_ADD_INDIVIDUALS_ASSOCIATIONS_SUCH_AS_SPECIMEN_AND_OBSERVATIONS));
1503

    
1504
        config.setAddMediaAsMediaSpecimen(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_ADD_MEDIA_AS_MEDIASPECIMEN));
1505

    
1506
        config.setAllowReuseOtherClassifications(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_ALLOW_REUSE_OTHER_CLASSIFICATIONS));
1507
        config.setDeduplicateClassifications(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_DEDUPLICATE_CLASSIFICATIONS));
1508
        config.setDeduplicateReferences(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_DEDUPLICATE_REFERENCES));
1509
        config.setRemoveCountryFromLocalityText(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_REMOVE_COUNTRY_FROM_LOCALITY_TEXT));
1510
        config.setGetSiblings(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_DO_SIBLINGS));
1511
        config.setIgnoreAuthorship(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_IGNORE_AUTHORSHIP));
1512
        config.setIgnoreImportOfExistingSpecimen(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_IGNORE_IMPORT_OF_EXISTING_SPECIMEN));
1513
        config.setMapUnitIdToAccessionNumber(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_MAP_UNIT_ID_TO_ACCESSION_NUMBER));
1514
        config.setMapUnitIdToBarcode(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_MAP_UNIT_ID_TO_BARCODE));
1515
        config.setMapUnitIdToCatalogNumber(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_MAP_UNIT_ID_TOCATALOG_NUMBER));
1516
        config.setMoveNewTaxaToDefaultClassification(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_MOVE_NEW_TAXA_TO_DEFAULT_CLASSIFICATION));
1517
        config.setOverwriteExistingSpecimens(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_OVERWRITE_EXISTING_SPECIMEN));
1518
        config.setReuseExistingDescriptiveGroups(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_REUSE_EXISTING_DESCRIPTIVE_GROUPS));
1519
        config.setReuseExistingMetaData(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_REUSE_EXISTING_META_DATA));
1520
        config.setReuseExistingTaxaWhenPossible(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_REUSE_EXISTING_TAXA_WHEN_POSSIBLE));
1521
        config.setNomenclaturalCode(NomenclaturalCode.getByKey(getStringValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_NOMENCLATURAL_CODE)));
1522
        try{
1523
            config.setDnaSoure(!StringUtils.isBlank(getStringValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_DNA_PROVIDER))? URI.create(getStringValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_DNA_PROVIDER)):null);
1524
        }catch(Exception e){
1525
            config.setDnaSoure(null);
1526
        }
1527
        return config;
1528

    
1529
    }
1530

    
1531
    public static void updateAbcdImportConfigurationPreference() {
1532
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1533

    
1534
        CdmPreference pref = cache.findBestMatching(CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AbcdImportConfig));
1535

    
1536
        if (!getBooleanValue(prefOverrideKey(PreferencePredicate.AbcdImportConfig.getKey())) || !pref.isAllowOverride()){
1537
            resetToDBPreferenceAbcdCOnfigurator();
1538

    
1539
        }
1540
    }
1541

    
1542
    public static void resetToDBPreferenceAbcdCOnfigurator(){
1543
        Abcd206ImportConfigurator config = getDBAbcdImportConfigurationPreference();
1544
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_ADD_INDIVIDUALS_ASSOCIATIONS_SUCH_AS_SPECIMEN_AND_OBSERVATIONS, config.isAddIndividualsAssociationsSuchAsSpecimenAndObservations());
1545
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_ADD_MEDIA_AS_MEDIASPECIMEN, config.isAddMediaAsMediaSpecimen());
1546

    
1547
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_ALLOW_REUSE_OTHER_CLASSIFICATIONS, config.isAllowReuseOtherClassifications());
1548
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_DEDUPLICATE_CLASSIFICATIONS, config.isDeduplicateClassifications());
1549
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_DEDUPLICATE_REFERENCES, config.isDeduplicateReferences());
1550

    
1551
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_DO_SIBLINGS, config.isGetSiblings());
1552
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_IGNORE_AUTHORSHIP, config.isIgnoreAuthorship());
1553
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_IGNORE_IMPORT_OF_EXISTING_SPECIMEN, config.isIgnoreImportOfExistingSpecimen());
1554
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_MAP_UNIT_ID_TO_ACCESSION_NUMBER, config.isMapUnitIdToAccessionNumber());
1555
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_MAP_UNIT_ID_TO_BARCODE, config.isMapUnitIdToBarcode());
1556
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_MAP_UNIT_ID_TOCATALOG_NUMBER, config.isMapUnitIdToCatalogNumber());
1557
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_MOVE_NEW_TAXA_TO_DEFAULT_CLASSIFICATION, config.isMoveNewTaxaToDefaultClassification());
1558
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_OVERWRITE_EXISTING_SPECIMEN, config.isOverwriteExistingSpecimens());
1559
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_REUSE_EXISTING_DESCRIPTIVE_GROUPS, config.isReuseExistingDescriptiveGroups());
1560
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_REUSE_EXISTING_META_DATA, config.isReuseExistingMetaData());
1561
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_REUSE_EXISTING_TAXA_WHEN_POSSIBLE, config.isReuseExistingTaxaWhenPossible());
1562
        if (config.getNomenclaturalCode() != null){
1563
            setStringValue(ABCD_IMPORT_CONFIGURATOR_NOMENCLATURAL_CODE, config.getNomenclaturalCode().getKey());
1564
        }
1565
    }
1566

    
1567
    public static boolean isSortTaxaByRankAndName() {
1568

    
1569
        return getBooleanValue(IPreferenceKeys.SORT_TAXA_BY_RANK_AND_NAME);
1570
    }
1571

    
1572
    public static String getSortNamedAreasInDistributionEditor() {
1573

    
1574
        return getStringValue(PreferencePredicate.AreasSortedInDistributionEditor.getKey());
1575
    }
1576

    
1577
    public static void setSortNamedAreasInDistributionEditor(String isSortByVocabularyOrder) {
1578
        setStringValue(PreferencePredicate.AreasSortedInDistributionEditor.getKey(), isSortByVocabularyOrder);
1579

    
1580
    }
1581

    
1582
    public static void setLastSelectedReference(
1583
            List<String> lastSelectedReferences) {
1584

    
1585
        setStringValue(PreferencesUtil.LAST_SELECTED_REFERENCES, lastSelectedReferences.toString());
1586
    }
1587

    
1588
    public static List<String> getLastSelectedReferences() {
1589

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

    
1599
    public static void setPreferredNamedAreasForDistributionEditor(
1600
            String saveCheckedElements, String saveGrayedElements, boolean local) {
1601
        if (local){
1602
            setStringValue(PreferencePredicate.AvailableDistributionAreaTerms.getKey(), saveCheckedElements);
1603

    
1604
        }
1605
        else{
1606
            CdmPreference preference = null;
1607

    
1608
            if (saveCheckedElements == null){
1609
                preference = getPreferenceFromDB(PreferencePredicate.AvailableDistributionAreaTerms);
1610

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

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

    
1626
            }
1627
        }
1628

    
1629
    }
1630

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

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

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

    
1660
            }
1661
        }
1662
    }
1663

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

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

    
1679
        }
1680
    }
1681

    
1682
    public static List<UUID> createUUIDListFromStringPref(String prefKey) {
1683
        String prefValue = PreferencesUtil.getStringValue(prefKey);
1684
        if (prefValue == null){
1685
            return null;
1686
        }
1687
        String[] stringArray = prefValue.split(";");
1688
        List<UUID> uuidList = new ArrayList();
1689
        for (String uuid: stringArray){
1690
            if (!StringUtils.isBlank(uuid)){
1691
                uuidList.add(UUID.fromString(uuid));
1692
            }
1693
        }
1694
        return uuidList;
1695
    }
1696

    
1697
    public static boolean getFilterCommonNameReferences(){
1698
        Boolean result = getBooleanValue(PreferencesUtil.FILTER_COMMON_NAME_REFERENCES);
1699
        if (result == null){
1700
            return false;
1701
        }
1702
        return result;
1703
    }
1704

    
1705
    public static void updateDBPreferences() {
1706

    
1707

    
1708
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1709
        cache.getAllTaxEditorDBPreferences();
1710

    
1711
        //ABCD Configurator
1712

    
1713
        //updateAbcdImportConfigurationPreference();
1714

    
1715
        //Name Details
1716
        NameDetailsConfigurator config = getPreferredNameDetailsConfiguration(false);
1717
        //    if (config != null ){
1718
        //        if (!getBooleanValue(OVERRIDE_NAME_DETAILS) ||  !getBooleanValue(ALLOW_OVERRIDE_NAME_DETAILS)){
1719
        //            setPreferredNameDetailsConfiguration(config, false);
1720
        //        }
1721
        //    }
1722

    
1723
    }
1724

    
1725
    public static void setPreferencesToDB(List<CdmPreference> preferences) {
1726

    
1727
        ICdmRepository controller;
1728
        //try{
1729
            if(CdmStore.isActive()){
1730
                controller = CdmStore.getCurrentApplicationConfiguration();
1731
                for (CdmPreference preference: preferences){
1732
                    if (preference.getValue() == null && preference.isAllowOverride()){
1733
                        controller.getPreferenceService().remove(preference.getKey());
1734

    
1735
                    }else{
1736
                        controller.getPreferenceService().set(preference);
1737

    
1738
                    }
1739

    
1740
                }
1741
                CdmPreferenceCache.instance().getAllTaxEditorDBPreferences();
1742

    
1743
            }
1744
        /*}catch(Exception e){
1745
            e.printStackTrace();
1746
        }*/
1747
    }
1748

    
1749
    /**
1750
     * Returns whether the named preference is known.
1751
     * @param prefKey the key of the preference
1752
     * @return <code>true</code> if the preference is known, <code>false</code> otherwise
1753
     */
1754
    public static boolean contains(String prefKey){
1755
        return getPreferenceStore().contains(prefKey(prefKey));
1756
    }
1757

    
1758

    
1759

    
1760
}
(32-32/48)