Project

General

Profile

Download (71.5 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
		if (StringUtils.isBlank(uuidString)) {
961
            return null;
962
        }
963
		FeatureTree tree = CdmStore.getService(
964
	                IFeatureTreeService.class).load(UUID.fromString(uuidString));
965
		if (tree.getId() == 0) {
966
            return null;
967
        }
968
		return tree;
969
	}
970

    
971
	/**
972
	 * <p>
973
	 * getDefaultFeatureTreeForStructuredDescription
974
	 * </p>
975
	 *
976
	 * @return a {@link eu.etaxonomy.cdm.model.description.FeatureTree} object.
977
	 */
978
	public static FeatureTree getDefaultFeatureTreeForStructuredDescription() {
979
		String uuidString = getStringValue(
980
				FEATURE_TREE_DEFAULT_STRUCTURE);
981
		return CdmUtils.isEmpty(uuidString) ? null : CdmStore.getService(
982
				IFeatureTreeService.class).load(UUID.fromString(uuidString));
983
	}
984

    
985
	/**
986
	 * <p>
987
	 * setSortRanksHierarchichally
988
	 * </p>
989
	 *
990
	 * @param selection
991
	 *            a boolean.
992
	 */
993
	public static void setSortRanksHierarchichally(boolean selection) {
994
		setBooleanValue(SORT_RANKS_HIERARCHICHALLY, selection);
995
	}
996

    
997
	/**
998
	 * <p>
999
	 * getSortRanksHierarchichally
1000
	 * </p>
1001
	 *
1002
	 * @return a boolean.
1003
	 */
1004
	public static boolean getSortRanksHierarchichally() {
1005
		return getBooleanValue(SORT_RANKS_HIERARCHICHALLY);
1006
	}
1007

    
1008
	public static boolean isMultilanguageTextEditingCapability() {
1009
		return getBooleanValue(
1010
				MULTILANGUAGE_TEXT_EDITING_CAPABILITY);
1011
	}
1012

    
1013
	public static Language getGlobalLanguage() {
1014

    
1015

    
1016
		String languageUuidString = getStringValue(
1017
				GLOBAL_LANGUAGE_UUID);
1018

    
1019
		if(!CdmStore.isActive()) {
1020
            MessagingUtils.noDataSourceWarningDialog(languageUuidString);
1021
            return null;
1022
        }
1023

    
1024
		if (CdmUtils.isBlank(languageUuidString)) {
1025
			return Language.getDefaultLanguage();
1026
		}
1027

    
1028
		UUID languageUuid = UUID.fromString(languageUuidString);
1029
		return (Language) CdmStore.getService(ITermService.class).load(
1030
				languageUuid);
1031
	}
1032

    
1033
	public static void setGlobalLanguage(Language language) {
1034
	    if(language != null) {
1035
	        setStringValue(GLOBAL_LANGUAGE_UUID,language.getUuid().toString());
1036
	        CdmStore.setDefaultLanguage(language);
1037
	    }
1038

    
1039
	}
1040

    
1041
	/**
1042
	 * @return
1043
	 */
1044
	public static Map<MarkerType, Boolean> getEditMarkerTypePreferences() {
1045
		List<MarkerType> markerTypes = CdmStore.getTermManager()
1046
				.getPreferredTerms(MarkerType.class);
1047

    
1048
		Map<MarkerType, Boolean> result = new HashMap<MarkerType, Boolean>();
1049

    
1050
		for (MarkerType markerType : markerTypes) {
1051
			String name = getMarkerTypeEditingPreferenceKey(markerType);
1052
			Boolean value = getBooleanValue(name);
1053

    
1054
			result.put(markerType, value);
1055
		}
1056

    
1057
		return result;
1058
	}
1059

    
1060
	/**
1061
	 * @param markerTypeEditingMap
1062
	 */
1063
	public static void setEditMarkerTypePreferences(
1064
			Map<MarkerType, Boolean> markerTypeEditingMap) {
1065
		for (MarkerType markerType : markerTypeEditingMap.keySet()) {
1066
			String name = getMarkerTypeEditingPreferenceKey(markerType);
1067
			setBooleanValue(name,
1068
					markerTypeEditingMap.get(markerType));
1069
		}
1070

    
1071
	}
1072

    
1073
	private static String getMarkerTypeEditingPreferenceKey(
1074
			MarkerType markerType) {
1075
		markerType = HibernateProxyHelper.deproxy(markerType);
1076
		return markerType.getClass().getName() + EDIT_MARKER_TYPE_PREFIX;
1077
	}
1078

    
1079
	/**
1080
	 * <p>
1081
	 * setEditMarkerTypePreference
1082
	 * </p>
1083
	 *
1084
	 * @param input
1085
	 *            a {@link org.eclipse.ui.IEditorInput} object.
1086
	 * @param markerType
1087
	 *            a {@link eu.etaxonomy.cdm.model.common.MarkerType} object.
1088
	 * @param edit
1089
	 *            a boolean.
1090
	 */
1091
	public static void setEditMarkerTypePreference(MarkerType markerType,
1092
			boolean edit) {
1093
		setBooleanValue(
1094
				getMarkerTypeEditingPreferenceKey(markerType), edit);
1095
	}
1096

    
1097
	/**
1098
	 * @return
1099
	 */
1100
	public static DerivedUnitFacadeConfigurator getDerivedUnitConfigurator() {
1101
		DerivedUnitFacadeConfigurator configurator = DerivedUnitFacadeConfigurator
1102
				.NewInstance();
1103
		configurator.setMoveDerivedUnitMediaToGallery(true);
1104
		configurator.setMoveFieldObjectMediaToGallery(true);
1105
		return configurator;
1106
	}
