Project

General

Profile

Download (62.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
	static String prefKey(String name) {
111
	    return name + "_"+  ((CdmRemoteSource)CdmStore.getActiveCdmSource()).toString();
112
	}
113

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

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

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

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

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

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

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

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

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

    
209
    }
210

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

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

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

    
253

    
254
    }
255

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

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

    
282
    }
283

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

    
310
    }
311

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

    
338
    }
339

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

    
367

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

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

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

    
411
    		}
412
	    }
413
        return null;
414

    
415

    
416

    
417
	}
418

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

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

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

    
445
    }
446

    
447

    
448
	public static NomenclaturalCode getPreferredNomenclaturalCode(){
449
	    if (getBooleanValue(prefOverrideKey(PreferencePredicate.NomenclaturalCode.getKey()))) {
450
            return getPreferredNomenclaturalCode(true);
451
        } else{
452
            return getPreferredNomenclaturalCode(false);
453
        }
454
	}
455

    
456
	/**
457
	 * <p>
458
	 * getPreferredNomenclaturalCode
459
	 * </p>
460
	 *
461
	 * @return a {@link eu.etaxonomy.cdm.model.name.NomenclaturalCode} object.
462
	 */
463
	public static NomenclaturalCode getPreferredNomenclaturalCode(boolean useLocal) {
464

    
465
		CdmPreference pref = null;
466
		if (!useLocal){
467
		    pref = getPreferenceFromDB(PreferencePredicate.NomenclaturalCode);
468
		}
469

    
470
	    String preferredCode;
471
	    if(pref == null){
472
	    	preferredCode = getStringValue(
473
					PREFERRED_NOMENCLATURAL_CODE_KEY, true);
474

    
475
	    }else{
476
	    	preferredCode = pref.getValue();
477
	    }
478

    
479
	    return getPreferredNomenclaturalCode(preferredCode);
480

    
481
	}
482

    
483
	/**
484
     * <p>
485
     * getPreferredNomenclaturalCode
486
     * </p>
487
     *
488
     * @return a {@link eu.etaxonomy.cdm.model.name.NomenclaturalCode} object.
489
     */
490
    public static NomenclaturalCode getPreferredNomenclaturalCode(String preferenceKeyNomenclaturalCode) {
491

    
492
        for (NomenclaturalCode code : NomenclaturalCodeHelper.getAllCodes()) {
493
            if (getPreferenceKey(code).equals(preferenceKeyNomenclaturalCode)) {
494
                return code;
495
            }
496
        }
497
        return null;
498
    }
499

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

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

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

    
515
	public static boolean isCollectingAreaInGeneralSection(){
516
	    boolean result =  getBooleanValue(PreferencePredicate.ShowCollectingAreasInGeneralSection.getKey());
517
        return result;
518
	}
519

    
520
	public static CdmPreference getPreferenceFromDB(IPreferencePredicate predicate){
521
        ICdmRepository controller;
522
        CdmPreference pref = null;
523

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

    
534
        return pref;
535

    
536
    }
537

    
538
    public static void setPreferenceToDB(CdmPreference preference){
539
        ICdmRepository controller;
540
        try{
541
            if(CdmStore.isActive()){
542
                controller = CdmStore.getCurrentApplicationConfiguration();
543
                controller.getPreferenceService().set(preference);
544
            }
545
        }catch(Exception e){
546
            e.printStackTrace();
547
        }
548

    
549
    }
550

    
551

    
552

    
553
	public static String getPreferredDefaultLangugae(){
554
	    String preferredLanguage = getStringValue(DEFAULT_LANGUAGE_EDITOR);
555
	    if(StringUtils.isNotEmpty(preferredLanguage) && StringUtils.isNotBlank(preferredLanguage)){
556
	        return preferredLanguage;
557
	    }
558
	    return null;
559
	}
560

    
561
	public static boolean isShowMediaPreview(){
562
        boolean isShowMediaPreview = getBooleanValue(SHOW_MEDIA_PREVIEW);
563
        return isShowMediaPreview;
564
    }
565

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

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

    
593
			return matchStrategy;
594
		}
595
		return getDefaultMatchStrategy(clazz);
596
	}
597

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

    
609
		List<FieldMatcher> fieldMatchers = matchStrategy.getMatching().getFieldMatchers(false);
610

    
611
		for (FieldMatcher fieldMatcher : fieldMatchers) {
612
			String fieldName = fieldMatcher.getPropertyName();
613
			setStringValue(
614
					getMatchStrategyFieldName(className, fieldName),
615
					fieldMatcher.getMatchMode().name());
616
		}
