Project

General

Profile

Download (65.1 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.equinox.internal.p2.ui.model.MetadataRepositoryElement;
31
import org.eclipse.jface.preference.IPreferenceStore;
32
import org.eclipse.jface.window.Window;
33
import org.eclipse.swt.widgets.Composite;
34
import org.eclipse.swt.widgets.Control;
35
import org.eclipse.swt.widgets.Shell;
36
import org.eclipse.ui.PlatformUI;
37

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

    
74
/**
75
 * <p>
76
 * PreferencesUtil class.
77
 * </p>
78
 *
79
 * @author p.ciardelli
80
 * @author n.hoffmann
81
 * @created 05.12.2008
82
 */
83
public class PreferencesUtil implements IPreferenceKeys {
84

    
85
	public static final String PREFERRED_TERMS_CHANGE = "preferred_terms";
86

    
87
	public static final String P2_REPOSITORIES_DELIM = ",";
88
	public static final String P2_REPOSITORY_FIELDS_DELIM = ";";
89

    
90
	private final static Logger logger = Logger.getLogger(PreferencesUtil.class);
91

    
92
	public static IPreferenceStore getPreferenceStore() {
93
		return TaxeditorStorePlugin.getDefault().getPreferenceStore();
94
	}
95

    
96
	private static String prefKey(String name) {
97
	    return name + "_"+  ((CdmRemoteSource)CdmStore.getActiveCdmSource()).toString();
98
	}
99

    
100
	public static String prefOverrideKey(String name) {
101
        return name + "_OVERRIDE_";
102
    }
103

    
104
    public static void setStringValue(String name, String value) {
105
        if (value != null){
106
            getPreferenceStore().setValue(prefKey(name), value);
107
        }else{
108
            getPreferenceStore().setToDefault(name);
109
        }
110
    }
111

    
112
    public static void setIntValue(String name, int value) {
113
        getPreferenceStore().setValue(prefKey(name), value);
114
    }
115

    
116
    public static void setBooleanValue(String name, boolean value) {
117
        getPreferenceStore().setValue(prefKey(name), value);
118
    }
119

    
120
    public static void setDoubleValue(String name, double value) {
121
        getPreferenceStore().setValue(prefKey(name), value);
122
    }
123

    
124
    public static void setFloatValue(String name, float value) {
125
        getPreferenceStore().setValue(prefKey(name), value);
126
    }
127

    
128
    public static void setLongValue(String name, long value) {
129
        getPreferenceStore().setValue(prefKey(name), value);
130
    }
131

    
132
    public static String getStringValue(String name, boolean local) {
133

    
134
        CdmPreference pref = getDBPreferenceValue(name);
135
        String prefValue = null;
136
        String overrideKey =  createPreferenceString(createOverridePreferenceString(name));
137
        boolean override = getPreferenceStore().getBoolean(overrideKey);
138

    
139
        if (local || pref == null || (pref != null && pref.isAllowOverride() && override)){
140
            String dbSpecific = prefKey(name);
141
            if (getPreferenceStore().contains(dbSpecific)){
142
                prefValue = getPreferenceStore().getString(dbSpecific);
143
            }else{
144
                prefValue = getPreferenceStore().
145
                        getString(name);
146
            }
147
       }else if (pref != null){
148
           prefValue = pref.getValue();
149
       }
150
        return prefValue;
151

    
152
    }
153

    
154
    public static String getStringValue(String name){
155
        return getStringValue(name, false);
156
    }
157

    
158
    private static CdmPreference getDBPreferenceValue(String name) {
159
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
160
        CdmPreference pref = null;
161
//
162
        pref = cache.get(name);
163
        if (pref == null ){
164
            //get default value for Predicate
165
            IPreferencePredicate pred = PreferencePredicate.getByKey(name);
166
            if (pred != null){
167
                if (pred.getDefaultValue() != null){
168
                    pref = CdmPreference.NewTaxEditorInstance(pred, pred.getDefaultValue().toString());
169
                }else{
170
                    pref = CdmPreference.NewTaxEditorInstance(pred, null);
171
                }
172
                pref.setAllowOverride(true);
173
            }
174
        }
175
        return pref;
176
    }
177

    
178
    public static int getIntValue(String name, boolean local) {
179
        CdmPreference pref= getDBPreferenceValue(name);
180
        String prefValue = null;
181
        if (pref != null){
182
            prefValue = pref.getValue();
183
        }
184
        Integer result = null;
185
        try{
186
            result = Integer.parseInt(prefValue);
187
        }catch(NumberFormatException e){
188
            logger.debug("Preference value of " + name + " is not a number");
189
        }
190

    
191
        String overrideKey =  createPreferenceString(createOverridePreferenceString(name));
192
        boolean override = true;
193
        if (getPreferenceStore().contains(overrideKey)){
194
            override = getPreferenceStore().getBoolean(overrideKey);
195
        }
196
        if (local || pref == null || (pref != null && pref.isAllowOverride() && override)){
197
            String dbSpecific = prefKey(name);
198
            if (getPreferenceStore().contains(dbSpecific)){
199
                result = getPreferenceStore().getInt(dbSpecific);
200
            }else{
201
                result =  getPreferenceStore().
202
                        getInt(name);
203
            }
204
        }
205
        return result;
206

    
207
    }
208

    
209
    public static boolean getBooleanValue(String name) {
210
        return getBooleanValue(name, false);
211
    }
212

    
213
    public static boolean getBooleanValue(String name, boolean local) {
214
        if (CdmStore.isActive()){
215
            CdmPreference pref = getDBPreferenceValue(name);
216

    
217
            String overrideKey =  createPreferenceString(createOverridePreferenceString(name));
218
            boolean override = getPreferenceStore().getBoolean(overrideKey);
219

    
220
            if (local || pref == null || (pref != null && pref.isAllowOverride() && override)){
221
                String dbSpecific = prefKey(name);
222
                return getPreferenceStore().getBoolean(dbSpecific);
223
             }else{
224
                return Boolean.valueOf(pref.getValue());
225
            }
226

    
227
        }else{
228
            return getPreferenceStore().getBoolean(name);
229
        }
230

    
231
    }
232

    
233
    public static double getDoubleValue(String name) {
234
        CdmPreference pref = getDBPreferenceValue(name);
235
        String prefValue = null;
236
        if (pref != null){
237
            prefValue = pref.getValue();
238
        }
239
        Double result = null;
240
        try{
241
            result = Double.parseDouble(prefValue);
242
        }catch(NumberFormatException e){
243
            logger.debug("Preference value of " + name + " is not a number");
244
        }
245
        if (result == null){
246
            String dbSpecific = prefKey(name);
247
            if (getPreferenceStore().contains(dbSpecific)){
248
                result = getPreferenceStore().getDouble(dbSpecific);
249
            }else{
250
                result =  getPreferenceStore().
251
                        getDouble(name);
252
            }
253
        }
254
        return result;
255

    
256
    }
257

    
258
    public static float getFloatValue(String name, boolean local) {
259
        CdmPreference pref = getDBPreferenceValue(name);
260
        String prefValue = null;
261
        if (pref != null){
262
            prefValue = pref.getValue();
263
        }
264
        Float result = null;
265
        try{
266
            result = Float.parseFloat(prefValue);
267
        }catch(NumberFormatException e){
268
            logger.debug("Preference value of " + name + " is not a number");
269
        }
270
        String overrideKey =  createPreferenceString(createOverridePreferenceString(name));
271
        boolean override = true;
272
        if (getPreferenceStore().contains(overrideKey)){
273
            override = getPreferenceStore().getBoolean(overrideKey);
274
        }
275
        if (local || pref == null || (pref != null && pref.isAllowOverride() && override)){
276
            String dbSpecific = prefKey(name);
277
            if (getPreferenceStore().contains(dbSpecific)){
278
                result = getPreferenceStore().getFloat(dbSpecific);
279
            }else{
280
                result =  getPreferenceStore().
281
                        getFloat(name);
282
            }
283
        }
284
        return result;
285

    
286
    }
287

    
288
    public static long getLongValue(String name) {
289
        CdmPreference pref = getDBPreferenceValue(name);
290
        String prefValue = null;
291
        if (pref != null){
292
            prefValue = pref.getValue();
293
        }
294
        Long result = null;
295
        try{
296
            result = Long.parseLong(prefValue);
297
        }catch(NumberFormatException e){
298
            logger.debug("Preference value of " + name + " is not a number");
299
        }
300
        if (result == null){
301
            String dbSpecific = prefKey(name);
302
            if (getPreferenceStore().contains(dbSpecific)){
303
                result = getPreferenceStore().getLong(dbSpecific);
304
            }else{
305
                result =  getPreferenceStore().
306
                        getLong(name);
307
            }
308
        }
309
        return result;
310
    }
311

    
312
	public static CdmPreference setPreferredNomenclaturalCode(
313
			String preferenceValue, boolean local) {
314
	    if (local){
315
	        setStringValue(PREFERRED_NOMENCLATURAL_CODE_KEY,
316
	                preferenceValue);
317
	    }
318
	    else{
319
    		ICdmRepository controller;
320
    		controller = CdmStore.getCurrentApplicationConfiguration();
321
    		if (controller == null){
322
                return null;
323
            }
324
    		PrefKey key = null;
325
    		try{
326
    		    key = CdmPreference.NewKey(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.NomenclaturalCode);
327
    		}catch (Exception e){
328
    		    System.out.println(e.getStackTrace());
329
    		}
330
    		CdmPreference preference = null;
331

    
332
    		if (preferenceValue == null){
333
    			preference = controller.getPreferenceService().find(key);
334
    			if (preference == null){
335
    				return null;
336
    			} else{
337
    			    setStringValue(PREFERRED_NOMENCLATURAL_CODE_KEY,
338
    				        preference.getValue());
339

    
340
    				return preference;
341
    			}
342
    		} else{
343
    			preference = CdmPreference.NewInstance(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.NomenclaturalCode, preferenceValue);
344
    			controller.getPreferenceService().set(preference);
345

    
346
    		}
347
	    }
348
        return null;
349

    
350

    
351

    
352
	}
353

    
354
    public static void setPreferredNomenclaturalCode(
355
        CdmPreference preference) {
356

    
357
        ICdmRepository controller;
358
        controller = CdmStore.getCurrentApplicationConfiguration();
359
        if (controller == null){
360
            return;
361
        }
362
        PrefKey key = null;
363
        try{
364
            key = CdmPreference.NewKey(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.NomenclaturalCode);
365
        }catch (Exception e){
366
            System.out.println(e.getStackTrace());
367
        }
368

    
369
        controller.getPreferenceService().set(preference);
370

    
371
    }
372

    
373
	public static NomenclaturalCode getPreferredNomenclaturalCode() {
374

    
375
		CdmPreference pref = getPreferenceFromDB(PreferencePredicate.NomenclaturalCode);
376

    
377

    
378
	    String preferredCode;
379
	    if(pref == null || (pref.isAllowOverride() && getBooleanValue(prefOverrideKey(PreferencePredicate.NomenclaturalCode.getKey())))){
380
	    	preferredCode = getStringValue(
381
	    	        PreferencePredicate.NomenclaturalCode.getKey(), true);
382

    
383
	    }else{
384
	    	preferredCode = pref.getValue();
385
	    }
386
	    if (StringUtils.isBlank(preferredCode)){
387
	        preferredCode = getPreferenceKey((NomenclaturalCode)PreferencePredicate.NomenclaturalCode.getDefaultValue());
388
	    }
389

    
390
	    return getPreferredNomenclaturalCode(preferredCode);
391

    
392
	}
393

    
394
    public static NomenclaturalCode getPreferredNomenclaturalCode(String preferenceKeyNomenclaturalCode) {
395

    
396
        for (NomenclaturalCode code : NomenclaturalCodeHelper.getAllCodes()) {
397
            if (getPreferenceKey(code).equals(preferenceKeyNomenclaturalCode)) {
398
                return code;
399
            }
400
        }
401
        return null;
402
    }
403

    
404
	public static boolean isShowTaxonAssociations(){
405
        boolean result = getBooleanValue(PreferencePredicate.ShowTaxonAssociations.getKey());
406
        return result;
407
    }
408

    
409
	public static boolean isShowLifeForm(){
410
	    boolean result =  getBooleanValue(PreferencePredicate.ShowLifeForm.getKey());
411
	    return result;
412
    }
413

    
414
	public static boolean isDeterminationOnlyForFieldUnits(){
415
	    boolean result =  getBooleanValue(PreferencePredicate.DeterminationOnlyForFieldUnits.getKey());
416
        return result;
417
    }
418

    
419
	public static boolean isCollectingAreaInGeneralSection(){
420
	    boolean result =  getBooleanValue(PreferencePredicate.ShowCollectingAreasInGeneralSection.getKey());
421
        return result;
422
	}
423

    
424
	public static CdmPreference getPreferenceFromDB(IPreferencePredicate predicate){
425
        ICdmRepository controller;
426
        CdmPreference pref = null;
427

    
428
        try{
429
            if(CdmStore.isActive()){
430
                controller = CdmStore.getCurrentApplicationConfiguration();
431
                PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), predicate);
432
                pref = controller.getPreferenceService().find(key);
433
            }
434
        }catch(Exception e){
435
            e.printStackTrace();
436
        }
437

    
438
        return pref;
439

    
440
    }
