Project

General

Profile

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

    
10
package eu.etaxonomy.taxeditor.preference;
11

    
12
import java.io.File;
13
import java.io.FileInputStream;
14
import java.io.FileOutputStream;
15
import java.io.IOException;
16
import java.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.IDefinedTerm;
49
import eu.etaxonomy.cdm.model.common.ISimpleTerm;
50
import eu.etaxonomy.cdm.model.common.Language;
51
import eu.etaxonomy.cdm.model.common.MarkerType;
52
import eu.etaxonomy.cdm.model.common.TermBase;
53
import eu.etaxonomy.cdm.model.description.FeatureTree;
54
import eu.etaxonomy.cdm.model.metadata.CdmPreference;
55
import eu.etaxonomy.cdm.model.metadata.CdmPreference.PrefKey;
56
import eu.etaxonomy.cdm.model.metadata.IPreferencePredicate;
57
import eu.etaxonomy.cdm.model.metadata.PreferencePredicate;
58
import eu.etaxonomy.cdm.model.metadata.PreferenceSubject;
59
import eu.etaxonomy.cdm.model.metadata.TermDisplayEnum;
60
import eu.etaxonomy.cdm.model.name.NomenclaturalCode;
61
import eu.etaxonomy.cdm.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
	private 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_"+ ((CdmRemoteSource)CdmStore.getActiveCdmSource()).toString();
116
    }
117

    
118
	/**
119
     * <p>
120
     * setStringValue
121
     * </p>
122
     *
123
     *
124
     **/
125
    public static void setStringValue(String name, String value) {
126
        getPreferenceStore().setValue(prefKey(name), value);
127
    }
128

    
129
    /**
130
     * <p>
131
     * setIntValue
132
     * </p>
133
     *
134
     *
135
     **/
136
    public static void setIntValue(String name, int value) {
137
        getPreferenceStore().setValue(prefKey(name), value);
138
    }
139

    
140
    /**
141
     * <p>
142
     * setBooleanValue
143
     * </p>
144
     *
145
     *
146
     **/
147
    public static void setBooleanValue(String name, boolean value) {
148
        getPreferenceStore().setValue(prefKey(name), value);
149
    }
150

    
151
    /**
152
     * <p>
153
     * setBooleanValue
154
     * </p>
155
     *
156
     *
157
     **/
158
    public static void setDoubleValue(String name, double value) {
159
        getPreferenceStore().setValue(prefKey(name), value);
160
    }
161

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

    
173
    /**
174
     * <p>
175
     * setFloatValue
176
     * </p>
177
     *
178
     *
179
     **/
180
    public static void setLongValue(String name, long value) {
181
        getPreferenceStore().setValue(prefKey(name), value);
182
    }
183

    
184
    /**
185
     * <p>
186
     * getStringValue
187
     * </p>
188
     *
189
     *
190
     **/
191
    public static String getStringValue(String name, boolean local) {
192

    
193
        String prefValue = getDBPreferenceValue(name);
194
        if (prefValue == null || local){
195
            String dbSpecific = prefKey(name);
196
            if (getPreferenceStore().contains(dbSpecific)){
197
                prefValue = getPreferenceStore().getString(dbSpecific);
198
            }else{
199
                prefValue = getPreferenceStore().
200
                        getString(name);
201
            }
202
        }
203
        return prefValue;
204

    
205
    }
206

    
207
    public static String getStringValue(String name){
208
        return getStringValue(name, false);
209
    }
210

    
211
    private static String getDBPreferenceValue(String name) {
212
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
213
        if (cache.get(name) != null){
214
            CdmPreference pref = cache.get(name);
215
            if (!pref.isAllowOverride() || !getBooleanValue(prefOverrideKey(name))){
216
                return pref.getValue();
217
            }
218
        }
219
        return null;
220
    }
221

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

    
248

    
249
    }
250

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

    
273
        }else{
274
            return getPreferenceStore().getBoolean(name);
275
        }
276

    
277
    }
278

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

    
305
    }
306

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

    
333
    }
334

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

    
362

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

    
392
    		if (preferenceValue == null){
393
    			preference = controller.getPreferenceService().find(key);
394
    			if (preference == null){
395
    				return null;
396
    			} else{
397
    			    setStringValue(PREFERRED_NOMENCLATURAL_CODE_KEY,
398
    				        preference.getValue());
399

    
400
    				return preference;
401
    			}
402
    		} else{
403
    			preference = CdmPreference.NewInstance(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.NomenclaturalCode, preferenceValue);
404
    			controller.getPreferenceService().set(preference);
405

    
406
    		}
407
	    }
408
        return null;
409

    
410

    
411

    
412
	}
413

    
414
	/**
415
     * <p>
416
     * setPreferredNomenclaturalCode
417
     * </p>
418
     *
419
     * @param preferredCode
420
     *            a {@link eu.etaxonomy.cdm.model.name.NomenclaturalCode}
421
     *            object.
422
     */
423
    public static void setPreferredNomenclaturalCode(
424
        CdmPreference preference) {
425

    
426
        ICdmRepository controller;
427
        controller = CdmStore.getCurrentApplicationConfiguration();
428
        if (controller == null){
429
            return;
430
        }
431
        PrefKey key = null;
432
        try{
433
            key = CdmPreference.NewKey(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.NomenclaturalCode);
434
        }catch (Exception e){
435
            System.out.println(e.getStackTrace());
436
        }
437

    
438
        controller.getPreferenceService().set(preference);
439

    
440
    }
441

    
442

    
443
	public static NomenclaturalCode getPreferredNomenclaturalCode(){
444
	    if (getBooleanValue(prefOverrideKey(PreferencePredicate.NomenclaturalCode.getKey()))) {
445
            return getPreferredNomenclaturalCode(true);
446
        } else{
447
            return getPreferredNomenclaturalCode(false);
448
        }
449
	}
450

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

    
460
		CdmPreference pref = null;
461
		if (!useLocal){
462
		    pref = getPreferenceFromDB(PreferencePredicate.NomenclaturalCode);
463
		}
464

    
465
	    String preferredCode;
466
	    if(pref == null){
467
	    	preferredCode = getStringValue(
468
					PREFERRED_NOMENCLATURAL_CODE_KEY, true);
469

    
470
	    }else{
471
	    	preferredCode = pref.getValue();
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(EditorPreferencePredicate.ShowTaxonAssociations.getKey());
497
        return result;
498
    }
