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
	/**
86
	 *
87
	 */
88
	public static final String PREFERRED_TERMS_CHANGE = "preferred_terms";
89

    
90
	public static final String P2_REPOSITORIES_DELIM = ",";
91
	public static final String P2_REPOSITORY_FIELDS_DELIM = ";";
92

    
93
	private final static Logger logger = Logger.getLogger(PreferencesUtil.class);
94

    
95

    
96

    
97

    
98

    
99
	/**
100
	 * <p>
101
	 * getPreferenceStore
102
	 * </p>
103
	 *
104
	 * @return a {@link org.eclipse.jface.preference.IPreferenceStore} object.
105
	 */
106
	public static IPreferenceStore getPreferenceStore() {
107
		return TaxeditorStorePlugin.getDefault().getPreferenceStore();
108
	}
109

    
110
	static String prefKey(String name) {
111
	    return name + "_"+  ((CdmRemoteSource)CdmStore.getActiveCdmSource()).toString();
112
	}
113

    
114
	public static String prefOverrideKey(String name) {
115
        return name + "_OVERRIDE_";
116
    }
117

    
118
	/**
119
     * <p>
120
     * setStringValue
121
     * </p>
122
     *
123
     *
124
     **/
125
    public static void setStringValue(String name, String value) {
126
        if (value != null){
127
            getPreferenceStore().setValue(prefKey(name), value);
128
        }else{
129
            getPreferenceStore().setToDefault(name);
130
        }
131
    }
132

    
133
    /**
134
     * <p>
135
     * setIntValue
136
     * </p>
137
     *
138
     *
139
     **/
140
    public static void setIntValue(String name, int value) {
141
        getPreferenceStore().setValue(prefKey(name), value);
142
    }
143

    
144
    /**
145
     * <p>
146
     * setBooleanValue
147
     * </p>
148
     *
149
     *
150
     **/
151
    public static void setBooleanValue(String name, boolean value) {
152
        getPreferenceStore().setValue(prefKey(name), value);
153
    }
154

    
155
    /**
156
     * <p>
157
     * setBooleanValue
158
     * </p>
159
     *
160
     *
161
     **/
162
    public static void setDoubleValue(String name, double value) {
163
        getPreferenceStore().setValue(prefKey(name), value);
164
    }
165

    
166
    /**
167
     * <p>
168
     * setFloatValue
169
     * </p>
170
     *
171
     *
172
     **/
173
    public static void setFloatValue(String name, float value) {
174
        getPreferenceStore().setValue(name + ((CdmRemoteSource)CdmStore.getActiveCdmSource()).toString(), value);
175
    }
176

    
177
    /**
178
     * <p>
179
     * setFloatValue
180
     * </p>
181
     *
182
     *
183
     **/
184
    public static void setLongValue(String name, long value) {
185
        getPreferenceStore().setValue(prefKey(name), value);
186
    }
187

    
188
    /**
189
     * <p>
190
     * getStringValue
191
     * </p>
192
     *
193
     *
194
     **/
195
    public static String getStringValue(String name, boolean local) {
196

    
197
        String prefValue = getDBPreferenceValue(name);
198
        if (prefValue == null || local){
199
            String dbSpecific = prefKey(name);
200
            if (getPreferenceStore().contains(dbSpecific)){
201
                prefValue = getPreferenceStore().getString(dbSpecific);
202
            }else{
203
                prefValue = getPreferenceStore().
204
                        getString(name);
205
            }
206
        }
207
        return prefValue;
208

    
209
    }
210

    
211
    public static String getStringValue(String name){
212
        return getStringValue(name, false);
213
    }
214

    
215
    private static String getDBPreferenceValue(String name) {
216
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
217
        if (cache.get(name) != null){
218
            CdmPreference pref = cache.get(name);
219
            boolean test = getBooleanValue(prefOverrideKey(name));
220
            if (!pref.isAllowOverride() || !getBooleanValue(prefOverrideKey(name))){
221
                return pref.getValue();
222
            }
223
        }
224
        return null;
225
    }
226

    
227
    /**
228
     * <p>
229
     * setIntValue
230
     * </p>
231
     *
232
     *
233
     **/
234
    public static int getIntValue(String name) {
235
        String prefValue = getDBPreferenceValue(name);
236
        Integer result = null;
237
        try{
238
            result = Integer.parseInt(prefValue);
239
        }catch(NumberFormatException e){
240
            logger.debug("Preference value of " + name + " is not a number");
241
        }
242
        if (result == null){
243
            String dbSpecific = prefKey(name);
244
            if (getPreferenceStore().contains(dbSpecific)){
245
                result = getPreferenceStore().getInt(dbSpecific);
246
            }else{
247
                result =  getPreferenceStore().
248
                        getInt(name);
249
            }
250
        }
251
        return result;
252

    
253

    
254
    }
255

    
256
    /**
257
     * <p>
258
     * setBooleanValue
259
     * </p>
260
     *
261
     *
262
     **/
263
    public static boolean getBooleanValue(String name) {
264
        if (CdmStore.isActive()){
265
            String prefValue = getDBPreferenceValue(name);
266
            if (prefValue == null){
267
                String dbSpecific = prefKey(name);
268
                if (getPreferenceStore().contains(dbSpecific)){
269
                    return getPreferenceStore().getBoolean(dbSpecific);
270
                }else{
271
                    return getPreferenceStore().
272
                            getBoolean(name);
273
                }
274
            }else{
275
                return Boolean.valueOf(prefValue);
276
            }
277

    
278
        }else{
279
            return getPreferenceStore().getBoolean(name);
280
        }
281

    
282
    }
283

    
284
    /**
285
     * <p>
286
     * setBooleanValue
287
     * </p>
288
     *
289
     *
290
     **/
291
    public static double getDoubleValue(String name) {
292
        String prefValue = getDBPreferenceValue(name);
293
        Double result = null;
294
        try{
295
            result = Double.parseDouble(prefValue);
296
        }catch(NumberFormatException e){
297
            logger.debug("Preference value of " + name + " is not a number");
298
        }
299
        if (result == null){
300
            String dbSpecific = prefKey(name);
301
            if (getPreferenceStore().contains(dbSpecific)){
302
                result = getPreferenceStore().getDouble(dbSpecific);
303
            }else{
304
                result =  getPreferenceStore().
305
                        getDouble(name);
306
            }
307
        }
308
        return result;
309

    
310
    }
311

    
312
    /**
313
     * <p>
314
     * getFloatValue
315
     * </p>
316
     *
317
     *
318
     **/
319
    public static float getFloatValue(String name) {
320
        String prefValue = getDBPreferenceValue(name);
321
        Float result = null;
322
        try{
323
            result = Float.parseFloat(prefValue);
324
        }catch(NumberFormatException e){
325
            logger.debug("Preference value of " + name + " is not a number");
326
        }
327
        if (result == null){
328
            String dbSpecific = prefKey(name);
329
            if (getPreferenceStore().contains(dbSpecific)){
330
                result = getPreferenceStore().getFloat(dbSpecific);
331
            }else{
332
                result =  getPreferenceStore().
333
                        getFloat(name);
334
            }
335
        }
336
        return result;
337

    
338
    }
339

    
340
    /**
341
     * <p>
342
     * getLongValue
343
     * </p>
344
     *
345
     *
346
     **/
347
    public static long getLongValue(String name) {
348
        String prefValue = getDBPreferenceValue(name);
349
        Long result = null;
350
        try{
351
            result = Long.parseLong(prefValue);
352
        }catch(NumberFormatException e){
353
            logger.debug("Preference value of " + name + " is not a number");
354
        }
355
        if (result == null){
356
            String dbSpecific = prefKey(name);
357
            if (getPreferenceStore().contains(dbSpecific)){
358
                result = getPreferenceStore().getLong(dbSpecific);
359
            }else{
360
                result =  getPreferenceStore().
361
                        getLong(name);
362
            }
363
        }
364
        return result;
365
    }