617
	}
618

    
619
	/**
620
	 * Helper method to create the preference property for a match field.
621
	 *
622
	 * @param className
623
	 * @param fieldName
624
	 * @return
625
	 */
626
	private static String getMatchStrategyFieldName(String className,
627
			String fieldName) {
628
		return MATCH_STRATEGY_PREFIX + className + "." + fieldName;
629
	}
630

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

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

    
655
	/**
656
	 * <p>
657
	 * addTermToPreferredTerms
658
	 * </p>
659
	 *
660
	 * @param term
661
	 *            a T object.
662
	 * @param <T>
663
	 *            a T object.
664
	 */
665
	public static <T extends TermBase> void addTermToPreferredTerms(T term) {
666

    
667
		// VocabularyEnum vocabulary =
668
		// VocabularyEnum.getVocabularyEnum(term.getClass());
669
		//
670
		// getPreferenceStore().setValue(getPreferenceKey(term),
671
		// VocabularyStore.getTermVocabulary(vocabulary).getTerms().contains(term));
672
		//
673
		// firePreferencesChanged(term.getClass());
674
	}
675

    
676
	/**
677
	 * Construct a unique key using the CdmBase object's uuid
678
	 *
679
	 * @param cdmBase
680
	 * @return
681
	 */
682
	private static String getPreferenceKey(ICdmBase cdmBase) {
683
		cdmBase = HibernateProxyHelper.deproxy(cdmBase);
684

    
685
		String key = cdmBase.getClass().getName().concat(".")
686
				.concat(cdmBase.getUuid().toString());
687
		if (key.contains("javassist")) {
688
			MessagingUtils.info("proxy");
689
		}
690
		return key;
691
	}
692

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

    
710

    
711

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

    
729
	/**
730
	 * Retrieves search preferences from the preference store
731
	 *
732
	 * @return an {@link ITaxonServiceConfigurator} to pass to search methods
733
	 */
734
	public static IFindTaxaAndNamesConfigurator getSearchConfigurator() {
735
		IFindTaxaAndNamesConfigurator configurator = initializeSearchConfigurator();
736

    
737
		configurator.setDoTaxa(getBooleanValue(
738
				TAXON_SERVICE_CONFIGURATOR_TAXA));
739
		configurator.setDoSynonyms(getBooleanValue(
740
				TAXON_SERVICE_CONFIGURATOR_SYNONYMS));
741
		configurator.setDoNamesWithoutTaxa(getBooleanValue(
742
				TAXON_SERVICE_CONFIGURATOR_NAMES));
743
		configurator.setDoTaxaByCommonNames(getBooleanValue(
744
				TAXON_SERVICE_CONFIGURATOR_COMMON_NAMES));
745
		//configurator.setMatchMode(eu.etaxonomy.cdm.persistence.query.MatchMode.valueOf(getStringValue(TAXON_SERVICE_CONFIGURATOR_MATCH_MODE)));
746

    
747
		return configurator;
748
	}
749

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

    
760
		configurator.setDoTaxa(true);
761
		configurator.setDoSynonyms(true);
762
		configurator.setDoNamesWithoutTaxa(true);
763
		configurator.setDoTaxaByCommonNames(true);
764

    
765
		configurator.setTaxonPropertyPath(Arrays.asList("$", "titleCache",
766
				"name", "name.$", "relationsFromThisTaxon.$"));
767

    
768
		configurator.setSynonymPropertyPath(Arrays.asList("$", "titleCache",
769
				"name", "name.$", "synonyms.relatedTo.*"));
770

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

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

    
804
	/**
805
	 * <p>
806
	 * firePreferencesChanged
807
	 * </p>
808
	 *
809
	 * @param clazz
810
	 *            a {@link java.lang.Class} object.
811
	 */
812
	public static void firePreferencesChanged(Class clazz) {
813
		getPreferenceStore().firePropertyChangeEvent(PREFERRED_TERMS_CHANGE,
814
				null, clazz);
815
	}
816

    
817
	public static String createPreferenceString(String property){
818
	   return prefKey(property);
819

    
820
	}
821
	public static String createOverridePreferenceString(String property){
822
	       return prefOverrideKey(property);
823

    
824
	    }
825

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

    
846

    
847
		//Name Details
848
		getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.NameDetailsView.getKey()), new NameDetailsConfigurator(false).toString());
849

    
850
		//Navigator preferences
851
		getPreferenceStore().setDefault(createPreferenceString(SORT_NODES), NavigatorOrderEnum.RankAndNameOrder.getKey());