499

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

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

    
510
	public static boolean isCollectingAreaInGeneralSection(){
511
	    boolean result =  getBooleanValue(EditorPreferencePredicate.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 void setPreferenceToDB(CdmPreference preference){
534
        ICdmRepository controller;
535
        try{
536
            if(CdmStore.isActive()){
537
                controller = CdmStore.getCurrentApplicationConfiguration();
538
                controller.getPreferenceService().set(preference);
539
            }
540
        }catch(Exception e){
541
            e.printStackTrace();
542
        }
543

    
544
    }
545

    
546

    
547

    
548
	public static String getPreferredDefaultLangugae(){
549
	    String preferredLanguage = getStringValue(DEFAULT_LANGUAGE_EDITOR);
550
	    if(StringUtils.isNotEmpty(preferredLanguage) && StringUtils.isNotBlank(preferredLanguage)){
551
	        return preferredLanguage;
552
	    }
553
	    return null;
554
	}
555

    
556
	public static boolean isShowMediaPreview(){
557
        boolean isShowMediaPreview = getBooleanValue(SHOW_MEDIA_PREVIEW);
558
        return isShowMediaPreview;
559
    }
560

    
561
	/**
562
	 * Get the match strategy for the given class that was stored in preferences
563
	 * or the default strategy if it was not stored in preferences
564
	 *
565
	 * @param clazz
566
	 *            a {@link java.lang.Class} object.
567
	 * @return a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy} object.
568
	 */
569
	public static IMatchStrategy getMatchStrategy(Class<?> clazz) {
570
		String className = clazz.getName();
571
		if (getBooleanValue(MATCH_STRATEGY_PREFIX + className)) {
572
			IMatchStrategy matchStrategy = getDefaultMatchStrategy(clazz);
573

    
574
			//TODO CacheMatchers (or multiple field matchers in future) are missing here
575
			for (FieldMatcher fieldMatcher : matchStrategy.getMatching().getFieldMatchers(false)) {
576
				String fieldName = fieldMatcher.getPropertyName();
577
				String matchModeName = getStringValue(
578
						getMatchStrategyFieldName(className, fieldName));
579
				MatchMode matchMode = MatchMode.valueOf(matchModeName);
580
				try {
581
					matchStrategy.setMatchMode(fieldName, matchMode);
582
				} catch (MatchException e) {
583
					MessagingUtils.error(PreferencesUtil.class, e);
584
					throw new RuntimeException(e);
585
				}
586
			}
587

    
588
			return matchStrategy;
589
		}
590
		return getDefaultMatchStrategy(clazz);
591
	}
592

    
593
	/**
594
	 * Stores a matchStrategy into the preference store.
595
	 *
596
	 * @param matchStrategy
597
	 *            a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy}
598
	 *            object.
599
	 */
600
	public static void setMatchStrategy(IMatchStrategy matchStrategy) {
601
		String className = "ANY class"; //FIXME was: matchStrategy.getMatchClass().getName(); seems currently not in use
602
		setBooleanValue(MATCH_STRATEGY_PREFIX + className, true);
603

    
604
		List<FieldMatcher> fieldMatchers = matchStrategy.getMatching().getFieldMatchers(false);
605

    
606
		for (FieldMatcher fieldMatcher : fieldMatchers) {
607
			String fieldName = fieldMatcher.getPropertyName();
608
			setStringValue(
609
					getMatchStrategyFieldName(className, fieldName),
610
					fieldMatcher.getMatchMode().name());
611
		}
612
	}
613

    
614
	/**
615
	 * Helper method to create the preference property for a match field.
616
	 *
617
	 * @param className
618
	 * @param fieldName
619
	 * @return
620
	 */
621
	private static String getMatchStrategyFieldName(String className,
622
			String fieldName) {
623
		return MATCH_STRATEGY_PREFIX + className + "." + fieldName;
624
	}
625

    
626
	/**
627
	 * Returns the default match strategy for a given class.
628
	 *
629
	 * @param clazz
630
	 *            a {@link java.lang.Class} object.
631
	 * @return a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy} object.
632
	 */
633
	public static IMatchStrategy getDefaultMatchStrategy(Class clazz) {
634
		return DefaultMatchStrategy.NewInstance(clazz);
635
	}
636

    
637
	/**
638
	 * <p>
639
	 * getDateFormatPattern
640
	 * </p>
641
	 *
642
	 * @return a {@link java.lang.String} object.
643
	 */
644
	public static String getDateFormatPattern() {
645
		// TODO make this configurable in properties
646
		String pattern = "Y-M-d H:m";
647
		return pattern;
648
	}
649

    
650
	/**
651
	 * <p>
652
	 * addTermToPreferredTerms
653
	 * </p>
654
	 *
655
	 * @param term
656
	 *            a T object.
657
	 * @param <T>
658
	 *            a T object.
659
	 */
660
	public static <T extends TermBase> void addTermToPreferredTerms(T term) {
661

    
662
		// VocabularyEnum vocabulary =
663
		// VocabularyEnum.getVocabularyEnum(term.getClass());
664
		//
665
		// getPreferenceStore().setValue(getPreferenceKey(term),
666
		// VocabularyStore.getTermVocabulary(vocabulary).getTerms().contains(term));
667
		//
668
		// firePreferencesChanged(term.getClass());
669
	}
670

    
671
	/**
672
	 * Construct a unique key using the CdmBase object's uuid
673
	 *
674
	 * @param cdmBase
675
	 * @return
676
	 */
677
	private static String getPreferenceKey(ICdmBase cdmBase) {
678
		cdmBase = HibernateProxyHelper.deproxy(cdmBase);
679

    
680
		String key = cdmBase.getClass().getName().concat(".")
681
				.concat(cdmBase.getUuid().toString());
682
		if (key.contains("javassist")) {
683
			MessagingUtils.info("proxy");
684
		}
685
		return key;
686
	}
687

    
688
	/**
689
	 * Construct a unique key using the CdmBase object's uuid
690
	 *
691
	 * @param cdmBase
692
	 * @return
693
	 */
694
	public static String getPreferenceKey(ISimpleTerm simpleTerm) {
695
		simpleTerm = HibernateProxyHelper.deproxy(simpleTerm);
696
		String key = simpleTerm.getClass().getName().concat(".")
697
				.concat(simpleTerm.getUuid().toString());
698
		if (key.contains("javassist")) {
699
			MessagingUtils.warn(PreferencesUtil.class,
700
					"Trying to persist a preference based on a proxy class.");
701
		}
702
		return key;
703
	}
704

    
705

    
706

    
707
	/**
708
	 * Construct a unique key using the CdmBase object's uuid
709
	 *
710
	 * @param cdmBase
711
	 * @return
712
	 */
713
	public static String getPreferenceKey(IDefinedTerm definedTerm) {
714
		definedTerm = HibernateProxyHelper.deproxy(definedTerm);
715
		String key = definedTerm.getClass().getName().concat(".")
716
				.concat(definedTerm.getUuid().toString());
717
		if (key.contains("javassist")) {
718
			MessagingUtils.warn(PreferencesUtil.class,
719
					"Trying to persist a preference based on a proxy class.");
720
		}
721
		return key;
722
	}
723

    
724
	/**
725
	 * Retrieves search preferences from the preference store
726
	 *
727
	 * @return an {@link ITaxonServiceConfigurator} to pass to search methods
728
	 */
729
	public static IFindTaxaAndNamesConfigurator getSearchConfigurator() {
730
		IFindTaxaAndNamesConfigurator configurator = initializeSearchConfigurator();
731

    
732
		configurator.setDoTaxa(getBooleanValue(
733
				TAXON_SERVICE_CONFIGURATOR_TAXA));
734
		configurator.setDoSynonyms(getBooleanValue(
735
				TAXON_SERVICE_CONFIGURATOR_SYNONYMS));
736
		configurator.setDoNamesWithoutTaxa(getBooleanValue(
737
				TAXON_SERVICE_CONFIGURATOR_NAMES));
738
		configurator.setDoTaxaByCommonNames(getBooleanValue(
739
				TAXON_SERVICE_CONFIGURATOR_COMMON_NAMES));
740
		//configurator.setMatchMode(eu.etaxonomy.cdm.persistence.query.MatchMode.valueOf(getStringValue(TAXON_SERVICE_CONFIGURATOR_MATCH_MODE)));
741

    
742
		return configurator;
743
	}
744

    
745
	/**
746
	 * create new preferences, setting all search options to true
747
	 *
748
	 * @return a
749
	 *         {@link eu.etaxonomy.cdm.api.service.config.ITaxonServiceConfigurator}
750
	 *         object.
751
	 */
752
	public static IFindTaxaAndNamesConfigurator initializeSearchConfigurator() {
753
		IFindTaxaAndNamesConfigurator configurator = FindTaxaAndNamesConfiguratorImpl.NewInstance();
754

    
755
		configurator.setDoTaxa(true);
756
		configurator.setDoSynonyms(true);
757
		configurator.setDoNamesWithoutTaxa(true);
758
		configurator.setDoTaxaByCommonNames(true);
759

    
760
		configurator.setTaxonPropertyPath(Arrays.asList("$", "titleCache",
761
				"name", "name.$", "relationsFromThisTaxon.$"));
762

    
763
		configurator.setSynonymPropertyPath(Arrays.asList("$", "titleCache",
764
				"name", "name.$", "synonyms.relatedTo.*"));
765

    
766
		// DEFAULT VALUES
767
		// match mode is a simple like, actually all other match modes are kind
768
		// of bogus
769
		configurator
770
				.setMatchMode(eu.etaxonomy.cdm.persistence.query.MatchMode.ANYWHERE);
771
		// we set page number and size here as this should always be unlimited
772
		configurator.setPageNumber(0);
773
		// TODO currently limit results to 10000
774
		configurator.setPageSize(10000);
775
		setSearchConfigurator(configurator) ;
776
		return configurator;
777
	}
778

    
779
	/**
780
	 * Store search preferences
781
	 *
782
	 * @param configurator
783
	 *            a
784
	 *            {@link eu.etaxonomy.cdm.api.service.config.ITaxonServiceConfigurator}
785
	 *            object.
786
	 */
787
	public static void setSearchConfigurator(
788
			IFindTaxaAndNamesConfigurator configurator) {
789
		getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_TAXA,
790
				configurator.isDoTaxa());
791
		getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_SYNONYMS,
792
				configurator.isDoSynonyms());
793
		getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_NAMES,
794
				configurator.isDoNamesWithoutTaxa());
795
		getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_COMMON_NAMES,
796
				configurator.isDoTaxaByCommonNames());
797
	}
798

    
799
	/**
800
	 * <p>
801
	 * firePreferencesChanged
802
	 * </p>
803
	 *
804
	 * @param clazz
805
	 *            a {@link java.lang.Class} object.
806
	 */
807
	public static void firePreferencesChanged(Class clazz) {
808
		getPreferenceStore().firePropertyChangeEvent(PREFERRED_TERMS_CHANGE,
809
				null, clazz);
810
	}
811

    
812
	public static String createPreferenceString(String property){
813
	   return prefKey(property);
814

    
815
	}
816
	public static String createOverridePreferenceString(String property){
817
	       return prefOverrideKey(property);
818

    
819
	    }
820

    
821
	/**
822
	 * Set default values for preferences
823
	 */
824
	public static void setDefaults() {
825
		getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_TAXA, true);
826
		getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_SYNONYMS,
827
				true);
828
		getPreferenceStore().setDefault(createPreferenceString(EDIT_MAP_SERVICE_ACCES_POINT),
829
				"http://edit.africamuseum.be/edit_wp5/v1.2/rest_gen.php");
830
		//FIXME : changed default for SHOULD_CONNECT_AT_STARTUP to false (ticket 3828) until resolution