441

    
442
	public static List<CdmPreference> getPreferencesFromDB(IPreferencePredicate predicate){
443
        ICdmRepository controller;
444
        List<CdmPreference> prefs = null;
445

    
446
        try{
447
            if(CdmStore.isActive()){
448
                controller = CdmStore.getCurrentApplicationConfiguration();
449
                PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), predicate);
450
                prefs = controller.getPreferenceService().list(predicate);
451
            }
452
        }catch(Exception e){
453
            e.printStackTrace();
454
        }
455

    
456
        return prefs;
457

    
458
    }
459

    
460
	public static void setPreferencesToDB(CdmPreference preference, boolean setDefault){
461
        ICdmRepository controller;
462

    
463

    
464
        try{
465
            if(CdmStore.isActive()){
466
                controller = CdmStore.getCurrentApplicationConfiguration();
467

    
468
                if (setDefault){
469
                    controller.getPreferenceService().remove(preference.getKey());
470
                }else{
471
                    controller.getPreferenceService().set(preference);
472
                }
473
            }
474
        }catch(Exception e){
475
            e.printStackTrace();
476
        }
477

    
478

    
479

    
480
    }
481

    
482
	public static CdmPreference getPreferenceFromDB(PrefKey key){
483
        ICdmRepository controller;
484
        CdmPreference pref = null;
485

    
486
        try{
487
            if(CdmStore.isActive()){
488
                controller = CdmStore.getCurrentApplicationConfiguration();
489
                pref = controller.getPreferenceService().find(key);
490
            }
491
        }catch(Exception e){
492
            e.printStackTrace();
493
        }
494

    
495
        return pref;
496

    
497
    }
498

    
499
    public static void setPreferenceToDB(CdmPreference preference){
500
        ICdmRepository controller;
501
        try{
502
            if(CdmStore.isActive()){
503
                controller = CdmStore.getCurrentApplicationConfiguration();
504
                controller.getPreferenceService().set(preference);
505
                CdmPreferenceCache.instance().put(preference);
506
            }
507
        }catch(Exception e){
508
            e.printStackTrace();
509
        }
510

    
511
    }
512

    
513
	public static String getPreferredDefaultLangugae(){
514
	    String preferredLanguage = getStringValue(DEFAULT_LANGUAGE_EDITOR);
515
	    if(StringUtils.isNotEmpty(preferredLanguage) && StringUtils.isNotBlank(preferredLanguage)){
516
	        return preferredLanguage;
517
	    }
518
	    return null;
519
	}
520

    
521
	public static boolean isShowMediaPreview(){
522
        boolean isShowMediaPreview = getBooleanValue(SHOW_MEDIA_PREVIEW);
523
        return isShowMediaPreview;
524
    }
525

    
526
	/**
527
	 * Get the match strategy for the given class that was stored in preferences
528
	 * or the default strategy if it was not stored in preferences
529
	 *
530
	 * @param clazz
531
	 *            a {@link java.lang.Class} object.
532
	 * @return a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy} object.
533
	 */
534
	public static IMatchStrategy getMatchStrategy(Class<?> clazz) {
535
		String className = clazz.getName();
536
		if (getBooleanValue(MATCH_STRATEGY_PREFIX + className)) {
537
			IMatchStrategy matchStrategy = getDefaultMatchStrategy(clazz);
538

    
539
			//TODO CacheMatchers (or multiple field matchers in future) are missing here
540
			for (FieldMatcher fieldMatcher : matchStrategy.getMatching().getFieldMatchers(false)) {
541
				String fieldName = fieldMatcher.getPropertyName();
542
				String matchModeName = getStringValue(
543
						getMatchStrategyFieldName(className, fieldName));
544
				MatchMode matchMode = MatchMode.valueOf(matchModeName);
545
				try {
546
					matchStrategy.setMatchMode(fieldName, matchMode);
547
				} catch (MatchException e) {
548
					MessagingUtils.error(PreferencesUtil.class, e);
549
					throw new RuntimeException(e);
550
				}
551
			}
552

    
553
			return matchStrategy;
554
		}
555
		return getDefaultMatchStrategy(clazz);
556
	}