1107

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

    
1137
    /**
1138
     * This method loads a property from a given file and returns it.
1139
     *
1140
     * @param filename
1141
     * @return
1142
     * @throws IOException
1143
     */
1144
    private Properties load(String filename) throws IOException {
1145
        FileInputStream in = new FileInputStream(filename);
1146
        Properties prop = new Properties();
1147
        prop.load(in);
1148
        in.close();
1149
        return prop;
1150
    }
1151

    
1152
    /**
1153
     * This method saves a property to the specified file.
1154
     *
1155
     * @param filename
1156
     * @param properties
1157
     * @throws IOException
1158
     */
1159
    private void save(String filename, Properties properties) throws IOException{
1160
        FileOutputStream fos =  new FileOutputStream(filename);
1161
        properties.store(fos, "");
1162
        fos.close();
1163
    }
1164

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

    
1187

    
1188
    /**
1189
     * Retrieves a list of previously saved P2 repositories
1190
     *
1191
     * @return
1192
     */
1193
    public static List<MetadataRepositoryElement> getP2Repositories() {
1194
        List<MetadataRepositoryElement> p2Repos = new ArrayList<MetadataRepositoryElement>();
1195
        String p2ReposPref =  getStringValue(P2_REPOSITORY_LIST);
1196
        if(p2ReposPref != null && !p2ReposPref.isEmpty()) {
1197
            StringTokenizer p2ReposPrefST = new StringTokenizer(p2ReposPref,P2_REPOSITORIES_DELIM);
1198

    
1199
            while(p2ReposPrefST.hasMoreTokens()) {
1200
                String p2RepoStr = p2ReposPrefST.nextToken();
1201
                StringTokenizer p2ReposStrST = new StringTokenizer(p2RepoStr,P2_REPOSITORY_FIELDS_DELIM);
1202
                if(p2ReposStrST.countTokens()==3) {
1203
                    String nickname = p2ReposStrST.nextToken();
1204
                    URI uri = null;
1205
                    try {
1206
                        uri = new URI(p2ReposStrST.nextToken());
1207
                    } catch (URISyntaxException e) {
1208
                        continue;
1209
                    }
1210
                    boolean enabled = Boolean.parseBoolean(p2ReposStrST.nextToken());
1211
                    MetadataRepositoryElement mre = new MetadataRepositoryElement(null, uri, true);
1212
                    mre.setNickname(nickname);
1213
                    mre.setEnabled(enabled);
1214
                    p2Repos.add(mre);
1215
                }
1216
            }
1217
        }
1218

    
1219
        return p2Repos;
1220
    }
1221

    
1222
    /**
1223
     * enables/disables nested composite. <br>
1224
     *
1225
     * @param ctrl - Composite to be en-/disabeld
1226
     * @param enabled - boolean
1227
     */
1228
    public static void recursiveSetEnabled(Control ctrl, boolean enabled) {
1229
        if (ctrl instanceof Composite) {
1230
            Composite comp = (Composite) ctrl;
1231
            for (Control c : comp.getChildren()) {
1232
                recursiveSetEnabled(c, enabled);
1233
            }
1234
        } else {
1235
            ctrl.setEnabled(enabled);
1236
        }
1237
    }
1238

    
1239

    
1240

    
1241

    
1242
    /**
1243
     * @param orderActivated
1244
     */
1245
    public static void setSortNodes(NavigatorOrderEnum nodesOrder) {
1246
        setStringValue(SORT_NODES, nodesOrder.key);
1247

    
1248
    }
1249

    
1250
    /**
1251
     * @param orderActivated
1252
     */
1253
    public static NavigatorOrderEnum getSortNodes() {
1254
        return NavigatorOrderEnum.valueOf(getStringValue(SORT_NODES));
1255

    
1256
    }
1257

    
1258
    /**
1259
     * @param orderActivated
1260
     */
1261
    public static boolean isNodesSortedNaturally() {
1262
        NavigatorOrderEnum value = NavigatorOrderEnum.valueOf(getStringValue(SORT_NODES));
1263
        return value.equals(NavigatorOrderEnum.NaturalOrder);
1264

    
1265
    }
1266

    
1267
    /**
1268
     * @param orderActivated
1269
     */
1270
    public static boolean isNodesSortedByName() {
1271
        NavigatorOrderEnum value = NavigatorOrderEnum.valueOf(getStringValue(SORT_NODES));
1272
        return value.equals(NavigatorOrderEnum.AlphabeticalOrder);
1273

    
1274
    }
1275

    
1276
    /**
1277
     * @param orderActivated
1278
     */
1279
    public static boolean isNodesSortedByNameAndRank() {
1280
        NavigatorOrderEnum value = NavigatorOrderEnum.valueOf(getStringValue(SORT_NODES));
1281
        return value.equals(NavigatorOrderEnum.RankAndNameOrder);
1282

    
1283
    }
1284
	/**
1285
	 * <p>
1286
	 * setStoreNavigatorState
1287
	 * </p>
1288
	 *
1289
	 * @param selection
1290
	 *            a boolean.
1291
	 */
1292
	public static boolean isStoreNavigatorState() {
1293
		return getBooleanValue(RESTORE_NAVIGATOR_STATE);
1294

    
1295
	}
1296

    
1297
	/**
1298
	 * <p>
1299
	 * setStoreNavigatorState
1300
	 * </p>
1301
	 *
1302
	 * @param selection
1303
	 *            a boolean.
1304
	 */
1305
	public static void setStoreNavigatorState(boolean selection) {
1306
		setBooleanValue(RESTORE_NAVIGATOR_STATE, selection);
1307

    
1308
	}