831
		getPreferenceStore().setDefault(createPreferenceString(SHOULD_CONNECT_AT_STARTUP), false);
832
		getPreferenceStore().setDefault(createPreferenceString(OPENURL_ACCESS_POINT),
833
				"http://www.biodiversitylibrary.org/openurl");
834
		getPreferenceStore().setDefault(createPreferenceString(OPENURL_IMAGE_MAX_WIDTH), "1000");
835
		getPreferenceStore().setDefault(createPreferenceString(OPENURL_IMAGE_MAX_HEIGHT), "1000");
836
		//Distribution Editor:
837
		getPreferenceStore().setDefault(createPreferenceString(EditorPreferencePredicate.DistributionEditorActivated.getKey()), Boolean.valueOf(EditorPreferencePredicate.DistributionEditorActivated.getDefaultValue().toString()));
838
		getPreferenceStore().setDefault(createPreferenceString(EditorPreferencePredicate.DisplayOfAreasInDistributionEditor.getKey()), EditorPreferencePredicate.DisplayOfAreasInDistributionEditor.getDefaultValue().toString());
839
		getPreferenceStore().setDefault(createPreferenceString(EditorPreferencePredicate.DisplayOfStatus.getKey()), EditorPreferencePredicate.DisplayOfStatus.getDefaultValue().toString());
840

    
841

    
842
		//Name Details
843
		getPreferenceStore().setDefault(createPreferenceString(SHOW_NAME_DETAILS_SECTION_ATOMISED_EPITHETS), true);
844
		getPreferenceStore().setDefault(createPreferenceString(SHOW_NAME_DETAILS_SECTION_AUTHORSHIP_CACHE), true);
845
		getPreferenceStore().setDefault(createPreferenceString(SHOW_NAME_DETAILS_SECTION_AUTHORSHIP), true);
846
		getPreferenceStore().setDefault(createPreferenceString(SHOW_NAME_DETAILS_SECTION_HYBRID), true);
847
		getPreferenceStore().setDefault(createPreferenceString(SHOW_NAME_DETAILS_SECTION_LSID), true);
848
		getPreferenceStore().setDefault(createPreferenceString(SHOW_NAME_DETAILS_SECTION_NAME_RELATIONSHIP), true);
849
		getPreferenceStore().setDefault(createPreferenceString(SHOW_NAME_DETAILS_SECTION_NAMECACHE), true);
850
		getPreferenceStore().setDefault(createPreferenceString(SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_CODE), true);
851
		getPreferenceStore().setDefault(createPreferenceString(SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_REFERENCE), true);
852
		getPreferenceStore().setDefault(createPreferenceString(SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_STATUS), true);
853
		getPreferenceStore().setDefault(createPreferenceString(SHOW_NAME_DETAILS_SECTION_PROTOLOGUE), true);
854
		getPreferenceStore().setDefault(createPreferenceString(SHOW_NAME_DETAILS_SECTION_RANK), true);
855
		getPreferenceStore().setDefault(createPreferenceString(SHOW_NAME_DETAILS_SECTION_TYPE_DESIGNATION), true);
856
		//Navigator preferences
857
		getPreferenceStore().setDefault(createPreferenceString(SORT_NODES), NavigatorOrderEnum.RankAndNameOrder.getKey());
858

    
859
		getPreferenceStore().setDefault(createPreferenceString(SORT_TAXA_BY_RANK_AND_NAME), true);
860
		//override db preferences
861
		getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(EditorPreferencePredicate.AbcdImportConfig.getKey())), false);
862
		getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(EditorPreferencePredicate.ShowSpecimen.getKey())), false);
863
		getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(EditorPreferencePredicate.NameDetailsView.getKey())), false);
864
		getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(EditorPreferencePredicate.DistributionEditorActivated.getKey())), false);
865

    
866
		getPreferenceStore().setDefault(createPreferenceString(FILTER_COMMON_NAME_REFERENCES), false);
867
		getPreferenceStore().setDefault(createPreferenceString(SHOW_SPECIMEN), true);
868
		getPreferenceStore().setDefault(createPreferenceString(EditorPreferencePredicate.ShowTaxonNodeWizard.getKey()), Boolean.valueOf(EditorPreferencePredicate.ShowTaxonNodeWizard.getDefaultValue().toString()));
869
		getPreferenceStore().setDefault(createPreferenceString(EditorPreferencePredicate.ShowNamespaceInSource.getKey()), Boolean.valueOf(EditorPreferencePredicate.ShowNamespaceInSource.getDefaultValue().toString()));
870
		getPreferenceStore().setDefault(createPreferenceString(EditorPreferencePredicate.ShowIdInSource.getKey()), Boolean.valueOf(EditorPreferencePredicate.ShowIdInSource.getDefaultValue().toString()));
871
		getPreferenceStore().setDefault(createPreferenceString(EditorPreferencePredicate.DisableMultiClassification.getKey()), Boolean.valueOf(EditorPreferencePredicate.DisableMultiClassification.getDefaultValue().toString()));
872
		getPreferenceStore().setDefault(createPreferenceString(DISABLE_SEC), false);
873
		getPreferenceStore().setDefault(createPreferenceString(SHOW_SEC_DETAILS), true);
874
	}
875

    
876
	/**
877
	 * <p>
878
	 * checkNomenclaturalCode
879
	 * </p>
880
	 */
881
	public static void checkNomenclaturalCode() {
882
		// First time Editor is opened, no nomenclatural code has been set
883
		if (PreferencesUtil.getPreferredNomenclaturalCode(true) == null) {
884
			PreferencesUtil.setPreferredNomenclaturalCode(getPreferenceKey(NomenclaturalCode.ICNAFP), true);
885
		}
886

    
887

    
888

    
889
	}
890
	public static void setNomenclaturalCodePreferences(){
891
	    ICdmRepository controller;
892
        controller = CdmStore.getCurrentApplicationConfiguration();
893
        PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.NomenclaturalCode);
894
        CdmPreference preference = null;
895
        if (controller == null){
896
            return ;
897
        }
898
        preference = controller.getPreferenceService().find(key);
899
        if (preference == null){
900
            return;
901
        }
902
//        setBooleanValue(ALLOW_OVERRIDE_NOMENCLATURAL_CODE_KEY, preference.isAllowOverride());
903

    
904
        int index = StringUtils.lastIndexOf(preference.getValue(), ".");
905
        UUID uuid = UUID.fromString(preference.getValue().substring(index +1, preference.getValue().length()));
906
        NomenclaturalCode preferredCode = NomenclaturalCode.getByUuid(uuid);
907

    
908
        setStringValue(PREFERRED_NOMENCLATURAL_CODE_KEY,
909
                getPreferenceKey(preferredCode));
910

    
911
	}
912

    
913
	public static void checkDefaultLanguage(){
914
	    if(PreferencesUtil.getPreferredDefaultLangugae() == null){
915
	       Shell shell = AbstractUtility.getShell();
916
	       int open = new DefaultLanguageDialog(shell).open();
917
	       if(open == Window.OK){
918
	           PlatformUI.getWorkbench().restart();
919
	       }
920
	    }else{
921
	        //TODO:In case of a reinstall, the config.ini will be overwritten
922
	        //     here you create config.ini with the stored key from preferences
923
	    }
924
	}
925

    
926
	/**
927
	 * <p>
928
	 * getMapServiceAccessPoint
929
	 * </p>
930
	 *
931
	 * @return a {@link java.lang.String} object.
932
	 */
933
	public static String getMapServiceAccessPoint() {
934
		return getStringValue(EDIT_MAP_SERVICE_ACCES_POINT);
935
	}
936

    
937
	/**
938
	 * <p>
939
	 * shouldConnectAtStartUp
940
	 * </p>
941
	 *
942
	 * @return a boolean.
943
	 */
944
	public static boolean shouldConnectAtStartUp() {
945
		//FIXME :  force SHOULD_CONNECT_AT_STARTUP to false (ticket 3828) until resolution
946
		//return getBooleanValue(SHOULD_CONNECT_AT_STARTUP);
947
		return false;
948
	}
949

    
950
	/**
951
	 * <p>
952
	 * getDefaultFeatureTreeForTextualDescription
953
	 * </p>
954
	 *
955
	 * @return a {@link eu.etaxonomy.cdm.model.description.FeatureTree} object.
956
	 */
957
	public static FeatureTree getDefaultFeatureTreeForTextualDescription() {
958
		String uuidString = getStringValue(
959
				FEATURE_TREE_DEFAULT_TEXT);
960
		return CdmUtils.isEmpty(uuidString) ? null : CdmStore.getService(
961
				IFeatureTreeService.class).load(UUID.fromString(uuidString));
962
	}
963

    
964
	/**
965
	 * <p>
966
	 * getDefaultFeatureTreeForStructuredDescription
967
	 * </p>
968
	 *
969
	 * @return a {@link eu.etaxonomy.cdm.model.description.FeatureTree} object.
970
	 */
971
	public static FeatureTree getDefaultFeatureTreeForStructuredDescription() {
972
		String uuidString = getStringValue(
973
				FEATURE_TREE_DEFAULT_STRUCTURE);
974
		return CdmUtils.isEmpty(uuidString) ? null : CdmStore.getService(
975
				IFeatureTreeService.class).load(UUID.fromString(uuidString));
976
	}