366

    
367

    
368
	/**
369
	 * <p>
370
	 * setPreferredNomenclaturalCode
371
	 * </p>
372
	 *
373
	 * @param preferredCode
374
	 *            a {@link eu.etaxonomy.cdm.model.name.NomenclaturalCode}
375
	 *            object.
376
	 */
377
	public static CdmPreference setPreferredNomenclaturalCode(
378
			String preferenceValue, boolean local) {
379
	    if (local){
380
	        setStringValue(PREFERRED_NOMENCLATURAL_CODE_KEY,
381
	                preferenceValue);
382
	    }
383
	    else{
384
    		ICdmRepository controller;
385
    		controller = CdmStore.getCurrentApplicationConfiguration();
386
    		if (controller == null){
387
                return null;
388
            }
389
    		PrefKey key = null;
390
    		try{
391
    		    key = CdmPreference.NewKey(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.NomenclaturalCode);
392
    		}catch (Exception e){
393
    		    System.out.println(e.getStackTrace());
394
    		}
395
    		CdmPreference preference = null;
396

    
397
    		if (preferenceValue == null){
398
    			preference = controller.getPreferenceService().find(key);
399
    			if (preference == null){
400
    				return null;
401
    			} else{
402
    			    setStringValue(PREFERRED_NOMENCLATURAL_CODE_KEY,
403
    				        preference.getValue());
404

    
405
    				return preference;
406
    			}
407
    		} else{
408
    			preference = CdmPreference.NewInstance(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.NomenclaturalCode, preferenceValue);
409
    			controller.getPreferenceService().set(preference);
410

    
411
    		}
412
	    }
413
        return null;
414

    
415

    
416

    
417
	}
418

    
419
	/**
420
     * <p>
421
     * setPreferredNomenclaturalCode
422
     * </p>
423
     *
424
     * @param preferredCode
425
     *            a {@link eu.etaxonomy.cdm.model.name.NomenclaturalCode}
426
     *            object.
427
     */
428
    public static void setPreferredNomenclaturalCode(
429
        CdmPreference preference) {
430

    
431
        ICdmRepository controller;
432
        controller = CdmStore.getCurrentApplicationConfiguration();
433
        if (controller == null){
434
            return;
435
        }
436
        PrefKey key = null;
437
        try{
438
            key = CdmPreference.NewKey(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.NomenclaturalCode);
439
        }catch (Exception e){
440
            System.out.println(e.getStackTrace());
441
        }
442

    
443
        controller.getPreferenceService().set(preference);
444

    
445
    }
446

    
447

    
448

    
449

    
450
	/**
451
	 * <p>
452
	 * getPreferredNomenclaturalCode
453
	 * </p>
454
	 *
455
	 * @return a {@link eu.etaxonomy.cdm.model.name.NomenclaturalCode} object.
456
	 */
457
	public static NomenclaturalCode getPreferredNomenclaturalCode() {
458

    
459
		CdmPreference pref = getPreferenceFromDB(PreferencePredicate.NomenclaturalCode);
460

    
461

    
462
	    String preferredCode;
463
	    if(pref == null || (pref.isAllowOverride() && getBooleanValue(prefOverrideKey(PreferencePredicate.NomenclaturalCode.getKey())))){
464
	    	preferredCode = getStringValue(
465
	    	        PreferencePredicate.NomenclaturalCode.getKey(), true);
466

    
467
	    }else{
468
	    	preferredCode = pref.getValue();
469
	    }
470
	    if (StringUtils.isBlank(preferredCode)){
471
	        preferredCode = getPreferenceKey((NomenclaturalCode)PreferencePredicate.NomenclaturalCode.getDefaultValue());
472
	    }
473

    
474
	    return getPreferredNomenclaturalCode(preferredCode);
475

    
476
	}
477

    
478
	/**
479
     * <p>
480
     * getPreferredNomenclaturalCode
481
     * </p>
482
     *
483
     * @return a {@link eu.etaxonomy.cdm.model.name.NomenclaturalCode} object.
484
     */
485
    public static NomenclaturalCode getPreferredNomenclaturalCode(String preferenceKeyNomenclaturalCode) {
486

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

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

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

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

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

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

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

    
529
        return pref;
530

    
531
    }
532

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

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

    
547
        return prefs;
548

    
549
    }
550

    
551
	public static CdmPreference getPreferenceFromDB(PrefKey key){
552
        ICdmRepository controller;
553
        CdmPreference pref = null;
554

    
555
        try{
556
            if(CdmStore.isActive()){
557
                controller = CdmStore.getCurrentApplicationConfiguration();
558
                pref = controller.getPreferenceService().find(key);
559
            }
560
        }catch(Exception e){
561
            e.printStackTrace();
562
        }
563

    
564
        return pref;
565

    
566
    }
567

    
568

    
569

    
570
    public static void setPreferenceToDB(CdmPreference preference){
571
        ICdmRepository controller;
572
        try{
573
            if(CdmStore.isActive()){
574
                controller = CdmStore.getCurrentApplicationConfiguration();
575
                controller.getPreferenceService().set(preference);
576
            }
577
        }catch(Exception e){
578
            e.printStackTrace();
579
        }
580

    
581
    }
582

    
583

    
584

    
585
	public static String getPreferredDefaultLangugae(){
586
	    String preferredLanguage = getStringValue(DEFAULT_LANGUAGE_EDITOR);
587
	    if(StringUtils.isNotEmpty(preferredLanguage) && StringUtils.isNotBlank(preferredLanguage)){
588
	        return preferredLanguage;
589
	    }
590
	    return null;
591
	}
592

    
593
	public static boolean isShowMediaPreview(){
594
        boolean isShowMediaPreview = getBooleanValue(SHOW_MEDIA_PREVIEW);
595
        return isShowMediaPreview;
596
    }
597

    
598
	/**
599
	 * Get the match strategy for the given class that was stored in preferences
600
	 * or the default strategy if it was not stored in preferences
601
	 *
602
	 * @param clazz
603
	 *            a {@link java.lang.Class} object.
604
	 * @return a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy} object.
605
	 */
606
	public static IMatchStrategy getMatchStrategy(Class<?> clazz) {
607
		String className = clazz.getName();
608
		if (getBooleanValue(MATCH_STRATEGY_PREFIX + className)) {
609
			IMatchStrategy matchStrategy = getDefaultMatchStrategy(clazz);
610

    
611
			//TODO CacheMatchers (or multiple field matchers in future) are missing here
612
			for (FieldMatcher fieldMatcher : matchStrategy.getMatching().getFieldMatchers(false)) {
613
				String fieldName = fieldMatcher.getPropertyName();
614
				String matchModeName = getStringValue(
615
						getMatchStrategyFieldName(className, fieldName));
616
				MatchMode matchMode = MatchMode.valueOf(matchModeName);
617
				try {
618
					matchStrategy.setMatchMode(fieldName, matchMode);
619
				} catch (MatchException e) {
620
					MessagingUtils.error(PreferencesUtil.class, e);
621
					throw new RuntimeException(e);
622
				}
623
			}
624

    
625
			return matchStrategy;
626
		}
627
		return getDefaultMatchStrategy(clazz);
628
	}
629

    
630
	/**
631
	 * Stores a matchStrategy into the preference store.
632
	 *
633
	 * @param matchStrategy
634
	 *            a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy}
635
	 *            object.
636
	 */
637
	public static void setMatchStrategy(IMatchStrategy matchStrategy) {
638
		String className = "ANY class"; //FIXME was: matchStrategy.getMatchClass().getName(); seems currently not in use
639
		setBooleanValue(MATCH_STRATEGY_PREFIX + className, true);
640

    
641
		List<FieldMatcher> fieldMatchers = matchStrategy.getMatching().getFieldMatchers(false);
642

    
643
		for (FieldMatcher fieldMatcher : fieldMatchers) {
644
			String fieldName = fieldMatcher.getPropertyName();
645
			setStringValue(
646
					getMatchStrategyFieldName(className, fieldName),
647
					fieldMatcher.getMatchMode().name());
648
		}
649
	}