1309

    
1310
    /**
1311
     * @return
1312
     */
1313
    public static boolean isShowUpWidgetIsDisposedMessages() {
1314
       return getBooleanValue(IS_SHOW_UP_WIDGET_IS_DISPOSED);
1315
    }
1316
    public static void setShowUpWidgetIsDisposedMessages(boolean selection) {
1317
        setBooleanValue(IS_SHOW_UP_WIDGET_IS_DISPOSED, selection);
1318
    }
1319

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

    
1351
    public static void setOwnDescriptionForChecklistEditor(boolean selection) {
1352
        setBooleanValue(EditorPreferencePredicate.OwnDescriptionForDistributionEditor.getKey(), selection);
1353
    }
1354

    
1355
    public static boolean isOwnDescriptionForChecklistEditor() {
1356
        return getBooleanValue(EditorPreferencePredicate.OwnDescriptionForDistributionEditor.getKey());
1357
    }
1358

    
1359
    /**
1360
     * @return
1361
     */
1362
    public static String displayAreaInChecklistEditor() {
1363
        String result = getStringValue(EditorPreferencePredicate.DisplayOfAreasInDistributionEditor.getKey());
1364
        if (result == null){
1365
            return (String) EditorPreferencePredicate.DisplayOfAreasInDistributionEditor.getDefaultValue();
1366
        }
1367
       return result;
1368
    }
1369

    
1370
    /**
1371
     * @return
1372
     */
1373
    public static String displayStatusInChecklistEditor() {
1374
        String result = getStringValue(EditorPreferencePredicate.DisplayOfStatus.getKey());
1375
        if (result == null){
1376
            return (String) EditorPreferencePredicate.DisplayOfStatus.getDefaultValue();
1377
        }
1378
       return result;
1379
    }
1380
    public static void setDisplayStatusInChecklistEditor(String selection) {
1381
        setStringValue(EditorPreferencePredicate.DisplayOfStatus.getKey(), selection);
1382
    }
1383

    
1384
    /**
1385
     * @return
1386
     */
1387
    public static boolean isShowRankInChecklistEditor() {
1388
        return getBooleanValue(EditorPreferencePredicate.ShowRankInDistributionEditor.getKey());
1389
    }
1390
    public static void setShowRankInChecklistEditor(boolean selection) {
1391
       setBooleanValue(EditorPreferencePredicate.ShowRankInDistributionEditor.getKey(), selection);
1392
    }
1393

    
1394
    /**
1395
     * @param object
1396
     * @param b
1397
     * @return
1398
     */