977

    
978
	/**
979
	 * <p>
980
	 * setSortRanksHierarchichally
981
	 * </p>
982
	 *
983
	 * @param selection
984
	 *            a boolean.
985
	 */
986
	public static void setSortRanksHierarchichally(boolean selection) {
987
		setBooleanValue(SORT_RANKS_HIERARCHICHALLY, selection);
988
	}
989

    
990
	/**
991
	 * <p>
992
	 * getSortRanksHierarchichally
993
	 * </p>
994
	 *
995
	 * @return a boolean.
996
	 */
997
	public static boolean getSortRanksHierarchichally() {
998
		return getBooleanValue(SORT_RANKS_HIERARCHICHALLY);
999
	}
1000

    
1001
	public static boolean isMultilanguageTextEditingCapability() {
1002
		return getBooleanValue(
1003
				MULTILANGUAGE_TEXT_EDITING_CAPABILITY);
1004
	}
1005

    
1006
	public static Language getGlobalLanguage() {
1007

    
1008

    
1009
		String languageUuidString = getStringValue(
1010
				GLOBAL_LANGUAGE_UUID);
1011

    
1012
		if(!CdmStore.isActive()) {
1013
            MessagingUtils.noDataSourceWarningDialog(languageUuidString);
1014
            return null;
1015
        }
1016

    
1017
		if (CdmUtils.isBlank(languageUuidString)) {
1018
			return Language.getDefaultLanguage();
1019
		}
1020

    
1021
		UUID languageUuid = UUID.fromString(languageUuidString);
1022
		return (Language) CdmStore.getService(ITermService.class).load(
1023
				languageUuid);
1024
	}
1025

    
1026
	public static void setGlobalLanguage(Language language) {
1027
	    if(language != null) {
1028
	        setStringValue(GLOBAL_LANGUAGE_UUID,language.getUuid().toString());
1029
	        CdmStore.setDefaultLanguage(language);
1030
	    }
1031

    
1032
	}
1033

    
1034
	/**
1035
	 * @return
1036
	 */
1037
	public static Map<MarkerType, Boolean> getEditMarkerTypePreferences() {
1038
		List<MarkerType> markerTypes = CdmStore.getTermManager()
1039
				.getPreferredTerms(MarkerType.class);
1040

    
1041
		Map<MarkerType, Boolean> result = new HashMap<MarkerType, Boolean>();
1042

    
1043
		for (MarkerType markerType : markerTypes) {
1044
			String name = getMarkerTypeEditingPreferenceKey(markerType);
1045
			Boolean value = getBooleanValue(name);
1046

    
1047
			result.put(markerType, value);
1048
		}
1049

    
1050
		return result;
1051
	}
1052

    
1053
	/**
1054
	 * @param markerTypeEditingMap
1055
	 */
1056
	public static void setEditMarkerTypePreferences(
1057
			Map<MarkerType, Boolean> markerTypeEditingMap) {
1058
		for (MarkerType markerType : markerTypeEditingMap.keySet()) {
1059
			String name = getMarkerTypeEditingPreferenceKey(markerType);
1060
			setBooleanValue(name,
1061
					markerTypeEditingMap.get(markerType));
1062
		}
1063

    
1064
	}
1065

    
1066
	private static String getMarkerTypeEditingPreferenceKey(
1067
			MarkerType markerType) {
1068
		markerType = HibernateProxyHelper.deproxy(markerType);
1069
		return markerType.getClass().getName() + EDIT_MARKER_TYPE_PREFIX;
1070
	}
1071

    
1072
	/**
1073
	 * <p>
1074
	 * setEditMarkerTypePreference
1075
	 * </p>
1076
	 *
1077
	 * @param input
1078
	 *            a {@link org.eclipse.ui.IEditorInput} object.
1079
	 * @param markerType
1080
	 *            a {@link eu.etaxonomy.cdm.model.common.MarkerType} object.
1081
	 * @param edit
1082
	 *            a boolean.
1083
	 */
1084
	public static void setEditMarkerTypePreference(MarkerType markerType,
1085
			boolean edit) {
1086
		setBooleanValue(
1087
				getMarkerTypeEditingPreferenceKey(markerType), edit);
1088
	}
1089

    
1090
	/**
1091
	 * @return
1092
	 */
1093
	public static DerivedUnitFacadeConfigurator getDerivedUnitConfigurator() {
1094
		DerivedUnitFacadeConfigurator configurator = DerivedUnitFacadeConfigurator
1095
				.NewInstance();
1096
		configurator.setMoveDerivedUnitMediaToGallery(true);
1097
		configurator.setMoveFieldObjectMediaToGallery(true);
1098
		return configurator;
1099
	}
1100

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

    
1130
    /**
1131
     * This method loads a property from a given file and returns it.
1132
     *
1133
     * @param filename
1134
     * @return
1135
     * @throws IOException
1136
     */
1137
    private Properties load(String filename) throws IOException {
1138
        FileInputStream in = new FileInputStream(filename);
1139
        Properties prop = new Properties();
1140
        prop.load(in);
1141
        in.close();
1142
        return prop;
1143
    }
1144

    
1145
    /**
1146
     * This method saves a property to the specified file.
1147
     *
1148
     * @param filename
1149
     * @param properties
1150
     * @throws IOException
1151
     */
1152
    private void save(String filename, Properties properties) throws IOException{
1153
        FileOutputStream fos =  new FileOutputStream(filename);
1154
        properties.store(fos, "");
1155
        fos.close();
1156
    }
1157

    
1158
    /**
1159
     * Saves a list of P2 Metadata Repositories as string with specified delimiters
1160
     *
1161
     * @param p2Repos
1162
     */
1163
    public static void setP2Repositories(List<MetadataRepositoryElement> p2Repos) {
1164
        StringBuilder sb = new StringBuilder();
1165
        for(MetadataRepositoryElement p2Repo : p2Repos) {
1166
            sb.append(P2_REPOSITORIES_DELIM);
1167
            if(p2Repo.getName() == null || p2Repo.getName().isEmpty()) {
1168
                sb.append("-");
1169
            } else {
1170
                sb.append(p2Repo.getName());
1171
            }
1172
            sb.append(P2_REPOSITORY_FIELDS_DELIM);
1173
            sb.append(p2Repo.getLocation().toString());
1174
            sb.append(P2_REPOSITORY_FIELDS_DELIM);
1175
            sb.append(String.valueOf(p2Repo.isEnabled()));
1176
        }
1177
        getPreferenceStore().setValue(P2_REPOSITORY_LIST, sb.toString());
1178
    }
1179

    
1180

    
1181
    /**
1182
     * Retrieves a list of previously saved P2 repositories
1183
     *
1184
     * @return
1185
     */
1186
    public static List<MetadataRepositoryElement> getP2Repositories() {
1187
        List<MetadataRepositoryElement> p2Repos = new ArrayList<MetadataRepositoryElement>();
1188
        String p2ReposPref =  getStringValue(P2_REPOSITORY_LIST);
1189
        if(p2ReposPref != null && !p2ReposPref.isEmpty()) {
1190
            StringTokenizer p2ReposPrefST = new StringTokenizer(p2ReposPref,P2_REPOSITORIES_DELIM);
1191

    
1192
            while(p2ReposPrefST.hasMoreTokens()) {
1193
                String p2RepoStr = p2ReposPrefST.nextToken();
1194
                StringTokenizer p2ReposStrST = new StringTokenizer(p2RepoStr,P2_REPOSITORY_FIELDS_DELIM);
1195
                if(p2ReposStrST.countTokens()==3) {
1196
                    String nickname = p2ReposStrST.nextToken();
1197
                    URI uri = null;
1198
                    try {
1199
                        uri = new URI(p2ReposStrST.nextToken());
1200
                    } catch (URISyntaxException e) {
1201
                        continue;
1202
                    }
1203
                    boolean enabled = Boolean.parseBoolean(p2ReposStrST.nextToken());
1204
                    MetadataRepositoryElement mre = new MetadataRepositoryElement(null, uri, true);
1205
                    mre.setNickname(nickname);
1206
                    mre.setEnabled(enabled);
1207
                    p2Repos.add(mre);
1208
                }
1209
            }
1210
        }
1211

    
1212
        return p2Repos;
1213
    }
1214

    
1215
    /**
1216
     * enables/disables nested composite. <br>
1217
     *
1218
     * @param ctrl - Composite to be en-/disabeld
1219
     * @param enabled - boolean
1220
     */
1221
    public static void recursiveSetEnabled(Control ctrl, boolean enabled) {
1222
        if (ctrl instanceof Composite) {
1223
            Composite comp = (Composite) ctrl;
1224
            for (Control c : comp.getChildren()) {
1225
                recursiveSetEnabled(c, enabled);
1226
            }
1227
        } else {
1228
            ctrl.setEnabled(enabled);
1229
        }
1230
    }
1231

    
1232

    
1233

    
1234

    
1235
    /**
1236
     * @param orderActivated
1237
     */
