Project

General

Profile

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

    
10
package eu.etaxonomy.taxeditor.preference;
11

    
12
import java.io.File;
13
import java.io.FileInputStream;
14
import java.io.FileOutputStream;
15
import java.io.IOException;
16
import java.net.URI;
17
import java.net.URISyntaxException;
18
import java.util.ArrayList;
19
import java.util.Arrays;
20
import java.util.Collections;
21
import java.util.HashMap;
22
import java.util.List;
23
import java.util.Map;
24
import java.util.Properties;
25
import java.util.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.IFeatureTreeService;
45
import eu.etaxonomy.cdm.api.service.ITermService;
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.FeatureTree;
62
import eu.etaxonomy.cdm.model.term.IDefinedTerm;
63
import eu.etaxonomy.cdm.model.term.ISimpleTerm;
64
import eu.etaxonomy.cdm.model.term.TermBase;
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
        return getBooleanValue(name, false);
291
    }
292

    
293
    public static boolean getBooleanValue(String name, boolean local) {
294
        if (CdmStore.isActive()){
295
            CdmPreference pref = getDBPreferenceValue(name);
296

    
297
            String overrideKey =  createPreferenceString(createOverridePreferenceString(name));
298
            boolean override = getPreferenceStore().getBoolean(overrideKey);
299

    
300
            if (local || pref == null || (pref != null && pref.isAllowOverride() && override)){
301
                String dbSpecific = prefKey(name);
302
                return getPreferenceStore().getBoolean(dbSpecific);
303
             }else{
304
                return Boolean.valueOf(pref.getValue());
305
            }
306

    
307
        }else{
308
            return getPreferenceStore().getBoolean(name);
309
        }
310

    
311
    }
312

    
313
    public static double getDoubleValue(String name) {
314
        CdmPreference pref = getDBPreferenceValue(name);
315
        String prefValue = null;
316
        if (pref != null){
317
            prefValue = pref.getValue();
318
        }
319
        Double result = null;
320
        try{
321
            result = Double.parseDouble(prefValue);
322
        }catch(NumberFormatException e){
323
            logger.debug("Preference value of " + name + " is not a number");
324
        }
325
        if (result == null){
326
            String dbSpecific = prefKey(name);
327
            if (getPreferenceStore().contains(dbSpecific)){
328
                result = getPreferenceStore().getDouble(dbSpecific);
329
            }else{
330
                result =  getPreferenceStore().
331
                        getDouble(name);
332
            }
333
        }
334
        return result;
335

    
336
    }
337

    
338
    public static float getFloatValue(String name, boolean local) {
339
        CdmPreference pref = getDBPreferenceValue(name);
340
        String prefValue = null;
341
        if (pref != null){
342
            prefValue = pref.getValue();
343
        }
344
        Float result = null;
345
        try{
346
            result = Float.parseFloat(prefValue);
347
        }catch(NumberFormatException e){
348
            logger.debug("Preference value of " + name + " is not a number");
349
        }
350
        String overrideKey =  createPreferenceString(createOverridePreferenceString(name));
351
        boolean override = true;
352
        if (getPreferenceStore().contains(overrideKey)){
353
            override = getPreferenceStore().getBoolean(overrideKey);
354
        }
355
        if (local || pref == null || (pref != null && pref.isAllowOverride() && override)){
356
            String dbSpecific = prefKey(name);
357
            if (getPreferenceStore().contains(dbSpecific)){
358
                result = getPreferenceStore().getFloat(dbSpecific);
359
            }else{
360
                result =  getPreferenceStore().
361
                        getFloat(name);
362
            }
363
        }
364
        return result;
365

    
366
    }
367

    
368
    public static long getLongValue(String name) {
369
        CdmPreference pref = getDBPreferenceValue(name);
370
        String prefValue = null;
371
        if (pref != null){
372
            prefValue = pref.getValue();
373
        }
374
        Long result = null;
375
        try{
376
            result = Long.parseLong(prefValue);
377
        }catch(NumberFormatException e){
378
            logger.debug("Preference value of " + name + " is not a number");
379
        }
380
        if (result == null){
381
            String dbSpecific = prefKey(name);
382
            if (getPreferenceStore().contains(dbSpecific)){
383
                result = getPreferenceStore().getLong(dbSpecific);
384
            }else{
385
                result =  getPreferenceStore().
386
                        getLong(name);
387
            }
388
        }
389
        return result;
390
    }
391

    
392
    public static CdmPreference setPreferredNomenclaturalCode(
393
            String preferenceValue, boolean local) {
394
        if (local){
395
            setStringValue(PREFERRED_NOMENCLATURAL_CODE_KEY,
396
                    preferenceValue);
397
        }
398
        else{
399
            ICdmRepository controller;
400
            controller = CdmStore.getCurrentApplicationConfiguration();
401
            if (controller == null){
402
                return null;
403
            }
404
            PrefKey key = null;
405
            try{
406
                key = CdmPreference.NewKey(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.NomenclaturalCode);
407
            }catch (Exception e){
408
                System.out.println(e.getStackTrace());
409
            }
410
            CdmPreference preference = null;
411

    
412
            if (preferenceValue == null){
413
                preference = controller.getPreferenceService().find(key);
414
                if (preference == null){
415
                    return null;
416
                } else{
417
                    setStringValue(PREFERRED_NOMENCLATURAL_CODE_KEY,
418
                            preference.getValue());
419

    
420
                    return preference;
421
                }
422
            } else{
423
                preference = CdmPreference.NewInstance(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.NomenclaturalCode, preferenceValue);
424
                controller.getPreferenceService().set(preference);
425

    
426
            }
427
        }
428
        return null;
429

    
430

    
431

    
432
    }
433

    
434
    public static void setPreferredNomenclaturalCode(
435
        CdmPreference preference) {
436

    
437
        ICdmRepository controller;
438
        controller = CdmStore.getCurrentApplicationConfiguration();
439
        if (controller == null){
440
            return;
441
        }
442
        PrefKey key = null;
443
        try{
444
            key = CdmPreference.NewKey(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.NomenclaturalCode);
445
        }catch (Exception e){
446
            System.out.println(e.getStackTrace());
447
        }
448

    
449
        controller.getPreferenceService().set(preference);
450

    
451
    }
452

    
453
    public static NomenclaturalCode getPreferredNomenclaturalCode() {
454

    
455
        CdmPreference pref = getPreferenceFromDB(PreferencePredicate.NomenclaturalCode);
456

    
457

    
458
        String preferredCode;
459
        if(pref == null || (pref.isAllowOverride() && getBooleanValue(prefOverrideKey(PreferencePredicate.NomenclaturalCode.getKey())))){
460
            preferredCode = getStringValue(
461
                    PreferencePredicate.NomenclaturalCode.getKey(), true);
462

    
463
        }else{
464
            preferredCode = pref.getValue();
465
        }
466
        if (StringUtils.isBlank(preferredCode)){
467
            preferredCode = getPreferenceKey((NomenclaturalCode)PreferencePredicate.NomenclaturalCode.getDefaultValue());
468
        }
469

    
470
        return getPreferredNomenclaturalCode(preferredCode);
471

    
472
    }
473

    
474
    public static NomenclaturalCode getPreferredNomenclaturalCode(String preferenceKeyNomenclaturalCode) {
475

    
476
        for (NomenclaturalCode code : NomenclaturalCodeHelper.getAllCodes()) {
477
            if (getPreferenceKey(code).equals(preferenceKeyNomenclaturalCode)) {
478
                return code;
479
            }
480
        }
481
        return null;
482
    }