650

    
651
	/**
652
	 * Helper method to create the preference property for a match field.
653
	 *
654
	 * @param className
655
	 * @param fieldName
656
	 * @return
657
	 */
658
	private static String getMatchStrategyFieldName(String className,
659
			String fieldName) {
660
		return MATCH_STRATEGY_PREFIX + className + "." + fieldName;
661
	}
662

    
663
	/**
664
	 * Returns the default match strategy for a given class.
665
	 *
666
	 * @param clazz
667
	 *            a {@link java.lang.Class} object.
668
	 * @return a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy} object.
669
	 */
670
	public static IMatchStrategy getDefaultMatchStrategy(Class clazz) {
671
		return DefaultMatchStrategy.NewInstance(clazz);
672
	}
673

    
674
	/**
675
	 * <p>
676
	 * getDateFormatPattern
677
	 * </p>
678
	 *
679
	 * @return a {@link java.lang.String} object.
680
	 */
681
	public static String getDateFormatPattern() {
682
		// TODO make this configurable in properties
683
		String pattern = "Y-M-d H:m";
684
		return pattern;
685
	}
686

    
687
	/**
688
	 * <p>
689
	 * addTermToPreferredTerms
690
	 * </p>
691
	 *
692
	 * @param term
693
	 *            a T object.
694
	 * @param <T>
695
	 *            a T object.
696
	 */
697
	public static <T extends TermBase> void addTermToPreferredTerms(T term) {
698

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

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

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

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

    
742

    
743

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

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

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

    
779
		return configurator;
780
	}
781

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

    
792
		configurator.setDoTaxa(true);
793
		configurator.setDoSynonyms(true);
794
		configurator.setDoNamesWithoutTaxa(true);
795
		configurator.setDoTaxaByCommonNames(true);
796

    
797
		configurator.setTaxonPropertyPath(Arrays.asList("$", "titleCache",
798
				"name", "name.$", "relationsFromThisTaxon.$"));
799

    
800
		configurator.setSynonymPropertyPath(Arrays.asList("$", "titleCache",
801
				"name", "name.$", "synonyms.relatedTo.*"));
802

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

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

    
836
	/**
837
	 * <p>
838
	 * firePreferencesChanged
839
	 * </p>
840
	 *
841
	 * @param clazz
842
	 *            a {@link java.lang.Class} object.
843
	 */
844
	public static void firePreferencesChanged(Class clazz) {
845
		getPreferenceStore().firePropertyChangeEvent(PREFERRED_TERMS_CHANGE,
846
				null, clazz);
847
	}
848

    
849
	public static String createPreferenceString(String property){
850
	   return prefKey(property);
851

    
852
	}
853
	public static String createOverridePreferenceString(String property){
854
	       return prefOverrideKey(property);
855

    
856
	    }
857

    
858
	/**
859
	 * Set default values for preferences
860
	 */
861
	public static void setDefaults() {
862
		getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_TAXA, true);
863
		getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_SYNONYMS,
864
				true);
865
		getPreferenceStore().setDefault(createPreferenceString(EDIT_MAP_SERVICE_ACCES_POINT),
866
				"http://edit.africamuseum.be/edit_wp5/v1.2/rest_gen.php");
867
		//FIXME : changed default for SHOULD_CONNECT_AT_STARTUP to false (ticket 3828) until resolution
868
		getPreferenceStore().setDefault(createPreferenceString(SHOULD_CONNECT_AT_STARTUP), false);
869
		getPreferenceStore().setDefault(createPreferenceString(OPENURL_ACCESS_POINT),
870
				"http://www.biodiversitylibrary.org/openurl");
871
		getPreferenceStore().setDefault(createPreferenceString(OPENURL_IMAGE_MAX_WIDTH), "1000");
872
		getPreferenceStore().setDefault(createPreferenceString(OPENURL_IMAGE_MAX_HEIGHT), "1000");
873
		//Distribution Editor:
874
		getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.DistributionEditorActivated.getKey()), Boolean.valueOf(PreferencePredicate.DistributionEditorActivated.getDefaultValue().toString()));
875
//		getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey()), PreferencePredicate.DisplayOfAreasInDistributionEditor.getDefaultValue().toString());
876
//		getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.DisplayOfStatus.getKey()), PreferencePredicate.DisplayOfStatus.getDefaultValue().toString());
877

    
878

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

    
882
		//Navigator preferences
883
		getPreferenceStore().setDefault(createPreferenceString(SORT_NODES), NavigatorOrderEnum.RankAndNameOrder.getKey());
884

    
885
		getPreferenceStore().setDefault(createPreferenceString(SORT_TAXA_BY_RANK_AND_NAME), true);
886

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

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

    
903
	}
904

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

    
916

    
917

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

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

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

    
940
	}
941

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

    
955
	/**
956
	 * <p>
957
	 * getMapServiceAccessPoint
958
	 * </p>
959
	 *
960
	 * @return a {@link java.lang.String} object.
961
	 */
962
	public static String getMapServiceAccessPoint() {
963
		return getStringValue(EDIT_MAP_SERVICE_ACCES_POINT);
964
	}
965

    
966
	/**
967
	 * <p>
968
	 * shouldConnectAtStartUp
969
	 * </p>
970
	 *
971
	 * @return a boolean.
972
	 */
973
	public static boolean shouldConnectAtStartUp() {
974
		//FIXME :  force SHOULD_CONNECT_AT_STARTUP to false (ticket 3828) until resolution
975
		//return getBooleanValue(SHOULD_CONNECT_AT_STARTUP);
976
		return false;
977
	}
978

    
979
	/**
980
	 * <p>
981
	 * getDefaultFeatureTreeForTextualDescription
982
	 * </p>
983
	 *
984
	 * @return a {@link eu.etaxonomy.cdm.model.term.FeatureTree} object.
985
	 */
986
	public static FeatureTree getDefaultFeatureTreeForTextualDescription() {
987
		String uuidString = getStringValue(
988
				FEATURE_TREE_DEFAULT_TEXT);
989
		if (StringUtils.isBlank(uuidString)) {
990
            return null;
991
        }
992
		FeatureTree tree = CdmStore.getService(
993
	                IFeatureTreeService.class).load(UUID.fromString(uuidString));
994
		if (tree.getId() == 0) {
995
            return null;
996
        }
997
		return tree;
998
	}
999

    
1000
	/**
1001
	 * <p>
1002
	 * getDefaultFeatureTreeForStructuredDescription
1003
	 * </p>
1004
	 *
1005
	 * @return a {@link eu.etaxonomy.cdm.model.term.FeatureTree} object.
1006
	 */
1007
	public static FeatureTree getDefaultFeatureTreeForStructuredDescription() {
1008
		String uuidString = getStringValue(
1009
				FEATURE_TREE_DEFAULT_STRUCTURE);
1010
		return CdmUtils.isEmpty(uuidString) ? null : CdmStore.getService(
1011
				IFeatureTreeService.class).load(UUID.fromString(uuidString));
1012
	}
1013

    
1014
	/**
1015
	 * <p>
1016
	 * setSortRanksHierarchichally
1017
	 * </p>
1018
	 *
1019
	 * @param selection
1020
	 *            a boolean.
1021
	 */
1022
	public static void setSortRanksHierarchichally(boolean selection) {
1023
		setBooleanValue(SORT_RANKS_HIERARCHICHALLY, selection);
1024
	}
1025

    
1026
	/**
1027
	 * <p>
1028
	 * getSortRanksHierarchichally
1029
	 * </p>
1030
	 *
1031
	 * @return a boolean.
1032
	 */
1033
	public static boolean getSortRanksHierarchichally() {
1034
		return getBooleanValue(SORT_RANKS_HIERARCHICHALLY);
1035
	}