1399
    public static NameDetailsConfigurator getPreferredNameDetailsConfiguration( boolean local) {
1400
        NameDetailsConfigurator config = new NameDetailsConfigurator(true);
1401
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1402
        CdmPreference preference = null;
1403

    
1404
        if (!local) {
1405
            preference = cache.get(EditorPreferencePredicate.NameDetailsView.getKey());
1406
            if (preference == null){
1407
                return null;
1408
            }
1409

    
1410
            setBooleanValue(ALLOW_OVERRIDE_NAME_DETAILS, preference.isAllowOverride());
1411

    
1412
            //the preference value is build like this:
1413
            //<section1>:true;<section2>:false....
1414

    
1415
            String value = preference.getValue();
1416
            String [] sections = value.split(";");
1417
            Map<String, Boolean> sectionMap = new HashMap<String, Boolean>();
1418
            String[] sectionValues;
1419
            for (String sectionValue: sections){
1420
                sectionValues = sectionValue.split(":");
1421
                sectionMap.put(sectionValues[0], Boolean.valueOf(sectionValues[1]));
1422
            }
1423
            config.setAllowOverride(preference.isAllowOverride());
1424
            config.setSimpleDetailsViewActivated(getValue(sectionMap, "simpleViewActivated"));
1425

    
1426
    //        getPreferenceStore().setValue(SHOW_SIMPLE_NAME_DETAILS_TAXON,
1427
    //                (getValue(sectionMap, "taxon")));
1428
            config.setTaxonSectionActivated(getValue(sectionMap, "taxon"));
1429

    
1430
            config.setSecDetailsActivated(getValue(sectionMap, "taxon.SecEnabled"));
1431
            config.setSecEnabled(getValue(sectionMap, "taxon.SecDetails"));
1432

    
1433
    //        getPreferenceStore().setValue(SHOW_NAME_DETAILS_SECTION_LSID,
1434
    //                (getValue(sectionMap, "lsid")));
1435
            config.setLSIDActivated(getValue(sectionMap, "lsid"));
1436

    
1437
    //        getPreferenceStore().setValue(SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_CODE,
1438
    //                (getValue(sectionMap, "nc")));
1439
            config.setNomenclaturalCodeActived(getValue(sectionMap, "nc"));
1440

    
1441
    //        getPreferenceStore().setValue(SHOW_NAME_DETAILS_SECTION_APPENDED_PHRASE,
1442
    //                (getValue(sectionMap, "ap")));
1443
            config.setAppendedPhraseActivated(getValue(sectionMap, "ap"));
1444

    
1445
    //        getPreferenceStore().setValue(SHOW_NAME_DETAILS_SECTION_RANK,
1446
    //                (getValue(sectionMap, "rank")));
1447
            config.setRankActivated(getValue(sectionMap, "rank"));
1448

    
1449

    
1450
    //        getPreferenceStore().setValue(SHOW_NAME_DETAILS_SECTION_ATOMISED_EPITHETS,
1451
    //                (getValue(sectionMap, "atomisedEpithets")));
1452
            config.setAtomisedEpithetsActivated(getValue(sectionMap, "atomisedEpithets"));
1453

    
1454
    //        getPreferenceStore().setValue(SHOW_NAME_DETAILS_SECTION_AUTHORSHIP,
1455
    //                (getValue(sectionMap,"author")));
1456
            config.setAuthorshipSectionActivated(getValue(sectionMap,"author"));
1457

    
1458
    //        getPreferenceStore().setValue(SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_REFERENCE,
1459
    //                (getValue(sectionMap, "nomRef")));
1460
            config.setNomenclaturalReferenceSectionActivated(sectionMap.get("nomRef"));
1461

    
1462
    //        getPreferenceStore().setValue(SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_STATUS,
1463
    //                (getValue(sectionMap, "nomStat")));
1464
            config.setNomenclaturalStatusSectionActivated(getValue(sectionMap, "nomStat"));
1465

    
1466

    
1467
    //        getPreferenceStore().setValue(SHOW_NAME_DETAILS_SECTION_PROTOLOGUE,
1468
    //                (getValue(sectionMap,"protologue")));
1469
            config.setProtologueActivated(getValue(sectionMap,"protologue"));
1470

    
1471
    //        getPreferenceStore().setValue(SHOW_NAME_DETAILS_SECTION_TYPE_DESIGNATION,
1472
    //                (getValue(sectionMap,"typeDes")));
1473
            config.setTypeDesignationSectionActivated(getValue(sectionMap,"typeDes"));
1474

    
1475
    //        getPreferenceStore().setValue(SHOW_NAME_DETAILS_SECTION_NAME_RELATIONSHIP,
1476
    //                (getValue(sectionMap,"nameRelation")));
1477
            config.setNameRelationsSectionActivated(getValue(sectionMap,"nameRelation"));
1478

    
1479
    //        getPreferenceStore().setValue(SHOW_NAME_DETAILS_SECTION_HYBRID,
1480
    //                (getValue(sectionMap, "hybrid")));
1481
            config.setHybridActivated(getValue(sectionMap,"hybrid"));
1482
        }else{
1483
            config.setSimpleDetailsViewActivated(getBooleanValue(SHOW_SIMPLE_NAME_DETAILS_SECTION));
1484
            config.setTaxonSectionActivated(getBooleanValue(SHOW_SIMPLE_NAME_DETAILS_TAXON));
1485
            config.setSecDetailsActivated(getBooleanValue(SHOW_SEC_DETAILS));
1486
            config.setSecEnabled(getBooleanValue(DISABLE_SEC));
1487
            config.setLSIDActivated(getBooleanValue(SHOW_NAME_DETAILS_SECTION_LSID));
1488
            config.setNomenclaturalCodeActived(getBooleanValue(SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_CODE));
1489
            config.setAppendedPhraseActivated(getBooleanValue(SHOW_NAME_DETAILS_SECTION_APPENDED_PHRASE));
1490
            config.setRankActivated(getBooleanValue(SHOW_NAME_DETAILS_SECTION_RANK));
1491
            config.setAtomisedEpithetsActivated(getBooleanValue(SHOW_NAME_DETAILS_SECTION_ATOMISED_EPITHETS));
1492
            config.setAuthorshipSectionActivated(getBooleanValue(SHOW_NAME_DETAILS_SECTION_AUTHORSHIP));
1493
            config.setNomenclaturalReferenceSectionActivated(getBooleanValue(SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_REFERENCE));
1494
            config.setNomenclaturalStatusSectionActivated(getBooleanValue(SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_STATUS));
1495
            config.setProtologueActivated(getBooleanValue(SHOW_NAME_DETAILS_SECTION_PROTOLOGUE));
1496
            config.setTypeDesignationSectionActivated(getBooleanValue(SHOW_NAME_DETAILS_SECTION_TYPE_DESIGNATION));
1497
            config.setNameRelationsSectionActivated(getBooleanValue(SHOW_NAME_DETAILS_SECTION_NAME_RELATIONSHIP));
1498
            config.setHybridActivated(getBooleanValue(SHOW_NAME_DETAILS_SECTION_HYBRID));
1499
        }
1500
        return config;
1501
    }
1502

    
1503
    /**
1504
     * @param object
1505
     * @param b
1506
     * @return
1507
     */
1508
    public static void setPreferredNameDetailsConfiguration(NameDetailsConfigurator config, boolean local) {
1509
        CdmPreference preference = null;
1510

    
1511
        if (!local) {
1512
            preference = CdmPreference.NewInstance(PreferenceSubject.NewDatabaseInstance(), EditorPreferencePredicate.NameDetailsView, config.toString());
1513

    
1514
            setPreferenceToDB(preference);
1515
        }
1516
        //also add to local preferences
1517
        setBooleanValue(SHOW_SIMPLE_NAME_DETAILS_SECTION, config.isSimpleDetailsViewActivated());
1518
        setBooleanValue(SHOW_SIMPLE_NAME_DETAILS_TAXON, config.isTaxonSectionActivated());
1519
        setBooleanValue(SHOW_SEC_DETAILS, config.isSecDetailsActivated());
1520
        setBooleanValue(DISABLE_SEC, config.isSecEnabled());
1521
        setBooleanValue(SHOW_NAME_DETAILS_SECTION_LSID, config.isLSIDActivated());
1522
        setBooleanValue(SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_CODE, config.isNomenclaturalCodeActived());
1523
        setBooleanValue(SHOW_NAME_DETAILS_SECTION_APPENDED_PHRASE, config.isAppendedPhraseActivated());
1524
        setBooleanValue(SHOW_NAME_DETAILS_SECTION_RANK, config.isRankActivated());
1525
        setBooleanValue(SHOW_NAME_DETAILS_SECTION_ATOMISED_EPITHETS, config.isAtomisedEpithetsActivated());
1526
        setBooleanValue(SHOW_NAME_DETAILS_SECTION_AUTHORSHIP, config.isAuthorshipSectionActivated());
1527
        setBooleanValue(SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_REFERENCE, config.isNomenclaturalReferenceSectionActivated());
1528
        setBooleanValue(SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_STATUS, config.isNomenclaturalStatusSectionActivated());
1529
        setBooleanValue(SHOW_NAME_DETAILS_SECTION_PROTOLOGUE, config.isProtologueActivated());
1530
        setBooleanValue(SHOW_NAME_DETAILS_SECTION_TYPE_DESIGNATION, config.isTypeDesignationSectionActivated());
1531
        setBooleanValue(SHOW_NAME_DETAILS_SECTION_NAME_RELATIONSHIP, config.isNameRelationsSectionActivated());
1532
        setBooleanValue(SHOW_NAME_DETAILS_SECTION_HYBRID, config.isHybridActivated());
1533

    
1534
    }