852

    
853
		getPreferenceStore().setDefault(createPreferenceString(SORT_TAXA_BY_RANK_AND_NAME), true);
854
		//override db preferences
855
		getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.AbcdImportConfig.getKey())), false);
856
		getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.ShowSpecimen.getKey())), true);
857
		getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.NameDetailsView.getKey())), false);
858
		getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.DistributionEditorActivated.getKey())), false);
859

    
860
		getPreferenceStore().setDefault(createPreferenceString(FILTER_COMMON_NAME_REFERENCES), false);
861
		getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowTaxonNodeWizard.getKey()), Boolean.valueOf(PreferencePredicate.ShowTaxonNodeWizard.getDefaultValue().toString()));
862
		getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowNamespaceInSource.getKey()), Boolean.valueOf(PreferencePredicate.ShowNamespaceInSource.getDefaultValue().toString()));
863
		getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowIdInSource.getKey()), Boolean.valueOf(PreferencePredicate.ShowIdInSource.getDefaultValue().toString()));
864
		getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.DisableMultiClassification.getKey()), Boolean.valueOf(PreferencePredicate.DisableMultiClassification.getDefaultValue().toString()));
865

    
866
	}
867

    
868
	/**
869
	 * <p>
870
	 * checkNomenclaturalCode
871
	 * </p>
872
	 */
873
	public static void checkNomenclaturalCode() {
874
		// First time Editor is opened, no nomenclatural code has been set
875
		if (PreferencesUtil.getPreferredNomenclaturalCode(true) == null) {
876
			PreferencesUtil.setPreferredNomenclaturalCode(getPreferenceKey(NomenclaturalCode.ICNAFP), true);
877
		}
878

    
879

    
880

    
881
	}
882
	public static void setNomenclaturalCodePreferences(){
883
	    ICdmRepository controller;
884
        controller = CdmStore.getCurrentApplicationConfiguration();
885
        PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.NomenclaturalCode);
886
        CdmPreference preference = null;
887
        if (controller == null){
888
            return ;
889
        }
890
        preference = controller.getPreferenceService().find(key);
891
        if (preference == null){
892
            return;
893
        }
894
//        setBooleanValue(ALLOW_OVERRIDE_NOMENCLATURAL_CODE_KEY, preference.isAllowOverride());
895

    
896
        int index = StringUtils.lastIndexOf(preference.getValue(), ".");
897
        UUID uuid = UUID.fromString(preference.getValue().substring(index +1, preference.getValue().length()));
898
        NomenclaturalCode preferredCode = NomenclaturalCode.getByUuid(uuid);
899

    
900
        setStringValue(PREFERRED_NOMENCLATURAL_CODE_KEY,
901
                getPreferenceKey(preferredCode));
902

    
903
	}
904

    
905
	public static void checkDefaultLanguage(){
906
	    if(PreferencesUtil.getPreferredDefaultLangugae() == null){
907
	       Shell shell = AbstractUtility.getShell();
908
	       int open = new DefaultLanguageDialog(shell).open();
909
	       if(open == Window.OK){
910
	           PlatformUI.getWorkbench().restart();
911
	       }
912
	    }else{
913
	        //TODO:In case of a reinstall, the config.ini will be overwritten
914
	        //     here you create config.ini with the stored key from preferences
915
	    }
916
	}
917

    
918
	/**
919
	 * <p>
920
	 * getMapServiceAccessPoint
921
	 * </p>
922
	 *
923
	 * @return a {@link java.lang.String} object.
924
	 */
925
	public static String getMapServiceAccessPoint() {
926
		return getStringValue(EDIT_MAP_SERVICE_ACCES_POINT);
927
	}
928

    
929
	/**
930
	 * <p>
931
	 * shouldConnectAtStartUp
932
	 * </p>
933
	 *
934
	 * @return a boolean.
935
	 */
936
	public static boolean shouldConnectAtStartUp() {
937
		//FIXME :  force SHOULD_CONNECT_AT_STARTUP to false (ticket 3828) until resolution
938
		//return getBooleanValue(SHOULD_CONNECT_AT_STARTUP);
939
		return false;
940
	}
941

    
942
	/**
943
	 * <p>
944
	 * getDefaultFeatureTreeForTextualDescription
945
	 * </p>
946
	 *
947
	 * @return a {@link eu.etaxonomy.cdm.model.description.FeatureTree} object.
948
	 */