1036

    
1037
	public static boolean isMultilanguageTextEditingCapability() {
1038
		return getBooleanValue(
1039
				MULTILANGUAGE_TEXT_EDITING_CAPABILITY);
1040
	}
1041

    
1042
	public static Language getGlobalLanguage() {
1043

    
1044

    
1045
		String languageUuidString = getStringValue(
1046
				GLOBAL_LANGUAGE_UUID);
1047

    
1048
		if(!CdmStore.isActive()) {
1049
            MessagingUtils.noDataSourceWarningDialog(languageUuidString);
1050
            return null;
1051
        }
1052

    
1053
		if (CdmUtils.isBlank(languageUuidString)) {
1054
			return Language.getDefaultLanguage();
1055
		}
1056

    
1057
		UUID languageUuid = UUID.fromString(languageUuidString);
1058
		return (Language) CdmStore.getService(ITermService.class).load(
1059
				languageUuid);
1060
	}
1061

    
1062
	public static void setGlobalLanguage(Language language) {
1063
	    if(language != null) {
1064
	        setStringValue(GLOBAL_LANGUAGE_UUID,language.getUuid().toString());
1065
	        CdmStore.setDefaultLanguage(language);
1066
	    }
1067

    
1068
	}
1069

    
1070
	/**
1071
	 * @return
1072
	 */
1073
	public static Map<MarkerType, Boolean> getEditMarkerTypePreferences() {
1074
		List<MarkerType> markerTypes = CdmStore.getTermManager()
1075
				.getPreferredTerms(MarkerType.class);
1076

    
1077
		Map<MarkerType, Boolean> result = new HashMap<MarkerType, Boolean>();
1078

    
1079
		for (MarkerType markerType : markerTypes) {
1080
			String name = getMarkerTypeEditingPreferenceKey(markerType);
1081
			Boolean value = getBooleanValue(name);
1082

    
1083
			result.put(markerType, value);
1084
		}
1085

    
1086
		return result;
1087
	}
1088

    
1089
	/**
1090
	 * @param markerTypeEditingMap
1091
	 */
1092
	public static void setEditMarkerTypePreferences(
1093
			Map<MarkerType, Boolean> markerTypeEditingMap) {
1094
		for (MarkerType markerType : markerTypeEditingMap.keySet()) {
1095
			String name = getMarkerTypeEditingPreferenceKey(markerType);
1096
			setBooleanValue(name,
1097
					markerTypeEditingMap.get(markerType));
1098
		}
1099

    
1100
	}
1101

    
1102
	private static String getMarkerTypeEditingPreferenceKey(
1103
			MarkerType markerType) {
1104
		markerType = HibernateProxyHelper.deproxy(markerType);
1105
		return markerType.getClass().getName() + EDIT_MARKER_TYPE_PREFIX;
1106
	}
1107

    
1108
	/**
1109
	 * <p>
1110
	 * setEditMarkerTypePreference
1111
	 * </p>
1112
	 *
1113
	 * @param input
1114
	 *            a {@link org.eclipse.ui.IEditorInput} object.
1115
	 * @param markerType
1116
	 *            a {@link eu.etaxonomy.cdm.model.common.MarkerType} object.
1117
	 * @param edit
1118
	 *            a boolean.
1119
	 */
1120
	public static void setEditMarkerTypePreference(MarkerType markerType,
1121
			boolean edit) {
1122
		setBooleanValue(
1123
				getMarkerTypeEditingPreferenceKey(markerType), edit);
1124
	}
1125

    
1126
	/**
1127
	 * @return
1128
	 */
1129
	public static DerivedUnitFacadeConfigurator getDerivedUnitConfigurator() {
1130
		DerivedUnitFacadeConfigurator configurator = DerivedUnitFacadeConfigurator
1131
				.NewInstance();
1132
		configurator.setMoveDerivedUnitMediaToGallery(true);
1133
		configurator.setMoveFieldObjectMediaToGallery(true);
1134
		return configurator;
1135
	}
1136

    
1137
	/**
1138
	 * This method will write language properties to the config.ini located in the configuration folder
1139
	 * of the Taxonomic Ediitor. <b>This method is only used to set the default language for Taxonomic Editor.</b>
1140
	 *
1141
	 * @param setLanguage 0 is for german and 1 for english.
1142
	 * @throws IOException
1143
	 */
1144
    public void writePropertyToConfigFile(int setLanguage) throws IOException {
1145
        File file = org.eclipse.core.runtime.preferences.ConfigurationScope.INSTANCE.getLocation().toFile();
1146
        //give warning to user if the directory has no write access
1147
        if(file == null){
1148
            throw new IOException();
1149
        }
1150
        Properties properties = load(file.getAbsolutePath()+"/config.ini");
1151
        switch(setLanguage){
1152
        case 0:
1153
            properties.setProperty("osgi.nl", "de");
1154
            setStringValue(IPreferenceKeys.DEFAULT_LANGUAGE_EDITOR, "de");
1155
            break;
1156
        case 1:
1157
            properties.setProperty("osgi.nl", "en");
1158
            setStringValue(IPreferenceKeys.DEFAULT_LANGUAGE_EDITOR, "en");
1159
            break;
1160
        default:
1161
            break;
1162
        }
1163
        save(file+"/config.ini", properties);
1164
    }
1165

    
1166
    /**
1167
     * This method loads a property from a given file and returns it.
1168
     *
1169
     * @param filename
1170
     * @return
1171
     * @throws IOException
1172
     */
1173
    private Properties load(String filename) throws IOException {
1174
        FileInputStream in = new FileInputStream(filename);
1175
        Properties prop = new Properties();
1176
        prop.load(in);
1177
        in.close();
1178
        return prop;
1179
    }
1180

    
1181
    /**
1182
     * This method saves a property to the specified file.
1183
     *
1184
     * @param filename
1185
     * @param properties
1186
     * @throws IOException
1187
     */
1188
    private void save(String filename, Properties properties) throws IOException{
1189
        FileOutputStream fos =  new FileOutputStream(filename);
1190
        properties.store(fos, "");
1191
        fos.close();
1192
    }
1193

    
1194
    /**
1195
     * Saves a list of P2 Metadata Repositories as string with specified delimiters
1196
     *
1197
     * @param p2Repos
1198
     */
1199
    public static void setP2Repositories(List<MetadataRepositoryElement> p2Repos) {
1200
        StringBuilder sb = new StringBuilder();
1201
        for(MetadataRepositoryElement p2Repo : p2Repos) {
1202
            sb.append(P2_REPOSITORIES_DELIM);
1203
            if(p2Repo.getName() == null || p2Repo.getName().isEmpty()) {
1204
                sb.append("-");
1205
            } else {
1206
                sb.append(p2Repo.getName());
1207
            }
1208
            sb.append(P2_REPOSITORY_FIELDS_DELIM);
1209
            sb.append(p2Repo.getLocation().toString());
1210
            sb.append(P2_REPOSITORY_FIELDS_DELIM);
1211
            sb.append(String.valueOf(p2Repo.isEnabled()));
1212
        }
1213
        getPreferenceStore().setValue(P2_REPOSITORY_LIST, sb.toString());
1214
    }
1215

    
1216

    
1217
    /**
1218
     * Retrieves a list of previously saved P2 repositories
1219
     *
1220
     * @return
1221
     */