1535

    
1536
    private static Boolean getValue(Map<String, Boolean> sectionMap, String string) {
1537
		if (sectionMap.containsKey(string)){
1538
			return sectionMap.get(string);
1539
		}else{
1540
			return true;
1541
		}
1542

    
1543
	}
1544

    
1545

    
1546

    
1547
    /**
1548
     * <p>
1549
     * setAbcdConfigurator
1550
     * </p>
1551
     *
1552
     * @param preferredConfiguration
1553
     *            a {@link eu.etaxonomy.cdm.io.specimen.abcd206.in.Abcd206ImportConfigurator}
1554
     *            object.
1555
     */
1556
    public static Abcd206ImportConfigurator getDBAbcdImportConfigurationPreference() {
1557

    
1558
        Abcd206ImportConfigurator config = Abcd206ImportConfigurator.NewInstance(null,null);
1559
        ICdmRepository controller;
1560
        controller = CdmStore.getCurrentApplicationConfiguration();
1561
        PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), EditorPreferencePredicate.AbcdImportConfig);
1562
        CdmPreference preference = null;
1563
        if (controller == null){
1564
            return null;
1565
        }
1566
        preference = controller.getPreferenceService().find(key);
1567
        if (preference == null){
1568
            return config;
1569
         } else{
1570
             String configString = preference.getValue();
1571
             String[] configArray = configString.split(";");
1572

    
1573
             for (String configItem: configArray){
1574
                 String[] keyValue = configItem.split(":");
1575
                 String keyString = keyValue[0];
1576
                 String valueString = null;
1577
                 if (keyValue.length>1){
1578
                      valueString = keyValue[1];
1579
                 }
1580
                 if (keyString.equals("ignoreImportOfExistingSpecimen")){
1581
                     config.setIgnoreImportOfExistingSpecimen(Boolean.valueOf(valueString));
1582
                 }else if (keyString.equals("addIndividualsAssociationsSuchAsSpecimenAndObservations")){
1583
                     config.setAddIndividualsAssociationsSuchAsSpecimenAndObservations(Boolean.valueOf(valueString));
1584
                 }else if (keyString.equals("reuseExistingTaxaWhenPossible")){
1585
                     config.setReuseExistingTaxaWhenPossible(Boolean.valueOf(valueString));
1586
                 }else if (keyString.equals("ignoreAuthorship")){
1587
                     config.setIgnoreAuthorship(Boolean.valueOf(valueString));
1588
                 }else if (keyString.equals("addMediaAsMediaSpecimen")){
1589
                     config.setAddMediaAsMediaSpecimen(Boolean.valueOf(valueString));
1590
                 }else if (keyString.equals("reuseExistingMetaData")){
1591
                     config.setReuseExistingMetaData(Boolean.valueOf(valueString));
1592
                 }else if (keyString.equals("reuseExistingDescriptiveGroups")){
1593
                     config.setReuseExistingDescriptiveGroups(Boolean.valueOf(valueString));
1594
                 }else if (keyString.equals("allowReuseOtherClassifications")){
1595
                     config.setAllowReuseOtherClassifications(Boolean.valueOf(valueString));
1596
                 }else if (keyString.equals("deduplicateReferences")){
1597
                     config.setDeduplicateReferences(Boolean.valueOf(valueString));
1598
                 }else if (keyString.equals("deduplicateClassifications")){
1599
                     config.setDeduplicateClassifications(Boolean.valueOf(valueString));
1600
                 }else if (keyString.equals("moveNewTaxaToDefaultClassification")){
1601
                     config.setMoveNewTaxaToDefaultClassification(Boolean.valueOf(valueString));
1602
                 }else if (keyString.equals("mapUnitIdToCatalogNumber")){
1603
                     config.setMapUnitIdToCatalogNumber(Boolean.valueOf(valueString));
1604
                 }else if (keyString.equals("mapUnitIdToAccessionNumber")){
1605
                     config.setMapUnitIdToAccessionNumber(Boolean.valueOf(valueString));
1606
                 }else if (keyString.equals("mapUnitIdToBarcode")){
1607
                     config.setMapUnitIdToBarcode(Boolean.valueOf(valueString));
1608
                 }else if (keyString.equals("overwriteExistingSpecimens")){
1609
                     config.setOverwriteExistingSpecimens(Boolean.valueOf(valueString));
1610
                 }else if (keyString.equals("nomenclaturalCode")){
1611
                         config.setNomenclaturalCode(NomenclaturalCode.fromString(valueString));
1612
                 }else{
1613
                     logger.debug("This key of the abcd configurator needs to be added to the transformer: " + keyString);
1614
                 }
1615

    
1616
             }
1617
        }