949
	public static FeatureTree getDefaultFeatureTreeForTextualDescription() {
950
		String uuidString = getStringValue(
951
				FEATURE_TREE_DEFAULT_TEXT);
952
		if (StringUtils.isBlank(uuidString)) {
953
            return null;
954
        }
955
		FeatureTree tree = CdmStore.getService(
956
	                IFeatureTreeService.class).load(UUID.fromString(uuidString));
957
		if (tree.getId() == 0) {
958
            return null;
959
        }
960
		return tree;
961
	}
962

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

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

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

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

    
1005
	public static Language getGlobalLanguage() {
1006

    
1007

    
1008
		String languageUuidString = getStringValue(
1009
				GLOBAL_LANGUAGE_UUID);
1010

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

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

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

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

    
1031
	}
1032

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

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

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

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

    
1049
		return result;
1050
	}
1051

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

    
1063
	}
1064

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

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

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

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

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

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

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

    
1179

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

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

    
1211
        return p2Repos;
1212
    }
1213

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

    
1231

    
1232

    
1233

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

    
1240
    }
1241

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

    
1248
    }
1249

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

    
1257
    }
1258

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

    
1266
    }
1267

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

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

    
1287
	}
1288

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

    
1300
	}
1301

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

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

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

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

    
1351
    /**
1352
     * @return
1353
     */
1354
    public static String displayAreaInChecklistEditor() {
1355
        String result = getStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey());
1356
        if (StringUtils.isBlank(result)){
1357
            return ((TermDisplayEnum) PreferencePredicate.DisplayOfAreasInDistributionEditor.getDefaultValue()).getKey();
1358
        }
1359
       return result;
1360
    }
1361

    
1362
    /**
1363
     * @return
1364
     */
1365
    public static String displayStatusInChecklistEditor() {
1366
        String result = getStringValue(PreferencePredicate.DisplayOfStatus.getKey());
1367
        if (StringUtils.isBlank(result)){
1368
            return((TermDisplayEnum) PreferencePredicate.DisplayOfStatus.getDefaultValue()).getKey();
1369
        }
1370
       return result;
1371
    }
1372
    public static void setDisplayStatusInChecklistEditor(String selection) {
1373
        setStringValue(PreferencePredicate.DisplayOfStatus.getKey(), selection);
1374

    
1375
    }
1376

    
1377
    /**
1378
     * @return
1379
     */
1380
    public static boolean isShowRankInChecklistEditor() {
1381
        return getBooleanValue(PreferencePredicate.ShowRankInDistributionEditor.getKey());
1382
    }
1383
    public static void setShowRankInChecklistEditor(boolean selection) {
1384
       setBooleanValue(PreferencePredicate.ShowRankInDistributionEditor.getKey(), selection);
1385
    }
1386

    
1387
    /**
1388
     * @param object
1389
     * @param b
1390
     * @return
1391
     */
1392
    public static NameDetailsConfigurator getPreferredNameDetailsConfiguration( boolean local) {
1393
        NameDetailsConfigurator config = new NameDetailsConfigurator(true);
1394
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1395
        CdmPreference preference = null;
1396
        String value;
1397
        if (!local) {
1398
            preference = cache.get(PreferencePredicate.NameDetailsView.getKey());
1399
            if (preference == null){
1400
                return null;
1401
            }
1402

    
1403
        //    setBooleanValue(ALLOW_OVERRIDE_NAME_DETAILS, preference.isAllowOverride());
1404
            value = preference.getValue();
1405
            config.setAllowOverride(preference.isAllowOverride());
1406
            //the preference value is build like this:
1407
            //<section1>:true;<section2>:false....
1408
        }else{
1409
            value = getStringValue(PreferencePredicate.NameDetailsView.getKey(), local);
1410
        }
1411
        String [] sections = value.split(";");
1412
        Map<String, Boolean> sectionMap = new HashMap<String, Boolean>();
1413
        String[] sectionValues;
1414
        for (String sectionValue: sections){
1415
            sectionValues = sectionValue.split(":");
1416
            sectionMap.put(sectionValues[0], Boolean.valueOf(sectionValues[1]));
1417
        }
1418

    
1419
        config.setSimpleDetailsViewActivated(getValue(sectionMap, "simpleViewActivated"));
1420

    
1421
        config.setTaxonSectionActivated(getValue(sectionMap, "taxon"));
1422

    
1423
        config.setSecDetailsActivated(getValue(sectionMap, "taxon.SecDetails"));
1424
        config.setSecEnabled(getValue(sectionMap, "taxon.SecEnabled"));
1425

    
1426
        config.setLSIDActivated(getValue(sectionMap, "lsid"));
1427

    
1428
        config.setNomenclaturalCodeActived(getValue(sectionMap, "nc"));
1429

    
1430
        config.setAppendedPhraseActivated(getValue(sectionMap, "ap"));
1431

    
1432
        config.setRankActivated(getValue(sectionMap, "rank"));
1433

    
1434
        config.setAtomisedEpithetsActivated(getValue(sectionMap, "atomisedEpithets"));
1435

    
1436
        config.setAuthorshipSectionActivated(getValue(sectionMap,"author"));
1437

    
1438
        config.setNomenclaturalReferenceSectionActivated(sectionMap.get("nomRef"));
1439

    
1440
        config.setNomenclaturalStatusSectionActivated(getValue(sectionMap, "nomStat"));
1441

    
1442
        config.setProtologueActivated(getValue(sectionMap,"protologue"));
1443

    
1444
        config.setTypeDesignationSectionActivated(getValue(sectionMap,"typeDes"));
1445

    
1446
        config.setNameRelationsSectionActivated(getValue(sectionMap,"nameRelation"));
1447

    
1448
            config.setHybridActivated(getValue(sectionMap,"hybrid"));
1449

    
1450
        return config;
1451
    }