1238
    public static void setSortNodes(NavigatorOrderEnum nodesOrder) {
1239
        setStringValue(SORT_NODES, nodesOrder.key);
1240

    
1241
    }
1242

    
1243
    /**
1244
     * @param orderActivated
1245
     */
1246
    public static NavigatorOrderEnum getSortNodes() {
1247
        return NavigatorOrderEnum.valueOf(getStringValue(SORT_NODES));
1248

    
1249
    }
1250

    
1251
    /**
1252
     * @param orderActivated
1253
     */
1254
    public static boolean isNodesSortedNaturally() {
1255
        NavigatorOrderEnum value = NavigatorOrderEnum.valueOf(getStringValue(SORT_NODES));
1256
        return value.equals(NavigatorOrderEnum.NaturalOrder);
1257

    
1258
    }
1259

    
1260
    /**
1261
     * @param orderActivated
1262
     */
1263
    public static boolean isNodesSortedByName() {
1264
        NavigatorOrderEnum value = NavigatorOrderEnum.valueOf(getStringValue(SORT_NODES));
1265
        return value.equals(NavigatorOrderEnum.AlphabeticalOrder);
1266

    
1267
    }
1268

    
1269
    /**
1270
     * @param orderActivated
1271
     */
1272
    public static boolean isNodesSortedByNameAndRank() {
1273
        NavigatorOrderEnum value = NavigatorOrderEnum.valueOf(getStringValue(SORT_NODES));
1274
        return value.equals(NavigatorOrderEnum.RankAndNameOrder);
1275

    
1276
    }
1277
	/**
1278
	 * <p>
1279
	 * setStoreNavigatorState
1280
	 * </p>
1281
	 *
1282
	 * @param selection
1283
	 *            a boolean.
1284
	 */
1285
	public static boolean isStoreNavigatorState() {
1286
		return getBooleanValue(RESTORE_NAVIGATOR_STATE);
1287

    
1288
	}
1289

    
1290
	/**
1291
	 * <p>
1292
	 * setStoreNavigatorState
1293
	 * </p>
1294
	 *
1295
	 * @param selection
1296
	 *            a boolean.
1297
	 */
1298
	public static void setStoreNavigatorState(boolean selection) {
1299
		setBooleanValue(RESTORE_NAVIGATOR_STATE, selection);
1300

    
1301
	}
1302

    
1303
    /**
1304
     * @return
1305
     */
1306
    public static boolean isShowUpWidgetIsDisposedMessages() {
1307
       return getBooleanValue(IS_SHOW_UP_WIDGET_IS_DISPOSED);
1308
    }
1309
    public static void setShowUpWidgetIsDisposedMessages(boolean selection) {
1310
        setBooleanValue(IS_SHOW_UP_WIDGET_IS_DISPOSED, selection);
1311
    }
1312

    
1313
    /**
1314
     * @return
1315
     */
1316
    public static boolean isShowIdInVocabularyInChecklistEditor() {
1317
        String area_display = getStringValue(EditorPreferencePredicate.DisplayOfAreasInDistributionEditor.getKey());
1318
        if (area_display.equals(TermDisplayEnum.IdInVocabulary.getKey())) {
1319
            return true;
1320
        }else{
1321
            return false;
1322
        }
1323
    }
1324
    public static boolean isShowSymbol1InChecklistEditor() {
1325
        String area_display = getStringValue(EditorPreferencePredicate.DisplayOfAreasInDistributionEditor.getKey());
1326
        if (area_display.equals(TermDisplayEnum.Symbol1.getKey())) {
1327
            return true;
1328
        }else{
1329
            return false;
1330
        }
1331
     }
1332
    public static boolean isShowSymbol2InChecklistEditor() {
1333
        String area_display = getStringValue(EditorPreferencePredicate.DisplayOfAreasInDistributionEditor.getKey());
1334
        if (area_display.equals(TermDisplayEnum.Symbol2.getKey())) {
1335
            return true;
1336
        }else{
1337
            return false;
1338
        }
1339
     }
1340
    public static void setAreaDisplayInChecklistEditor(String selection) {
1341
        setStringValue(EditorPreferencePredicate.DisplayOfAreasInDistributionEditor.getKey(), selection);
1342
    }
1343

    
1344
    public static void setOwnDescriptionForChecklistEditor(boolean selection) {
1345
        setBooleanValue(EditorPreferencePredicate.OwnDescriptionForDistributionEditor.getKey(), selection);
1346
    }
1347

    
1348
    public static boolean isOwnDescriptionForChecklistEditor() {
1349
        return getBooleanValue(EditorPreferencePredicate.OwnDescriptionForDistributionEditor.getKey());
1350
    }
1351

    
1352
    /**
1353
     * @return
1354
     */
1355
    public static String displayStatusInChecklistEditor() {
1356
       return getStringValue(EditorPreferencePredicate.DisplayOfStatus.getKey());
1357
    }
1358
    public static void setDisplayStatusInChecklistEditor(String selection) {
1359
        setStringValue(EditorPreferencePredicate.DisplayOfStatus.getKey(), selection);
1360
    }
1361

    
1362
    /**
1363
     * @return
1364
     */
1365
    public static boolean isShowRankInChecklistEditor() {
1366
        return getBooleanValue(EditorPreferencePredicate.ShowRankInDistributionEditor.getKey());
1367
    }
1368
    public static void setShowRankInChecklistEditor(boolean selection) {
1369
       setBooleanValue(EditorPreferencePredicate.ShowRankInDistributionEditor.getKey(), selection);
1370
    }
1371

    
1372
    /**
1373
     * @param object
1374
     * @param b
1375
     * @return
1376
     */