483

    
484
    public static boolean isShowTaxonAssociations(){
485
        boolean result = getBooleanValue(PreferencePredicate.ShowTaxonAssociations.getKey());
486
        return result;
487
    }
488

    
489
    public static boolean isShowLifeForm(){
490
        boolean result =  getBooleanValue(PreferencePredicate.ShowLifeForm.getKey());
491
        return result;
492
    }
493

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

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

    
504
    public static CdmPreference getPreferenceFromDB(IPreferencePredicate predicate){
505
        ICdmRepository controller;
506
        CdmPreference pref = null;
507

    
508
        try{
509
            if(CdmStore.isActive()){
510
                controller = CdmStore.getCurrentApplicationConfiguration();
511
                PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), predicate);
512
                pref = controller.getPreferenceService().find(key);
513
            }
514
        }catch(Exception e){
515
            e.printStackTrace();
516
        }
517

    
518
        return pref;
519

    
520
    }
521

    
522
    public static List<CdmPreference> getPreferencesFromDB(IPreferencePredicate predicate){
523
        ICdmRepository controller;
524
        List<CdmPreference> prefs = null;
525

    
526
        try{
527
            if(CdmStore.isActive()){
528
                controller = CdmStore.getCurrentApplicationConfiguration();
529
                PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), predicate);
530
                prefs = controller.getPreferenceService().list(predicate);
531
            }
532
        }catch(Exception e){
533
            e.printStackTrace();
534
        }
535

    
536
        return prefs;
537

    
538
    }
539

    
540
    public static void setPreferencesToDB(CdmPreference preference, boolean setDefault){
541
        ICdmRepository controller;
542

    
543

    
544
        try{
545
            if(CdmStore.isActive()){
546
                controller = CdmStore.getCurrentApplicationConfiguration();
547

    
548
                if (setDefault){
549
                    controller.getPreferenceService().remove(preference.getKey());
550
                }else{
551
                    controller.getPreferenceService().set(preference);
552
                }
553
            }
554
        }catch(Exception e){
555
            e.printStackTrace();
556
        }
557

    
558

    
559

    
560
    }
561

    
562
    public static CdmPreference getPreferenceFromDB(PrefKey key){
563
        ICdmRepository controller;
564
        CdmPreference pref = null;
565

    
566
        try{
567
            if(CdmStore.isActive()){
568
                controller = CdmStore.getCurrentApplicationConfiguration();
569
                pref = controller.getPreferenceService().find(key);
570
            }
571
        }catch(Exception e){
572
            e.printStackTrace();
573
        }
574

    
575
        return pref;
576

    
577
    }
578

    
579
    public static void setPreferenceToDB(CdmPreference preference){
580
        ICdmRepository controller;
581
        try{
582
            if(CdmStore.isActive()){
583
                controller = CdmStore.getCurrentApplicationConfiguration();
584
                controller.getPreferenceService().set(preference);
585
                CdmPreferenceCache.instance().put(preference);
586
            }
587
        }catch(Exception e){
588
            e.printStackTrace();
589
        }
590

    
591
    }
592

    
593
    public static String getPreferredDefaultLangugae(){
594
        String preferredLanguage = getStringValue(DEFAULT_LANGUAGE_EDITOR);
595
        if(StringUtils.isNotEmpty(preferredLanguage) && StringUtils.isNotBlank(preferredLanguage)){
596
            return preferredLanguage;
597
        }
598
        return null;
599
    }
600

    
601
    public static boolean isShowMediaPreview(){
602
        boolean isShowMediaPreview = getBooleanValue(SHOW_MEDIA_PREVIEW);
603
        return isShowMediaPreview;
604
    }
605

    
606
    /**
607
     * Get the match strategy for the given class that was stored in preferences
608
     * or the default strategy if it was not stored in preferences
609
     *
610
     * @param clazz
611
     *            a {@link java.lang.Class} object.
612
     * @return a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy} object.
613
     */
614
    public static IMatchStrategy getMatchStrategy(Class<?> clazz) {
615
        String className = clazz.getName();
616
        if (getBooleanValue(MATCH_STRATEGY_PREFIX + className)) {
617
            IMatchStrategy matchStrategy = getDefaultMatchStrategy(clazz);
618

    
619
            //TODO CacheMatchers (or multiple field matchers in future) are missing here
620
            for (FieldMatcher fieldMatcher : matchStrategy.getMatching().getFieldMatchers(false)) {
621
                String fieldName = fieldMatcher.getPropertyName();
622
                String matchModeName = getStringValue(
623
                        getMatchStrategyFieldName(className, fieldName));
624
                MatchMode matchMode = MatchMode.valueOf(matchModeName);
625
                try {
626
                    matchStrategy.setMatchMode(fieldName, matchMode);
627
                } catch (MatchException e) {
628
                    MessagingUtils.error(PreferencesUtil.class, e);
629
                    throw new RuntimeException(e);
630
                }
631
            }
632

    
633
            return matchStrategy;
634
        }
635
        return getDefaultMatchStrategy(clazz);
636
    }
637

    
638
    /**
639
     * Stores a matchStrategy into the preference store.
640
     *
641
     * @param matchStrategy
642
     *            a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy}
643
     *            object.
644
     */
645
    public static void setMatchStrategy(IMatchStrategy matchStrategy) {
646
        String className = "ANY class"; //FIXME was: matchStrategy.getMatchClass().getName(); seems currently not in use
647
        setBooleanValue(MATCH_STRATEGY_PREFIX + className, true);
648

    
649
        List<FieldMatcher> fieldMatchers = matchStrategy.getMatching().getFieldMatchers(false);
650

    
651
        for (FieldMatcher fieldMatcher : fieldMatchers) {
652
            String fieldName = fieldMatcher.getPropertyName();
653
            setStringValue(
654
                    getMatchStrategyFieldName(className, fieldName),
655
                    fieldMatcher.getMatchMode().name());
656
        }
657
    }
658

    
659
    /**
660
     * Helper method to create the preference property for a match field.
661
     *
662
     * @param className
663
     * @param fieldName
664
     * @return
665
     */
666
    private static String getMatchStrategyFieldName(String className,
667
            String fieldName) {
668
        return MATCH_STRATEGY_PREFIX + className + "." + fieldName;
669
    }
670

    
671
    /**
672
     * Returns the default match strategy for a given class.
673
     *
674
     * @param clazz
675
     *            a {@link java.lang.Class} object.
676
     * @return a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy} object.
677
     */
678
    public static IMatchStrategy getDefaultMatchStrategy(Class clazz) {
679
        return DefaultMatchStrategy.NewInstance(clazz);
680
    }
681

    
682
    public static String getDateFormatPattern() {
683
        // TODO make this configurable in properties
684
        String pattern = "Y-M-d H:m";
685
        return pattern;
686
    }
687

    
688
    public static <T extends TermBase> void addTermToPreferredTerms(T term) {
689

    
690
        // VocabularyEnum vocabulary =
691
        // VocabularyEnum.getVocabularyEnum(term.getClass());
692
        //
693
        // getPreferenceStore().setValue(getPreferenceKey(term),
694
        // VocabularyStore.getTermVocabulary(vocabulary).getTerms().contains(term));
695
        //
696
        // firePreferencesChanged(term.getClass());
697
    }
698

    
699
    /**
700
     * Construct a unique key using the CdmBase object's uuid
701
     *
702
     * @param cdmBase
703
     * @return
704
     */
705
    private static String getPreferenceKey(ICdmBase cdmBase) {
706
        cdmBase = HibernateProxyHelper.deproxy(cdmBase);
707

    
708
        String key = cdmBase.getClass().getName().concat(".")
709
                .concat(cdmBase.getUuid().toString());
710
        if (key.contains("javassist")) {
711
            MessagingUtils.info("proxy");
712
        }
713
        return key;
714
    }