1452

    
1453
    public static NameDetailsConfigurator getPreferredNameDetailsConfiguration() {
1454
        NameDetailsConfigurator config = new NameDetailsConfigurator(true);
1455

    
1456
        String value;
1457

    
1458
        value = getStringValue(PreferencePredicate.NameDetailsView.getKey(), false);
1459

    
1460
        String [] sections = value.split(";");
1461
        Map<String, Boolean> sectionMap = new HashMap<String, Boolean>();
1462
        String[] sectionValues;
1463
        for (String sectionValue: sections){
1464
            sectionValues = sectionValue.split(":");
1465
            sectionMap.put(sectionValues[0], Boolean.valueOf(sectionValues[1]));
1466
        }
1467

    
1468
        config.setSimpleDetailsViewActivated(getValue(sectionMap, "simpleViewActivated"));
1469

    
1470
        config.setTaxonSectionActivated(getValue(sectionMap, "taxon"));
1471

    
1472
        config.setSecDetailsActivated(getValue(sectionMap, "taxon.SecDetails"));
1473
        config.setSecEnabled(getValue(sectionMap, "taxon.SecEnabled"));
1474

    
1475
        config.setLSIDActivated(getValue(sectionMap, "lsid"));
1476

    
1477
        config.setNomenclaturalCodeActived(getValue(sectionMap, "nc"));
1478

    
1479
        config.setAppendedPhraseActivated(getValue(sectionMap, "ap"));
1480

    
1481
        config.setRankActivated(getValue(sectionMap, "rank"));
1482

    
1483
        config.setAtomisedEpithetsActivated(getValue(sectionMap, "atomisedEpithets"));
1484

    
1485
        config.setAuthorshipSectionActivated(getValue(sectionMap,"author"));
1486

    
1487
        config.setNomenclaturalReferenceSectionActivated(sectionMap.get("nomRef"));
1488

    
1489
        config.setNomenclaturalStatusSectionActivated(getValue(sectionMap, "nomStat"));
1490

    
1491
        config.setProtologueActivated(getValue(sectionMap,"protologue"));
1492

    
1493
        config.setTypeDesignationSectionActivated(getValue(sectionMap,"typeDes"));
1494

    
1495
        config.setNameRelationsSectionActivated(getValue(sectionMap,"nameRelation"));
1496

    
1497
            config.setHybridActivated(getValue(sectionMap,"hybrid"));
1498

    
1499
        return config;
1500
    }
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.NewTaxEditorInstance(), PreferencePredicate.NameDetailsView, config.toString());
1513

    
1514
            setPreferenceToDB(preference);
1515
        }
1516
        else{
1517
            setStringValue(PreferencePredicate.NameDetailsView.getKey(), config.toString());
1518
        }
1519

    
1520

    
1521
    }
1522

    
1523
    private static Boolean getValue(Map<String, Boolean> sectionMap, String string) {
1524
		if (sectionMap.containsKey(string)){
1525
			return sectionMap.get(string);
1526
		}else{
1527
			return true;
1528
		}
1529

    
1530
	}
1531

    
1532

    
1533

    
1534
    /**
1535
     * <p>
1536
     * setAbcdConfigurator
1537
     * </p>
1538
     *
1539
     * @param preferredConfiguration
1540
     *            a {@link eu.etaxonomy.cdm.io.specimen.abcd206.in.Abcd206ImportConfigurator}
1541
     *            object.
1542
     */