557

    
558
	/**
559
	 * Stores a matchStrategy into the preference store.
560
	 *
561
	 * @param matchStrategy
562
	 *            a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy}
563
	 *            object.
564
	 */
565
	public static void setMatchStrategy(IMatchStrategy matchStrategy) {
566
		String className = "ANY class"; //FIXME was: matchStrategy.getMatchClass().getName(); seems currently not in use
567
		setBooleanValue(MATCH_STRATEGY_PREFIX + className, true);
568

    
569
		List<FieldMatcher> fieldMatchers = matchStrategy.getMatching().getFieldMatchers(false);
570

    
571
		for (FieldMatcher fieldMatcher : fieldMatchers) {
572
			String fieldName = fieldMatcher.getPropertyName();
573
			setStringValue(
574
					getMatchStrategyFieldName(className, fieldName),
575
					fieldMatcher.getMatchMode().name());
576
		}
577
	}
578

    
579
	/**
580
	 * Helper method to create the preference property for a match field.
581
	 *
582
	 * @param className
583
	 * @param fieldName
584
	 * @return
585
	 */
586
	private static String getMatchStrategyFieldName(String className,
587
			String fieldName) {
588
		return MATCH_STRATEGY_PREFIX + className + "." + fieldName;
589
	}
590

    
591
	/**
592
	 * Returns the default match strategy for a given class.
593
	 *
594
	 * @param clazz
595
	 *            a {@link java.lang.Class} object.
596
	 * @return a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy} object.
597
	 */
598
	public static IMatchStrategy getDefaultMatchStrategy(Class clazz) {
599
		return DefaultMatchStrategy.NewInstance(clazz);
600
	}
601

    
602
	public static String getDateFormatPattern() {
603
		// TODO make this configurable in properties
604
		String pattern = "Y-M-d H:m";
605
		return pattern;
606
	}
607

    
608
	public static <T extends TermBase> void addTermToPreferredTerms(T term) {
609

    
610
		// VocabularyEnum vocabulary =
611
		// VocabularyEnum.getVocabularyEnum(term.getClass());
612
		//
613
		// getPreferenceStore().setValue(getPreferenceKey(term),
614
		// VocabularyStore.getTermVocabulary(vocabulary).getTerms().contains(term));
615
		//
616
		// firePreferencesChanged(term.getClass());
617
	}
618

    
619
	/**
620
	 * Construct a unique key using the CdmBase object's uuid
621
	 *
622
	 * @param cdmBase
623
	 * @return
624
	 */
625
	private static String getPreferenceKey(ICdmBase cdmBase) {
626
		cdmBase = HibernateProxyHelper.deproxy(cdmBase);
627

    
628
		String key = cdmBase.getClass().getName().concat(".")
629
				.concat(cdmBase.getUuid().toString());
630
		if (key.contains("javassist")) {
631
			MessagingUtils.info("proxy");
632
		}
633
		return key;
634
	}
635

    
636
	/**
637
	 * Construct a unique key using the CdmBase object's uuid
638
	 *
639
	 * @param cdmBase
640
	 * @return
641
	 */
642
	public static String getPreferenceKey(ISimpleTerm simpleTerm) {
643
		simpleTerm = HibernateProxyHelper.deproxy(simpleTerm);
644
		String key = simpleTerm.getClass().getName().concat(".")
645
				.concat(simpleTerm.getUuid().toString());
646
		if (key.contains("javassist")) {
647
			MessagingUtils.warn(PreferencesUtil.class,
648
					"Trying to persist a preference based on a proxy class.");
649
		}
650
		return key;
651
	}
652

    
653

    
654

    
655
	/**
656
	 * Construct a unique key using the CdmBase object's uuid
657
	 *
658
	 * @param cdmBase
659
	 * @return
660
	 */
661
	public static String getPreferenceKey(IDefinedTerm definedTerm) {
662
		definedTerm = HibernateProxyHelper.deproxy(definedTerm);
663
		String key = definedTerm.getClass().getName().concat(".")
664
				.concat(definedTerm.getUuid().toString());
665
		if (key.contains("javassist")) {
666
			MessagingUtils.warn(PreferencesUtil.class,
667
					"Trying to persist a preference based on a proxy class.");
668
		}
669
		return key;
670
	}
671

    
672
	/**
673
	 * Retrieves search preferences from the preference store
674
	 *
675
	 * @return an {@link ITaxonServiceConfigurator} to pass to search methods
676
	 */
677
	public static IFindTaxaAndNamesConfigurator getSearchConfigurator() {
678
		IFindTaxaAndNamesConfigurator configurator = initializeSearchConfigurator();
679

    
680
		configurator.setDoTaxa(getBooleanValue(
681
				TAXON_SERVICE_CONFIGURATOR_TAXA));
682
		configurator.setDoSynonyms(getBooleanValue(
683
				TAXON_SERVICE_CONFIGURATOR_SYNONYMS));
684
		configurator.setDoNamesWithoutTaxa(getBooleanValue(
685
				TAXON_SERVICE_CONFIGURATOR_NAMES));
686
		configurator.setDoTaxaByCommonNames(getBooleanValue(
687
				TAXON_SERVICE_CONFIGURATOR_COMMON_NAMES));
688
		//configurator.setMatchMode(eu.etaxonomy.cdm.persistence.query.MatchMode.valueOf(getStringValue(TAXON_SERVICE_CONFIGURATOR_MATCH_MODE)));
689

    
690
		return configurator;
691
	}
692

    
693
	/**
694
	 * create new preferences, setting all search options to true
695
	 *
696
	 * @return a
697
	 *         {@link eu.etaxonomy.cdm.api.service.config.ITaxonServiceConfigurator}
698
	 *         object.
699
	 */
700
	public static IFindTaxaAndNamesConfigurator initializeSearchConfigurator() {
701
		IFindTaxaAndNamesConfigurator configurator = FindTaxaAndNamesConfiguratorImpl.NewInstance();
702

    
703
		configurator.setDoTaxa(true);
704
		configurator.setDoSynonyms(true);
705
		configurator.setDoNamesWithoutTaxa(true);
706
		configurator.setDoTaxaByCommonNames(true);
707

    
708
		configurator.setTaxonPropertyPath(Arrays.asList("$", "titleCache",
709
				"name", "name.$", "relationsFromThisTaxon.$"));
710

    
711
		configurator.setSynonymPropertyPath(Arrays.asList("$", "titleCache",
712
				"name", "name.$", "synonyms.relatedTo.*"));
713

    
714
		// DEFAULT VALUES
715
		// match mode is a simple like, actually all other match modes are kind
716
		// of bogus
717
		configurator
718
				.setMatchMode(eu.etaxonomy.cdm.persistence.query.MatchMode.ANYWHERE);
719
		// we set page number and size here as this should always be unlimited
720
		configurator.setPageNumber(0);
721
		// TODO currently limit results to 10000
722
		configurator.setPageSize(10000);
723
		//setSearchConfigurator(configurator) ;
724
		return configurator;
725
	}
726

    
727
	/**
728
	 * Store search preferences
729
	 *
730
	 * @param configurator
731
	 *            a
732
	 *            {@link eu.etaxonomy.cdm.api.service.config.ITaxonServiceConfigurator}
733
	 *            object.
734
	 */
735
	public static void setSearchConfigurator(
736
			IFindTaxaAndNamesConfigurator configurator) {
737
		getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_TAXA,
738
				configurator.isDoTaxa());
739
		getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_SYNONYMS,
740
				configurator.isDoSynonyms());
741
		getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_NAMES,
742
				configurator.isDoNamesWithoutTaxa());
743
		getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_COMMON_NAMES,
744
				configurator.isDoTaxaByCommonNames());
745
	}
746

    
747
	public static void firePreferencesChanged(Class clazz) {
748
		getPreferenceStore().firePropertyChangeEvent(PREFERRED_TERMS_CHANGE,
749
				null, clazz);
750
	}
751

    
752
	public static String createPreferenceString(String property){
753
	   return prefKey(property);
754

    
755
	}
756
	public static String createOverridePreferenceString(String property){
757
	       return prefOverrideKey(property);
758

    
759
	    }
760

    
761
	/**
762
	 * Set default values for preferences
763
	 */
764
	public static void setDefaults() {
765
		getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_TAXA, true);
766
		getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_SYNONYMS,
767
				true);
768
		getPreferenceStore().setDefault(createPreferenceString(EDIT_MAP_SERVICE_ACCES_POINT),
769
				"http://edit.africamuseum.be/edit_wp5/v1.2/rest_gen.php");