715

    
716
    /**
717
     * Construct a unique key using the CdmBase object's uuid
718
     *
719
     * @param cdmBase
720
     * @return
721
     */
722
    public static String getPreferenceKey(ISimpleTerm simpleTerm) {
723
        simpleTerm = HibernateProxyHelper.deproxy(simpleTerm);
724
        String key = simpleTerm.getClass().getName().concat(".")
725
                .concat(simpleTerm.getUuid().toString());
726
        if (key.contains("javassist")) {
727
            MessagingUtils.warn(PreferencesUtil.class,
728
                    "Trying to persist a preference based on a proxy class.");
729
        }
730
        return key;
731
    }
732

    
733

    
734

    
735
    /**
736
     * Construct a unique key using the CdmBase object's uuid
737
     *
738
     * @param cdmBase
739
     * @return
740
     */
741
    public static String getPreferenceKey(IDefinedTerm definedTerm) {
742
        definedTerm = HibernateProxyHelper.deproxy(definedTerm);
743
        String key = definedTerm.getClass().getName().concat(".")
744
                .concat(definedTerm.getUuid().toString());
745
        if (key.contains("javassist")) {
746
            MessagingUtils.warn(PreferencesUtil.class,
747
                    "Trying to persist a preference based on a proxy class.");
748
        }
749
        return key;
750
    }
751

    
752
    /**
753
     * Retrieves search preferences from the preference store
754
     *
755
     * @return an {@link ITaxonServiceConfigurator} to pass to search methods
756
     */
757
    public static IFindTaxaAndNamesConfigurator getSearchConfigurator() {
758
        IFindTaxaAndNamesConfigurator configurator = initializeSearchConfigurator();
759

    
760
        configurator.setDoTaxa(getBooleanValue(
761
                TAXON_SERVICE_CONFIGURATOR_TAXA));
762
        configurator.setDoSynonyms(getBooleanValue(
763
                TAXON_SERVICE_CONFIGURATOR_SYNONYMS));
764
        configurator.setDoNamesWithoutTaxa(getBooleanValue(
765
                TAXON_SERVICE_CONFIGURATOR_NAMES));
766
        configurator.setDoTaxaByCommonNames(getBooleanValue(
767
                TAXON_SERVICE_CONFIGURATOR_COMMON_NAMES));
768
        //configurator.setMatchMode(eu.etaxonomy.cdm.persistence.query.MatchMode.valueOf(getStringValue(TAXON_SERVICE_CONFIGURATOR_MATCH_MODE)));
769

    
770
        return configurator;
771
    }
772

    
773
    /**
774
     * create new preferences, setting all search options to true
775
     *
776
     * @return a
777
     *         {@link eu.etaxonomy.cdm.api.service.config.ITaxonServiceConfigurator}
778
     *         object.
779
     */
780
    public static IFindTaxaAndNamesConfigurator initializeSearchConfigurator() {
781
        IFindTaxaAndNamesConfigurator configurator = FindTaxaAndNamesConfiguratorImpl.NewInstance();
782

    
783
        configurator.setDoTaxa(true);
784
        configurator.setDoSynonyms(true);
785
        configurator.setDoNamesWithoutTaxa(true);
786
        configurator.setDoTaxaByCommonNames(true);
787

    
788
        configurator.setTaxonPropertyPath(Arrays.asList("$", "titleCache",
789
                "name", "name.$", "relationsFromThisTaxon.$"));
790

    
791
        configurator.setSynonymPropertyPath(Arrays.asList("$", "titleCache",
792
                "name", "name.$", "synonyms.relatedTo.*"));
793

    
794
        // DEFAULT VALUES
795
        // match mode is a simple like, actually all other match modes are kind
796
        // of bogus
797
        configurator
798
                .setMatchMode(eu.etaxonomy.cdm.persistence.query.MatchMode.ANYWHERE);
799
        // we set page number and size here as this should always be unlimited
800
        configurator.setPageNumber(0);
801
        // TODO currently limit results to 10000
802
        configurator.setPageSize(10000);
803
        //setSearchConfigurator(configurator) ;
804
        return configurator;
805
    }
806

    
807
    /**
808
     * Store search preferences
809
     *
810
     * @param configurator
811
     *            a
812
     *            {@link eu.etaxonomy.cdm.api.service.config.ITaxonServiceConfigurator}
813
     *            object.
814
     */
815
    public static void setSearchConfigurator(
816
            IFindTaxaAndNamesConfigurator configurator) {
817
        getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_TAXA,
818
                configurator.isDoTaxa());
819
        getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_SYNONYMS,
820
                configurator.isDoSynonyms());
821
        getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_NAMES,
822
                configurator.isDoNamesWithoutTaxa());
823
        getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_COMMON_NAMES,
824
                configurator.isDoTaxaByCommonNames());
825
    }
826

    
827
    public static void firePreferencesChanged(Class clazz) {
828
        getPreferenceStore().firePropertyChangeEvent(PREFERRED_TERMS_CHANGE,
829
                null, clazz);
830
    }
831

    
832
    public static String createPreferenceString(String property){
833
       return prefKey(property);
834

    
835
    }
836
    public static String createOverridePreferenceString(String property){
837
           return prefOverrideKey(property);
838

    
839
        }
840

    
841
    /**
842
     * Set default values for preferences
843
     */
844
    public static void setDefaults() {
845
        getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_TAXA, true);
846
        getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_SYNONYMS,
847
                true);
848
        getPreferenceStore().setDefault(createPreferenceString(EDIT_MAP_SERVICE_ACCES_POINT),
849
                "http://edit.africamuseum.be/edit_wp5/v1.2/rest_gen.php");
850
        //FIXME : changed default for SHOULD_CONNECT_AT_STARTUP to false (ticket 3828) until resolution
851
        getPreferenceStore().setDefault(createPreferenceString(SHOULD_CONNECT_AT_STARTUP), false);
852
        getPreferenceStore().setDefault(createPreferenceString(OPENURL_ACCESS_POINT),
853
                "http://www.biodiversitylibrary.org/openurl");
854
        getPreferenceStore().setDefault(createPreferenceString(OPENURL_IMAGE_MAX_WIDTH), "1000");
855
        getPreferenceStore().setDefault(createPreferenceString(OPENURL_IMAGE_MAX_HEIGHT), "1000");
856
        getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_TAXA, true);
857
        getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_SYNONYMS, true);
858
        getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_NAMES, true);
859
        getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_COMMON_NAMES, true);
860

    
861
        //Distribution Editor:
862
//      getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.DistributionEditorActivated.getKey()), Boolean.valueOf(PreferencePredicate.DistributionEditorActivated.getDefaultValue().toString()));
863
//      getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey()), PreferencePredicate.DisplayOfAreasInDistributionEditor.getDefaultValue().toString());
864
//      getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.DisplayOfStatus.getKey()), PreferencePredicate.DisplayOfStatus.getDefaultValue().toString());
865

    
866

    
867
        //Name Details
868
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.NameDetailsView.getKey()), new NameDetailsConfigurator(false).toString());
869

    
870
        //Navigator preferences
871
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.TaxonNodeOrder.getKey()), NavigatorOrderEnum.RankAndNameOrder.getKey());
872

    
873
        //getPreferenceStore().setDefault(createPreferenceString(Prefe), true);
874

    
875
        getPreferenceStore().setDefault(createPreferenceString(SHOW_ADVANCED_MEDIA_SECTION), false);