1377
    public static NameDetailsConfigurator getPreferredNameDetailsConfiguration( boolean local) {
1378
        NameDetailsConfigurator config = new NameDetailsConfigurator(true);
1379
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1380
        CdmPreference preference = null;
1381

    
1382
        if (!local) {
1383
            preference = cache.get(EditorPreferencePredicate.NameDetailsView.getKey());
1384
            if (preference == null){
1385
                return null;
1386
            }
1387

    
1388
            setBooleanValue(ALLOW_OVERRIDE_NAME_DETAILS, preference.isAllowOverride());
1389

    
1390
            //the preference value is build like this:
1391
            //<section1>:true;<section2>:false....
1392

    
1393
            String value = preference.getValue();
1394
            String [] sections = value.split(";");
1395
            Map<String, Boolean> sectionMap = new HashMap<String, Boolean>();
1396
            String[] sectionValues;
1397
            for (String sectionValue: sections){
1398
                sectionValues = sectionValue.split(":");
1399
                sectionMap.put(sectionValues[0], Boolean.valueOf(sectionValues[1]));
1400
            }
1401
            config.setAllowOverride(preference.isAllowOverride());
1402
            config.setSimpleDetailsViewActivated(getValue(sectionMap, "simpleViewActivated"));
1403

    
1404
    //        getPreferenceStore().setValue(SHOW_SIMPLE_NAME_DETAILS_TAXON,
1405
    //                (getValue(sectionMap, "taxon")));
1406
            config.setTaxonSectionActivated(getValue(sectionMap, "taxon"));
1407

    
1408
            config.setSecDetailsActivated(getValue(sectionMap, "taxon.SecEnabled"));
1409
            config.setSecEnabled(getValue(sectionMap, "taxon.SecDetails"));
1410

    
1411
    //        getPreferenceStore().setValue(SHOW_NAME_DETAILS_SECTION_LSID,
1412
    //                (getValue(sectionMap, "lsid")));
1413
            config.setLSIDActivated(getValue(sectionMap, "lsid"));
1414

    
1415
    //        getPreferenceStore().setValue(SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_CODE,
1416
    //                (getValue(sectionMap, "nc")));
1417
            config.setNomenclaturalCodeActived(getValue(sectionMap, "nc"));
1418

    
1419
    //        getPreferenceStore().setValue(SHOW_NAME_DETAILS_SECTION_APPENDED_PHRASE,
1420
    //                (getValue(sectionMap, "ap")));
1421
            config.setAppendedPhraseActivated(getValue(sectionMap, "ap"));
1422

    
1423
    //        getPreferenceStore().setValue(SHOW_NAME_DETAILS_SECTION_RANK,
1424
    //                (getValue(sectionMap, "rank")));
1425
            config.setRankActivated(getValue(sectionMap, "rank"));
1426

    
1427

    
1428
    //        getPreferenceStore().setValue(SHOW_NAME_DETAILS_SECTION_ATOMISED_EPITHETS,
1429
    //                (getValue(sectionMap, "atomisedEpithets")));
1430
            config.setAtomisedEpithetsActivated(getValue(sectionMap, "atomisedEpithets"));
1431

    
1432
    //        getPreferenceStore().setValue(SHOW_NAME_DETAILS_SECTION_AUTHORSHIP,
1433
    //                (getValue(sectionMap,"author")));
1434
            config.setAuthorshipSectionActivated(getValue(sectionMap,"author"));
1435

    
1436
    //        getPreferenceStore().setValue(SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_REFERENCE,
1437
    //                (getValue(sectionMap, "nomRef")));
1438
            config.setNomenclaturalReferenceSectionActivated(sectionMap.get("nomRef"));
1439

    
1440
    //        getPreferenceStore().setValue(SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_STATUS,
1441
    //                (getValue(sectionMap, "nomStat")));
1442
            config.setNomenclaturalStatusSectionActivated(getValue(sectionMap, "nomStat"));
1443

    
1444

    
1445
    //        getPreferenceStore().setValue(SHOW_NAME_DETAILS_SECTION_PROTOLOGUE,
1446
    //                (getValue(sectionMap,"protologue")));
1447
            config.setProtologueActivated(getValue(sectionMap,"protologue"));
1448

    
1449
    //        getPreferenceStore().setValue(SHOW_NAME_DETAILS_SECTION_TYPE_DESIGNATION,
1450
    //                (getValue(sectionMap,"typeDes")));
1451
            config.setTypeDesignationSectionActivated(getValue(sectionMap,"typeDes"));
1452

    
1453
    //        getPreferenceStore().setValue(SHOW_NAME_DETAILS_SECTION_NAME_RELATIONSHIP,
1454
    //                (getValue(sectionMap,"nameRelation")));
1455
            config.setNameRelationsSectionActivated(getValue(sectionMap,"nameRelation"));
1456

    
1457
    //        getPreferenceStore().setValue(SHOW_NAME_DETAILS_SECTION_HYBRID,
1458
    //                (getValue(sectionMap, "hybrid")));
1459
            config.setHybridActivated(getValue(sectionMap,"hybrid"));
1460
        }else{
1461
            config.setSimpleDetailsViewActivated(getBooleanValue(SHOW_SIMPLE_NAME_DETAILS_SECTION));
1462
            config.setTaxonSectionActivated(getBooleanValue(SHOW_SIMPLE_NAME_DETAILS_TAXON));
1463
            config.setSecDetailsActivated(getBooleanValue(SHOW_SEC_DETAILS));
1464
            config.setSecEnabled(getBooleanValue(DISABLE_SEC));
1465
            config.setLSIDActivated(getBooleanValue(SHOW_NAME_DETAILS_SECTION_LSID));
1466
            config.setNomenclaturalCodeActived(getBooleanValue(SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_CODE));
1467
            config.setAppendedPhraseActivated(getBooleanValue(SHOW_NAME_DETAILS_SECTION_APPENDED_PHRASE));
1468
            config.setRankActivated(getBooleanValue(SHOW_NAME_DETAILS_SECTION_RANK));
1469
            config.setAtomisedEpithetsActivated(getBooleanValue(SHOW_NAME_DETAILS_SECTION_ATOMISED_EPITHETS));
1470
            config.setAuthorshipSectionActivated(getBooleanValue(SHOW_NAME_DETAILS_SECTION_AUTHORSHIP));
1471
            config.setNomenclaturalReferenceSectionActivated(getBooleanValue(SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_REFERENCE));
1472
            config.setNomenclaturalStatusSectionActivated(getBooleanValue(SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_STATUS));
1473
            config.setProtologueActivated(getBooleanValue(SHOW_NAME_DETAILS_SECTION_PROTOLOGUE));
1474
            config.setTypeDesignationSectionActivated(getBooleanValue(SHOW_NAME_DETAILS_SECTION_TYPE_DESIGNATION));
1475
            config.setNameRelationsSectionActivated(getBooleanValue(SHOW_NAME_DETAILS_SECTION_NAME_RELATIONSHIP));
1476
            config.setHybridActivated(getBooleanValue(SHOW_NAME_DETAILS_SECTION_HYBRID));
1477
        }
1478
        return config;
1479
    }
1480

    
1481
    /**
1482
     * @param object
1483
     * @param b
1484
     * @return
1485
     */
1486
    public static void setPreferredNameDetailsConfiguration(NameDetailsConfigurator config, boolean local) {
1487
        CdmPreference preference = null;
1488

    
1489
        if (!local) {
1490
            preference = CdmPreference.NewInstance(PreferenceSubject.NewDatabaseInstance(), EditorPreferencePredicate.NameDetailsView, config.toString());
1491

    
1492
            setPreferenceToDB(preference);
1493
        }
1494
        //also add to local preferences
1495
        setBooleanValue(SHOW_SIMPLE_NAME_DETAILS_SECTION, config.isSimpleDetailsViewActivated());
1496
        setBooleanValue(SHOW_SIMPLE_NAME_DETAILS_TAXON, config.isTaxonSectionActivated());
1497
        setBooleanValue(SHOW_SEC_DETAILS, config.isSecDetailsActivated());
1498
        setBooleanValue(DISABLE_SEC, config.isSecEnabled());
1499
        setBooleanValue(SHOW_NAME_DETAILS_SECTION_LSID, config.isLSIDActivated());
1500
        setBooleanValue(SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_CODE, config.isNomenclaturalCodeActived());
1501
        setBooleanValue(SHOW_NAME_DETAILS_SECTION_APPENDED_PHRASE, config.isAppendedPhraseActivated());
1502
        setBooleanValue(SHOW_NAME_DETAILS_SECTION_RANK, config.isRankActivated());
1503
        setBooleanValue(SHOW_NAME_DETAILS_SECTION_ATOMISED_EPITHETS, config.isAtomisedEpithetsActivated());
1504
        setBooleanValue(SHOW_NAME_DETAILS_SECTION_AUTHORSHIP, config.isAuthorshipSectionActivated());
1505
        setBooleanValue(SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_REFERENCE, config.isNomenclaturalReferenceSectionActivated());
1506
        setBooleanValue(SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_STATUS, config.isNomenclaturalStatusSectionActivated());
1507
        setBooleanValue(SHOW_NAME_DETAILS_SECTION_PROTOLOGUE, config.isProtologueActivated());
1508
        setBooleanValue(SHOW_NAME_DETAILS_SECTION_TYPE_DESIGNATION, config.isTypeDesignationSectionActivated());
1509
        setBooleanValue(SHOW_NAME_DETAILS_SECTION_NAME_RELATIONSHIP, config.isNameRelationsSectionActivated());
1510
        setBooleanValue(SHOW_NAME_DETAILS_SECTION_HYBRID, config.isHybridActivated());
1511

    
1512
    }
1513

    
1514
    private static Boolean getValue(Map<String, Boolean> sectionMap, String string) {
1515
		if (sectionMap.containsKey(string)){
1516
			return sectionMap.get(string);
1517
		}else{
1518
			return true;
1519
		}
1520

    
1521
	}
1522

    
1523

    
1524

    
1525
    /**
1526
     * <p>
1527
     * setAbcdConfigurator
1528
     * </p>
1529
     *
1530
     * @param preferredConfiguration
1531
     *            a {@link eu.etaxonomy.cdm.io.specimen.abcd206.in.Abcd206ImportConfigurator}
1532
     *            object.
1533
     */
1534
    public static Abcd206ImportConfigurator getDBAbcdImportConfigurationPreference() {
1535

    
1536
        Abcd206ImportConfigurator config = Abcd206ImportConfigurator.NewInstance(null,null);
1537
        ICdmRepository controller;
1538
        controller = CdmStore.getCurrentApplicationConfiguration();
1539
        PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), EditorPreferencePredicate.AbcdImportConfig);
1540
        CdmPreference preference = null;
1541
        if (controller == null){
1542
            return null;
1543
        }
1544
        preference = controller.getPreferenceService().find(key);