1222
    public static List<MetadataRepositoryElement> getP2Repositories() {
1223
        List<MetadataRepositoryElement> p2Repos = new ArrayList<MetadataRepositoryElement>();
1224
        String p2ReposPref =  getStringValue(P2_REPOSITORY_LIST);
1225
        if(p2ReposPref != null && !p2ReposPref.isEmpty()) {
1226
            StringTokenizer p2ReposPrefST = new StringTokenizer(p2ReposPref,P2_REPOSITORIES_DELIM);
1227

    
1228
            while(p2ReposPrefST.hasMoreTokens()) {
1229
                String p2RepoStr = p2ReposPrefST.nextToken();
1230
                StringTokenizer p2ReposStrST = new StringTokenizer(p2RepoStr,P2_REPOSITORY_FIELDS_DELIM);
1231
                if(p2ReposStrST.countTokens()==3) {
1232
                    String nickname = p2ReposStrST.nextToken();
1233
                    URI uri = null;
1234
                    try {
1235
                        uri = new URI(p2ReposStrST.nextToken());
1236
                    } catch (URISyntaxException e) {
1237
                        continue;
1238
                    }
1239
                    boolean enabled = Boolean.parseBoolean(p2ReposStrST.nextToken());
1240
                    MetadataRepositoryElement mre = new MetadataRepositoryElement(null, uri, true);
1241
                    mre.setNickname(nickname);
1242
                    mre.setEnabled(enabled);
1243
                    p2Repos.add(mre);
1244
                }
1245
            }
1246
        }
1247

    
1248
        return p2Repos;
1249
    }
1250

    
1251
    /**
1252
     * enables/disables nested composite. <br>
1253
     *
1254
     * @param ctrl - Composite to be en-/disabeld
1255
     * @param enabled - boolean
1256
     */
1257
    public static void recursiveSetEnabled(Control ctrl, boolean enabled) {
1258
        if (ctrl instanceof Composite) {
1259
            Composite comp = (Composite) ctrl;
1260
            for (Control c : comp.getChildren()) {
1261
                recursiveSetEnabled(c, enabled);
1262
            }
1263
        } else {
1264
            ctrl.setEnabled(enabled);
1265
        }
1266
    }
1267

    
1268

    
1269

    
1270

    
1271
    /**
1272
     * @param orderActivated
1273
     */
1274
    public static void setSortNodes(NavigatorOrderEnum nodesOrder) {
1275
        setStringValue(SORT_NODES, nodesOrder.key);
1276

    
1277
    }
1278

    
1279
    /**
1280
     * @param orderActivated
1281
     */
1282
    public static NavigatorOrderEnum getSortNodes() {
1283
        return NavigatorOrderEnum.valueOf(getStringValue(SORT_NODES));
1284

    
1285
    }
1286

    
1287
    /**
1288
     * @param orderActivated
1289
     */
1290
    public static boolean isNodesSortedNaturally() {
1291
        NavigatorOrderEnum value = NavigatorOrderEnum.valueOf(getStringValue(SORT_NODES));
1292
        return value.equals(NavigatorOrderEnum.NaturalOrder);
1293

    
1294
    }
1295

    
1296
    /**
1297
     * @param orderActivated
1298
     */
1299
    public static boolean isNodesSortedByName() {
1300
        NavigatorOrderEnum value = NavigatorOrderEnum.valueOf(getStringValue(SORT_NODES));
1301
        return value.equals(NavigatorOrderEnum.AlphabeticalOrder);
1302

    
1303
    }
1304

    
1305
    /**
1306
     * @param orderActivated
1307
     */
1308
    public static boolean isNodesSortedByNameAndRank() {
1309
        NavigatorOrderEnum value = NavigatorOrderEnum.valueOf(getStringValue(SORT_NODES));
1310
        return value.equals(NavigatorOrderEnum.RankAndNameOrder);
1311

    
1312
    }
1313
	/**
1314
	 * <p>
1315
	 * setStoreNavigatorState
1316
	 * </p>
1317
	 *
1318
	 * @param selection
1319
	 *            a boolean.
1320
	 */
1321
	public static boolean isStoreNavigatorState() {
1322
		return getBooleanValue(RESTORE_NAVIGATOR_STATE);
1323

    
1324
	}
1325

    
1326
	/**
1327
	 * <p>
1328
	 * setStoreNavigatorState
1329
	 * </p>
1330
	 *
1331
	 * @param selection
1332
	 *            a boolean.
1333
	 */
1334
	public static void setStoreNavigatorState(boolean selection) {
1335
		setBooleanValue(RESTORE_NAVIGATOR_STATE, selection);
1336

    
1337
	}
1338

    
1339
    /**
1340
     * @return
1341
     */
1342
    public static boolean isShowUpWidgetIsDisposedMessages() {
1343
       return getBooleanValue(IS_SHOW_UP_WIDGET_IS_DISPOSED);
1344
    }
1345
    public static void setShowUpWidgetIsDisposedMessages(boolean selection) {
1346
        setBooleanValue(IS_SHOW_UP_WIDGET_IS_DISPOSED, selection);
1347
    }
1348

    
1349
    /**
1350
     * @return
1351
     */
1352
    public static boolean isShowIdInVocabularyInChecklistEditor() {
1353
        String area_display = getStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey());
1354
        if (area_display.equals(TermDisplayEnum.IdInVocabulary.getKey())) {
1355
            return true;
1356
        }else{
1357
            return false;
1358
        }
1359
    }
1360
    public static boolean isShowSymbol1InChecklistEditor() {
1361
        String area_display = getStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey());
1362
        if (area_display.equals(TermDisplayEnum.Symbol1.getKey())) {
1363
            return true;
1364
        }else{
1365
            return false;
1366
        }
1367
     }
1368
    public static boolean isShowSymbol2InChecklistEditor() {
1369
        String area_display = getStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey());
1370
        if (area_display.equals(TermDisplayEnum.Symbol2.getKey())) {
1371
            return true;
1372
        }else{
1373
            return false;
1374
        }
1375
     }
1376
    public static void setAreaDisplayInChecklistEditor(String selection) {
1377
        setStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey(), selection);
1378
    }
1379

    
1380
    public static void setOwnDescriptionForChecklistEditor(boolean selection) {
1381
        setBooleanValue(PreferencePredicate.OwnDescriptionForDistributionEditor.getKey(), selection);
1382
    }
1383

    
1384
    public static boolean isOwnDescriptionForChecklistEditor() {
1385
        return getBooleanValue(PreferencePredicate.OwnDescriptionForDistributionEditor.getKey());
1386
    }
1387

    
1388
    /**
1389
     * @return
1390
     */
1391
    public static String displayAreaInChecklistEditor() {
1392
        String result = getStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey());
1393
        if (StringUtils.isBlank(result)){
1394
            return ((TermDisplayEnum) PreferencePredicate.DisplayOfAreasInDistributionEditor.getDefaultValue()).getKey();
1395
        }
1396
       return result;
1397
    }
1398

    
1399
    /**
1400
     * @return
1401
     */
1402
    public static String displayStatusInChecklistEditor() {
1403
        String result = getStringValue(PreferencePredicate.DisplayOfStatus.getKey());
1404
        if (StringUtils.isBlank(result)){
1405
            return((TermDisplayEnum) PreferencePredicate.DisplayOfStatus.getDefaultValue()).getKey();
1406
        }
1407
       return result;
1408
    }
1409
    public static void setDisplayStatusInChecklistEditor(String selection) {
1410
        setStringValue(PreferencePredicate.DisplayOfStatus.getKey(), selection);
1411

    
1412
    }
1413

    
1414
    /**
1415
     * @return
1416
     */
1417
    public static boolean isShowRankInChecklistEditor() {
1418
        return getBooleanValue(PreferencePredicate.ShowRankInDistributionEditor.getKey());
1419
    }
1420
    public static void setShowRankInChecklistEditor(boolean selection) {
1421
       setBooleanValue(PreferencePredicate.ShowRankInDistributionEditor.getKey(), selection);
1422
    }
1423

    
1424
    /**
1425
     * @param object
1426
     * @param b
1427
     * @return
1428
     */