876

    
877
        getPreferenceStore().setDefault(createPreferenceString(SHOW_MEDIA_PREVIEW), false);
878
        //override db preferences
879
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.AbcdImportConfig.getKey())), false);
880
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.ShowSpecimen.getKey())), true);
881
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.NameDetailsView.getKey())), false);
882
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.DistributionEditorActivated.getKey())), true);
883
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.AvailableDistributionStatus.getKey())), true);
884
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.AvailableDistributionAreaTerms.getKey())), true);
885
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey())), true);
886
        getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.CommonNameAreaVocabularies.getKey())), false);
887
        getPreferenceStore().setDefault(createPreferenceString(FILTER_COMMON_NAME_REFERENCES), false);
888
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowTaxonNodeWizard.getKey()), Boolean.valueOf(PreferencePredicate.ShowTaxonNodeWizard.getDefaultValue().toString()));
889
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowNamespaceInSource.getKey()), Boolean.valueOf(PreferencePredicate.ShowNamespaceInSource.getDefaultValue().toString()));
890
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowIdInSource.getKey()), Boolean.valueOf(PreferencePredicate.ShowIdInSource.getDefaultValue().toString()));
891
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.DisableMultiClassification.getKey()), Boolean.valueOf(PreferencePredicate.DisableMultiClassification.getDefaultValue().toString()));
892
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowImportExportMenu.getKey()), Boolean.valueOf(PreferencePredicate.ShowImportExportMenu.getDefaultValue().toString()));
893
        getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowSpecimen.getKey()), Boolean.valueOf(PreferencePredicate.ShowSpecimen.getDefaultValue().toString()));
894

    
895
    }
896

    
897
    public static void checkNomenclaturalCode() {
898
        // First time Editor is opened, no nomenclatural code has been set
899
        if (PreferencesUtil.getPreferredNomenclaturalCode() == null) {
900
            PreferencesUtil.setPreferredNomenclaturalCode(getPreferenceKey(NomenclaturalCode.ICNAFP), true);
901
        }
902

    
903

    
904

    
905
    }
906
    public static void setNomenclaturalCodePreferences(){
907
        ICdmRepository controller;
908
        controller = CdmStore.getCurrentApplicationConfiguration();
909
        PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.NomenclaturalCode);
910
        CdmPreference preference = null;
911
        if (controller == null){
912
            return ;
913
        }
914
        preference = controller.getPreferenceService().find(key);
915
        if (preference == null){
916
            return;
917
        }
918
//        setBooleanValue(ALLOW_OVERRIDE_NOMENCLATURAL_CODE_KEY, preference.isAllowOverride());
919

    
920
        int index = StringUtils.lastIndexOf(preference.getValue(), ".");
921
        UUID uuid = UUID.fromString(preference.getValue().substring(index +1, preference.getValue().length()));
922
        NomenclaturalCode preferredCode = NomenclaturalCode.getByUuid(uuid);
923

    
924
        setStringValue(PREFERRED_NOMENCLATURAL_CODE_KEY,
925
                getPreferenceKey(preferredCode));
926

    
927
    }
928

    
929
    public static void checkDefaultLanguage(){
930
        if(PreferencesUtil.getPreferredDefaultLangugae() == null){
931
           Shell shell = AbstractUtility.getShell();
932
           int open = new DefaultLanguageDialog(shell).open();
933
           if(open == Window.OK){
934
               PlatformUI.getWorkbench().restart();
935
           }
936
        }else{
937
            //TODO:In case of a reinstall, the config.ini will be overwritten
938
            //     here you create config.ini with the stored key from preferences
939
        }
940
    }
941

    
942
    public static String getMapServiceAccessPoint() {
943
        return getStringValue(EDIT_MAP_SERVICE_ACCES_POINT);
944
    }
945

    
946
    public static boolean shouldConnectAtStartUp() {
947
        //FIXME :  force SHOULD_CONNECT_AT_STARTUP to false (ticket 3828) until resolution
948
        //return getBooleanValue(SHOULD_CONNECT_AT_STARTUP);
949
        return false;
950
    }
951

    
952
    public static FeatureTree getDefaultFeatureTreeForTextualDescription() {
953
        String uuidString = getStringValue(
954
                FEATURE_TREE_DEFAULT_TEXT);
955
        if (StringUtils.isBlank(uuidString)) {
956
            return null;
957
        }
958
        FeatureTree tree = CdmStore.getService(
959
                    IFeatureTreeService.class).load(UUID.fromString(uuidString));
960
        if (tree.getId() == 0) {
961
            return null;
962
        }
963
        return tree;
964
    }
965

    
966
    public static FeatureTree getDefaultFeatureTreeForStructuredDescription() {
967
        String uuidString = getStringValue(
968
                FEATURE_TREE_DEFAULT_STRUCTURE);
969
        return CdmUtils.isEmpty(uuidString) ? null : CdmStore.getService(
970
                IFeatureTreeService.class).load(UUID.fromString(uuidString));
971
    }
972

    
973
    public static void setSortRanksHierarchichally(boolean selection) {
974
        setBooleanValue(SORT_RANKS_HIERARCHICHALLY, selection);
975
    }
976

    
977
    public static boolean getSortRanksHierarchichally() {
978
        return getBooleanValue(SORT_RANKS_HIERARCHICHALLY);
979
    }
980

    
981
    public static boolean isMultilanguageTextEditingCapability() {
982
        return getBooleanValue(
983
                MULTILANGUAGE_TEXT_EDITING_CAPABILITY);
984
    }
985

    
986
    public static Language getGlobalLanguage() {
987

    
988

    
989
        String languageUuidString = getStringValue(
990
                GLOBAL_LANGUAGE_UUID);
991

    
992
        if(!CdmStore.isActive()) {
993
            MessagingUtils.noDataSourceWarningDialog(languageUuidString);
994
            return null;
995
        }
996

    
997
        if (CdmUtils.isBlank(languageUuidString)) {
998
            return Language.getDefaultLanguage();
999
        }
1000

    
1001
        UUID languageUuid = UUID.fromString(languageUuidString);
1002
        return (Language) CdmStore.getService(ITermService.class).load(
1003
                languageUuid);
1004
    }
1005

    
1006
    public static void setGlobalLanguage(Language language) {
1007
        if(language != null) {
1008
            setStringValue(GLOBAL_LANGUAGE_UUID,language.getUuid().toString());
1009
            CdmStore.setDefaultLanguage(language);
1010
        }
1011

    
1012
    }
1013

    
1014
    public static Map<MarkerType, Boolean> getEditMarkerTypePreferences() {
1015
        List<MarkerType> markerTypes = CdmStore.getTermManager()
1016
                .getPreferredTerms(MarkerType.class);
1017

    
1018
        Map<MarkerType, Boolean> result = new HashMap<MarkerType, Boolean>();
1019

    
1020
        for (MarkerType markerType : markerTypes) {
1021
            String name = getMarkerTypeEditingPreferenceKey(markerType);
1022
            Boolean value = getBooleanValue(name);
1023

    
1024
            result.put(markerType, value);
1025
        }
1026

    
1027
        return result;
1028
    }
1029

    
1030
    public static void setEditMarkerTypePreferences(
1031
            Map<MarkerType, Boolean> markerTypeEditingMap) {
1032
        for (MarkerType markerType : markerTypeEditingMap.keySet()) {
1033
            String name = getMarkerTypeEditingPreferenceKey(markerType);
1034
            setBooleanValue(name,
1035
                    markerTypeEditingMap.get(markerType));
1036
        }
1037

    
1038
    }