1543
    public static Abcd206ImportConfigurator getDBAbcdImportConfigurationPreference() {
1544

    
1545
        Abcd206ImportConfigurator config = Abcd206ImportConfigurator.NewInstance(null,null);
1546
        ICdmRepository controller;
1547
        controller = CdmStore.getCurrentApplicationConfiguration();
1548
        PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AbcdImportConfig);
1549
        CdmPreference preference = null;
1550
        if (controller == null){
1551
            return null;
1552
        }
1553
        preference = controller.getPreferenceService().find(key);
1554
        if (preference == null){
1555
            return config;
1556
         } else{
1557
             String configString = preference.getValue();
1558
             String[] configArray = configString.split(";");
1559

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

    
1603
             }
1604
        }
1605
        return config;
1606
    }
1607

    
1608
    public static Abcd206ImportConfigurator getLocalAbcdImportConfigurator(){
1609
       Abcd206ImportConfigurator config = Abcd206ImportConfigurator.NewInstance(null,null);
1610

    
1611
        config.setAddIndividualsAssociationsSuchAsSpecimenAndObservations(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_ADD_INDIVIDUALS_ASSOCIATIONS_SUCH_AS_SPECIMEN_AND_OBSERVATIONS));
1612

    
1613
        config.setAddMediaAsMediaSpecimen(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_ADD_MEDIA_AS_MEDIASPECIMEN));
1614

    
1615
        config.setAllowReuseOtherClassifications(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_ALLOW_REUSE_OTHER_CLASSIFICATIONS));
1616
        config.setDeduplicateClassifications(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_DEDUPLICATE_CLASSIFICATIONS));
1617
        config.setDeduplicateReferences(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_DEDUPLICATE_REFERENCES));
1618
        config.setRemoveCountryFromLocalityText(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_REMOVE_COUNTRY_FROM_LOCALITY_TEXT));
1619
        config.setGetSiblings(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_DO_SIBLINGS));
1620
        config.setIgnoreAuthorship(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_IGNORE_AUTHORSHIP));
1621
        config.setIgnoreImportOfExistingSpecimen(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_IGNORE_IMPORT_OF_EXISTING_SPECIMEN));
1622
        config.setMapUnitIdToAccessionNumber(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_MAP_UNIT_ID_TO_ACCESSION_NUMBER));
1623
        config.setMapUnitIdToBarcode(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_MAP_UNIT_ID_TO_BARCODE));
1624
        config.setMapUnitIdToCatalogNumber(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_MAP_UNIT_ID_TOCATALOG_NUMBER));
1625
        config.setMoveNewTaxaToDefaultClassification(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_MOVE_NEW_TAXA_TO_DEFAULT_CLASSIFICATION));
1626
        config.setOverwriteExistingSpecimens(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_OVERWRITE_EXISTING_SPECIMEN));
1627
        config.setReuseExistingDescriptiveGroups(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_REUSE_EXISTING_DESCRIPTIVE_GROUPS));
1628
        config.setReuseExistingMetaData(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_REUSE_EXISTING_META_DATA));
1629
        config.setReuseExistingTaxaWhenPossible(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_REUSE_EXISTING_TAXA_WHEN_POSSIBLE));
1630
        config.setNomenclaturalCode(NomenclaturalCode.getByKey(getStringValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_NOMENCLATURAL_CODE)));
1631

    
1632
        return config;
1633

    
1634
    }
1635

    
1636

    
1637
    public static void updateAbcdImportConfigurationPreference() {
1638
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1639
        CdmPreference pref = cache.get(PreferencePredicate.AbcdImportConfig.getKey());
1640

    
1641
        if (!getBooleanValue(prefOverrideKey(PreferencePredicate.AbcdImportConfig.getKey())) || !pref.isAllowOverride()){
1642
            resetToDBPreferenceAbcdCOnfigurator();
1643

    
1644
        }
1645
    }