770
		//FIXME : changed default for SHOULD_CONNECT_AT_STARTUP to false (ticket 3828) until resolution
771
		getPreferenceStore().setDefault(createPreferenceString(SHOULD_CONNECT_AT_STARTUP), false);
772
		getPreferenceStore().setDefault(createPreferenceString(OPENURL_ACCESS_POINT),
773
				"http://www.biodiversitylibrary.org/openurl");
774
		getPreferenceStore().setDefault(createPreferenceString(OPENURL_IMAGE_MAX_WIDTH), "1000");
775
		getPreferenceStore().setDefault(createPreferenceString(OPENURL_IMAGE_MAX_HEIGHT), "1000");
776
		getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_TAXA, true);
777
		getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_SYNONYMS, true);
778
		getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_NAMES, true);
779
		getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_COMMON_NAMES, true);
780

    
781
		//Distribution Editor:
782
//		getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.DistributionEditorActivated.getKey()), Boolean.valueOf(PreferencePredicate.DistributionEditorActivated.getDefaultValue().toString()));
783
//		getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey()), PreferencePredicate.DisplayOfAreasInDistributionEditor.getDefaultValue().toString());
784
//		getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.DisplayOfStatus.getKey()), PreferencePredicate.DisplayOfStatus.getDefaultValue().toString());
785

    
786

    
787
		//Name Details
788
		getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.NameDetailsView.getKey()), new NameDetailsConfigurator(false).toString());
789

    
790
		//Navigator preferences
791
		getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.TaxonNodeOrder.getKey()), NavigatorOrderEnum.RankAndNameOrder.getKey());
792

    
793
		//getPreferenceStore().setDefault(createPreferenceString(Prefe), true);
794

    
795
		getPreferenceStore().setDefault(createPreferenceString(SHOW_ADVANCED_MEDIA_SECTION), false);
796

    
797
        getPreferenceStore().setDefault(createPreferenceString(SHOW_MEDIA_PREVIEW), false);
798
		//override db preferences
799
		getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.AbcdImportConfig.getKey())), false);
800
		getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.ShowSpecimen.getKey())), true);
801
		getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.NameDetailsView.getKey())), false);
802
		getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.DistributionEditorActivated.getKey())), true);
803
		getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.AvailableDistributionStatus.getKey())), true);
804
		getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.AvailableDistributionAreaTerms.getKey())), true);
805
		getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey())), true);
806
		getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.CommonNameAreaVocabularies.getKey())), false);
807
		getPreferenceStore().setDefault(createPreferenceString(FILTER_COMMON_NAME_REFERENCES), false);
808
		getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowTaxonNodeWizard.getKey()), Boolean.valueOf(PreferencePredicate.ShowTaxonNodeWizard.getDefaultValue().toString()));
809
		getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowNamespaceInSource.getKey()), Boolean.valueOf(PreferencePredicate.ShowNamespaceInSource.getDefaultValue().toString()));
810
		getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowIdInSource.getKey()), Boolean.valueOf(PreferencePredicate.ShowIdInSource.getDefaultValue().toString()));
811
		getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.DisableMultiClassification.getKey()), Boolean.valueOf(PreferencePredicate.DisableMultiClassification.getDefaultValue().toString()));
812
		getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowImportExportMenu.getKey()), Boolean.valueOf(PreferencePredicate.ShowImportExportMenu.getDefaultValue().toString()));
813
		getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowSpecimen.getKey()), Boolean.valueOf(PreferencePredicate.ShowSpecimen.getDefaultValue().toString()));
814

    
815
	}
816

    
817
	public static void checkNomenclaturalCode() {
818
		// First time Editor is opened, no nomenclatural code has been set
819
		if (PreferencesUtil.getPreferredNomenclaturalCode() == null) {
820
			PreferencesUtil.setPreferredNomenclaturalCode(getPreferenceKey(NomenclaturalCode.ICNAFP), true);
821
		}
822

    
823

    
824

    
825
	}
826
	public static void setNomenclaturalCodePreferences(){
827
	    ICdmRepository controller;
828
        controller = CdmStore.getCurrentApplicationConfiguration();
829
        PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.NomenclaturalCode);
830
        CdmPreference preference = null;
831
        if (controller == null){
832
            return ;
833
        }
834
        preference = controller.getPreferenceService().find(key);
835
        if (preference == null){
836
            return;
837
        }
838
//        setBooleanValue(ALLOW_OVERRIDE_NOMENCLATURAL_CODE_KEY, preference.isAllowOverride());
839

    
840
        int index = StringUtils.lastIndexOf(preference.getValue(), ".");
841
        UUID uuid = UUID.fromString(preference.getValue().substring(index +1, preference.getValue().length()));
842
        NomenclaturalCode preferredCode = NomenclaturalCode.getByUuid(uuid);
843

    
844
        setStringValue(PREFERRED_NOMENCLATURAL_CODE_KEY,
845
                getPreferenceKey(preferredCode));
846

    
847
	}
848

    
849
	public static void checkDefaultLanguage(){
850
	    if(PreferencesUtil.getPreferredDefaultLangugae() == null){
851
	       Shell shell = AbstractUtility.getShell();
852
	       int open = new DefaultLanguageDialog(shell).open();
853
	       if(open == Window.OK){
854
	           PlatformUI.getWorkbench().restart();
855
	       }
856
	    }else{
857
	        //TODO:In case of a reinstall, the config.ini will be overwritten
858
	        //     here you create config.ini with the stored key from preferences
859
	    }
860
	}
861

    
862
	public static String getMapServiceAccessPoint() {
863
		return getStringValue(EDIT_MAP_SERVICE_ACCES_POINT);
864
	}
865

    
866
	public static boolean shouldConnectAtStartUp() {
867
		//FIXME :  force SHOULD_CONNECT_AT_STARTUP to false (ticket 3828) until resolution
868
		//return getBooleanValue(SHOULD_CONNECT_AT_STARTUP);
869
		return false;
870
	}
871

    
872
	public static FeatureTree getDefaultFeatureTreeForTextualDescription() {
873
		String uuidString = getStringValue(
874
				FEATURE_TREE_DEFAULT_TEXT);
875
		if (StringUtils.isBlank(uuidString)) {
876
            return null;
877
        }
878
		FeatureTree tree = CdmStore.getService(
879
	                IFeatureTreeService.class).load(UUID.fromString(uuidString));
880
		if (tree.getId() == 0) {
881
            return null;
882
        }
883
		return tree;
884
	}
885

    
886
	public static FeatureTree getDefaultFeatureTreeForStructuredDescription() {
887
		String uuidString = getStringValue(
888
				FEATURE_TREE_DEFAULT_STRUCTURE);
889
		return CdmUtils.isEmpty(uuidString) ? null : CdmStore.getService(
890
				IFeatureTreeService.class).load(UUID.fromString(uuidString));
891
	}
892

    
893
	public static void setSortRanksHierarchichally(boolean selection) {
894
		setBooleanValue(SORT_RANKS_HIERARCHICHALLY, selection);
895
	}
896

    
897
	public static boolean getSortRanksHierarchichally() {
898
		return getBooleanValue(SORT_RANKS_HIERARCHICHALLY);
899
	}
900

    
901
	public static boolean isMultilanguageTextEditingCapability() {
902
		return getBooleanValue(
903
				MULTILANGUAGE_TEXT_EDITING_CAPABILITY);
904
	}
905

    
906
	public static Language getGlobalLanguage() {
907

    
908

    
909
		String languageUuidString = getStringValue(
910
				GLOBAL_LANGUAGE_UUID);
911

    
912
		if(!CdmStore.isActive()) {
913
            MessagingUtils.noDataSourceWarningDialog(languageUuidString);
914
            return null;
915
        }
916

    
917
		if (CdmUtils.isBlank(languageUuidString)) {
918
			return Language.getDefaultLanguage();
919
		}
920

    
921
		UUID languageUuid = UUID.fromString(languageUuidString);
922
		return (Language) CdmStore.getService(ITermService.class).load(
923
				languageUuid);
924
	}
925

    
926
	public static void setGlobalLanguage(Language language) {
927
	    if(language != null) {
928
	        setStringValue(GLOBAL_LANGUAGE_UUID,language.getUuid().toString());
929
	        CdmStore.setDefaultLanguage(language);
930
	    }
931

    
932
	}