1039

    
1040
    private static String getMarkerTypeEditingPreferenceKey(
1041
            MarkerType markerType) {
1042
        markerType = HibernateProxyHelper.deproxy(markerType);
1043
        return markerType.getClass().getName() + EDIT_MARKER_TYPE_PREFIX;
1044
    }
1045

    
1046
    public static void setEditMarkerTypePreference(MarkerType markerType,
1047
            boolean edit) {
1048
        setBooleanValue(
1049
                getMarkerTypeEditingPreferenceKey(markerType), edit);
1050
    }
1051

    
1052
    public static DerivedUnitFacadeConfigurator getDerivedUnitConfigurator() {
1053
        DerivedUnitFacadeConfigurator configurator = DerivedUnitFacadeConfigurator
1054
                .NewInstance();
1055
        configurator.setMoveDerivedUnitMediaToGallery(true);
1056
        configurator.setMoveFieldObjectMediaToGallery(true);
1057
        return configurator;
1058
    }
1059

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

    
1089
    /**
1090
     * This method loads a property from a given file and returns it.
1091
     *
1092
     * @param filename
1093
     * @return
1094
     * @throws IOException
1095
     */
1096
    private Properties load(String filename) throws IOException {
1097
        FileInputStream in = new FileInputStream(filename);
1098
        Properties prop = new Properties();
1099
        prop.load(in);
1100
        in.close();
1101
        return prop;
1102
    }
1103

    
1104
    /**
1105
     * This method saves a property to the specified file.
1106
     *
1107
     * @param filename
1108
     * @param properties
1109
     * @throws IOException
1110
     */
1111
    private void save(String filename, Properties properties) throws IOException{
1112
        FileOutputStream fos =  new FileOutputStream(filename);
1113
        properties.store(fos, "");
1114
        fos.close();
1115
    }
1116

    
1117
    /**
1118
     * Saves a list of P2 Metadata Repositories as string with specified delimiters
1119
     *
1120
     * @param p2Repos
1121
     */
1122
    public static void setP2Repositories(List<MetadataRepositoryElement> p2Repos) {
1123
        StringBuilder sb = new StringBuilder();
1124
        for(MetadataRepositoryElement p2Repo : p2Repos) {
1125
            sb.append(P2_REPOSITORIES_DELIM);
1126
            if(p2Repo.getName() == null || p2Repo.getName().isEmpty()) {
1127
                sb.append("-");
1128
            } else {
1129
                sb.append(p2Repo.getName());
1130
            }
1131
            sb.append(P2_REPOSITORY_FIELDS_DELIM);
1132
            sb.append(p2Repo.getLocation().toString());
1133
            sb.append(P2_REPOSITORY_FIELDS_DELIM);
1134
            sb.append(String.valueOf(p2Repo.isEnabled()));
1135
        }
1136
        getPreferenceStore().setValue(P2_REPOSITORY_LIST, sb.toString());
1137
    }
1138

    
1139

    
1140
    /**
1141
     * Retrieves a list of previously saved P2 repositories
1142
     *
1143
     * @return
1144
     */
1145
    public static List<MetadataRepositoryElement> getP2Repositories() {
1146
        List<MetadataRepositoryElement> p2Repos = new ArrayList<MetadataRepositoryElement>();
1147
        String p2ReposPref =  getStringValue(P2_REPOSITORY_LIST);
1148
        if(p2ReposPref != null && !p2ReposPref.isEmpty()) {
1149
            StringTokenizer p2ReposPrefST = new StringTokenizer(p2ReposPref,P2_REPOSITORIES_DELIM);
1150

    
1151
            while(p2ReposPrefST.hasMoreTokens()) {
1152
                String p2RepoStr = p2ReposPrefST.nextToken();
1153
                StringTokenizer p2ReposStrST = new StringTokenizer(p2RepoStr,P2_REPOSITORY_FIELDS_DELIM);
1154
                if(p2ReposStrST.countTokens()==3) {
1155
                    String nickname = p2ReposStrST.nextToken();
1156
                    URI uri = null;
1157
                    try {
1158
                        uri = new URI(p2ReposStrST.nextToken());
1159
                    } catch (URISyntaxException e) {
1160
                        continue;
1161
                    }
1162
                    boolean enabled = Boolean.parseBoolean(p2ReposStrST.nextToken());
1163
                    MetadataRepositoryElement mre = new MetadataRepositoryElement(null, uri, true);
1164
                    mre.setNickname(nickname);
1165
                    mre.setEnabled(enabled);
1166
                    p2Repos.add(mre);
1167
                }
1168
            }
1169
        }
1170

    
1171
        return p2Repos;
1172
    }
1173

    
1174
    /**
1175
     * enables/disables nested composite. <br>
1176
     *
1177
     * @param ctrl - Composite to be en-/disabeld
1178
     * @param enabled - boolean
1179
     */
1180
    public static void recursiveSetEnabled(Control ctrl, boolean enabled) {
1181
        if (ctrl instanceof Composite) {
1182
            Composite comp = (Composite) ctrl;
1183
            for (Control c : comp.getChildren()) {
1184
                recursiveSetEnabled(c, enabled);
1185
            }
1186
        } else {
1187
            ctrl.setEnabled(enabled);
1188
        }
1189
    }
1190

    
1191
    public static void setSortNodes(NavigatorOrderEnum nodesOrder) {
1192
        setStringValue(PreferencePredicate.TaxonNodeOrder.getKey(), nodesOrder.key);
1193

    
1194
    }
1195

    
1196
    public static NavigatorOrderEnum getSortNodes() {
1197
        return NavigatorOrderEnum.valueOf(getStringValue(PreferencePredicate.TaxonNodeOrder.getKey()));
1198

    
1199
    }
1200

    
1201
    public static boolean isNodesSortedNaturally() {
1202
        NavigatorOrderEnum value = NavigatorOrderEnum.valueOf(getStringValue(PreferencePredicate.TaxonNodeOrder.getKey()));
1203
        return value.equals(NavigatorOrderEnum.NaturalOrder);
1204

    
1205
    }
1206

    
1207
    public static boolean isNodesSortedByName() {
1208
        NavigatorOrderEnum value = NavigatorOrderEnum.valueOf(getStringValue(PreferencePredicate.TaxonNodeOrder.getKey()));
1209
        return value.equals(NavigatorOrderEnum.AlphabeticalOrder);
1210

    
1211
    }
1212

    
1213
    public static boolean isNodesSortedByNameAndRank() {
1214
        NavigatorOrderEnum value = NavigatorOrderEnum.valueOf(getStringValue(PreferencePredicate.TaxonNodeOrder.getKey()));
1215
        return value.equals(NavigatorOrderEnum.RankAndNameOrder);
1216

    
1217
    }
1218

    
1219
    public static boolean isStoreNavigatorState() {
1220
        return getBooleanValue(RESTORE_NAVIGATOR_STATE);
1221

    
1222
    }
1223

    
1224
    public static void setStoreNavigatorState(boolean selection) {
1225
        setBooleanValue(RESTORE_NAVIGATOR_STATE, selection);
1226

    
1227
    }
1228

    
1229
    public static boolean isShowUpWidgetIsDisposedMessages() {
1230
       return getBooleanValue(IS_SHOW_UP_WIDGET_IS_DISPOSED);
1231
    }
1232
    public static void setShowUpWidgetIsDisposedMessages(boolean selection) {
1233
        setBooleanValue(IS_SHOW_UP_WIDGET_IS_DISPOSED, selection);
1234
    }
1235

    
1236
    public static boolean isShowIdInVocabularyInChecklistEditor() {
1237
        String area_display = getStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey());