1545
        if (preference == null){
1546
            return config;
1547
         } else{
1548
             String configString = preference.getValue();
1549
             String[] configArray = configString.split(";");
1550

    
1551
             for (String configItem: configArray){
1552
                 String[] keyValue = configItem.split(":");
1553
                 String keyString = keyValue[0];
1554
                 String valueString = null;
1555
                 if (keyValue.length>1){
1556
                      valueString = keyValue[1];
1557
                 }
1558
                 if (keyString.equals("ignoreImportOfExistingSpecimen")){
1559
                     config.setIgnoreImportOfExistingSpecimen(Boolean.valueOf(valueString));
1560
                 }else if (keyString.equals("addIndividualsAssociationsSuchAsSpecimenAndObservations")){
1561
                     config.setAddIndividualsAssociationsSuchAsSpecimenAndObservations(Boolean.valueOf(valueString));
1562
                 }else if (keyString.equals("reuseExistingTaxaWhenPossible")){
1563
                     config.setReuseExistingTaxaWhenPossible(Boolean.valueOf(valueString));
1564
                 }else if (keyString.equals("ignoreAuthorship")){
1565
                     config.setIgnoreAuthorship(Boolean.valueOf(valueString));
1566
                 }else if (keyString.equals("addMediaAsMediaSpecimen")){
1567
                     config.setAddMediaAsMediaSpecimen(Boolean.valueOf(valueString));
1568
                 }else if (keyString.equals("reuseExistingMetaData")){
1569
                     config.setReuseExistingMetaData(Boolean.valueOf(valueString));
1570
                 }else if (keyString.equals("reuseExistingDescriptiveGroups")){
1571
                     config.setReuseExistingDescriptiveGroups(Boolean.valueOf(valueString));
1572
                 }else if (keyString.equals("allowReuseOtherClassifications")){
1573
                     config.setAllowReuseOtherClassifications(Boolean.valueOf(valueString));
1574
                 }else if (keyString.equals("deduplicateReferences")){
1575
                     config.setDeduplicateReferences(Boolean.valueOf(valueString));
1576
                 }else if (keyString.equals("deduplicateClassifications")){
1577
                     config.setDeduplicateClassifications(Boolean.valueOf(valueString));
1578
                 }else if (keyString.equals("moveNewTaxaToDefaultClassification")){
1579
                     config.setMoveNewTaxaToDefaultClassification(Boolean.valueOf(valueString));
1580
                 }else if (keyString.equals("mapUnitIdToCatalogNumber")){
1581
                     config.setMapUnitIdToCatalogNumber(Boolean.valueOf(valueString));
1582
                 }else if (keyString.equals("mapUnitIdToAccessionNumber")){
1583
                     config.setMapUnitIdToAccessionNumber(Boolean.valueOf(valueString));
1584
                 }else if (keyString.equals("mapUnitIdToBarcode")){
1585
                     config.setMapUnitIdToBarcode(Boolean.valueOf(valueString));
1586
                 }else if (keyString.equals("overwriteExistingSpecimens")){
1587
                     config.setOverwriteExistingSpecimens(Boolean.valueOf(valueString));
1588
                 }else if (keyString.equals("nomenclaturalCode")){
1589
                         config.setNomenclaturalCode(NomenclaturalCode.fromString(valueString));
1590
                 }else{
1591
                     logger.debug("This key of the abcd configurator needs to be added to the transformer: " + keyString);
1592
                 }
1593

    
1594
             }
1595
        }
1596
        return config;
1597
    }
1598

    
1599
    public static Abcd206ImportConfigurator getLocalAbcdImportConfigurator(){
1600
       Abcd206ImportConfigurator config = Abcd206ImportConfigurator.NewInstance(null,null);
1601

    
1602
        config.setAddIndividualsAssociationsSuchAsSpecimenAndObservations(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_ADD_INDIVIDUALS_ASSOCIATIONS_SUCH_AS_SPECIMEN_AND_OBSERVATIONS));
1603

    
1604
        config.setAddMediaAsMediaSpecimen(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_ADD_MEDIA_AS_MEDIASPECIMEN));
1605

    
1606
        config.setAllowReuseOtherClassifications(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_ALLOW_REUSE_OTHER_CLASSIFICATIONS));
1607
        config.setDeduplicateClassifications(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_DEDUPLICATE_CLASSIFICATIONS));
1608
        config.setDeduplicateReferences(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_DEDUPLICATE_REFERENCES));
1609
        config.setRemoveCountryFromLocalityText(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_REMOVE_COUNTRY_FROM_LOCALITY_TEXT));
1610
        config.setGetSiblings(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_DO_SIBLINGS));
1611
        config.setIgnoreAuthorship(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_IGNORE_AUTHORSHIP));
1612
        config.setIgnoreImportOfExistingSpecimen(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_IGNORE_IMPORT_OF_EXISTING_SPECIMEN));
1613
        config.setMapUnitIdToAccessionNumber(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_MAP_UNIT_ID_TO_ACCESSION_NUMBER));
1614
        config.setMapUnitIdToBarcode(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_MAP_UNIT_ID_TO_BARCODE));
1615
        config.setMapUnitIdToCatalogNumber(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_MAP_UNIT_ID_TOCATALOG_NUMBER));
1616
        config.setMoveNewTaxaToDefaultClassification(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_MOVE_NEW_TAXA_TO_DEFAULT_CLASSIFICATION));
1617
        config.setOverwriteExistingSpecimens(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_OVERWRITE_EXISTING_SPECIMEN));
1618
        config.setReuseExistingDescriptiveGroups(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_REUSE_EXISTING_DESCRIPTIVE_GROUPS));
1619
        config.setReuseExistingMetaData(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_REUSE_EXISTING_META_DATA));
1620
        config.setReuseExistingTaxaWhenPossible(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_REUSE_EXISTING_TAXA_WHEN_POSSIBLE));
1621
        config.setNomenclaturalCode(NomenclaturalCode.getByKey(getStringValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_NOMENCLATURAL_CODE)));
1622

    
1623
        return config;
1624

    
1625
    }
1626

    
1627

    
1628
    public static void updateAbcdImportConfigurationPreference() {
1629
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1630
        CdmPreference pref = cache.get(EditorPreferencePredicate.AbcdImportConfig.getKey());
1631

    
1632
        if (!getBooleanValue(prefOverrideKey(EditorPreferencePredicate.AbcdImportConfig.getKey())) || !pref.isAllowOverride()){
1633
            resetToDBPreferenceAbcdCOnfigurator();
1634

    
1635
        }
1636
    }
1637

    
1638
    public static void resetToDBPreferenceAbcdCOnfigurator(){
1639
        Abcd206ImportConfigurator config = getDBAbcdImportConfigurationPreference();
1640
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_ADD_INDIVIDUALS_ASSOCIATIONS_SUCH_AS_SPECIMEN_AND_OBSERVATIONS, config.isAddIndividualsAssociationsSuchAsSpecimenAndObservations());
1641
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_ADD_MEDIA_AS_MEDIASPECIMEN, config.isAddMediaAsMediaSpecimen());
1642

    
1643
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_ALLOW_REUSE_OTHER_CLASSIFICATIONS, config.isAllowReuseOtherClassifications());
1644
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_DEDUPLICATE_CLASSIFICATIONS, config.isDeduplicateClassifications());
1645
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_DEDUPLICATE_REFERENCES, config.isDeduplicateReferences());
1646

    
1647
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_DO_SIBLINGS, config.isGetSiblings());
1648
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_IGNORE_AUTHORSHIP, config.isIgnoreAuthorship());
1649
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_IGNORE_IMPORT_OF_EXISTING_SPECIMEN, config.isIgnoreImportOfExistingSpecimen());
1650
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_MAP_UNIT_ID_TO_ACCESSION_NUMBER, config.isMapUnitIdToAccessionNumber());
1651
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_MAP_UNIT_ID_TO_BARCODE, config.isMapUnitIdToBarcode());
1652
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_MAP_UNIT_ID_TOCATALOG_NUMBER, config.isMapUnitIdToCatalogNumber());
1653
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_MOVE_NEW_TAXA_TO_DEFAULT_CLASSIFICATION, config.isMoveNewTaxaToDefaultClassification());
1654
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_OVERWRITE_EXISTING_SPECIMEN, config.isOverwriteExistingSpecimens());
1655
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_REUSE_EXISTING_DESCRIPTIVE_GROUPS, config.isReuseExistingDescriptiveGroups());
1656
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_REUSE_EXISTING_META_DATA, config.isReuseExistingMetaData());
1657
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_REUSE_EXISTING_TAXA_WHEN_POSSIBLE, config.isReuseExistingTaxaWhenPossible());
1658
        if (config.getNomenclaturalCode() != null){
1659
            setStringValue(ABCD_IMPORT_CONFIGURATOR_NOMENCLATURAL_CODE, config.getNomenclaturalCode().getKey());
1660
        }
1661
    }
1662

    
1663

    
1664
    /**
1665
    *
1666
    */
1667
   public NameDetailsConfigurator createLocalNameDetailsViewConfig(boolean local) {
1668
       NameDetailsConfigurator config = new NameDetailsConfigurator(true);
1669
       if (local){
1670
          config.setSimpleDetailsViewActivated(getBooleanValue(IPreferenceKeys.SHOW_SIMPLE_NAME_DETAILS_SECTION));
1671
          config.setAppendedPhraseActivated(getBooleanValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_APPENDED_PHRASE));
1672
          config.setAtomisedEpithetsActivated(getBooleanValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_ATOMISED_EPITHETS));
1673
          config.setAuthorshipSectionActivated(getBooleanValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_AUTHORSHIP));
1674
          config.setLSIDActivated(getBooleanValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_LSID));
1675
          config.setNameApprobiationActivated(getBooleanValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_NAME_APPROBATION));
1676
          config.setNameCacheActivated(getBooleanValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_CACHE));
1677
          config.setNameRelationsSectionActivated(getBooleanValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_NAME_RELATIONSHIP));
1678
          config.setNomenclaturalCodeActived(getBooleanValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_CODE));
1679
          config.setNomenclaturalStatusSectionActivated(getBooleanValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_STATUS));
1680
          config.setNomenclaturalReferenceSectionActivated(getBooleanValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_REFERENCE));
1681
          config.setProtologueActivated(getBooleanValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_PROTOLOGUE));
1682
          config.setRankActivated(getBooleanValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_RANK));
1683
          config.setTaxonSectionActivated(getBooleanValue(IPreferenceKeys.SHOW_SIMPLE_NAME_DETAILS_TAXON));
1684
          config.setTypeDesignationSectionActivated(getBooleanValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_TYPE_DESIGNATION));
1685
          config.setHybridActivated(getBooleanValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_HYBRID));