1646

    
1647
    public static void resetToDBPreferenceAbcdCOnfigurator(){
1648
        Abcd206ImportConfigurator config = getDBAbcdImportConfigurationPreference();
1649
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_ADD_INDIVIDUALS_ASSOCIATIONS_SUCH_AS_SPECIMEN_AND_OBSERVATIONS, config.isAddIndividualsAssociationsSuchAsSpecimenAndObservations());
1650
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_ADD_MEDIA_AS_MEDIASPECIMEN, config.isAddMediaAsMediaSpecimen());
1651

    
1652
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_ALLOW_REUSE_OTHER_CLASSIFICATIONS, config.isAllowReuseOtherClassifications());
1653
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_DEDUPLICATE_CLASSIFICATIONS, config.isDeduplicateClassifications());
1654
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_DEDUPLICATE_REFERENCES, config.isDeduplicateReferences());
1655

    
1656
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_DO_SIBLINGS, config.isGetSiblings());
1657
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_IGNORE_AUTHORSHIP, config.isIgnoreAuthorship());
1658
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_IGNORE_IMPORT_OF_EXISTING_SPECIMEN, config.isIgnoreImportOfExistingSpecimen());
1659
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_MAP_UNIT_ID_TO_ACCESSION_NUMBER, config.isMapUnitIdToAccessionNumber());
1660
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_MAP_UNIT_ID_TO_BARCODE, config.isMapUnitIdToBarcode());
1661
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_MAP_UNIT_ID_TOCATALOG_NUMBER, config.isMapUnitIdToCatalogNumber());
1662
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_MOVE_NEW_TAXA_TO_DEFAULT_CLASSIFICATION, config.isMoveNewTaxaToDefaultClassification());
1663
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_OVERWRITE_EXISTING_SPECIMEN, config.isOverwriteExistingSpecimens());
1664
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_REUSE_EXISTING_DESCRIPTIVE_GROUPS, config.isReuseExistingDescriptiveGroups());
1665
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_REUSE_EXISTING_META_DATA, config.isReuseExistingMetaData());
1666
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_REUSE_EXISTING_TAXA_WHEN_POSSIBLE, config.isReuseExistingTaxaWhenPossible());
1667
        if (config.getNomenclaturalCode() != null){
1668
            setStringValue(ABCD_IMPORT_CONFIGURATOR_NOMENCLATURAL_CODE, config.getNomenclaturalCode().getKey());
1669
        }
1670
    }
1671

    
1672

    
1673

    
1674

    
1675

    
1676

    
1677

    
1678
/**
1679
 * @return
1680
 */
1681
public static boolean isSortTaxaByRankAndName() {
1682

    
1683
    return getBooleanValue(IPreferenceKeys.SORT_TAXA_BY_RANK_AND_NAME);
1684
}
1685

    
1686
/**
1687
 * @return
1688
 */
1689
public static String getSortNamedAreasInDistributionEditor() {
1690

    
1691
    return getStringValue(PreferencePredicate.AreasSortedInDistributionEditor.getKey());
1692
}
1693

    
1694
public static void setSortNamedAreasInDistributionEditor(String isSortByVocabularyOrder) {
1695
    setStringValue(PreferencePredicate.AreasSortedInDistributionEditor.getKey(), isSortByVocabularyOrder);
1696

    
1697
}
1698

    
1699
/**
1700
 * <p>
1701
 * setPreferredNamedAreasForDistributionEditor
1702
 * </p>
1703
 *
1704
 * @param saveCheckedElements
1705
 * @param saveGrayedElements
1706
 */
1707
public static void setLastSelectedReference(
1708
        List<String> lastSelectedReferences) {
1709

    
1710
        setStringValue(PreferencesUtil.LAST_SELECTED_REFERENCES, lastSelectedReferences.toString());
1711
    }
1712

    
1713
/**
1714
 * <p>
1715
 * setPreferredNamedAreasForDistributionEditor
1716
 * </p>
1717
 *
1718
 * @param saveCheckedElements
1719
 * @param saveGrayedElements
1720
 */
1721
public static List<String> getLastSelectedReferences() {
1722

    
1723
        //IPreferenceStore preferenceStore = PreferencesUtil.getPreferenceStore();
1724
        String lastSelected = getStringValue(PreferencesUtil.LAST_SELECTED_REFERENCES);
1725
        List<String> result = new ArrayList<>();
1726
        if (!StringUtils.isBlank(lastSelected)){
1727
            Collections.addAll(result, lastSelected.substring(1,lastSelected.length()-1).split(", "));
1728
        }
1729
        return result;
1730
    }
1731

    
1732

    
1733
/**
1734
 * <p>
1735
 * setPreferredNamedAreasForDistributionEditor
1736
 * </p>
1737
 *
1738
 * @param saveCheckedElements
1739
 * @param saveGrayedElements
1740
 */