1618
        return config;
1619
    }
1620

    
1621
    public static Abcd206ImportConfigurator getLocalAbcdImportConfigurator(){
1622
       Abcd206ImportConfigurator config = Abcd206ImportConfigurator.NewInstance(null,null);
1623

    
1624
        config.setAddIndividualsAssociationsSuchAsSpecimenAndObservations(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_ADD_INDIVIDUALS_ASSOCIATIONS_SUCH_AS_SPECIMEN_AND_OBSERVATIONS));
1625

    
1626
        config.setAddMediaAsMediaSpecimen(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_ADD_MEDIA_AS_MEDIASPECIMEN));
1627

    
1628
        config.setAllowReuseOtherClassifications(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_ALLOW_REUSE_OTHER_CLASSIFICATIONS));
1629
        config.setDeduplicateClassifications(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_DEDUPLICATE_CLASSIFICATIONS));
1630
        config.setDeduplicateReferences(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_DEDUPLICATE_REFERENCES));
1631
        config.setRemoveCountryFromLocalityText(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_REMOVE_COUNTRY_FROM_LOCALITY_TEXT));
1632
        config.setGetSiblings(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_DO_SIBLINGS));
1633
        config.setIgnoreAuthorship(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_IGNORE_AUTHORSHIP));
1634
        config.setIgnoreImportOfExistingSpecimen(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_IGNORE_IMPORT_OF_EXISTING_SPECIMEN));
1635
        config.setMapUnitIdToAccessionNumber(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_MAP_UNIT_ID_TO_ACCESSION_NUMBER));
1636
        config.setMapUnitIdToBarcode(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_MAP_UNIT_ID_TO_BARCODE));
1637
        config.setMapUnitIdToCatalogNumber(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_MAP_UNIT_ID_TOCATALOG_NUMBER));
1638
        config.setMoveNewTaxaToDefaultClassification(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_MOVE_NEW_TAXA_TO_DEFAULT_CLASSIFICATION));
1639
        config.setOverwriteExistingSpecimens(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_OVERWRITE_EXISTING_SPECIMEN));
1640
        config.setReuseExistingDescriptiveGroups(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_REUSE_EXISTING_DESCRIPTIVE_GROUPS));
1641
        config.setReuseExistingMetaData(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_REUSE_EXISTING_META_DATA));
1642
        config.setReuseExistingTaxaWhenPossible(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_REUSE_EXISTING_TAXA_WHEN_POSSIBLE));
1643
        config.setNomenclaturalCode(NomenclaturalCode.getByKey(getStringValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_NOMENCLATURAL_CODE)));
1644

    
1645
        return config;
1646

    
1647
    }
1648

    
1649

    
1650
    public static void updateAbcdImportConfigurationPreference() {
1651
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1652
        CdmPreference pref = cache.get(EditorPreferencePredicate.AbcdImportConfig.getKey());
1653

    
1654
        if (!getBooleanValue(prefOverrideKey(EditorPreferencePredicate.AbcdImportConfig.getKey())) || !pref.isAllowOverride()){
1655
            resetToDBPreferenceAbcdCOnfigurator();
1656

    
1657
        }
1658
    }
1659

    
1660
    public static void resetToDBPreferenceAbcdCOnfigurator(){
1661
        Abcd206ImportConfigurator config = getDBAbcdImportConfigurationPreference();
1662
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_ADD_INDIVIDUALS_ASSOCIATIONS_SUCH_AS_SPECIMEN_AND_OBSERVATIONS, config.isAddIndividualsAssociationsSuchAsSpecimenAndObservations());
1663
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_ADD_MEDIA_AS_MEDIASPECIMEN, config.isAddMediaAsMediaSpecimen());
1664

    
1665
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_ALLOW_REUSE_OTHER_CLASSIFICATIONS, config.isAllowReuseOtherClassifications());
1666
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_DEDUPLICATE_CLASSIFICATIONS, config.isDeduplicateClassifications());
1667
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_DEDUPLICATE_REFERENCES, config.isDeduplicateReferences());
1668

    
1669
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_DO_SIBLINGS, config.isGetSiblings());
1670
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_IGNORE_AUTHORSHIP, config.isIgnoreAuthorship());
1671
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_IGNORE_IMPORT_OF_EXISTING_SPECIMEN, config.isIgnoreImportOfExistingSpecimen());
1672
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_MAP_UNIT_ID_TO_ACCESSION_NUMBER, config.isMapUnitIdToAccessionNumber());
1673
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_MAP_UNIT_ID_TO_BARCODE, config.isMapUnitIdToBarcode());
1674
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_MAP_UNIT_ID_TOCATALOG_NUMBER, config.isMapUnitIdToCatalogNumber());
1675
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_MOVE_NEW_TAXA_TO_DEFAULT_CLASSIFICATION, config.isMoveNewTaxaToDefaultClassification());
1676
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_OVERWRITE_EXISTING_SPECIMEN, config.isOverwriteExistingSpecimens());
1677
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_REUSE_EXISTING_DESCRIPTIVE_GROUPS, config.isReuseExistingDescriptiveGroups());
1678
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_REUSE_EXISTING_META_DATA, config.isReuseExistingMetaData());
1679
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_REUSE_EXISTING_TAXA_WHEN_POSSIBLE, config.isReuseExistingTaxaWhenPossible());
1680
        if (config.getNomenclaturalCode() != null){
1681
            setStringValue(ABCD_IMPORT_CONFIGURATOR_NOMENCLATURAL_CODE, config.getNomenclaturalCode().getKey());
1682
        }