1686
       }else{
1687

    
1688
       }
1689

    
1690
      return config;
1691
   }
1692

    
1693

    
1694
   public static void saveConfigToPrefernceStore(NameDetailsConfigurator config) {
1695
       setBooleanValue(IPreferenceKeys.SHOW_SIMPLE_NAME_DETAILS_SECTION,
1696
               config.isSimpleDetailsViewActivated());
1697
       setBooleanValue(IPreferenceKeys.SHOW_SIMPLE_NAME_DETAILS_TAXON, config.isTaxonSectionActivated());
1698
       setBooleanValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_LSID, config.isLSIDActivated());
1699
       setBooleanValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_CODE,
1700
               config.isNomenclaturalCodeActived());
1701
       setBooleanValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_NAMECACHE,
1702
               config.isNameCacheActivated());
1703
       setBooleanValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_APPENDED_PHRASE,
1704
               config.isAppendedPhraseActivated());
1705
       setBooleanValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_RANK, config.isRankActivated());
1706
       setBooleanValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_ATOMISED_EPITHETS,
1707
               config.isAtomisedEpithetsActivated());
1708
       setBooleanValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_AUTHORSHIP_CACHE,
1709
               config.isAuthorCacheActivated());
1710
       setBooleanValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_AUTHORSHIP,
1711
               config.isAuthorshipSectionActivated());
1712
       setBooleanValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_REFERENCE,
1713
               config.isNomenclaturalReferenceSectionActivated());
1714
       setBooleanValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_STATUS,
1715
               config.isNomenclaturalStatusSectionActivated());
1716
       setBooleanValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_PROTOLOGUE,
1717
               config.isProtologueActivated());
1718
       setBooleanValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_TYPE_DESIGNATION,
1719
               config.isTypeDesignationSectionActivated());
1720
       setBooleanValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_NAME_RELATIONSHIP,
1721
               config.isNameRelationsSectionActivated());
1722
       setBooleanValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_HYBRID,
1723
               config.isHybridActivated());
1724

    
1725
   }
1726

    
1727
/**
1728
 * @return
1729
 */
1730
public static boolean isSortTaxaByRankAndName() {
1731

    
1732
    return getBooleanValue(IPreferenceKeys.SORT_TAXA_BY_RANK_AND_NAME);
1733
}
1734

    
1735
/**
1736
 * @return
1737
 */
1738
public static boolean isSortNamedAreaByOrderInVocabulary() {
1739

    
1740
    return getBooleanValue(EditorPreferencePredicate.AreasSortedByIdInVocabulary.getKey());
1741
}
1742

    
1743
public static void setSortNamedAreasByOrderInVocabulary(boolean isSortByVocabularyOrder) {
1744
    setBooleanValue(EditorPreferencePredicate.AreasSortedByIdInVocabulary.getKey(), isSortByVocabularyOrder);
1745

    
1746
}
1747

    
1748
/**
1749
 * <p>
1750
 * setPreferredNamedAreasForDistributionEditor
1751
 * </p>
1752
 *
1753
 * @param saveCheckedElements
1754
 * @param saveGrayedElements
1755
 */
1756
public static void setLastSelectedReference(
1757
        List<String> lastSelectedReferences) {
1758

    
1759
        setStringValue(PreferencesUtil.LAST_SELECTED_REFERENCES, lastSelectedReferences.toString());
1760
    }
1761

    
1762
/**
1763
 * <p>
1764
 * setPreferredNamedAreasForDistributionEditor
1765
 * </p>
1766
 *
1767
 * @param saveCheckedElements
1768
 * @param saveGrayedElements
1769
 */
1770
public static List<String> getLastSelectedReferences() {
1771

    
1772
        //IPreferenceStore preferenceStore = PreferencesUtil.getPreferenceStore();
1773
        String lastSelected = getStringValue(PreferencesUtil.LAST_SELECTED_REFERENCES);
1774
        List<String> result = new ArrayList<>();
1775
        if (!StringUtils.isBlank(lastSelected)){
1776
            Collections.addAll(result, lastSelected.substring(1,lastSelected.length()-1).split(", "));
1777
        }
1778
        return result;
1779
    }
1780

    
1781

    
1782
/**
1783
 * <p>
1784
 * setPreferredNamedAreasForDistributionEditor
1785
 * </p>
1786
 *
1787
 * @param saveCheckedElements
1788
 * @param saveGrayedElements
1789
 */
1790
public static void setPreferredNamedAreasForDistributionEditor(
1791
        String saveCheckedElements, String saveGrayedElements, boolean local) {
1792
    if (local){
1793
        setStringValue(EditorPreferencePredicate.AvailableDistributionAreaTerms.getKey(), saveCheckedElements);
1794

    
1795
    }
1796
    else{
1797
        CdmPreference preference = null;
1798

    
1799
        if (saveCheckedElements == null){
1800
            preference = getPreferenceFromDB(EditorPreferencePredicate.AvailableDistributionAreaTerms);
1801

    
1802
            if (preference == null){
1803
                return ;
1804
            } else{
1805
                setStringValue(EditorPreferencePredicate.AvailableDistributionAreaTerms.getKey(),
1806
                        saveCheckedElements);
1807
                preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), EditorPreferencePredicate.AvailableDistributionAreaTerms, saveCheckedElements);
1808
                setPreferenceToDB(preference);
1809

    
1810
            }
1811
        } else{
1812
           preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), EditorPreferencePredicate.AvailableDistributionAreaTerms, saveCheckedElements);
1813
           setPreferenceToDB(preference);
1814
           setStringValue(EditorPreferencePredicate.AvailableDistributionAreaTerms.getKey(),
1815
                    saveCheckedElements);
1816

    
1817
        }
1818
    }
1819

    
1820
}
1821

    
1822
/**
1823
 * @param saveCheckedElements
1824
 * @param saveCheckedElements2
1825
 * @param b
1826
 */
1827
public static void setPreferredVocabulariesForDistributionEditor(String saveCheckedElements,
1828
        boolean local, boolean isOverride) {
1829
    if (local){
1830
      setStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(), saveCheckedElements);
1831
      setBooleanValue(prefOverrideKey(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey()), isOverride);
1832
    }
1833
    else{
1834
        ICdmRepository controller;
1835
        CdmPreference preference = null;
1836

    
1837
        if (saveCheckedElements == null){
1838
            preference = getPreferenceFromDB(PreferencePredicate.AvailableDistributionAreaVocabularies);
1839

    
1840
            if (preference == null){
1841
                return ;
1842
            } else{
1843
                setStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(),
1844
                        saveCheckedElements);
1845
                preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AvailableDistributionAreaVocabularies, saveCheckedElements);
1846
                preference.setAllowOverride(isOverride);
1847
                setPreferenceToDB(preference);
1848
            }
1849
        } else{
1850
            preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AvailableDistributionAreaVocabularies, saveCheckedElements);
1851
            preference.setAllowOverride(isOverride);
1852
            setPreferenceToDB(preference);
1853
            setStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(),
1854
                    saveCheckedElements);
1855

    
1856
        }
1857
    }
1858
}
1859

    
1860

    
1861

    
1862

    
1863
/**
1864
 * @param saveCheckedElements
1865
 * @param saveCheckedElements2
1866
 * @param b
1867
 */
1868
public static String getPreferredVocabulariesForDistributionEditor(boolean local) {
1869
    if (local){
1870

    
1871
        String pref = getStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(), local);
1872
        return pref;
1873
    }
1874
    else{
1875
        CdmPreference preference = null;
1876
        preference = getPreferenceFromDB(PreferencePredicate.AvailableDistributionAreaVocabularies);
1877
        if (preference == null){
1878
            return null;
1879
        } else{
1880
            return preference.getValue();
1881
        }
1882

    
1883
    }
1884

    
1885

    
1886

    
1887
}
1888

    
1889
public static boolean getFilterCommonNameReferences(){
1890
    return getBooleanValue(PreferencesUtil.FILTER_COMMON_NAME_REFERENCES);
1891
}
1892

    
1893
/**
1894
 *
1895
 */
1896
public static void updateDBPreferences() {
1897
    CdmPreference preference = null;
1898
    CdmPreferenceCache cache = CdmPreferenceCache.instance();
1899
    cache.getAllTaxEditorDBPreferences();
1900

    
1901
    //ABCD Configurator
1902

    
1903
    updateAbcdImportConfigurationPreference();
1904

    
1905
    //Name Details
1906
    NameDetailsConfigurator config = getPreferredNameDetailsConfiguration(false);
1907
    if (config != null ){
1908
        if (!getBooleanValue(OVERRIDE_NAME_DETAILS) ||  !getBooleanValue(ALLOW_OVERRIDE_NAME_DETAILS)){
1909
            setPreferredNameDetailsConfiguration(config, false);
1910
        }
1911
    }
1912

    
1913

    
1914

    
1915

    
1916

    
1917

    
1918

    
1919

    
1920
}
1921

    
1922

    
1923

    
1924

    
1925

    
1926

    
1927

    
1928

    
1929
}
(22-22/30)