1741
public static void setPreferredNamedAreasForDistributionEditor(
1742
        String saveCheckedElements, String saveGrayedElements, boolean local) {
1743
    if (local){
1744
        setStringValue(PreferencePredicate.AvailableDistributionAreaTerms.getKey(), saveCheckedElements);
1745

    
1746
    }
1747
    else{
1748
        CdmPreference preference = null;
1749

    
1750
        if (saveCheckedElements == null){
1751
            preference = getPreferenceFromDB(PreferencePredicate.AvailableDistributionAreaTerms);
1752

    
1753
            if (preference == null){
1754
                return ;
1755
            } else{
1756
                setStringValue(PreferencePredicate.AvailableDistributionAreaTerms.getKey(),
1757
                        saveCheckedElements);
1758
                preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AvailableDistributionAreaTerms, saveCheckedElements);
1759
                setPreferenceToDB(preference);
1760

    
1761
            }
1762
        } else{
1763
           preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AvailableDistributionAreaTerms, saveCheckedElements);
1764
           setPreferenceToDB(preference);
1765
           setStringValue(PreferencePredicate.AvailableDistributionAreaTerms.getKey(),
1766
                    saveCheckedElements);
1767

    
1768
        }
1769
    }
1770

    
1771
}
1772

    
1773
/**
1774
 * @param saveCheckedElements
1775
 * @param saveCheckedElements2
1776
 * @param b
1777
 */
1778
public static void setPreferredVocabulariesForDistributionEditor(String saveCheckedElements,
1779
        boolean local, boolean isOverride) {
1780
    if (local){
1781
      setStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(), saveCheckedElements);
1782
      setBooleanValue(prefOverrideKey(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey()), isOverride);
1783
    }
1784
    else{
1785
        ICdmRepository controller;
1786
        CdmPreference preference = null;
1787

    
1788
        if (saveCheckedElements == null){
1789
            preference = getPreferenceFromDB(PreferencePredicate.AvailableDistributionAreaVocabularies);
1790

    
1791
            if (preference == null){
1792
                return ;
1793
            } else{
1794
                setStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(),
1795
                        saveCheckedElements);
1796
                preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AvailableDistributionAreaVocabularies, saveCheckedElements);
1797
                preference.setAllowOverride(isOverride);
1798
                setPreferenceToDB(preference);
1799
            }
1800
        } else{
1801
            preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AvailableDistributionAreaVocabularies, saveCheckedElements);
1802
            preference.setAllowOverride(isOverride);
1803
            setPreferenceToDB(preference);
1804
            setStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(),
1805
                    saveCheckedElements);
1806

    
1807
        }
1808
    }
1809
}
1810

    
1811

    
1812

    
1813

    
1814
/**
1815
 * @param saveCheckedElements
1816
 * @param saveCheckedElements2
1817
 * @param b
1818
 */
1819
public static String getPreferredVocabulariesForDistributionEditor(boolean local) {
1820
    if (local){
1821

    
1822
        String pref = getStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(), local);
1823
        return pref;
1824
    }
1825
    else{
1826
        CdmPreference preference = null;
1827
        preference = getPreferenceFromDB(PreferencePredicate.AvailableDistributionAreaVocabularies);
1828
        if (preference == null){
1829
            return null;
1830
        } else{
1831
            return preference.getValue();
1832
        }
1833

    
1834
    }
1835

    
1836

    
1837

    
1838
}
1839

    
1840
public static boolean getFilterCommonNameReferences(){
1841
    return getBooleanValue(PreferencesUtil.FILTER_COMMON_NAME_REFERENCES);
1842
}
1843

    
1844
/**
1845
 *
1846
 */
1847
public static void updateDBPreferences() {
1848
    CdmPreference preference = null;
1849
    CdmPreferenceCache cache = CdmPreferenceCache.instance();
1850
    cache.getAllTaxEditorDBPreferences();
1851

    
1852
    //ABCD Configurator
1853

    
1854
    updateAbcdImportConfigurationPreference();
1855

    
1856
    //Name Details
1857
    NameDetailsConfigurator config = getPreferredNameDetailsConfiguration(false);
1858
//    if (config != null ){
1859
//        if (!getBooleanValue(OVERRIDE_NAME_DETAILS) ||  !getBooleanValue(ALLOW_OVERRIDE_NAME_DETAILS)){
1860
//            setPreferredNameDetailsConfiguration(config, false);
1861
//        }
1862
//    }
1863

    
1864

    
1865

    
1866

    
1867

    
1868

    
1869

    
1870

    
1871
}
1872

    
1873

    
1874

    
1875

    
1876

    
1877

    
1878

    
1879

    
1880
}
(27-27/41)