1429
    public static NameDetailsConfigurator getPreferredNameDetailsConfiguration( boolean local) {
1430
        NameDetailsConfigurator config = new NameDetailsConfigurator(true);
1431
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1432
        CdmPreference preference = null;
1433
        String value;
1434
        if (!local) {
1435
            preference = cache.get(PreferencePredicate.NameDetailsView.getKey());
1436
            if (preference == null){
1437
                return null;
1438
            }
1439

    
1440
        //    setBooleanValue(ALLOW_OVERRIDE_NAME_DETAILS, preference.isAllowOverride());
1441
            value = preference.getValue();
1442
            config.setAllowOverride(preference.isAllowOverride());
1443
            //the preference value is build like this:
1444
            //<section1>:true;<section2>:false....
1445
        }else{
1446
            value = getStringValue(PreferencePredicate.NameDetailsView.getKey(), local);
1447
        }
1448
        String [] sections = value.split(";");
1449
        Map<String, Boolean> sectionMap = new HashMap<String, Boolean>();
1450
        String[] sectionValues;
1451
        for (String sectionValue: sections){
1452
            sectionValues = sectionValue.split(":");
1453
            sectionMap.put(sectionValues[0], Boolean.valueOf(sectionValues[1]));
1454
        }
1455

    
1456
        config.setSimpleDetailsViewActivated(getValue(sectionMap, "simpleViewActivated"));
1457

    
1458
        config.setTaxonSectionActivated(getValue(sectionMap, "taxon"));
1459

    
1460
        config.setSecDetailsActivated(getValue(sectionMap, "taxon.SecDetails"));
1461
        config.setSecEnabled(getValue(sectionMap, "taxon.SecEnabled"));
1462

    
1463
        config.setLSIDActivated(getValue(sectionMap, "lsid"));
1464

    
1465
        config.setNomenclaturalCodeActived(getValue(sectionMap, "nc"));
1466

    
1467
        config.setAppendedPhraseActivated(getValue(sectionMap, "ap"));
1468

    
1469
        config.setRankActivated(getValue(sectionMap, "rank"));
1470

    
1471
        config.setAtomisedEpithetsActivated(getValue(sectionMap, "atomisedEpithets"));
1472

    
1473
        config.setAuthorshipSectionActivated(getValue(sectionMap,"author"));
1474

    
1475
        config.setNomenclaturalReferenceSectionActivated(sectionMap.get("nomRef"));
1476

    
1477
        config.setNomenclaturalStatusSectionActivated(getValue(sectionMap, "nomStat"));
1478

    
1479
        config.setProtologueActivated(getValue(sectionMap,"protologue"));
1480

    
1481
        config.setTypeDesignationSectionActivated(getValue(sectionMap,"typeDes"));
1482

    
1483
        config.setNameRelationsSectionActivated(getValue(sectionMap,"nameRelation"));
1484

    
1485
            config.setHybridActivated(getValue(sectionMap,"hybrid"));
1486

    
1487
        return config;
1488
    }
1489

    
1490
    public static NameDetailsConfigurator getPreferredNameDetailsConfiguration() {
1491
        NameDetailsConfigurator config = new NameDetailsConfigurator(true);
1492

    
1493
        String value;
1494

    
1495
        value = getStringValue(PreferencePredicate.NameDetailsView.getKey(), false);
1496

    
1497
        String [] sections = value.split(";");
1498
        Map<String, Boolean> sectionMap = new HashMap<String, Boolean>();
1499
        String[] sectionValues;
1500
        for (String sectionValue: sections){
1501
            sectionValues = sectionValue.split(":");
1502
            sectionMap.put(sectionValues[0], Boolean.valueOf(sectionValues[1]));
1503
        }
1504

    
1505
        config.setSimpleDetailsViewActivated(getValue(sectionMap, "simpleViewActivated"));
1506

    
1507
        config.setTaxonSectionActivated(getValue(sectionMap, "taxon"));
1508

    
1509
        config.setSecDetailsActivated(getValue(sectionMap, "taxon.SecDetails"));
1510
        config.setSecEnabled(getValue(sectionMap, "taxon.SecEnabled"));
1511

    
1512
        config.setLSIDActivated(getValue(sectionMap, "lsid"));
1513

    
1514
        config.setNomenclaturalCodeActived(getValue(sectionMap, "nc"));
1515

    
1516
        config.setAppendedPhraseActivated(getValue(sectionMap, "ap"));
1517

    
1518
        config.setRankActivated(getValue(sectionMap, "rank"));
1519

    
1520
        config.setAtomisedEpithetsActivated(getValue(sectionMap, "atomisedEpithets"));
1521

    
1522
        config.setAuthorshipSectionActivated(getValue(sectionMap,"author"));
1523

    
1524
        config.setNomenclaturalReferenceSectionActivated(sectionMap.get("nomRef"));
1525

    
1526
        config.setNomenclaturalStatusSectionActivated(getValue(sectionMap, "nomStat"));
1527

    
1528
        config.setProtologueActivated(getValue(sectionMap,"protologue"));
1529

    
1530
        config.setTypeDesignationSectionActivated(getValue(sectionMap,"typeDes"));
1531

    
1532
        config.setNameRelationsSectionActivated(getValue(sectionMap,"nameRelation"));
1533

    
1534
            config.setHybridActivated(getValue(sectionMap,"hybrid"));
1535

    
1536
        return config;
1537
    }
1538

    
1539

    
1540
    /**
1541
     * @param object
1542
     * @param b
1543
     * @return
1544
     */
1545
    public static void setPreferredNameDetailsConfiguration(NameDetailsConfigurator config, boolean local) {
1546
        CdmPreference preference = null;
1547

    
1548
        if (!local) {
1549
            preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.NameDetailsView, config.toString());
1550

    
1551
            setPreferenceToDB(preference);
1552
        }
1553
        else{
1554
            setStringValue(PreferencePredicate.NameDetailsView.getKey(), config.toString());
1555
        }
1556

    
1557

    
1558
    }
1559

    
1560
    private static Boolean getValue(Map<String, Boolean> sectionMap, String string) {
1561
		if (sectionMap.containsKey(string)){
1562
			return sectionMap.get(string);
1563
		}else{
1564
			return true;
1565
		}
1566

    
1567
	}
1568

    
1569

    
1570

    
1571
    /**
1572
     * <p>
1573
     * setAbcdConfigurator
1574
     * </p>
1575
     *
1576
     * @param preferredConfiguration
1577
     *            a {@link eu.etaxonomy.cdm.io.specimen.abcd206.in.Abcd206ImportConfigurator}
1578
     *            object.
1579
     */
1580
    public static Abcd206ImportConfigurator getDBAbcdImportConfigurationPreference() {
1581

    
1582
        Abcd206ImportConfigurator config = Abcd206ImportConfigurator.NewInstance(null,null);
1583
        ICdmRepository controller;
1584
        controller = CdmStore.getCurrentApplicationConfiguration();
1585
        PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AbcdImportConfig);
1586
        CdmPreference preference = null;
1587
        if (controller == null){
1588
            return null;
1589
        }
1590
        preference = controller.getPreferenceService().find(key);