1238
        if (area_display.equals(TermDisplayEnum.IdInVocabulary.getKey())) {
1239
            return true;
1240
        }else{
1241
            return false;
1242
        }
1243
    }
1244
    public static boolean isShowSymbol1InChecklistEditor() {
1245
        String area_display = getStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey());
1246
        if (area_display.equals(TermDisplayEnum.Symbol1.getKey())) {
1247
            return true;
1248
        }else{
1249
            return false;
1250
        }
1251
     }
1252
    public static boolean isShowSymbol2InChecklistEditor() {
1253
        String area_display = getStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey());
1254
        if (area_display.equals(TermDisplayEnum.Symbol2.getKey())) {
1255
            return true;
1256
        }else{
1257
            return false;
1258
        }
1259
     }
1260
    public static void setAreaDisplayInChecklistEditor(String selection) {
1261
        setStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey(), selection);
1262
    }
1263

    
1264
    public static void setOwnDescriptionForChecklistEditor(boolean selection) {
1265
        setBooleanValue(PreferencePredicate.OwnDescriptionForDistributionEditor.getKey(), selection);
1266
    }
1267

    
1268
    public static boolean isOwnDescriptionForChecklistEditor() {
1269
        return getBooleanValue(PreferencePredicate.OwnDescriptionForDistributionEditor.getKey());
1270
    }
1271

    
1272
    public static String displayAreaInChecklistEditor() {
1273
        String result = getStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey());
1274
        if (StringUtils.isBlank(result)){
1275
            return ((TermDisplayEnum) PreferencePredicate.DisplayOfAreasInDistributionEditor.getDefaultValue()).getKey();
1276
        }
1277
       return result;
1278
    }
1279

    
1280
    public static String displayStatusInChecklistEditor() {
1281
        String result = getStringValue(PreferencePredicate.DisplayOfStatus.getKey());
1282
        if (StringUtils.isBlank(result)){
1283
            return((TermDisplayEnum) PreferencePredicate.DisplayOfStatus.getDefaultValue()).getKey();
1284
        }
1285
       return result;
1286
    }
1287
    public static void setDisplayStatusInChecklistEditor(String selection) {
1288
        setStringValue(PreferencePredicate.DisplayOfStatus.getKey(), selection);
1289

    
1290
    }
1291

    
1292
    public static boolean isShowRankInChecklistEditor() {
1293
        return getBooleanValue(PreferencePredicate.ShowRankInDistributionEditor.getKey());
1294
    }
1295
    public static void setShowRankInChecklistEditor(boolean selection) {
1296
       setBooleanValue(PreferencePredicate.ShowRankInDistributionEditor.getKey(), selection);
1297
    }
1298

    
1299
    public static NameDetailsConfigurator getPreferredNameDetailsConfiguration( boolean local) {
1300
        NameDetailsConfigurator config = new NameDetailsConfigurator(true);
1301
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1302
        CdmPreference preference = null;
1303
        String value;
1304
        if (!local) {
1305
            PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.NameDetailsView);
1306
            preference = cache.findBestMatching(key);
1307
            if (preference == null){
1308
                return null;
1309
            }
1310

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

    
1347
    public static NameDetailsConfigurator getPreferredNameDetailsConfiguration() {
1348
        NameDetailsConfigurator config = new NameDetailsConfigurator(true);
1349

    
1350
        String value;
1351

    
1352
        value = getStringValue(PreferencePredicate.NameDetailsView.getKey(), false);
1353
        if (value != null){
1354
            String [] sections = value.split(";");
1355
            Map<String, Boolean> sectionMap = new HashMap<String, Boolean>();
1356
            String[] sectionValues;
1357
            for (String sectionValue: sections){
1358
                sectionValues = sectionValue.split(":");
1359
                sectionMap.put(sectionValues[0], Boolean.valueOf(sectionValues[1]));
1360
            }
1361

    
1362
            config.setSimpleDetailsViewActivated(getValue(sectionMap, "simpleViewActivated"));
1363

    
1364
            config.setTaxonSectionActivated(getValue(sectionMap, "taxon"));
1365

    
1366
            config.setSecDetailsActivated(getValue(sectionMap, "taxon.SecDetails"));
1367
            config.setSecEnabled(getValue(sectionMap, "taxon.SecEnabled"));
1368

    
1369
            config.setLSIDActivated(getValue(sectionMap, "lsid"));
1370

    
1371
            config.setNomenclaturalCodeActived(getValue(sectionMap, "nc"));
1372

    
1373
            config.setAppendedPhraseActivated(getValue(sectionMap, "ap"));
1374

    
1375
            config.setRankActivated(getValue(sectionMap, "rank"));
1376

    
1377
            config.setAtomisedEpithetsActivated(getValue(sectionMap, "atomisedEpithets"));
1378

    
1379
            config.setAuthorshipSectionActivated(getValue(sectionMap,"author"));
1380

    
1381
            config.setNomenclaturalReferenceSectionActivated(sectionMap.get("nomRef"));
1382

    
1383
            config.setNomenclaturalStatusSectionActivated(getValue(sectionMap, "nomStat"));
1384

    
1385
            config.setProtologueActivated(getValue(sectionMap,"protologue"));
1386

    
1387
            config.setTypeDesignationSectionActivated(getValue(sectionMap,"typeDes"));
1388

    
1389
            config.setNameRelationsSectionActivated(getValue(sectionMap,"nameRelation"));
1390

    
1391
                config.setHybridActivated(getValue(sectionMap,"hybrid"));
1392
        }
1393
        return config;
1394
    }
1395

    
1396
    public static void setPreferredNameDetailsConfiguration(NameDetailsConfigurator config, boolean local) {
1397
        CdmPreference preference = null;
1398

    
1399
        if (!local) {
1400
            preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.NameDetailsView, config.toString());
1401

    
1402
            setPreferenceToDB(preference);
1403
        }
1404
        else{
1405
            setStringValue(PreferencePredicate.NameDetailsView.getKey(), config.toString());
1406
        }
1407

    
1408

    
1409
    }
1410

    
1411
    private static Boolean getValue(Map<String, Boolean> sectionMap, String string) {
1412
        if (sectionMap.containsKey(string)){
1413
            return sectionMap.get(string);
1414
        }else{
1415
            return true;
1416
        }
1417

    
1418
    }
1419

    
1420
    public static Abcd206ImportConfigurator getDBAbcdImportConfigurationPreference() {
1421

    
1422
        Abcd206ImportConfigurator config = Abcd206ImportConfigurator.NewInstance(null,null);
1423
        ICdmRepository controller;
1424
        controller = CdmStore.getCurrentApplicationConfiguration();
1425
        PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AbcdImportConfig);
1426
        CdmPreference preference = null;
1427
        if (controller == null){
1428
            return null;
1429
        }
1430
        preference = controller.getPreferenceService().find(key);