1683
    }
1684

    
1685

    
1686
    /**
1687
    *
1688
    */
1689
   public NameDetailsConfigurator createLocalNameDetailsViewConfig(boolean local) {
1690
       NameDetailsConfigurator config = new NameDetailsConfigurator(true);
1691
       if (local){
1692
          config.setSimpleDetailsViewActivated(getBooleanValue(IPreferenceKeys.SHOW_SIMPLE_NAME_DETAILS_SECTION));
1693
          config.setAppendedPhraseActivated(getBooleanValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_APPENDED_PHRASE));
1694
          config.setAtomisedEpithetsActivated(getBooleanValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_ATOMISED_EPITHETS));
1695
          config.setAuthorshipSectionActivated(getBooleanValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_AUTHORSHIP));
1696
          config.setLSIDActivated(getBooleanValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_LSID));
1697
          config.setNameApprobiationActivated(getBooleanValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_NAME_APPROBATION));
1698
          config.setNameCacheActivated(getBooleanValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_CACHE));
1699
          config.setNameRelationsSectionActivated(getBooleanValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_NAME_RELATIONSHIP));
1700
          config.setNomenclaturalCodeActived(getBooleanValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_CODE));
1701
          config.setNomenclaturalStatusSectionActivated(getBooleanValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_STATUS));
1702
          config.setNomenclaturalReferenceSectionActivated(getBooleanValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_REFERENCE));
1703
          config.setProtologueActivated(getBooleanValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_PROTOLOGUE));
1704
          config.setRankActivated(getBooleanValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_RANK));
1705
          config.setTaxonSectionActivated(getBooleanValue(IPreferenceKeys.SHOW_SIMPLE_NAME_DETAILS_TAXON));
1706
          config.setTypeDesignationSectionActivated(getBooleanValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_TYPE_DESIGNATION));
1707
          config.setHybridActivated(getBooleanValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_HYBRID));
1708
       }else{
1709

    
1710
       }
1711

    
1712
      return config;
1713
   }
1714

    
1715

    
1716
   public static void saveConfigToPrefernceStore(NameDetailsConfigurator config) {
1717
       setBooleanValue(IPreferenceKeys.SHOW_SIMPLE_NAME_DETAILS_SECTION,
1718
               config.isSimpleDetailsViewActivated());
1719
       setBooleanValue(IPreferenceKeys.SHOW_SIMPLE_NAME_DETAILS_TAXON, config.isTaxonSectionActivated());
1720
       setBooleanValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_LSID, config.isLSIDActivated());
1721
       setBooleanValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_CODE,
1722
               config.isNomenclaturalCodeActived());
1723
       setBooleanValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_NAMECACHE,
1724
               config.isNameCacheActivated());
1725
       setBooleanValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_APPENDED_PHRASE,
1726
               config.isAppendedPhraseActivated());
1727
       setBooleanValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_RANK, config.isRankActivated());
1728
       setBooleanValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_ATOMISED_EPITHETS,
1729
               config.isAtomisedEpithetsActivated());
1730
       setBooleanValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_AUTHORSHIP_CACHE,
1731
               config.isAuthorCacheActivated());
1732
       setBooleanValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_AUTHORSHIP,
1733
               config.isAuthorshipSectionActivated());
1734
       setBooleanValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_REFERENCE,
1735
               config.isNomenclaturalReferenceSectionActivated());
1736
       setBooleanValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_NOMENCLATURAL_STATUS,
1737
               config.isNomenclaturalStatusSectionActivated());
1738
       setBooleanValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_PROTOLOGUE,
1739
               config.isProtologueActivated());
1740
       setBooleanValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_TYPE_DESIGNATION,
1741
               config.isTypeDesignationSectionActivated());
1742
       setBooleanValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_NAME_RELATIONSHIP,
1743
               config.isNameRelationsSectionActivated());
1744
       setBooleanValue(IPreferenceKeys.SHOW_NAME_DETAILS_SECTION_HYBRID,
1745
               config.isHybridActivated());
1746

    
1747
   }
1748

    
1749
/**
1750
 * @return
1751
 */
1752
public static boolean isSortTaxaByRankAndName() {
1753

    
1754
    return getBooleanValue(IPreferenceKeys.SORT_TAXA_BY_RANK_AND_NAME);
1755
}
1756

    
1757
/**
1758
 * @return
1759
 */
1760
public static boolean isSortNamedAreaByOrderInVocabulary() {
1761

    
1762
    return getBooleanValue(EditorPreferencePredicate.AreasSortedByIdInVocabulary.getKey());
1763
}
1764

    
1765
public static void setSortNamedAreasByOrderInVocabulary(boolean isSortByVocabularyOrder) {
1766
    setBooleanValue(EditorPreferencePredicate.AreasSortedByIdInVocabulary.getKey(), isSortByVocabularyOrder);
1767

    
1768
}
1769

    
1770
/**
1771
 * <p>
1772
 * setPreferredNamedAreasForDistributionEditor
1773
 * </p>
1774
 *
1775
 * @param saveCheckedElements
1776
 * @param saveGrayedElements
1777
 */
1778
public static void setLastSelectedReference(
1779
        List<String> lastSelectedReferences) {
1780

    
1781
        setStringValue(PreferencesUtil.LAST_SELECTED_REFERENCES, lastSelectedReferences.toString());
1782
    }
1783

    
1784
/**
1785
 * <p>
1786
 * setPreferredNamedAreasForDistributionEditor
1787
 * </p>
1788
 *
1789
 * @param saveCheckedElements
1790
 * @param saveGrayedElements
1791
 */