933

    
934
	public static Map<MarkerType, Boolean> getEditMarkerTypePreferences() {
935
		List<MarkerType> markerTypes = CdmStore.getTermManager()
936
				.getPreferredTerms(MarkerType.class);
937

    
938
		Map<MarkerType, Boolean> result = new HashMap<MarkerType, Boolean>();
939

    
940
		for (MarkerType markerType : markerTypes) {
941
			String name = getMarkerTypeEditingPreferenceKey(markerType);
942
			Boolean value = getBooleanValue(name);
943

    
944
			result.put(markerType, value);
945
		}
946

    
947
		return result;
948
	}
949

    
950
	public static void setEditMarkerTypePreferences(
951
			Map<MarkerType, Boolean> markerTypeEditingMap) {
952
		for (MarkerType markerType : markerTypeEditingMap.keySet()) {
953
			String name = getMarkerTypeEditingPreferenceKey(markerType);
954
			setBooleanValue(name,
955
					markerTypeEditingMap.get(markerType));
956
		}
957

    
958
	}
959

    
960
	private static String getMarkerTypeEditingPreferenceKey(
961
			MarkerType markerType) {
962
		markerType = HibernateProxyHelper.deproxy(markerType);
963
		return markerType.getClass().getName() + EDIT_MARKER_TYPE_PREFIX;
964
	}
965

    
966
	public static void setEditMarkerTypePreference(MarkerType markerType,
967
			boolean edit) {
968
		setBooleanValue(
969
				getMarkerTypeEditingPreferenceKey(markerType), edit);
970
	}
971

    
972
	public static DerivedUnitFacadeConfigurator getDerivedUnitConfigurator() {
973
		DerivedUnitFacadeConfigurator configurator = DerivedUnitFacadeConfigurator
974
				.NewInstance();
975
		configurator.setMoveDerivedUnitMediaToGallery(true);
976
		configurator.setMoveFieldObjectMediaToGallery(true);
977
		return configurator;
978
	}
979

    
980
	/**
981
	 * This method will write language properties to the config.ini located in the configuration folder
982
	 * of the Taxonomic Ediitor. <b>This method is only used to set the default language for Taxonomic Editor.</b>
983
	 *
984
	 * @param setLanguage 0 is for german and 1 for english.
985
	 * @throws IOException
986
	 */
987
    public void writePropertyToConfigFile(int setLanguage) throws IOException {
988
        File file = org.eclipse.core.runtime.preferences.ConfigurationScope.INSTANCE.getLocation().toFile();
989
        //give warning to user if the directory has no write access
990
        if(file == null){
991
            throw new IOException();
992
        }
993
        Properties properties = load(file.getAbsolutePath()+"/config.ini");
994
        switch(setLanguage){
995
        case 0:
996
            properties.setProperty("osgi.nl", "de");
997
            setStringValue(IPreferenceKeys.DEFAULT_LANGUAGE_EDITOR, "de");
998
            break;
999
        case 1:
1000
            properties.setProperty("osgi.nl", "en");
1001
            setStringValue(IPreferenceKeys.DEFAULT_LANGUAGE_EDITOR, "en");
1002
            break;
1003
        default:
1004
            break;
1005
        }
1006
        save(file+"/config.ini", properties);
1007
    }
1008

    
1009
    /**
1010
     * This method loads a property from a given file and returns it.
1011
     *
1012
     * @param filename
1013
     * @return
1014
     * @throws IOException
1015
     */
1016
    private Properties load(String filename) throws IOException {
1017
        FileInputStream in = new FileInputStream(filename);
1018
        Properties prop = new Properties();
1019
        prop.load(in);
1020
        in.close();
1021
        return prop;
1022
    }
1023

    
1024
    /**
1025
     * This method saves a property to the specified file.
1026
     *
1027
     * @param filename
1028
     * @param properties
1029
     * @throws IOException
1030
     */
1031
    private void save(String filename, Properties properties) throws IOException{
1032
        FileOutputStream fos =  new FileOutputStream(filename);
1033
        properties.store(fos, "");
1034
        fos.close();
1035
    }
1036

    
1037
    /**
1038
     * Saves a list of P2 Metadata Repositories as string with specified delimiters
1039
     *
1040
     * @param p2Repos
1041
     */
1042
    public static void setP2Repositories(List<MetadataRepositoryElement> p2Repos) {
1043
        StringBuilder sb = new StringBuilder();
1044
        for(MetadataRepositoryElement p2Repo : p2Repos) {
1045
            sb.append(P2_REPOSITORIES_DELIM);
1046
            if(p2Repo.getName() == null || p2Repo.getName().isEmpty()) {
1047
                sb.append("-");
1048
            } else {
1049
                sb.append(p2Repo.getName());
1050
            }
1051
            sb.append(P2_REPOSITORY_FIELDS_DELIM);
1052
            sb.append(p2Repo.getLocation().toString());
1053
            sb.append(P2_REPOSITORY_FIELDS_DELIM);
1054
            sb.append(String.valueOf(p2Repo.isEnabled()));
1055
        }
1056
        getPreferenceStore().setValue(P2_REPOSITORY_LIST, sb.toString());
1057
    }
1058

    
1059

    
1060
    /**
1061
     * Retrieves a list of previously saved P2 repositories
1062
     *
1063
     * @return
1064
     */
1065
    public static List<MetadataRepositoryElement> getP2Repositories() {
1066
        List<MetadataRepositoryElement> p2Repos = new ArrayList<MetadataRepositoryElement>();
1067
        String p2ReposPref =  getStringValue(P2_REPOSITORY_LIST);
1068
        if(p2ReposPref != null && !p2ReposPref.isEmpty()) {
1069
            StringTokenizer p2ReposPrefST = new StringTokenizer(p2ReposPref,P2_REPOSITORIES_DELIM);
1070

    
1071
            while(p2ReposPrefST.hasMoreTokens()) {
1072
                String p2RepoStr = p2ReposPrefST.nextToken();
1073
                StringTokenizer p2ReposStrST = new StringTokenizer(p2RepoStr,P2_REPOSITORY_FIELDS_DELIM);
1074
                if(p2ReposStrST.countTokens()==3) {
1075
                    String nickname = p2ReposStrST.nextToken();
1076
                    URI uri = null;
1077
                    try {
1078
                        uri = new URI(p2ReposStrST.nextToken());
1079
                    } catch (URISyntaxException e) {
1080
                        continue;
1081
                    }
1082
                    boolean enabled = Boolean.parseBoolean(p2ReposStrST.nextToken());
1083
                    MetadataRepositoryElement mre = new MetadataRepositoryElement(null, uri, true);
1084
                    mre.setNickname(nickname);
1085
                    mre.setEnabled(enabled);
1086
                    p2Repos.add(mre);
1087
                }
1088
            }
1089
        }
1090

    
1091
        return p2Repos;
1092
    }
1093

    
1094
    /**
1095
     * enables/disables nested composite. <br>
1096
     *
1097
     * @param ctrl - Composite to be en-/disabeld
1098
     * @param enabled - boolean
1099
     */
1100
    public static void recursiveSetEnabled(Control ctrl, boolean enabled) {
1101
        if (ctrl instanceof Composite) {
1102
            Composite comp = (Composite) ctrl;
1103
            for (Control c : comp.getChildren()) {
1104
                recursiveSetEnabled(c, enabled);
1105
            }
1106
        } else {
1107
            ctrl.setEnabled(enabled);
1108
        }
1109
    }
1110

    
1111
    public static void setSortNodes(NavigatorOrderEnum nodesOrder) {
1112
        setStringValue(PreferencePredicate.TaxonNodeOrder.getKey(), nodesOrder.key);
1113

    
1114
    }
1115

    
1116
    public static NavigatorOrderEnum getSortNodes() {
1117
        return NavigatorOrderEnum.valueOf(getStringValue(PreferencePredicate.TaxonNodeOrder.getKey()));
1118

    
1119
    }
1120

    
1121
    public static boolean isNodesSortedNaturally() {
1122
        NavigatorOrderEnum value = NavigatorOrderEnum.valueOf(getStringValue(PreferencePredicate.TaxonNodeOrder.getKey()));
1123
        return value.equals(NavigatorOrderEnum.NaturalOrder);
1124

    
1125
    }
1126

    
1127
    public static boolean isNodesSortedByName() {
1128
        NavigatorOrderEnum value = NavigatorOrderEnum.valueOf(getStringValue(PreferencePredicate.TaxonNodeOrder.getKey()));
1129
        return value.equals(NavigatorOrderEnum.AlphabeticalOrder);
1130

    
1131
    }
1132

    
1133
    public static boolean isNodesSortedByNameAndRank() {
1134
        NavigatorOrderEnum value = NavigatorOrderEnum.valueOf(getStringValue(PreferencePredicate.TaxonNodeOrder.getKey()));
1135
        return value.equals(NavigatorOrderEnum.RankAndNameOrder);
1136

    
1137
    }