1431
        if (preference == null){
1432
            return config;
1433
         } else{
1434
             String configString = preference.getValue();
1435
             String[] configArray = configString.split(";");
1436

    
1437
             for (String configItem: configArray){
1438
                 String[] keyValue = configItem.split(":");
1439
                 String keyString = keyValue[0];
1440
                 String valueString = null;
1441
                 if (keyValue.length>1){
1442
                      valueString = keyValue[1];
1443
                 }
1444
                 if (keyString.equals("ignoreImportOfExistingSpecimen")){
1445
                     config.setIgnoreImportOfExistingSpecimen(Boolean.valueOf(valueString));
1446
                 }else if (keyString.equals("addIndividualsAssociationsSuchAsSpecimenAndObservations")){
1447
                     config.setAddIndividualsAssociationsSuchAsSpecimenAndObservations(Boolean.valueOf(valueString));
1448
                 }else if (keyString.equals("reuseExistingTaxaWhenPossible")){
1449
                     config.setReuseExistingTaxaWhenPossible(Boolean.valueOf(valueString));
1450
                 }else if (keyString.equals("ignoreAuthorship")){
1451
                     config.setIgnoreAuthorship(Boolean.valueOf(valueString));
1452
                 }else if (keyString.equals("addMediaAsMediaSpecimen")){
1453
                     config.setAddMediaAsMediaSpecimen(Boolean.valueOf(valueString));
1454
                 }else if (keyString.equals("reuseExistingMetaData")){
1455
                     config.setReuseExistingMetaData(Boolean.valueOf(valueString));
1456
                 }else if (keyString.equals("reuseExistingDescriptiveGroups")){
1457
                     config.setReuseExistingDescriptiveGroups(Boolean.valueOf(valueString));
1458
                 }else if (keyString.equals("allowReuseOtherClassifications")){
1459
                     config.setAllowReuseOtherClassifications(Boolean.valueOf(valueString));
1460
                 }else if (keyString.equals("deduplicateReferences")){
1461
                     config.setDeduplicateReferences(Boolean.valueOf(valueString));
1462
                 }else if (keyString.equals("deduplicateClassifications")){
1463
                     config.setDeduplicateClassifications(Boolean.valueOf(valueString));
1464
                 }else if (keyString.equals("moveNewTaxaToDefaultClassification")){
1465
                     config.setMoveNewTaxaToDefaultClassification(Boolean.valueOf(valueString));
1466
                 }else if (keyString.equals("mapUnitIdToCatalogNumber")){
1467
                     config.setMapUnitIdToCatalogNumber(Boolean.valueOf(valueString));
1468
                 }else if (keyString.equals("mapUnitIdToAccessionNumber")){
1469
                     config.setMapUnitIdToAccessionNumber(Boolean.valueOf(valueString));
1470
                 }else if (keyString.equals("mapUnitIdToBarcode")){
1471
                     config.setMapUnitIdToBarcode(Boolean.valueOf(valueString));
1472
                 }else if (keyString.equals("overwriteExistingSpecimens")){
1473
                     config.setOverwriteExistingSpecimens(Boolean.valueOf(valueString));
1474
                 }else if (keyString.equals("nomenclaturalCode")){
1475
                         config.setNomenclaturalCode(NomenclaturalCode.fromString(valueString));
1476
                 }else{
1477
                     logger.debug("This key of the abcd configurator needs to be added to the transformer: " + keyString);
1478
                 }
1479

    
1480
             }
1481
        }
1482
        return config;
1483
    }
1484

    
1485
    public static Abcd206ImportConfigurator getLocalAbcdImportConfigurator(){
1486
       Abcd206ImportConfigurator config = Abcd206ImportConfigurator.NewInstance(null,null);
1487

    
1488
        config.setAddIndividualsAssociationsSuchAsSpecimenAndObservations(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_ADD_INDIVIDUALS_ASSOCIATIONS_SUCH_AS_SPECIMEN_AND_OBSERVATIONS));
1489

    
1490
        config.setAddMediaAsMediaSpecimen(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_ADD_MEDIA_AS_MEDIASPECIMEN));
1491

    
1492
        config.setAllowReuseOtherClassifications(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_ALLOW_REUSE_OTHER_CLASSIFICATIONS));
1493
        config.setDeduplicateClassifications(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_DEDUPLICATE_CLASSIFICATIONS));
1494
        config.setDeduplicateReferences(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_DEDUPLICATE_REFERENCES));
1495
        config.setRemoveCountryFromLocalityText(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_REMOVE_COUNTRY_FROM_LOCALITY_TEXT));
1496
        config.setGetSiblings(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_DO_SIBLINGS));
1497
        config.setIgnoreAuthorship(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_IGNORE_AUTHORSHIP));
1498
        config.setIgnoreImportOfExistingSpecimen(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_IGNORE_IMPORT_OF_EXISTING_SPECIMEN));
1499
        config.setMapUnitIdToAccessionNumber(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_MAP_UNIT_ID_TO_ACCESSION_NUMBER));
1500
        config.setMapUnitIdToBarcode(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_MAP_UNIT_ID_TO_BARCODE));
1501
        config.setMapUnitIdToCatalogNumber(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_MAP_UNIT_ID_TOCATALOG_NUMBER));
1502
        config.setMoveNewTaxaToDefaultClassification(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_MOVE_NEW_TAXA_TO_DEFAULT_CLASSIFICATION));
1503
        config.setOverwriteExistingSpecimens(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_OVERWRITE_EXISTING_SPECIMEN));
1504
        config.setReuseExistingDescriptiveGroups(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_REUSE_EXISTING_DESCRIPTIVE_GROUPS));
1505
        config.setReuseExistingMetaData(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_REUSE_EXISTING_META_DATA));
1506
        config.setReuseExistingTaxaWhenPossible(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_REUSE_EXISTING_TAXA_WHEN_POSSIBLE));
1507
        config.setNomenclaturalCode(NomenclaturalCode.getByKey(getStringValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_NOMENCLATURAL_CODE)));
1508

    
1509
        return config;
1510

    
1511
    }
1512

    
1513
    public static void updateAbcdImportConfigurationPreference() {
1514
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1515

    
1516
        CdmPreference pref = cache.findBestMatching(CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AbcdImportConfig));
1517

    
1518
        if (!getBooleanValue(prefOverrideKey(PreferencePredicate.AbcdImportConfig.getKey())) || !pref.isAllowOverride()){
1519
            resetToDBPreferenceAbcdCOnfigurator();
1520

    
1521
        }
1522
    }
1523

    
1524
    public static void resetToDBPreferenceAbcdCOnfigurator(){
1525
        Abcd206ImportConfigurator config = getDBAbcdImportConfigurationPreference();
1526
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_ADD_INDIVIDUALS_ASSOCIATIONS_SUCH_AS_SPECIMEN_AND_OBSERVATIONS, config.isAddIndividualsAssociationsSuchAsSpecimenAndObservations());
1527
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_ADD_MEDIA_AS_MEDIASPECIMEN, config.isAddMediaAsMediaSpecimen());
1528

    
1529
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_ALLOW_REUSE_OTHER_CLASSIFICATIONS, config.isAllowReuseOtherClassifications());
1530
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_DEDUPLICATE_CLASSIFICATIONS, config.isDeduplicateClassifications());
1531
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_DEDUPLICATE_REFERENCES, config.isDeduplicateReferences());
1532

    
1533
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_DO_SIBLINGS, config.isGetSiblings());
1534
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_IGNORE_AUTHORSHIP, config.isIgnoreAuthorship());
1535
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_IGNORE_IMPORT_OF_EXISTING_SPECIMEN, config.isIgnoreImportOfExistingSpecimen());
1536
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_MAP_UNIT_ID_TO_ACCESSION_NUMBER, config.isMapUnitIdToAccessionNumber());
1537
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_MAP_UNIT_ID_TO_BARCODE, config.isMapUnitIdToBarcode());
1538
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_MAP_UNIT_ID_TOCATALOG_NUMBER, config.isMapUnitIdToCatalogNumber());
1539
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_MOVE_NEW_TAXA_TO_DEFAULT_CLASSIFICATION, config.isMoveNewTaxaToDefaultClassification());
1540
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_OVERWRITE_EXISTING_SPECIMEN, config.isOverwriteExistingSpecimens());
1541
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_REUSE_EXISTING_DESCRIPTIVE_GROUPS, config.isReuseExistingDescriptiveGroups());
1542
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_REUSE_EXISTING_META_DATA, config.isReuseExistingMetaData());
1543
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_REUSE_EXISTING_TAXA_WHEN_POSSIBLE, config.isReuseExistingTaxaWhenPossible());
1544
        if (config.getNomenclaturalCode() != null){
1545
            setStringValue(ABCD_IMPORT_CONFIGURATOR_NOMENCLATURAL_CODE, config.getNomenclaturalCode().getKey());
1546
        }