1792
public static List<String> getLastSelectedReferences() {
1793

    
1794
        //IPreferenceStore preferenceStore = PreferencesUtil.getPreferenceStore();
1795
        String lastSelected = getStringValue(PreferencesUtil.LAST_SELECTED_REFERENCES);
1796
        List<String> result = new ArrayList<>();
1797
        if (!StringUtils.isBlank(lastSelected)){
1798
            Collections.addAll(result, lastSelected.substring(1,lastSelected.length()-1).split(", "));
1799
        }
1800
        return result;
1801
    }
1802

    
1803

    
1804
/**
1805
 * <p>
1806
 * setPreferredNamedAreasForDistributionEditor
1807
 * </p>
1808
 *
1809
 * @param saveCheckedElements
1810
 * @param saveGrayedElements
1811
 */
1812
public static void setPreferredNamedAreasForDistributionEditor(
1813
        String saveCheckedElements, String saveGrayedElements, boolean local) {
1814
    if (local){
1815
        setStringValue(EditorPreferencePredicate.AvailableDistributionAreaTerms.getKey(), saveCheckedElements);
1816

    
1817
    }
1818
    else{
1819
        CdmPreference preference = null;
1820

    
1821
        if (saveCheckedElements == null){
1822
            preference = getPreferenceFromDB(EditorPreferencePredicate.AvailableDistributionAreaTerms);
1823

    
1824
            if (preference == null){
1825
                return ;
1826
            } else{
1827
                setStringValue(EditorPreferencePredicate.AvailableDistributionAreaTerms.getKey(),
1828
                        saveCheckedElements);
1829
                preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), EditorPreferencePredicate.AvailableDistributionAreaTerms, saveCheckedElements);
1830
                setPreferenceToDB(preference);
1831

    
1832
            }
1833
        } else{
1834
           preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), EditorPreferencePredicate.AvailableDistributionAreaTerms, saveCheckedElements);
1835
           setPreferenceToDB(preference);
1836
           setStringValue(EditorPreferencePredicate.AvailableDistributionAreaTerms.getKey(),
1837
                    saveCheckedElements);
1838

    
1839
        }
1840
    }
1841

    
1842
}
1843

    
1844
/**
1845
 * @param saveCheckedElements
1846
 * @param saveCheckedElements2
1847
 * @param b
1848
 */
1849
public static void setPreferredVocabulariesForDistributionEditor(String saveCheckedElements,
1850
        boolean local, boolean isOverride) {
1851
    if (local){
1852
      setStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(), saveCheckedElements);
1853
      setBooleanValue(prefOverrideKey(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey()), isOverride);
1854
    }
1855
    else{
1856
        ICdmRepository controller;
1857
        CdmPreference preference = null;
1858

    
1859
        if (saveCheckedElements == null){
1860
            preference = getPreferenceFromDB(PreferencePredicate.AvailableDistributionAreaVocabularies);
1861

    
1862
            if (preference == null){
1863
                return ;
1864
            } else{
1865
                setStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(),
1866
                        saveCheckedElements);
1867
                preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AvailableDistributionAreaVocabularies, saveCheckedElements);
1868
                preference.setAllowOverride(isOverride);
1869
                setPreferenceToDB(preference);
1870
            }
1871
        } else{
1872
            preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AvailableDistributionAreaVocabularies, saveCheckedElements);
1873
            preference.setAllowOverride(isOverride);
1874
            setPreferenceToDB(preference);
1875
            setStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(),
1876
                    saveCheckedElements);
1877

    
1878
        }
1879
    }
1880
}
1881

    
1882

    
1883

    
1884

    
1885
/**
1886
 * @param saveCheckedElements
1887
 * @param saveCheckedElements2
1888
 * @param b
1889
 */
1890
public static String getPreferredVocabulariesForDistributionEditor(boolean local) {
1891
    if (local){
1892

    
1893
        String pref = getStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(), local);
1894
        return pref;
1895
    }
1896
    else{
1897
        CdmPreference preference = null;
1898
        preference = getPreferenceFromDB(PreferencePredicate.AvailableDistributionAreaVocabularies);
1899
        if (preference == null){
1900
            return null;
1901
        } else{
1902
            return preference.getValue();
1903
        }
1904

    
1905
    }
1906

    
1907

    
1908

    
1909
}
1910

    
1911
public static boolean getFilterCommonNameReferences(){
1912
    return getBooleanValue(PreferencesUtil.FILTER_COMMON_NAME_REFERENCES);
1913
}
1914

    
1915
/**
1916
 *
1917
 */
1918
public static void updateDBPreferences() {
1919
    CdmPreference preference = null;
1920
    CdmPreferenceCache cache = CdmPreferenceCache.instance();
1921
    cache.getAllTaxEditorDBPreferences();
1922

    
1923
    //ABCD Configurator
1924

    
1925
    updateAbcdImportConfigurationPreference();
1926

    
1927
    //Name Details
1928
    NameDetailsConfigurator config = getPreferredNameDetailsConfiguration(false);
1929
    if (config != null ){
1930
        if (!getBooleanValue(OVERRIDE_NAME_DETAILS) ||  !getBooleanValue(ALLOW_OVERRIDE_NAME_DETAILS)){
1931
            setPreferredNameDetailsConfiguration(config, false);
1932
        }
1933
    }
1934

    
1935

    
1936

    
1937

    
1938

    
1939

    
1940

    
1941

    
1942
}
1943

    
1944

    
1945

    
1946

    
1947

    
1948

    
1949

    
1950

    
1951
}
(26-26/39)