1138

    
1139
    public static boolean isStoreNavigatorState() {
1140
		return getBooleanValue(RESTORE_NAVIGATOR_STATE);
1141

    
1142
	}
1143

    
1144
	public static void setStoreNavigatorState(boolean selection) {
1145
		setBooleanValue(RESTORE_NAVIGATOR_STATE, selection);
1146

    
1147
	}
1148

    
1149
    public static boolean isShowUpWidgetIsDisposedMessages() {
1150
       return getBooleanValue(IS_SHOW_UP_WIDGET_IS_DISPOSED);
1151
    }
1152
    public static void setShowUpWidgetIsDisposedMessages(boolean selection) {
1153
        setBooleanValue(IS_SHOW_UP_WIDGET_IS_DISPOSED, selection);
1154
    }
1155

    
1156
    public static boolean isShowIdInVocabularyInChecklistEditor() {
1157
        String area_display = getStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey());
1158
        if (area_display.equals(TermDisplayEnum.IdInVocabulary.getKey())) {
1159
            return true;
1160
        }else{
1161
            return false;
1162
        }
1163
    }
1164
    public static boolean isShowSymbol1InChecklistEditor() {
1165
        String area_display = getStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey());
1166
        if (area_display.equals(TermDisplayEnum.Symbol1.getKey())) {
1167
            return true;
1168
        }else{
1169
            return false;
1170
        }
1171
     }
1172
    public static boolean isShowSymbol2InChecklistEditor() {
1173
        String area_display = getStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey());
1174
        if (area_display.equals(TermDisplayEnum.Symbol2.getKey())) {
1175
            return true;
1176
        }else{
1177
            return false;
1178
        }
1179
     }
1180
    public static void setAreaDisplayInChecklistEditor(String selection) {
1181
        setStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey(), selection);
1182
    }
1183

    
1184
    public static void setOwnDescriptionForChecklistEditor(boolean selection) {
1185
        setBooleanValue(PreferencePredicate.OwnDescriptionForDistributionEditor.getKey(), selection);
1186
    }
1187

    
1188
    public static boolean isOwnDescriptionForChecklistEditor() {
1189
        return getBooleanValue(PreferencePredicate.OwnDescriptionForDistributionEditor.getKey());
1190
    }
1191

    
1192
    public static String displayAreaInChecklistEditor() {
1193
        String result = getStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey());
1194
        if (StringUtils.isBlank(result)){
1195
            return ((TermDisplayEnum) PreferencePredicate.DisplayOfAreasInDistributionEditor.getDefaultValue()).getKey();
1196
        }
1197
       return result;
1198
    }
1199

    
1200
    public static String displayStatusInChecklistEditor() {
1201
        String result = getStringValue(PreferencePredicate.DisplayOfStatus.getKey());
1202
        if (StringUtils.isBlank(result)){
1203
            return((TermDisplayEnum) PreferencePredicate.DisplayOfStatus.getDefaultValue()).getKey();
1204
        }
1205
       return result;
1206
    }
1207
    public static void setDisplayStatusInChecklistEditor(String selection) {
1208
        setStringValue(PreferencePredicate.DisplayOfStatus.getKey(), selection);
1209

    
1210
    }
1211

    
1212
    public static boolean isShowRankInChecklistEditor() {
1213
        return getBooleanValue(PreferencePredicate.ShowRankInDistributionEditor.getKey());
1214
    }
1215
    public static void setShowRankInChecklistEditor(boolean selection) {
1216
       setBooleanValue(PreferencePredicate.ShowRankInDistributionEditor.getKey(), selection);
1217
    }
1218

    
1219
    public static NameDetailsConfigurator getPreferredNameDetailsConfiguration( boolean local) {
1220
        NameDetailsConfigurator config = new NameDetailsConfigurator(true);
1221
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1222
        CdmPreference preference = null;
1223
        String value;
1224
        if (!local) {
1225
            PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.NameDetailsView);
1226
            preference = cache.findBestMatching(key);
1227
            if (preference == null){
1228
                return null;
1229
            }
1230

    
1231
        //    setBooleanValue(ALLOW_OVERRIDE_NAME_DETAILS, preference.isAllowOverride());
1232
            value = preference.getValue();
1233
            config.setAllowOverride(preference.isAllowOverride());
1234
            //the preference value is build like this:
1235
            //<section1>:true;<section2>:false....
1236
        }else{
1237
            value = getStringValue(PreferencePredicate.NameDetailsView.getKey(), local);
1238
        }
1239
        if (value!= null){
1240
            String [] sections = value.split(";");
1241
            Map<String, Boolean> sectionMap = new HashMap<String, Boolean>();
1242
            String[] sectionValues;
1243
            for (String sectionValue: sections){
1244
                sectionValues = sectionValue.split(":");
1245
                sectionMap.put(sectionValues[0], Boolean.valueOf(sectionValues[1]));
1246
            }
1247
            config.setSimpleDetailsViewActivated(getValue(sectionMap, "simpleViewActivated"));
1248
            config.setTaxonSectionActivated(getValue(sectionMap, "taxon"));
1249
            config.setSecDetailsActivated(getValue(sectionMap, "taxon.SecDetails"));
1250
            config.setSecEnabled(getValue(sectionMap, "taxon.SecEnabled"));
1251
            config.setLSIDActivated(getValue(sectionMap, "lsid"));
1252
            config.setNomenclaturalCodeActived(getValue(sectionMap, "nc"));
1253
            config.setAppendedPhraseActivated(getValue(sectionMap, "ap"));
1254
            config.setRankActivated(getValue(sectionMap, "rank"));
1255
            config.setAtomisedEpithetsActivated(getValue(sectionMap, "atomisedEpithets"));
1256
            config.setAuthorshipSectionActivated(getValue(sectionMap,"author"));
1257
            config.setNomenclaturalReferenceSectionActivated(sectionMap.get("nomRef"));
1258
            config.setNomenclaturalStatusSectionActivated(getValue(sectionMap, "nomStat"));
1259
            config.setProtologueActivated(getValue(sectionMap,"protologue"));
1260
            config.setTypeDesignationSectionActivated(getValue(sectionMap,"typeDes"));
1261
            config.setNameRelationsSectionActivated(getValue(sectionMap,"nameRelation"));
1262
            config.setHybridActivated(getValue(sectionMap,"hybrid"));
1263
        }
1264
        return config;
1265
    }
1266

    
1267
    public static NameDetailsConfigurator getPreferredNameDetailsConfiguration() {
1268
        NameDetailsConfigurator config = new NameDetailsConfigurator(true);
1269

    
1270
        String value;
1271

    
1272
        value = getStringValue(PreferencePredicate.NameDetailsView.getKey(), false);
1273
        if (value != null){
1274
            String [] sections = value.split(";");
1275
            Map<String, Boolean> sectionMap = new HashMap<String, Boolean>();
1276
            String[] sectionValues;
1277
            for (String sectionValue: sections){
1278
                sectionValues = sectionValue.split(":");
1279
                sectionMap.put(sectionValues[0], Boolean.valueOf(sectionValues[1]));
1280
            }
1281

    
1282
            config.setSimpleDetailsViewActivated(getValue(sectionMap, "simpleViewActivated"));
1283

    
1284
            config.setTaxonSectionActivated(getValue(sectionMap, "taxon"));
1285

    
1286
            config.setSecDetailsActivated(getValue(sectionMap, "taxon.SecDetails"));
1287
            config.setSecEnabled(getValue(sectionMap, "taxon.SecEnabled"));
1288

    
1289
            config.setLSIDActivated(getValue(sectionMap, "lsid"));
1290

    
1291
            config.setNomenclaturalCodeActived(getValue(sectionMap, "nc"));
1292

    
1293
            config.setAppendedPhraseActivated(getValue(sectionMap, "ap"));
1294

    
1295
            config.setRankActivated(getValue(sectionMap, "rank"));
1296

    
1297
            config.setAtomisedEpithetsActivated(getValue(sectionMap, "atomisedEpithets"));
1298

    
1299
            config.setAuthorshipSectionActivated(getValue(sectionMap,"author"));
1300

    
1301
            config.setNomenclaturalReferenceSectionActivated(sectionMap.get("nomRef"));
1302

    
1303
            config.setNomenclaturalStatusSectionActivated(getValue(sectionMap, "nomStat"));
1304

    
1305
            config.setProtologueActivated(getValue(sectionMap,"protologue"));
1306

    
1307
            config.setTypeDesignationSectionActivated(getValue(sectionMap,"typeDes"));
1308

    
1309
            config.setNameRelationsSectionActivated(getValue(sectionMap,"nameRelation"));
1310

    
1311
                config.setHybridActivated(getValue(sectionMap,"hybrid"));
1312
        }
1313
        return config;
1314
    }