1547
    }
1548

    
1549
    public static boolean isSortTaxaByRankAndName() {
1550

    
1551
        return getBooleanValue(IPreferenceKeys.SORT_TAXA_BY_RANK_AND_NAME);
1552
    }
1553

    
1554
    public static String getSortNamedAreasInDistributionEditor() {
1555

    
1556
        return getStringValue(PreferencePredicate.AreasSortedInDistributionEditor.getKey());
1557
    }
1558

    
1559
    public static void setSortNamedAreasInDistributionEditor(String isSortByVocabularyOrder) {
1560
        setStringValue(PreferencePredicate.AreasSortedInDistributionEditor.getKey(), isSortByVocabularyOrder);
1561

    
1562
    }
1563

    
1564
    public static void setLastSelectedReference(
1565
            List<String> lastSelectedReferences) {
1566

    
1567
        setStringValue(PreferencesUtil.LAST_SELECTED_REFERENCES, lastSelectedReferences.toString());
1568
    }
1569

    
1570
    public static List<String> getLastSelectedReferences() {
1571

    
1572
        //IPreferenceStore preferenceStore = PreferencesUtil.getPreferenceStore();
1573
        String lastSelected = getStringValue(PreferencesUtil.LAST_SELECTED_REFERENCES);
1574
        List<String> result = new ArrayList<>();
1575
        if (!StringUtils.isBlank(lastSelected)){
1576
            Collections.addAll(result, lastSelected.substring(1,lastSelected.length()-1).split(", "));
1577
        }
1578
        return result;
1579
    }
1580

    
1581
    public static void setPreferredNamedAreasForDistributionEditor(
1582
            String saveCheckedElements, String saveGrayedElements, boolean local) {
1583
        if (local){
1584
            setStringValue(PreferencePredicate.AvailableDistributionAreaTerms.getKey(), saveCheckedElements);
1585

    
1586
        }
1587
        else{
1588
            CdmPreference preference = null;
1589

    
1590
            if (saveCheckedElements == null){
1591
                preference = getPreferenceFromDB(PreferencePredicate.AvailableDistributionAreaTerms);
1592

    
1593
                if (preference == null){
1594
                    return ;
1595
                } else{
1596
                    setStringValue(PreferencePredicate.AvailableDistributionAreaTerms.getKey(),
1597
                            saveCheckedElements);
1598
                    preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AvailableDistributionAreaTerms, saveCheckedElements);
1599
                    setPreferenceToDB(preference);
1600

    
1601
                }
1602
            } else{
1603
                preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AvailableDistributionAreaTerms, saveCheckedElements);
1604
                setPreferenceToDB(preference);
1605
                setStringValue(PreferencePredicate.AvailableDistributionAreaTerms.getKey(),
1606
                        saveCheckedElements);
1607

    
1608
            }
1609
        }
1610

    
1611
    }
1612

    
1613
    public static void setPreferredVocabulariesForDistributionEditor(String saveCheckedElements,
1614
            boolean local, boolean isOverride) {
1615
        if (local){
1616
            setStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(), saveCheckedElements);
1617
            setBooleanValue(prefOverrideKey(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey()), isOverride);
1618
        }
1619
        else{
1620
            ICdmRepository controller;
1621
            CdmPreference preference = null;
1622

    
1623
            if (saveCheckedElements == null){
1624
                preference = getPreferenceFromDB(PreferencePredicate.AvailableDistributionAreaVocabularies);
1625

    
1626
                if (preference == null){
1627
                    return ;
1628
                } else{
1629
                    setStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(),
1630
                            saveCheckedElements);
1631
                    preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AvailableDistributionAreaVocabularies, saveCheckedElements);
1632
                    preference.setAllowOverride(isOverride);
1633
                    setPreferenceToDB(preference);
1634
                }
1635
            } else{
1636
                preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AvailableDistributionAreaVocabularies, saveCheckedElements);
1637
                preference.setAllowOverride(isOverride);
1638
                setPreferenceToDB(preference);
1639
                setStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(),
1640
                        saveCheckedElements);
1641

    
1642
            }
1643
        }
1644
    }
1645

    
1646
    public static String getPreferredVocabulariesForDistributionEditor(boolean local) {
1647
        if (local){
1648

    
1649
            String pref = getStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(), local);
1650
            return pref;
1651
        }
1652
        else{
1653
            CdmPreference preference = null;
1654
            preference = getPreferenceFromDB(PreferencePredicate.AvailableDistributionAreaVocabularies);
1655
            if (preference == null){
1656
                return null;
1657
            } else{
1658
                return preference.getValue();
1659
            }
1660

    
1661
        }
1662
    }
1663

    
1664
    public static List<UUID> createUUIDListFromStringPref(String prefKey) {
1665
        String prefValue = PreferencesUtil.getStringValue(prefKey);
1666
        String[] stringArray = prefValue.split(";");
1667
        List<UUID> uuidList = new ArrayList();
1668
        for (String uuid: stringArray){
1669
            if (!StringUtils.isBlank(uuid)){
1670
                uuidList.add(UUID.fromString(uuid));
1671
            }
1672
        }
1673
        return uuidList;
1674
    }
1675

    
1676
    public static boolean getFilterCommonNameReferences(){
1677
        return getBooleanValue(PreferencesUtil.FILTER_COMMON_NAME_REFERENCES);
1678
    }
1679

    
1680
    public static void updateDBPreferences() {
1681

    
1682

    
1683
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1684
        cache.getAllTaxEditorDBPreferences();
1685

    
1686
        //ABCD Configurator
1687

    
1688
        updateAbcdImportConfigurationPreference();
1689

    
1690
        //Name Details
1691
        NameDetailsConfigurator config = getPreferredNameDetailsConfiguration(false);
1692
        //    if (config != null ){
1693
        //        if (!getBooleanValue(OVERRIDE_NAME_DETAILS) ||  !getBooleanValue(ALLOW_OVERRIDE_NAME_DETAILS)){
1694
        //            setPreferredNameDetailsConfiguration(config, false);
1695
        //        }
1696
        //    }
1697

    
1698
    }
1699

    
1700
    public static void setPreferencesToDB(List<CdmPreference> preferences) {
1701

    
1702
        ICdmRepository controller;
1703
        try{
1704
            if(CdmStore.isActive()){
1705
                controller = CdmStore.getCurrentApplicationConfiguration();
1706
                for (CdmPreference preference: preferences){
1707

    
1708
                    controller.getPreferenceService().set(preference);
1709

    
1710
                    CdmPreferenceCache.instance().put(preference);
1711
                }
1712
            }
1713
        }catch(Exception e){
1714
            e.printStackTrace();
1715
        }
1716
    }
1717

    
1718
    /**
1719
     * Returns whether the named preference is known.
1720
     * @param prefKey the key of the preference
1721
     * @return <code>true</code> if the preference is known, <code>false</code> otherwise
1722
     */
1723
    public static boolean contains(String prefKey){
1724
        return getPreferenceStore().contains(prefKey(prefKey));
1725
    }
1726

    
1727

    
1728

    
1729
}
(27-27/41)