1591
        if (preference == null){
1592
            return config;
1593
         } else{
1594
             String configString = preference.getValue();
1595
             String[] configArray = configString.split(";");
1596

    
1597
             for (String configItem: configArray){
1598
                 String[] keyValue = configItem.split(":");
1599
                 String keyString = keyValue[0];
1600
                 String valueString = null;
1601
                 if (keyValue.length>1){
1602
                      valueString = keyValue[1];
1603
                 }
1604
                 if (keyString.equals("ignoreImportOfExistingSpecimen")){
1605
                     config.setIgnoreImportOfExistingSpecimen(Boolean.valueOf(valueString));
1606
                 }else if (keyString.equals("addIndividualsAssociationsSuchAsSpecimenAndObservations")){
1607
                     config.setAddIndividualsAssociationsSuchAsSpecimenAndObservations(Boolean.valueOf(valueString));
1608
                 }else if (keyString.equals("reuseExistingTaxaWhenPossible")){
1609
                     config.setReuseExistingTaxaWhenPossible(Boolean.valueOf(valueString));
1610
                 }else if (keyString.equals("ignoreAuthorship")){
1611
                     config.setIgnoreAuthorship(Boolean.valueOf(valueString));
1612
                 }else if (keyString.equals("addMediaAsMediaSpecimen")){
1613
                     config.setAddMediaAsMediaSpecimen(Boolean.valueOf(valueString));
1614
                 }else if (keyString.equals("reuseExistingMetaData")){
1615
                     config.setReuseExistingMetaData(Boolean.valueOf(valueString));
1616
                 }else if (keyString.equals("reuseExistingDescriptiveGroups")){
1617
                     config.setReuseExistingDescriptiveGroups(Boolean.valueOf(valueString));
1618
                 }else if (keyString.equals("allowReuseOtherClassifications")){
1619
                     config.setAllowReuseOtherClassifications(Boolean.valueOf(valueString));
1620
                 }else if (keyString.equals("deduplicateReferences")){
1621
                     config.setDeduplicateReferences(Boolean.valueOf(valueString));
1622
                 }else if (keyString.equals("deduplicateClassifications")){
1623
                     config.setDeduplicateClassifications(Boolean.valueOf(valueString));
1624
                 }else if (keyString.equals("moveNewTaxaToDefaultClassification")){
1625
                     config.setMoveNewTaxaToDefaultClassification(Boolean.valueOf(valueString));
1626
                 }else if (keyString.equals("mapUnitIdToCatalogNumber")){
1627
                     config.setMapUnitIdToCatalogNumber(Boolean.valueOf(valueString));
1628
                 }else if (keyString.equals("mapUnitIdToAccessionNumber")){
1629
                     config.setMapUnitIdToAccessionNumber(Boolean.valueOf(valueString));
1630
                 }else if (keyString.equals("mapUnitIdToBarcode")){
1631
                     config.setMapUnitIdToBarcode(Boolean.valueOf(valueString));
1632
                 }else if (keyString.equals("overwriteExistingSpecimens")){
1633
                     config.setOverwriteExistingSpecimens(Boolean.valueOf(valueString));
1634
                 }else if (keyString.equals("nomenclaturalCode")){
1635
                         config.setNomenclaturalCode(NomenclaturalCode.fromString(valueString));
1636
                 }else{
1637
                     logger.debug("This key of the abcd configurator needs to be added to the transformer: " + keyString);
1638
                 }
1639

    
1640
             }
1641
        }
1642
        return config;
1643
    }
1644

    
1645
    public static Abcd206ImportConfigurator getLocalAbcdImportConfigurator(){
1646
       Abcd206ImportConfigurator config = Abcd206ImportConfigurator.NewInstance(null,null);
1647

    
1648
        config.setAddIndividualsAssociationsSuchAsSpecimenAndObservations(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_ADD_INDIVIDUALS_ASSOCIATIONS_SUCH_AS_SPECIMEN_AND_OBSERVATIONS));
1649

    
1650
        config.setAddMediaAsMediaSpecimen(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_ADD_MEDIA_AS_MEDIASPECIMEN));
1651

    
1652
        config.setAllowReuseOtherClassifications(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_ALLOW_REUSE_OTHER_CLASSIFICATIONS));
1653
        config.setDeduplicateClassifications(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_DEDUPLICATE_CLASSIFICATIONS));
1654
        config.setDeduplicateReferences(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_DEDUPLICATE_REFERENCES));
1655
        config.setRemoveCountryFromLocalityText(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_REMOVE_COUNTRY_FROM_LOCALITY_TEXT));
1656
        config.setGetSiblings(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_DO_SIBLINGS));
1657
        config.setIgnoreAuthorship(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_IGNORE_AUTHORSHIP));
1658
        config.setIgnoreImportOfExistingSpecimen(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_IGNORE_IMPORT_OF_EXISTING_SPECIMEN));
1659
        config.setMapUnitIdToAccessionNumber(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_MAP_UNIT_ID_TO_ACCESSION_NUMBER));
1660
        config.setMapUnitIdToBarcode(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_MAP_UNIT_ID_TO_BARCODE));
1661
        config.setMapUnitIdToCatalogNumber(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_MAP_UNIT_ID_TOCATALOG_NUMBER));
1662
        config.setMoveNewTaxaToDefaultClassification(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_MOVE_NEW_TAXA_TO_DEFAULT_CLASSIFICATION));
1663
        config.setOverwriteExistingSpecimens(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_OVERWRITE_EXISTING_SPECIMEN));
1664
        config.setReuseExistingDescriptiveGroups(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_REUSE_EXISTING_DESCRIPTIVE_GROUPS));
1665
        config.setReuseExistingMetaData(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_REUSE_EXISTING_META_DATA));
1666
        config.setReuseExistingTaxaWhenPossible(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_REUSE_EXISTING_TAXA_WHEN_POSSIBLE));
1667
        config.setNomenclaturalCode(NomenclaturalCode.getByKey(getStringValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_NOMENCLATURAL_CODE)));
1668

    
1669
        return config;
1670

    
1671
    }
1672

    
1673

    
1674
    public static void updateAbcdImportConfigurationPreference() {
1675
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1676
        CdmPreference pref = cache.get(PreferencePredicate.AbcdImportConfig.getKey());
1677

    
1678
        if (!getBooleanValue(prefOverrideKey(PreferencePredicate.AbcdImportConfig.getKey())) || !pref.isAllowOverride()){
1679
            resetToDBPreferenceAbcdCOnfigurator();
1680

    
1681
        }
1682
    }
1683

    
1684
    public static void resetToDBPreferenceAbcdCOnfigurator(){
1685
        Abcd206ImportConfigurator config = getDBAbcdImportConfigurationPreference();
1686
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_ADD_INDIVIDUALS_ASSOCIATIONS_SUCH_AS_SPECIMEN_AND_OBSERVATIONS, config.isAddIndividualsAssociationsSuchAsSpecimenAndObservations());
1687
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_ADD_MEDIA_AS_MEDIASPECIMEN, config.isAddMediaAsMediaSpecimen());
1688

    
1689
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_ALLOW_REUSE_OTHER_CLASSIFICATIONS, config.isAllowReuseOtherClassifications());
1690
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_DEDUPLICATE_CLASSIFICATIONS, config.isDeduplicateClassifications());
1691
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_DEDUPLICATE_REFERENCES, config.isDeduplicateReferences());
1692

    
1693
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_DO_SIBLINGS, config.isGetSiblings());
1694
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_IGNORE_AUTHORSHIP, config.isIgnoreAuthorship());
1695
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_IGNORE_IMPORT_OF_EXISTING_SPECIMEN, config.isIgnoreImportOfExistingSpecimen());
1696
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_MAP_UNIT_ID_TO_ACCESSION_NUMBER, config.isMapUnitIdToAccessionNumber());
1697
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_MAP_UNIT_ID_TO_BARCODE, config.isMapUnitIdToBarcode());
1698
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_MAP_UNIT_ID_TOCATALOG_NUMBER, config.isMapUnitIdToCatalogNumber());
1699
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_MOVE_NEW_TAXA_TO_DEFAULT_CLASSIFICATION, config.isMoveNewTaxaToDefaultClassification());
1700
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_OVERWRITE_EXISTING_SPECIMEN, config.isOverwriteExistingSpecimens());
1701
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_REUSE_EXISTING_DESCRIPTIVE_GROUPS, config.isReuseExistingDescriptiveGroups());
1702
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_REUSE_EXISTING_META_DATA, config.isReuseExistingMetaData());
1703
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_REUSE_EXISTING_TAXA_WHEN_POSSIBLE, config.isReuseExistingTaxaWhenPossible());
1704
        if (config.getNomenclaturalCode() != null){
1705
            setStringValue(ABCD_IMPORT_CONFIGURATOR_NOMENCLATURAL_CODE, config.getNomenclaturalCode().getKey());
1706
        }
1707
    }
1708

    
1709

    
1710

    
1711

    
1712

    
1713

    
1714

    
1715
/**
1716
 * @return
1717
 */