1315

    
1316
    public static void setPreferredNameDetailsConfiguration(NameDetailsConfigurator config, boolean local) {
1317
        CdmPreference preference = null;
1318

    
1319
        if (!local) {
1320
            preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.NameDetailsView, config.toString());
1321

    
1322
            setPreferenceToDB(preference);
1323
        }
1324
        else{
1325
            setStringValue(PreferencePredicate.NameDetailsView.getKey(), config.toString());
1326
        }
1327

    
1328

    
1329
    }
1330

    
1331
    private static Boolean getValue(Map<String, Boolean> sectionMap, String string) {
1332
		if (sectionMap.containsKey(string)){
1333
			return sectionMap.get(string);
1334
		}else{
1335
			return true;
1336
		}
1337

    
1338
	}
1339

    
1340
    public static Abcd206ImportConfigurator getDBAbcdImportConfigurationPreference() {
1341

    
1342
        Abcd206ImportConfigurator config = Abcd206ImportConfigurator.NewInstance(null,null);
1343
        ICdmRepository controller;
1344
        controller = CdmStore.getCurrentApplicationConfiguration();
1345
        PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AbcdImportConfig);
1346
        CdmPreference preference = null;
1347
        if (controller == null){
1348
            return null;
1349
        }
1350
        preference = controller.getPreferenceService().find(key);
1351
        if (preference == null){
1352
            return config;
1353
         } else{
1354
             String configString = preference.getValue();
1355
             String[] configArray = configString.split(";");
1356

    
1357
             for (String configItem: configArray){
1358
                 String[] keyValue = configItem.split(":");
1359
                 String keyString = keyValue[0];
1360
                 String valueString = null;
1361
                 if (keyValue.length>1){
1362
                      valueString = keyValue[1];
1363
                 }
1364
                 if (keyString.equals("ignoreImportOfExistingSpecimen")){
1365
                     config.setIgnoreImportOfExistingSpecimen(Boolean.valueOf(valueString));
1366
                 }else if (keyString.equals("addIndividualsAssociationsSuchAsSpecimenAndObservations")){
1367
                     config.setAddIndividualsAssociationsSuchAsSpecimenAndObservations(Boolean.valueOf(valueString));
1368
                 }else if (keyString.equals("reuseExistingTaxaWhenPossible")){
1369
                     config.setReuseExistingTaxaWhenPossible(Boolean.valueOf(valueString));
1370
                 }else if (keyString.equals("ignoreAuthorship")){
1371
                     config.setIgnoreAuthorship(Boolean.valueOf(valueString));
1372
                 }else if (keyString.equals("addMediaAsMediaSpecimen")){
1373
                     config.setAddMediaAsMediaSpecimen(Boolean.valueOf(valueString));
1374
                 }else if (keyString.equals("reuseExistingMetaData")){
1375
                     config.setReuseExistingMetaData(Boolean.valueOf(valueString));
1376
                 }else if (keyString.equals("reuseExistingDescriptiveGroups")){
1377
                     config.setReuseExistingDescriptiveGroups(Boolean.valueOf(valueString));
1378
                 }else if (keyString.equals("allowReuseOtherClassifications")){
1379
                     config.setAllowReuseOtherClassifications(Boolean.valueOf(valueString));
1380
                 }else if (keyString.equals("deduplicateReferences")){
1381
                     config.setDeduplicateReferences(Boolean.valueOf(valueString));
1382
                 }else if (keyString.equals("deduplicateClassifications")){
1383
                     config.setDeduplicateClassifications(Boolean.valueOf(valueString));
1384
                 }else if (keyString.equals("moveNewTaxaToDefaultClassification")){
1385
                     config.setMoveNewTaxaToDefaultClassification(Boolean.valueOf(valueString));
1386
                 }else if (keyString.equals("mapUnitIdToCatalogNumber")){
1387
                     config.setMapUnitIdToCatalogNumber(Boolean.valueOf(valueString));
1388
                 }else if (keyString.equals("mapUnitIdToAccessionNumber")){
1389
                     config.setMapUnitIdToAccessionNumber(Boolean.valueOf(valueString));
1390
                 }else if (keyString.equals("mapUnitIdToBarcode")){
1391
                     config.setMapUnitIdToBarcode(Boolean.valueOf(valueString));
1392
                 }else if (keyString.equals("overwriteExistingSpecimens")){
1393
                     config.setOverwriteExistingSpecimens(Boolean.valueOf(valueString));
1394
                 }else if (keyString.equals("nomenclaturalCode")){
1395
                         config.setNomenclaturalCode(NomenclaturalCode.fromString(valueString));
1396
                 }else{
1397
                     logger.debug("This key of the abcd configurator needs to be added to the transformer: " + keyString);
1398
                 }
1399

    
1400
             }
1401
        }
1402
        return config;
1403
    }
1404

    
1405
    public static Abcd206ImportConfigurator getLocalAbcdImportConfigurator(){
1406
       Abcd206ImportConfigurator config = Abcd206ImportConfigurator.NewInstance(null,null);
1407

    
1408
        config.setAddIndividualsAssociationsSuchAsSpecimenAndObservations(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_ADD_INDIVIDUALS_ASSOCIATIONS_SUCH_AS_SPECIMEN_AND_OBSERVATIONS));
1409

    
1410
        config.setAddMediaAsMediaSpecimen(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_ADD_MEDIA_AS_MEDIASPECIMEN));
1411

    
1412
        config.setAllowReuseOtherClassifications(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_ALLOW_REUSE_OTHER_CLASSIFICATIONS));
1413
        config.setDeduplicateClassifications(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_DEDUPLICATE_CLASSIFICATIONS));
1414
        config.setDeduplicateReferences(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_DEDUPLICATE_REFERENCES));
1415
        config.setRemoveCountryFromLocalityText(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_REMOVE_COUNTRY_FROM_LOCALITY_TEXT));
1416
        config.setGetSiblings(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_DO_SIBLINGS));
1417
        config.setIgnoreAuthorship(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_IGNORE_AUTHORSHIP));
1418
        config.setIgnoreImportOfExistingSpecimen(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_IGNORE_IMPORT_OF_EXISTING_SPECIMEN));
1419
        config.setMapUnitIdToAccessionNumber(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_MAP_UNIT_ID_TO_ACCESSION_NUMBER));
1420
        config.setMapUnitIdToBarcode(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_MAP_UNIT_ID_TO_BARCODE));
1421
        config.setMapUnitIdToCatalogNumber(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_MAP_UNIT_ID_TOCATALOG_NUMBER));
1422
        config.setMoveNewTaxaToDefaultClassification(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_MOVE_NEW_TAXA_TO_DEFAULT_CLASSIFICATION));
1423
        config.setOverwriteExistingSpecimens(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_OVERWRITE_EXISTING_SPECIMEN));
1424
        config.setReuseExistingDescriptiveGroups(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_REUSE_EXISTING_DESCRIPTIVE_GROUPS));
1425
        config.setReuseExistingMetaData(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_REUSE_EXISTING_META_DATA));
1426
        config.setReuseExistingTaxaWhenPossible(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_REUSE_EXISTING_TAXA_WHEN_POSSIBLE));
1427
        config.setNomenclaturalCode(NomenclaturalCode.getByKey(getStringValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_NOMENCLATURAL_CODE)));
1428

    
1429
        return config;
1430

    
1431
    }
1432

    
1433
    public static void updateAbcdImportConfigurationPreference() {
1434
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1435

    
1436
        CdmPreference pref = cache.findBestMatching(CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AbcdImportConfig));
1437

    
1438
        if (!getBooleanValue(prefOverrideKey(PreferencePredicate.AbcdImportConfig.getKey())) || !pref.isAllowOverride()){
1439
            resetToDBPreferenceAbcdCOnfigurator();
1440

    
1441
        }
1442
    }
1443

    
1444
    public static void resetToDBPreferenceAbcdCOnfigurator(){
1445
        Abcd206ImportConfigurator config = getDBAbcdImportConfigurationPreference();
1446
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_ADD_INDIVIDUALS_ASSOCIATIONS_SUCH_AS_SPECIMEN_AND_OBSERVATIONS, config.isAddIndividualsAssociationsSuchAsSpecimenAndObservations());
1447
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_ADD_MEDIA_AS_MEDIASPECIMEN, config.isAddMediaAsMediaSpecimen());
1448

    
1449
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_ALLOW_REUSE_OTHER_CLASSIFICATIONS, config.isAllowReuseOtherClassifications());
1450
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_DEDUPLICATE_CLASSIFICATIONS, config.isDeduplicateClassifications());
1451
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_DEDUPLICATE_REFERENCES, config.isDeduplicateReferences());
1452

    
1453
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_DO_SIBLINGS, config.isGetSiblings());
1454
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_IGNORE_AUTHORSHIP, config.isIgnoreAuthorship());
1455
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_IGNORE_IMPORT_OF_EXISTING_SPECIMEN, config.isIgnoreImportOfExistingSpecimen());
1456
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_MAP_UNIT_ID_TO_ACCESSION_NUMBER, config.isMapUnitIdToAccessionNumber());
1457
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_MAP_UNIT_ID_TO_BARCODE, config.isMapUnitIdToBarcode());
1458
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_MAP_UNIT_ID_TOCATALOG_NUMBER, config.isMapUnitIdToCatalogNumber());
1459
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_MOVE_NEW_TAXA_TO_DEFAULT_CLASSIFICATION, config.isMoveNewTaxaToDefaultClassification());
1460
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_OVERWRITE_EXISTING_SPECIMEN, config.isOverwriteExistingSpecimens());
1461
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_REUSE_EXISTING_DESCRIPTIVE_GROUPS, config.isReuseExistingDescriptiveGroups());
1462
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_REUSE_EXISTING_META_DATA, config.isReuseExistingMetaData());
1463
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_REUSE_EXISTING_TAXA_WHEN_POSSIBLE, config.isReuseExistingTaxaWhenPossible());
1464
        if (config.getNomenclaturalCode() != null){
1465
            setStringValue(ABCD_IMPORT_CONFIGURATOR_NOMENCLATURAL_CODE, config.getNomenclaturalCode().getKey());
1466
        }
1467
    }
1468

    
1469
    public static boolean isSortTaxaByRankAndName() {
1470

    
1471
        return getBooleanValue(IPreferenceKeys.SORT_TAXA_BY_RANK_AND_NAME);
1472
    }
1473

    
1474
    public static String getSortNamedAreasInDistributionEditor() {
1475

    
1476
        return getStringValue(PreferencePredicate.AreasSortedInDistributionEditor.getKey());
1477
    }
1478

    
1479
    public static void setSortNamedAreasInDistributionEditor(String isSortByVocabularyOrder) {
1480
        setStringValue(PreferencePredicate.AreasSortedInDistributionEditor.getKey(), isSortByVocabularyOrder);
1481

    
1482
    }
1483

    
1484
    public static void setLastSelectedReference(
1485
            List<String> lastSelectedReferences) {
1486

    
1487
        setStringValue(PreferencesUtil.LAST_SELECTED_REFERENCES, lastSelectedReferences.toString());
1488
    }
1489

    
1490
    public static List<String> getLastSelectedReferences() {
1491

    
1492
        //IPreferenceStore preferenceStore = PreferencesUtil.getPreferenceStore();
1493
        String lastSelected = getStringValue(PreferencesUtil.LAST_SELECTED_REFERENCES);
1494
        List<String> result = new ArrayList<>();
1495
        if (!StringUtils.isBlank(lastSelected)){
1496
            Collections.addAll(result, lastSelected.substring(1,lastSelected.length()-1).split(", "));
1497
        }
1498
        return result;
1499
    }
1500

    
1501
    public static void setPreferredNamedAreasForDistributionEditor(
1502
            String saveCheckedElements, String saveGrayedElements, boolean local) {
1503
        if (local){
1504
            setStringValue(PreferencePredicate.AvailableDistributionAreaTerms.getKey(), saveCheckedElements);
1505

    
1506
        }
1507
        else{
1508
            CdmPreference preference = null;
1509

    
1510
            if (saveCheckedElements == null){
1511
                preference = getPreferenceFromDB(PreferencePredicate.AvailableDistributionAreaTerms);
1512

    
1513
                if (preference == null){
1514
                    return ;
1515
                } else{
1516
                    setStringValue(PreferencePredicate.AvailableDistributionAreaTerms.getKey(),
1517
                            saveCheckedElements);
1518
                    preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AvailableDistributionAreaTerms, saveCheckedElements);
1519
                    setPreferenceToDB(preference);
1520

    
1521
                }
1522
            } else{
1523
                preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AvailableDistributionAreaTerms, saveCheckedElements);
1524
                setPreferenceToDB(preference);
1525
                setStringValue(PreferencePredicate.AvailableDistributionAreaTerms.getKey(),
1526
                        saveCheckedElements);
1527

    
1528
            }
1529
        }
1530

    
1531
    }
1532

    
1533
    public static void setPreferredVocabulariesForDistributionEditor(String saveCheckedElements,
1534
            boolean local, boolean isOverride) {
1535
        if (local){
1536
            setStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(), saveCheckedElements);
1537
            setBooleanValue(prefOverrideKey(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey()), isOverride);
1538
        }
1539
        else{
1540
            ICdmRepository controller;
1541
            CdmPreference preference = null;
1542

    
1543
            if (saveCheckedElements == null){
1544
                preference = getPreferenceFromDB(PreferencePredicate.AvailableDistributionAreaVocabularies);
1545

    
1546
                if (preference == null){
1547
                    return ;
1548
                } else{
1549
                    setStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(),
1550
                            saveCheckedElements);
1551
                    preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AvailableDistributionAreaVocabularies, saveCheckedElements);
1552
                    preference.setAllowOverride(isOverride);
1553
                    setPreferenceToDB(preference);
1554
                }
1555
            } else{
1556
                preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AvailableDistributionAreaVocabularies, saveCheckedElements);
1557
                preference.setAllowOverride(isOverride);
1558
                setPreferenceToDB(preference);
1559
                setStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(),
1560
                        saveCheckedElements);
1561

    
1562
            }
1563
        }
1564
    }
1565

    
1566
    public static String getPreferredVocabulariesForDistributionEditor(boolean local) {
1567
        if (local){
1568

    
1569
            String pref = getStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(), local);
1570
            return pref;
1571
        }
1572
        else{
1573
            CdmPreference preference = null;
1574
            preference = getPreferenceFromDB(PreferencePredicate.AvailableDistributionAreaVocabularies);
1575
            if (preference == null){
1576
                return null;
1577
            } else{
1578
                return preference.getValue();
1579
            }
1580

    
1581
        }
1582
    }
1583

    
1584
    public static List<UUID> createUUIDListFromStringPref(String prefKey) {
1585
        String prefValue = PreferencesUtil.getStringValue(prefKey);
1586
        String[] stringArray = prefValue.split(";");
1587
        List<UUID> uuidList = new ArrayList();
1588
        for (String uuid: stringArray){
1589
            if (!StringUtils.isBlank(uuid)){
1590
                uuidList.add(UUID.fromString(uuid));
1591
            }
1592
        }
1593
        return uuidList;
1594
    }
1595

    
1596
    public static boolean getFilterCommonNameReferences(){
1597
        return getBooleanValue(PreferencesUtil.FILTER_COMMON_NAME_REFERENCES);
1598
    }
1599

    
1600
    public static void updateDBPreferences() {
1601
        CdmPreference preference = null;
1602
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1603
        cache.getAllTaxEditorDBPreferences();
1604

    
1605
        //ABCD Configurator
1606

    
1607
        updateAbcdImportConfigurationPreference();
1608

    
1609
        //Name Details
1610
        NameDetailsConfigurator config = getPreferredNameDetailsConfiguration(false);
1611
        //    if (config != null ){
1612
        //        if (!getBooleanValue(OVERRIDE_NAME_DETAILS) ||  !getBooleanValue(ALLOW_OVERRIDE_NAME_DETAILS)){
1613
        //            setPreferredNameDetailsConfiguration(config, false);
1614
        //        }
1615
        //    }
1616

    
1617
    }
1618

    
1619
    public static void setPreferencesToDB(List<CdmPreference> preferences) {
1620

    
1621
        ICdmRepository controller;
1622
        try{
1623
            if(CdmStore.isActive()){
1624
                controller = CdmStore.getCurrentApplicationConfiguration();
1625
                for (CdmPreference preference: preferences){
1626

    
1627
                    controller.getPreferenceService().set(preference);
1628

    
1629
                    CdmPreferenceCache.instance().put(preference);
1630
                }
1631
            }
1632
        }catch(Exception e){
1633
            e.printStackTrace();
1634
        }
1635
    }
1636

    
1637
    /**
1638
     * Returns whether the named preference is known.
1639
     * @param prefKey the key of the preference
1640
     * @return <code>true</code> if the preference is known, <code>false</code> otherwise
1641
     */
1642
    public static boolean contains(String prefKey){
1643
        return getPreferenceStore().contains(prefKey(prefKey));
1644
    }
1645

    
1646
}
(27-27/41)