1718
public static boolean isSortTaxaByRankAndName() {
1719

    
1720
    return getBooleanValue(IPreferenceKeys.SORT_TAXA_BY_RANK_AND_NAME);
1721
}
1722

    
1723
/**
1724
 * @return
1725
 */
1726
public static String getSortNamedAreasInDistributionEditor() {
1727

    
1728
    return getStringValue(PreferencePredicate.AreasSortedInDistributionEditor.getKey());
1729
}
1730

    
1731
public static void setSortNamedAreasInDistributionEditor(String isSortByVocabularyOrder) {
1732
    setStringValue(PreferencePredicate.AreasSortedInDistributionEditor.getKey(), isSortByVocabularyOrder);
1733

    
1734
}
1735

    
1736
/**
1737
 * <p>
1738
 * setPreferredNamedAreasForDistributionEditor
1739
 * </p>
1740
 *
1741
 * @param saveCheckedElements
1742
 * @param saveGrayedElements
1743
 */
1744
public static void setLastSelectedReference(
1745
        List<String> lastSelectedReferences) {
1746

    
1747
        setStringValue(PreferencesUtil.LAST_SELECTED_REFERENCES, lastSelectedReferences.toString());
1748
    }
1749

    
1750
/**
1751
 * <p>
1752
 * setPreferredNamedAreasForDistributionEditor
1753
 * </p>
1754
 *
1755
 * @param saveCheckedElements
1756
 * @param saveGrayedElements
1757
 */
1758
public static List<String> getLastSelectedReferences() {
1759

    
1760
        //IPreferenceStore preferenceStore = PreferencesUtil.getPreferenceStore();
1761
        String lastSelected = getStringValue(PreferencesUtil.LAST_SELECTED_REFERENCES);
1762
        List<String> result = new ArrayList<>();
1763
        if (!StringUtils.isBlank(lastSelected)){
1764
            Collections.addAll(result, lastSelected.substring(1,lastSelected.length()-1).split(", "));
1765
        }
1766
        return result;
1767
    }
1768

    
1769

    
1770
/**
1771
 * <p>
1772
 * setPreferredNamedAreasForDistributionEditor
1773
 * </p>
1774
 *
1775
 * @param saveCheckedElements
1776
 * @param saveGrayedElements
1777
 */
1778
public static void setPreferredNamedAreasForDistributionEditor(
1779
        String saveCheckedElements, String saveGrayedElements, boolean local) {
1780
    if (local){
1781
        setStringValue(PreferencePredicate.AvailableDistributionAreaTerms.getKey(), saveCheckedElements);
1782

    
1783
    }
1784
    else{
1785
        CdmPreference preference = null;
1786

    
1787
        if (saveCheckedElements == null){
1788
            preference = getPreferenceFromDB(PreferencePredicate.AvailableDistributionAreaTerms);
1789

    
1790
            if (preference == null){
1791
                return ;
1792
            } else{
1793
                setStringValue(PreferencePredicate.AvailableDistributionAreaTerms.getKey(),
1794
                        saveCheckedElements);
1795
                preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AvailableDistributionAreaTerms, saveCheckedElements);
1796
                setPreferenceToDB(preference);
1797

    
1798
            }
1799
        } else{
1800
           preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AvailableDistributionAreaTerms, saveCheckedElements);
1801
           setPreferenceToDB(preference);
1802
           setStringValue(PreferencePredicate.AvailableDistributionAreaTerms.getKey(),
1803
                    saveCheckedElements);
1804

    
1805
        }
1806
    }
1807

    
1808
}
1809

    
1810
/**
1811
 * @param saveCheckedElements
1812
 * @param saveCheckedElements2
1813
 * @param b
1814
 */
1815
public static void setPreferredVocabulariesForDistributionEditor(String saveCheckedElements,
1816
        boolean local, boolean isOverride) {
1817
    if (local){
1818
      setStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(), saveCheckedElements);
1819
      setBooleanValue(prefOverrideKey(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey()), isOverride);
1820
    }
1821
    else{
1822
        ICdmRepository controller;
1823
        CdmPreference preference = null;
1824

    
1825
        if (saveCheckedElements == null){
1826
            preference = getPreferenceFromDB(PreferencePredicate.AvailableDistributionAreaVocabularies);
1827

    
1828
            if (preference == null){
1829
                return ;
1830
            } else{
1831
                setStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(),
1832
                        saveCheckedElements);
1833
                preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AvailableDistributionAreaVocabularies, saveCheckedElements);
1834
                preference.setAllowOverride(isOverride);
1835
                setPreferenceToDB(preference);
1836
            }
1837
        } else{
1838
            preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AvailableDistributionAreaVocabularies, saveCheckedElements);
1839
            preference.setAllowOverride(isOverride);
1840
            setPreferenceToDB(preference);
1841
            setStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(),
1842
                    saveCheckedElements);
1843

    
1844
        }
1845
    }
1846
}
1847

    
1848

    
1849
/**
1850
 * @param saveCheckedElements
1851
 * @param saveCheckedElements2
1852
 * @param b
1853
 */
1854
public static String getPreferredVocabulariesForDistributionEditor(boolean local) {
1855
    if (local){
1856

    
1857
        String pref = getStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(), local);
1858
        return pref;
1859
    }
1860
    else{
1861
        CdmPreference preference = null;
1862
        preference = getPreferenceFromDB(PreferencePredicate.AvailableDistributionAreaVocabularies);
1863
        if (preference == null){
1864
            return null;
1865
        } else{
1866
            return preference.getValue();
1867
        }
1868

    
1869
    }
1870
}
1871

    
1872
public static List<UUID> createUUIDListFromStringPref(String prefKey) {
1873
    String prefValue = PreferencesUtil.getStringValue(prefKey);
1874
    String[] stringArray = prefValue.split(";");
1875
    List<UUID> uuidList = new ArrayList();
1876
    for (String uuid: stringArray){
1877
        if (!StringUtils.isBlank(uuid)){
1878
            uuidList.add(UUID.fromString(uuid));
1879
        }
1880
    }
1881
    return uuidList;
1882
}
1883

    
1884
public static boolean getFilterCommonNameReferences(){
1885
    return getBooleanValue(PreferencesUtil.FILTER_COMMON_NAME_REFERENCES);
1886
}
1887

    
1888
/**
1889
 *
1890
 */
1891
public static void updateDBPreferences() {
1892
    CdmPreference preference = null;
1893
    CdmPreferenceCache cache = CdmPreferenceCache.instance();
1894
    cache.getAllTaxEditorDBPreferences();
1895

    
1896
    //ABCD Configurator
1897

    
1898
    updateAbcdImportConfigurationPreference();
1899

    
1900
    //Name Details
1901
    NameDetailsConfigurator config = getPreferredNameDetailsConfiguration(false);
1902
//    if (config != null ){
1903
//        if (!getBooleanValue(OVERRIDE_NAME_DETAILS) ||  !getBooleanValue(ALLOW_OVERRIDE_NAME_DETAILS)){
1904
//            setPreferredNameDetailsConfiguration(config, false);
1905
//        }
1906
//    }
1907

    
1908

    
1909

    
1910

    
1911

    
1912

    
1913

    
1914

    
1915
}
1916

    
1917
/**
1918
 * @param string
1919
 * @param saveCheckedElements
1920
 */
1921
public static void setPreferencesToDB(List<CdmPreference> preferences) {
1922

    
1923
    ICdmRepository controller;
1924
    try{
1925
        if(CdmStore.isActive()){
1926
            controller = CdmStore.getCurrentApplicationConfiguration();
1927
            for (CdmPreference preference: preferences){
1928
                controller.getPreferenceService().set(preference);
1929
            }
1930
        }
1931
    }catch(Exception e){
1932
        e.printStackTrace();
1933
    }
1934
}
1935

    
1936

    
1937

    
1938

    
1939

    
1940

    
1941

    
1942

    
1943
}
(27-27/41)