Project

General

Profile

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

    
10
package eu.etaxonomy.taxeditor.preference;
11

    
12
import java.io.File;
13
import java.io.FileInputStream;
14
import java.io.FileOutputStream;
15
import java.io.IOException;
16
import java.net.URI;
17
import java.net.URISyntaxException;
18
import java.util.ArrayList;
19
import java.util.Arrays;
20
import java.util.Collections;
21
import java.util.HashMap;
22
import java.util.List;
23
import java.util.Map;
24
import java.util.Properties;
25
import java.util.StringTokenizer;
26
import java.util.UUID;
27

    
28
import org.apache.commons.lang.StringUtils;
29
import org.apache.log4j.Logger;
30
import org.eclipse.equinox.internal.p2.ui.model.MetadataRepositoryElement;
31
import org.eclipse.jface.preference.IPreferenceStore;
32
import org.eclipse.jface.window.Window;
33
import org.eclipse.swt.widgets.Composite;
34
import org.eclipse.swt.widgets.Control;
35
import org.eclipse.swt.widgets.Shell;
36
import org.eclipse.ui.PlatformUI;
37

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

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

    
85
	/**
86
	 *
87
	 */
88
	public static final String PREFERRED_TERMS_CHANGE = "preferred_terms";
89

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

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

    
95

    
96

    
97

    
98

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

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

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

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

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

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

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

    
166
    /**
167
     * <p>
168
     * setFloatValue
169
     * </p>
170
     *
171
     *
172
     **/
173
    public static void setFloatValue(String name, float value) {
174
        getPreferenceStore().setValue(prefKey(name), 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
        CdmPreference pref = getDBPreferenceValue(name);
198
        String prefValue = null;
199
        String overrideKey =  createPreferenceString(createOverridePreferenceString(name));
200
        boolean override = true;
201
        if (getPreferenceStore().contains(overrideKey)){
202
            override = getPreferenceStore().getBoolean(overrideKey);
203
        }
204
        if (local || pref == null || (pref != null && pref.isAllowOverride() && override)){
205
            String dbSpecific = prefKey(name);
206
            if (getPreferenceStore().contains(dbSpecific)){
207
                prefValue = getPreferenceStore().getString(dbSpecific);
208
            }else{
209
                prefValue = getPreferenceStore().
210
                        getString(name);
211
            }
212
       }else if (pref != null){
213
           prefValue = pref.getValue();
214
       }
215
        return prefValue;
216

    
217
    }
218

    
219
    public static String getStringValue(String name){
220
        return getStringValue(name, false);
221
    }
222

    
223
    private static CdmPreference getDBPreferenceValue(String name) {
224
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
225
        CdmPreference pref = null;
226
//
227
        pref = cache.get(name);
228
        if (pref == null ){
229
            //get default value for Predicate
230
            IPreferencePredicate pred = PreferencePredicate.getByKey(name);
231
            if (pred != null){
232
                if (pred.getDefaultValue() != null){
233
                    pref = CdmPreference.NewTaxEditorInstance(pred, pred.getDefaultValue().toString());
234
                }else{
235
                    pref = CdmPreference.NewTaxEditorInstance(pred, null);
236
                }
237
                pref.setAllowOverride(true);
238
            }
239
        }
240
        return pref;
241
    }
242

    
243
    /**
244
     * <p>
245
     * setIntValue
246
     * </p>
247
     *
248
     *
249
     **/
250
    public static int getIntValue(String name) {
251
        CdmPreference pref= getDBPreferenceValue(name);
252
        String prefValue = null;
253
        if (pref != null){
254
            prefValue = pref.getValue();
255
        }
256
        Integer result = null;
257
        try{
258
            result = Integer.parseInt(prefValue);
259
        }catch(NumberFormatException e){
260
            logger.debug("Preference value of " + name + " is not a number");
261
        }
262
        if (result == null){
263
            String dbSpecific = prefKey(name);
264
            if (getPreferenceStore().contains(dbSpecific)){
265
                result = getPreferenceStore().getInt(dbSpecific);
266
            }else{
267
                result =  getPreferenceStore().
268
                        getInt(name);
269
            }
270
        }
271
        return result;
272

    
273

    
274
    }
275

    
276
    public static boolean getBooleanValue(String name) {
277
        return getBooleanValue(name, false);
278
    }
279

    
280
    /**
281
     * <p>
282
     * getBooleanValue
283
     * </p>
284
     *
285
     *
286
     **/
287
    public static boolean getBooleanValue(String name, boolean local) {
288
        if (CdmStore.isActive()){
289
            CdmPreference pref = getDBPreferenceValue(name);
290
            String prefValue = null;
291
            if (pref == null || local){
292
                String dbSpecific = prefKey(name);
293
                if (getPreferenceStore().contains(dbSpecific)){
294
                    return getPreferenceStore().getBoolean(dbSpecific);
295
                }else{
296
                    return getPreferenceStore().
297
                            getBoolean(name);
298
                }
299
            }else{
300
                return Boolean.valueOf(pref.getValue());
301
            }
302

    
303
        }else{
304
            return getPreferenceStore().getBoolean(name);
305
        }
306

    
307
    }
308

    
309
    /**
310
     * <p>
311
     * setBooleanValue
312
     * </p>
313
     *
314
     *
315
     **/
316
    public static double getDoubleValue(String name) {
317
        CdmPreference pref = getDBPreferenceValue(name);
318
        String prefValue = null;
319
        if (pref != null){
320
            prefValue = pref.getValue();
321
        }
322
        Double result = null;
323
        try{
324
            result = Double.parseDouble(prefValue);
325
        }catch(NumberFormatException e){
326
            logger.debug("Preference value of " + name + " is not a number");
327
        }
328
        if (result == null){
329
            String dbSpecific = prefKey(name);
330
            if (getPreferenceStore().contains(dbSpecific)){
331
                result = getPreferenceStore().getDouble(dbSpecific);
332
            }else{
333
                result =  getPreferenceStore().
334
                        getDouble(name);
335
            }
336
        }
337
        return result;
338

    
339
    }
340

    
341
    /**
342
     * <p>
343
     * getFloatValue
344
     * </p>
345
     *
346
     *
347
     **/
348
    public static float getFloatValue(String name) {
349
        CdmPreference pref = getDBPreferenceValue(name);
350
        String prefValue = null;
351
        if (pref != null){
352
            prefValue = pref.getValue();
353
        }
354
        Float result = null;
355
        try{
356
            result = Float.parseFloat(prefValue);
357
        }catch(NumberFormatException e){
358
            logger.debug("Preference value of " + name + " is not a number");
359
        }
360
        if (result == null){
361
            String dbSpecific = prefKey(name);
362
            if (getPreferenceStore().contains(dbSpecific)){
363
                result = getPreferenceStore().getFloat(dbSpecific);
364
            }else{
365
                result =  getPreferenceStore().
366
                        getFloat(name);
367
            }
368
        }
369
        return result;
370

    
371
    }
372

    
373
    /**
374
     * <p>
375
     * getLongValue
376
     * </p>
377
     *
378
     *
379
     **/
380
    public static long getLongValue(String name) {
381
        CdmPreference pref = getDBPreferenceValue(name);
382
        String prefValue = null;
383
        if (pref != null){
384
            prefValue = pref.getValue();
385
        }
386
        Long result = null;
387
        try{
388
            result = Long.parseLong(prefValue);
389
        }catch(NumberFormatException e){
390
            logger.debug("Preference value of " + name + " is not a number");
391
        }
392
        if (result == null){
393
            String dbSpecific = prefKey(name);
394
            if (getPreferenceStore().contains(dbSpecific)){
395
                result = getPreferenceStore().getLong(dbSpecific);
396
            }else{
397
                result =  getPreferenceStore().
398
                        getLong(name);
399
            }
400
        }
401
        return result;
402
    }
403

    
404

    
405
	/**
406
	 * <p>
407
	 * setPreferredNomenclaturalCode
408
	 * </p>
409
	 *
410
	 * @param preferredCode
411
	 *            a {@link eu.etaxonomy.cdm.model.name.NomenclaturalCode}
412
	 *            object.
413
	 */
414
	public static CdmPreference setPreferredNomenclaturalCode(
415
			String preferenceValue, boolean local) {
416
	    if (local){
417
	        setStringValue(PREFERRED_NOMENCLATURAL_CODE_KEY,
418
	                preferenceValue);
419
	    }
420
	    else{
421
    		ICdmRepository controller;
422
    		controller = CdmStore.getCurrentApplicationConfiguration();
423
    		if (controller == null){
424
                return null;
425
            }
426
    		PrefKey key = null;
427
    		try{
428
    		    key = CdmPreference.NewKey(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.NomenclaturalCode);
429
    		}catch (Exception e){
430
    		    System.out.println(e.getStackTrace());
431
    		}
432
    		CdmPreference preference = null;
433

    
434
    		if (preferenceValue == null){
435
    			preference = controller.getPreferenceService().find(key);
436
    			if (preference == null){
437
    				return null;
438
    			} else{
439
    			    setStringValue(PREFERRED_NOMENCLATURAL_CODE_KEY,
440
    				        preference.getValue());
441

    
442
    				return preference;
443
    			}
444
    		} else{
445
    			preference = CdmPreference.NewInstance(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.NomenclaturalCode, preferenceValue);
446
    			controller.getPreferenceService().set(preference);
447

    
448
    		}
449
	    }
450
        return null;
451

    
452

    
453

    
454
	}
455

    
456
	/**
457
     * <p>
458
     * setPreferredNomenclaturalCode
459
     * </p>
460
     *
461
     * @param preferredCode
462
     *            a {@link eu.etaxonomy.cdm.model.name.NomenclaturalCode}
463
     *            object.
464
     */
465
    public static void setPreferredNomenclaturalCode(
466
        CdmPreference preference) {
467

    
468
        ICdmRepository controller;
469
        controller = CdmStore.getCurrentApplicationConfiguration();
470
        if (controller == null){
471
            return;
472
        }
473
        PrefKey key = null;
474
        try{
475
            key = CdmPreference.NewKey(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.NomenclaturalCode);
476
        }catch (Exception e){
477
            System.out.println(e.getStackTrace());
478
        }
479

    
480
        controller.getPreferenceService().set(preference);
481

    
482
    }
483

    
484

    
485

    
486

    
487
	/**
488
	 * <p>
489
	 * getPreferredNomenclaturalCode
490
	 * </p>
491
	 *
492
	 * @return a {@link eu.etaxonomy.cdm.model.name.NomenclaturalCode} object.
493
	 */
494
	public static NomenclaturalCode getPreferredNomenclaturalCode() {
495

    
496
		CdmPreference pref = getPreferenceFromDB(PreferencePredicate.NomenclaturalCode);
497

    
498

    
499
	    String preferredCode;
500
	    if(pref == null || (pref.isAllowOverride() && getBooleanValue(prefOverrideKey(PreferencePredicate.NomenclaturalCode.getKey())))){
501
	    	preferredCode = getStringValue(
502
	    	        PreferencePredicate.NomenclaturalCode.getKey(), true);
503

    
504
	    }else{
505
	    	preferredCode = pref.getValue();
506
	    }
507
	    if (StringUtils.isBlank(preferredCode)){
508
	        preferredCode = getPreferenceKey((NomenclaturalCode)PreferencePredicate.NomenclaturalCode.getDefaultValue());
509
	    }
510

    
511
	    return getPreferredNomenclaturalCode(preferredCode);
512

    
513
	}
514

    
515
	/**
516
     * <p>
517
     * getPreferredNomenclaturalCode
518
     * </p>
519
     *
520
     * @return a {@link eu.etaxonomy.cdm.model.name.NomenclaturalCode} object.
521
     */
522
    public static NomenclaturalCode getPreferredNomenclaturalCode(String preferenceKeyNomenclaturalCode) {
523

    
524
        for (NomenclaturalCode code : NomenclaturalCodeHelper.getAllCodes()) {
525
            if (getPreferenceKey(code).equals(preferenceKeyNomenclaturalCode)) {
526
                return code;
527
            }
528
        }
529
        return null;
530
    }
531

    
532
	public static boolean isShowTaxonAssociations(){
533
        boolean result = getBooleanValue(PreferencePredicate.ShowTaxonAssociations.getKey());
534
        return result;
535
    }
536

    
537
	public static boolean isShowLifeForm(){
538
	    boolean result =  getBooleanValue(PreferencePredicate.ShowLifeForm.getKey());
539
	    return result;
540
    }
541

    
542
	public static boolean isDeterminationOnlyForFieldUnits(){
543
	    boolean result =  getBooleanValue(PreferencePredicate.DeterminationOnlyForFieldUnits.getKey());
544
        return result;
545
    }
546

    
547
	public static boolean isCollectingAreaInGeneralSection(){
548
	    boolean result =  getBooleanValue(PreferencePredicate.ShowCollectingAreasInGeneralSection.getKey());
549
        return result;
550
	}
551

    
552
	public static CdmPreference getPreferenceFromDB(IPreferencePredicate predicate){
553
        ICdmRepository controller;
554
        CdmPreference pref = null;
555

    
556
        try{
557
            if(CdmStore.isActive()){
558
                controller = CdmStore.getCurrentApplicationConfiguration();
559
                PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), predicate);
560
                pref = controller.getPreferenceService().find(key);
561
            }
562
        }catch(Exception e){
563
            e.printStackTrace();
564
        }
565

    
566
        return pref;
567

    
568
    }
569

    
570
	public static List<CdmPreference> getPreferencesFromDB(IPreferencePredicate predicate){
571
        ICdmRepository controller;
572
        List<CdmPreference> prefs = null;
573

    
574
        try{
575
            if(CdmStore.isActive()){
576
                controller = CdmStore.getCurrentApplicationConfiguration();
577
                PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), predicate);
578
                prefs = controller.getPreferenceService().list(predicate);
579
            }
580
        }catch(Exception e){
581
            e.printStackTrace();
582
        }
583

    
584
        return prefs;
585

    
586
    }
587

    
588
	public static CdmPreference getPreferenceFromDB(PrefKey key){
589
        ICdmRepository controller;
590
        CdmPreference pref = null;
591

    
592
        try{
593
            if(CdmStore.isActive()){
594
                controller = CdmStore.getCurrentApplicationConfiguration();
595
                pref = controller.getPreferenceService().find(key);
596
            }
597
        }catch(Exception e){
598
            e.printStackTrace();
599
        }
600

    
601
        return pref;
602

    
603
    }
604

    
605

    
606

    
607
    public static void setPreferenceToDB(CdmPreference preference){
608
        ICdmRepository controller;
609
        try{
610
            if(CdmStore.isActive()){
611
                controller = CdmStore.getCurrentApplicationConfiguration();
612
                controller.getPreferenceService().set(preference);
613
                CdmPreferenceCache.instance().put(preference);
614
            }
615
        }catch(Exception e){
616
            e.printStackTrace();
617
        }
618

    
619
    }
620

    
621

    
622

    
623
	public static String getPreferredDefaultLangugae(){
624
	    String preferredLanguage = getStringValue(DEFAULT_LANGUAGE_EDITOR);
625
	    if(StringUtils.isNotEmpty(preferredLanguage) && StringUtils.isNotBlank(preferredLanguage)){
626
	        return preferredLanguage;
627
	    }
628
	    return null;
629
	}
630

    
631
	public static boolean isShowMediaPreview(){
632
        boolean isShowMediaPreview = getBooleanValue(SHOW_MEDIA_PREVIEW);
633
        return isShowMediaPreview;
634
    }
635

    
636
	/**
637
	 * Get the match strategy for the given class that was stored in preferences
638
	 * or the default strategy if it was not stored in preferences
639
	 *
640
	 * @param clazz
641
	 *            a {@link java.lang.Class} object.
642
	 * @return a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy} object.
643
	 */
644
	public static IMatchStrategy getMatchStrategy(Class<?> clazz) {
645
		String className = clazz.getName();
646
		if (getBooleanValue(MATCH_STRATEGY_PREFIX + className)) {
647
			IMatchStrategy matchStrategy = getDefaultMatchStrategy(clazz);
648

    
649
			//TODO CacheMatchers (or multiple field matchers in future) are missing here
650
			for (FieldMatcher fieldMatcher : matchStrategy.getMatching().getFieldMatchers(false)) {
651
				String fieldName = fieldMatcher.getPropertyName();
652
				String matchModeName = getStringValue(
653
						getMatchStrategyFieldName(className, fieldName));
654
				MatchMode matchMode = MatchMode.valueOf(matchModeName);
655
				try {
656
					matchStrategy.setMatchMode(fieldName, matchMode);
657
				} catch (MatchException e) {
658
					MessagingUtils.error(PreferencesUtil.class, e);
659
					throw new RuntimeException(e);
660
				}
661
			}
662

    
663
			return matchStrategy;
664
		}
665
		return getDefaultMatchStrategy(clazz);
666
	}
667

    
668
	/**
669
	 * Stores a matchStrategy into the preference store.
670
	 *
671
	 * @param matchStrategy
672
	 *            a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy}
673
	 *            object.
674
	 */
675
	public static void setMatchStrategy(IMatchStrategy matchStrategy) {
676
		String className = "ANY class"; //FIXME was: matchStrategy.getMatchClass().getName(); seems currently not in use
677
		setBooleanValue(MATCH_STRATEGY_PREFIX + className, true);
678

    
679
		List<FieldMatcher> fieldMatchers = matchStrategy.getMatching().getFieldMatchers(false);
680

    
681
		for (FieldMatcher fieldMatcher : fieldMatchers) {
682
			String fieldName = fieldMatcher.getPropertyName();
683
			setStringValue(
684
					getMatchStrategyFieldName(className, fieldName),
685
					fieldMatcher.getMatchMode().name());
686
		}
687
	}
688

    
689
	/**
690
	 * Helper method to create the preference property for a match field.
691
	 *
692
	 * @param className
693
	 * @param fieldName
694
	 * @return
695
	 */
696
	private static String getMatchStrategyFieldName(String className,
697
			String fieldName) {
698
		return MATCH_STRATEGY_PREFIX + className + "." + fieldName;
699
	}
700

    
701
	/**
702
	 * Returns the default match strategy for a given class.
703
	 *
704
	 * @param clazz
705
	 *            a {@link java.lang.Class} object.
706
	 * @return a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy} object.
707
	 */
708
	public static IMatchStrategy getDefaultMatchStrategy(Class clazz) {
709
		return DefaultMatchStrategy.NewInstance(clazz);
710
	}
711

    
712
	/**
713
	 * <p>
714
	 * getDateFormatPattern
715
	 * </p>
716
	 *
717
	 * @return a {@link java.lang.String} object.
718
	 */
719
	public static String getDateFormatPattern() {
720
		// TODO make this configurable in properties
721
		String pattern = "Y-M-d H:m";
722
		return pattern;
723
	}
724

    
725
	/**
726
	 * <p>
727
	 * addTermToPreferredTerms
728
	 * </p>
729
	 *
730
	 * @param term
731
	 *            a T object.
732
	 * @param <T>
733
	 *            a T object.
734
	 */
735
	public static <T extends TermBase> void addTermToPreferredTerms(T term) {
736

    
737
		// VocabularyEnum vocabulary =
738
		// VocabularyEnum.getVocabularyEnum(term.getClass());
739
		//
740
		// getPreferenceStore().setValue(getPreferenceKey(term),
741
		// VocabularyStore.getTermVocabulary(vocabulary).getTerms().contains(term));
742
		//
743
		// firePreferencesChanged(term.getClass());
744
	}
745

    
746
	/**
747
	 * Construct a unique key using the CdmBase object's uuid
748
	 *
749
	 * @param cdmBase
750
	 * @return
751
	 */
752
	private static String getPreferenceKey(ICdmBase cdmBase) {
753
		cdmBase = HibernateProxyHelper.deproxy(cdmBase);
754

    
755
		String key = cdmBase.getClass().getName().concat(".")
756
				.concat(cdmBase.getUuid().toString());
757
		if (key.contains("javassist")) {
758
			MessagingUtils.info("proxy");
759
		}
760
		return key;
761
	}
762

    
763
	/**
764
	 * Construct a unique key using the CdmBase object's uuid
765
	 *
766
	 * @param cdmBase
767
	 * @return
768
	 */
769
	public static String getPreferenceKey(ISimpleTerm simpleTerm) {
770
		simpleTerm = HibernateProxyHelper.deproxy(simpleTerm);
771
		String key = simpleTerm.getClass().getName().concat(".")
772
				.concat(simpleTerm.getUuid().toString());
773
		if (key.contains("javassist")) {
774
			MessagingUtils.warn(PreferencesUtil.class,
775
					"Trying to persist a preference based on a proxy class.");
776
		}
777
		return key;
778
	}
779

    
780

    
781

    
782
	/**
783
	 * Construct a unique key using the CdmBase object's uuid
784
	 *
785
	 * @param cdmBase
786
	 * @return
787
	 */
788
	public static String getPreferenceKey(IDefinedTerm definedTerm) {
789
		definedTerm = HibernateProxyHelper.deproxy(definedTerm);
790
		String key = definedTerm.getClass().getName().concat(".")
791
				.concat(definedTerm.getUuid().toString());
792
		if (key.contains("javassist")) {
793
			MessagingUtils.warn(PreferencesUtil.class,
794
					"Trying to persist a preference based on a proxy class.");
795
		}
796
		return key;
797
	}
798

    
799
	/**
800
	 * Retrieves search preferences from the preference store
801
	 *
802
	 * @return an {@link ITaxonServiceConfigurator} to pass to search methods
803
	 */
804
	public static IFindTaxaAndNamesConfigurator getSearchConfigurator() {
805
		IFindTaxaAndNamesConfigurator configurator = initializeSearchConfigurator();
806

    
807
		configurator.setDoTaxa(getBooleanValue(
808
				TAXON_SERVICE_CONFIGURATOR_TAXA));
809
		configurator.setDoSynonyms(getBooleanValue(
810
				TAXON_SERVICE_CONFIGURATOR_SYNONYMS));
811
		configurator.setDoNamesWithoutTaxa(getBooleanValue(
812
				TAXON_SERVICE_CONFIGURATOR_NAMES));
813
		configurator.setDoTaxaByCommonNames(getBooleanValue(
814
				TAXON_SERVICE_CONFIGURATOR_COMMON_NAMES));
815
		//configurator.setMatchMode(eu.etaxonomy.cdm.persistence.query.MatchMode.valueOf(getStringValue(TAXON_SERVICE_CONFIGURATOR_MATCH_MODE)));
816

    
817
		return configurator;
818
	}
819

    
820
	/**
821
	 * create new preferences, setting all search options to true
822
	 *
823
	 * @return a
824
	 *         {@link eu.etaxonomy.cdm.api.service.config.ITaxonServiceConfigurator}
825
	 *         object.
826
	 */
827
	public static IFindTaxaAndNamesConfigurator initializeSearchConfigurator() {
828
		IFindTaxaAndNamesConfigurator configurator = FindTaxaAndNamesConfiguratorImpl.NewInstance();
829

    
830
		configurator.setDoTaxa(true);
831
		configurator.setDoSynonyms(true);
832
		configurator.setDoNamesWithoutTaxa(true);
833
		configurator.setDoTaxaByCommonNames(true);
834

    
835
		configurator.setTaxonPropertyPath(Arrays.asList("$", "titleCache",
836
				"name", "name.$", "relationsFromThisTaxon.$"));
837

    
838
		configurator.setSynonymPropertyPath(Arrays.asList("$", "titleCache",
839
				"name", "name.$", "synonyms.relatedTo.*"));
840

    
841
		// DEFAULT VALUES
842
		// match mode is a simple like, actually all other match modes are kind
843
		// of bogus
844
		configurator
845
				.setMatchMode(eu.etaxonomy.cdm.persistence.query.MatchMode.ANYWHERE);
846
		// we set page number and size here as this should always be unlimited
847
		configurator.setPageNumber(0);
848
		// TODO currently limit results to 10000
849
		configurator.setPageSize(10000);
850
		//setSearchConfigurator(configurator) ;
851
		return configurator;
852
	}
853

    
854
	/**
855
	 * Store search preferences
856
	 *
857
	 * @param configurator
858
	 *            a
859
	 *            {@link eu.etaxonomy.cdm.api.service.config.ITaxonServiceConfigurator}
860
	 *            object.
861
	 */
862
	public static void setSearchConfigurator(
863
			IFindTaxaAndNamesConfigurator configurator) {
864
		getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_TAXA,
865
				configurator.isDoTaxa());
866
		getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_SYNONYMS,
867
				configurator.isDoSynonyms());
868
		getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_NAMES,
869
				configurator.isDoNamesWithoutTaxa());
870
		getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_COMMON_NAMES,
871
				configurator.isDoTaxaByCommonNames());
872
	}
873

    
874
	/**
875
	 * <p>
876
	 * firePreferencesChanged
877
	 * </p>
878
	 *
879
	 * @param clazz
880
	 *            a {@link java.lang.Class} object.
881
	 */
882
	public static void firePreferencesChanged(Class clazz) {
883
		getPreferenceStore().firePropertyChangeEvent(PREFERRED_TERMS_CHANGE,
884
				null, clazz);
885
	}
886

    
887
	public static String createPreferenceString(String property){
888
	   return prefKey(property);
889

    
890
	}
891
	public static String createOverridePreferenceString(String property){
892
	       return prefOverrideKey(property);
893

    
894
	    }
895

    
896
	/**
897
	 * Set default values for preferences
898
	 */
899
	public static void setDefaults() {
900
		getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_TAXA, true);
901
		getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_SYNONYMS,
902
				true);
903
		getPreferenceStore().setDefault(createPreferenceString(EDIT_MAP_SERVICE_ACCES_POINT),
904
				"http://edit.africamuseum.be/edit_wp5/v1.2/rest_gen.php");
905
		//FIXME : changed default for SHOULD_CONNECT_AT_STARTUP to false (ticket 3828) until resolution
906
		getPreferenceStore().setDefault(createPreferenceString(SHOULD_CONNECT_AT_STARTUP), false);
907
		getPreferenceStore().setDefault(createPreferenceString(OPENURL_ACCESS_POINT),
908
				"http://www.biodiversitylibrary.org/openurl");
909
		getPreferenceStore().setDefault(createPreferenceString(OPENURL_IMAGE_MAX_WIDTH), "1000");
910
		getPreferenceStore().setDefault(createPreferenceString(OPENURL_IMAGE_MAX_HEIGHT), "1000");
911
		getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_TAXA, true);
912
		getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_SYNONYMS, true);
913
		getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_NAMES, true);
914
		getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_COMMON_NAMES, true);
915

    
916
		//Distribution Editor:
917
		getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.DistributionEditorActivated.getKey()), Boolean.valueOf(PreferencePredicate.DistributionEditorActivated.getDefaultValue().toString()));
918
//		getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey()), PreferencePredicate.DisplayOfAreasInDistributionEditor.getDefaultValue().toString());
919
//		getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.DisplayOfStatus.getKey()), PreferencePredicate.DisplayOfStatus.getDefaultValue().toString());
920

    
921

    
922
		//Name Details
923
		getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.NameDetailsView.getKey()), new NameDetailsConfigurator(false).toString());
924

    
925
		//Navigator preferences
926
		getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.TaxonNodeOrder.getKey()), NavigatorOrderEnum.RankAndNameOrder.getKey());
927

    
928
		//getPreferenceStore().setDefault(createPreferenceString(Prefe), true);
929

    
930
		getPreferenceStore().setDefault(createPreferenceString(SHOW_ADVANCED_MEDIA_SECTION), false);
931

    
932
        getPreferenceStore().setDefault(createPreferenceString(SHOW_MEDIA_PREVIEW), false);
933
		//override db preferences
934
		getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.AbcdImportConfig.getKey())), false);
935
		getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.ShowSpecimen.getKey())), true);
936
		getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.NameDetailsView.getKey())), false);
937
		getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.DistributionEditorActivated.getKey())), true);
938
		getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.AvailableDistributionStatus.getKey())), true);
939
		getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.AvailableDistributionAreaTerms.getKey())), true);
940
		getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey())), true);
941
		getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.CommonNameAreaVocabularies.getKey())), false);
942
		getPreferenceStore().setDefault(createPreferenceString(FILTER_COMMON_NAME_REFERENCES), false);
943
		getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowTaxonNodeWizard.getKey()), Boolean.valueOf(PreferencePredicate.ShowTaxonNodeWizard.getDefaultValue().toString()));
944
		getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowNamespaceInSource.getKey()), Boolean.valueOf(PreferencePredicate.ShowNamespaceInSource.getDefaultValue().toString()));
945
		getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowIdInSource.getKey()), Boolean.valueOf(PreferencePredicate.ShowIdInSource.getDefaultValue().toString()));
946
		getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.DisableMultiClassification.getKey()), Boolean.valueOf(PreferencePredicate.DisableMultiClassification.getDefaultValue().toString()));
947
		getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowImportExportMenu.getKey()), Boolean.valueOf(PreferencePredicate.ShowImportExportMenu.getDefaultValue().toString()));
948

    
949
	}
950

    
951
	/**
952
	 * <p>
953
	 * checkNomenclaturalCode
954
	 * </p>
955
	 */
956
	public static void checkNomenclaturalCode() {
957
		// First time Editor is opened, no nomenclatural code has been set
958
		if (PreferencesUtil.getPreferredNomenclaturalCode() == null) {
959
			PreferencesUtil.setPreferredNomenclaturalCode(getPreferenceKey(NomenclaturalCode.ICNAFP), true);
960
		}
961

    
962

    
963

    
964
	}
965
	public static void setNomenclaturalCodePreferences(){
966
	    ICdmRepository controller;
967
        controller = CdmStore.getCurrentApplicationConfiguration();
968
        PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.NomenclaturalCode);
969
        CdmPreference preference = null;
970
        if (controller == null){
971
            return ;
972
        }
973
        preference = controller.getPreferenceService().find(key);
974
        if (preference == null){
975
            return;
976
        }
977
//        setBooleanValue(ALLOW_OVERRIDE_NOMENCLATURAL_CODE_KEY, preference.isAllowOverride());
978

    
979
        int index = StringUtils.lastIndexOf(preference.getValue(), ".");
980
        UUID uuid = UUID.fromString(preference.getValue().substring(index +1, preference.getValue().length()));
981
        NomenclaturalCode preferredCode = NomenclaturalCode.getByUuid(uuid);
982

    
983
        setStringValue(PREFERRED_NOMENCLATURAL_CODE_KEY,
984
                getPreferenceKey(preferredCode));
985

    
986
	}
987

    
988
	public static void checkDefaultLanguage(){
989
	    if(PreferencesUtil.getPreferredDefaultLangugae() == null){
990
	       Shell shell = AbstractUtility.getShell();
991
	       int open = new DefaultLanguageDialog(shell).open();
992
	       if(open == Window.OK){
993
	           PlatformUI.getWorkbench().restart();
994
	       }
995
	    }else{
996
	        //TODO:In case of a reinstall, the config.ini will be overwritten
997
	        //     here you create config.ini with the stored key from preferences
998
	    }
999
	}
1000

    
1001
	/**
1002
	 * <p>
1003
	 * getMapServiceAccessPoint
1004
	 * </p>
1005
	 *
1006
	 * @return a {@link java.lang.String} object.
1007
	 */
1008
	public static String getMapServiceAccessPoint() {
1009
		return getStringValue(EDIT_MAP_SERVICE_ACCES_POINT);
1010
	}
1011

    
1012
	/**
1013
	 * <p>
1014
	 * shouldConnectAtStartUp
1015
	 * </p>
1016
	 *
1017
	 * @return a boolean.
1018
	 */
1019
	public static boolean shouldConnectAtStartUp() {
1020
		//FIXME :  force SHOULD_CONNECT_AT_STARTUP to false (ticket 3828) until resolution
1021
		//return getBooleanValue(SHOULD_CONNECT_AT_STARTUP);
1022
		return false;
1023
	}
1024

    
1025
	/**
1026
	 * <p>
1027
	 * getDefaultFeatureTreeForTextualDescription
1028
	 * </p>
1029
	 *
1030
	 * @return a {@link eu.etaxonomy.cdm.model.term.FeatureTree} object.
1031
	 */
1032
	public static FeatureTree getDefaultFeatureTreeForTextualDescription() {
1033
		String uuidString = getStringValue(
1034
				FEATURE_TREE_DEFAULT_TEXT);
1035
		if (StringUtils.isBlank(uuidString)) {
1036
            return null;
1037
        }
1038
		FeatureTree tree = CdmStore.getService(
1039
	                IFeatureTreeService.class).load(UUID.fromString(uuidString));
1040
		if (tree.getId() == 0) {
1041
            return null;
1042
        }
1043
		return tree;
1044
	}
1045

    
1046
	/**
1047
	 * <p>
1048
	 * getDefaultFeatureTreeForStructuredDescription
1049
	 * </p>
1050
	 *
1051
	 * @return a {@link eu.etaxonomy.cdm.model.term.FeatureTree} object.
1052
	 */
1053
	public static FeatureTree getDefaultFeatureTreeForStructuredDescription() {
1054
		String uuidString = getStringValue(
1055
				FEATURE_TREE_DEFAULT_STRUCTURE);
1056
		return CdmUtils.isEmpty(uuidString) ? null : CdmStore.getService(
1057
				IFeatureTreeService.class).load(UUID.fromString(uuidString));
1058
	}
1059

    
1060
	/**
1061
	 * <p>
1062
	 * setSortRanksHierarchichally
1063
	 * </p>
1064
	 *
1065
	 * @param selection
1066
	 *            a boolean.
1067
	 */
1068
	public static void setSortRanksHierarchichally(boolean selection) {
1069
		setBooleanValue(SORT_RANKS_HIERARCHICHALLY, selection);
1070
	}
1071

    
1072
	/**
1073
	 * <p>
1074
	 * getSortRanksHierarchichally
1075
	 * </p>
1076
	 *
1077
	 * @return a boolean.
1078
	 */
1079
	public static boolean getSortRanksHierarchichally() {
1080
		return getBooleanValue(SORT_RANKS_HIERARCHICHALLY);
1081
	}
1082

    
1083
	public static boolean isMultilanguageTextEditingCapability() {
1084
		return getBooleanValue(
1085
				MULTILANGUAGE_TEXT_EDITING_CAPABILITY);
1086
	}
1087

    
1088
	public static Language getGlobalLanguage() {
1089

    
1090

    
1091
		String languageUuidString = getStringValue(
1092
				GLOBAL_LANGUAGE_UUID);
1093

    
1094
		if(!CdmStore.isActive()) {
1095
            MessagingUtils.noDataSourceWarningDialog(languageUuidString);
1096
            return null;
1097
        }
1098

    
1099
		if (CdmUtils.isBlank(languageUuidString)) {
1100
			return Language.getDefaultLanguage();
1101
		}
1102

    
1103
		UUID languageUuid = UUID.fromString(languageUuidString);
1104
		return (Language) CdmStore.getService(ITermService.class).load(
1105
				languageUuid);
1106
	}
1107

    
1108
	public static void setGlobalLanguage(Language language) {
1109
	    if(language != null) {
1110
	        setStringValue(GLOBAL_LANGUAGE_UUID,language.getUuid().toString());
1111
	        CdmStore.setDefaultLanguage(language);
1112
	    }
1113

    
1114
	}
1115

    
1116
	/**
1117
	 * @return
1118
	 */
1119
	public static Map<MarkerType, Boolean> getEditMarkerTypePreferences() {
1120
		List<MarkerType> markerTypes = CdmStore.getTermManager()
1121
				.getPreferredTerms(MarkerType.class);
1122

    
1123
		Map<MarkerType, Boolean> result = new HashMap<MarkerType, Boolean>();
1124

    
1125
		for (MarkerType markerType : markerTypes) {
1126
			String name = getMarkerTypeEditingPreferenceKey(markerType);
1127
			Boolean value = getBooleanValue(name);
1128

    
1129
			result.put(markerType, value);
1130
		}
1131

    
1132
		return result;
1133
	}
1134

    
1135
	/**
1136
	 * @param markerTypeEditingMap
1137
	 */
1138
	public static void setEditMarkerTypePreferences(
1139
			Map<MarkerType, Boolean> markerTypeEditingMap) {
1140
		for (MarkerType markerType : markerTypeEditingMap.keySet()) {
1141
			String name = getMarkerTypeEditingPreferenceKey(markerType);
1142
			setBooleanValue(name,
1143
					markerTypeEditingMap.get(markerType));
1144
		}
1145

    
1146
	}
1147

    
1148
	private static String getMarkerTypeEditingPreferenceKey(
1149
			MarkerType markerType) {
1150
		markerType = HibernateProxyHelper.deproxy(markerType);
1151
		return markerType.getClass().getName() + EDIT_MARKER_TYPE_PREFIX;
1152
	}
1153

    
1154
	/**
1155
	 * <p>
1156
	 * setEditMarkerTypePreference
1157
	 * </p>
1158
	 *
1159
	 * @param input
1160
	 *            a {@link org.eclipse.ui.IEditorInput} object.
1161
	 * @param markerType
1162
	 *            a {@link eu.etaxonomy.cdm.model.common.MarkerType} object.
1163
	 * @param edit
1164
	 *            a boolean.
1165
	 */
1166
	public static void setEditMarkerTypePreference(MarkerType markerType,
1167
			boolean edit) {
1168
		setBooleanValue(
1169
				getMarkerTypeEditingPreferenceKey(markerType), edit);
1170
	}
1171

    
1172
	/**
1173
	 * @return
1174
	 */
1175
	public static DerivedUnitFacadeConfigurator getDerivedUnitConfigurator() {
1176
		DerivedUnitFacadeConfigurator configurator = DerivedUnitFacadeConfigurator
1177
				.NewInstance();
1178
		configurator.setMoveDerivedUnitMediaToGallery(true);
1179
		configurator.setMoveFieldObjectMediaToGallery(true);
1180
		return configurator;
1181
	}
1182

    
1183
	/**
1184
	 * This method will write language properties to the config.ini located in the configuration folder
1185
	 * of the Taxonomic Ediitor. <b>This method is only used to set the default language for Taxonomic Editor.</b>
1186
	 *
1187
	 * @param setLanguage 0 is for german and 1 for english.
1188
	 * @throws IOException
1189
	 */
1190
    public void writePropertyToConfigFile(int setLanguage) throws IOException {
1191
        File file = org.eclipse.core.runtime.preferences.ConfigurationScope.INSTANCE.getLocation().toFile();
1192
        //give warning to user if the directory has no write access
1193
        if(file == null){
1194
            throw new IOException();
1195
        }
1196
        Properties properties = load(file.getAbsolutePath()+"/config.ini");
1197
        switch(setLanguage){
1198
        case 0:
1199
            properties.setProperty("osgi.nl", "de");
1200
            setStringValue(IPreferenceKeys.DEFAULT_LANGUAGE_EDITOR, "de");
1201
            break;
1202
        case 1:
1203
            properties.setProperty("osgi.nl", "en");
1204
            setStringValue(IPreferenceKeys.DEFAULT_LANGUAGE_EDITOR, "en");
1205
            break;
1206
        default:
1207
            break;
1208
        }
1209
        save(file+"/config.ini", properties);
1210
    }
1211

    
1212
    /**
1213
     * This method loads a property from a given file and returns it.
1214
     *
1215
     * @param filename
1216
     * @return
1217
     * @throws IOException
1218
     */
1219
    private Properties load(String filename) throws IOException {
1220
        FileInputStream in = new FileInputStream(filename);
1221
        Properties prop = new Properties();
1222
        prop.load(in);
1223
        in.close();
1224
        return prop;
1225
    }
1226

    
1227
    /**
1228
     * This method saves a property to the specified file.
1229
     *
1230
     * @param filename
1231
     * @param properties
1232
     * @throws IOException
1233
     */
1234
    private void save(String filename, Properties properties) throws IOException{
1235
        FileOutputStream fos =  new FileOutputStream(filename);
1236
        properties.store(fos, "");
1237
        fos.close();
1238
    }
1239

    
1240
    /**
1241
     * Saves a list of P2 Metadata Repositories as string with specified delimiters
1242
     *
1243
     * @param p2Repos
1244
     */
1245
    public static void setP2Repositories(List<MetadataRepositoryElement> p2Repos) {
1246
        StringBuilder sb = new StringBuilder();
1247
        for(MetadataRepositoryElement p2Repo : p2Repos) {
1248
            sb.append(P2_REPOSITORIES_DELIM);
1249
            if(p2Repo.getName() == null || p2Repo.getName().isEmpty()) {
1250
                sb.append("-");
1251
            } else {
1252
                sb.append(p2Repo.getName());
1253
            }
1254
            sb.append(P2_REPOSITORY_FIELDS_DELIM);
1255
            sb.append(p2Repo.getLocation().toString());
1256
            sb.append(P2_REPOSITORY_FIELDS_DELIM);
1257
            sb.append(String.valueOf(p2Repo.isEnabled()));
1258
        }
1259
        getPreferenceStore().setValue(P2_REPOSITORY_LIST, sb.toString());
1260
    }
1261

    
1262

    
1263
    /**
1264
     * Retrieves a list of previously saved P2 repositories
1265
     *
1266
     * @return
1267
     */
1268
    public static List<MetadataRepositoryElement> getP2Repositories() {
1269
        List<MetadataRepositoryElement> p2Repos = new ArrayList<MetadataRepositoryElement>();
1270
        String p2ReposPref =  getStringValue(P2_REPOSITORY_LIST);
1271
        if(p2ReposPref != null && !p2ReposPref.isEmpty()) {
1272
            StringTokenizer p2ReposPrefST = new StringTokenizer(p2ReposPref,P2_REPOSITORIES_DELIM);
1273

    
1274
            while(p2ReposPrefST.hasMoreTokens()) {
1275
                String p2RepoStr = p2ReposPrefST.nextToken();
1276
                StringTokenizer p2ReposStrST = new StringTokenizer(p2RepoStr,P2_REPOSITORY_FIELDS_DELIM);
1277
                if(p2ReposStrST.countTokens()==3) {
1278
                    String nickname = p2ReposStrST.nextToken();
1279
                    URI uri = null;
1280
                    try {
1281
                        uri = new URI(p2ReposStrST.nextToken());
1282
                    } catch (URISyntaxException e) {
1283
                        continue;
1284
                    }
1285
                    boolean enabled = Boolean.parseBoolean(p2ReposStrST.nextToken());
1286
                    MetadataRepositoryElement mre = new MetadataRepositoryElement(null, uri, true);
1287
                    mre.setNickname(nickname);
1288
                    mre.setEnabled(enabled);
1289
                    p2Repos.add(mre);
1290
                }
1291
            }
1292
        }
1293

    
1294
        return p2Repos;
1295
    }
1296

    
1297
    /**
1298
     * enables/disables nested composite. <br>
1299
     *
1300
     * @param ctrl - Composite to be en-/disabeld
1301
     * @param enabled - boolean
1302
     */
1303
    public static void recursiveSetEnabled(Control ctrl, boolean enabled) {
1304
        if (ctrl instanceof Composite) {
1305
            Composite comp = (Composite) ctrl;
1306
            for (Control c : comp.getChildren()) {
1307
                recursiveSetEnabled(c, enabled);
1308
            }
1309
        } else {
1310
            ctrl.setEnabled(enabled);
1311
        }
1312
    }
1313

    
1314

    
1315

    
1316

    
1317
    /**
1318
     * @param orderActivated
1319
     */
1320
    public static void setSortNodes(NavigatorOrderEnum nodesOrder) {
1321
        setStringValue(PreferencePredicate.TaxonNodeOrder.getKey(), nodesOrder.key);
1322

    
1323
    }
1324

    
1325
    /**
1326
     * @param orderActivated
1327
     */
1328
    public static NavigatorOrderEnum getSortNodes() {
1329
        return NavigatorOrderEnum.valueOf(getStringValue(PreferencePredicate.TaxonNodeOrder.getKey()));
1330

    
1331
    }
1332

    
1333
    /**
1334
     * @param orderActivated
1335
     */
1336
    public static boolean isNodesSortedNaturally() {
1337
        NavigatorOrderEnum value = NavigatorOrderEnum.valueOf(getStringValue(PreferencePredicate.TaxonNodeOrder.getKey()));
1338
        return value.equals(NavigatorOrderEnum.NaturalOrder);
1339

    
1340
    }
1341

    
1342
    /**
1343
     * @param orderActivated
1344
     */
1345
    public static boolean isNodesSortedByName() {
1346
        NavigatorOrderEnum value = NavigatorOrderEnum.valueOf(getStringValue(PreferencePredicate.TaxonNodeOrder.getKey()));
1347
        return value.equals(NavigatorOrderEnum.AlphabeticalOrder);
1348

    
1349
    }
1350

    
1351
    /**
1352
     * @param orderActivated
1353
     */
1354
    public static boolean isNodesSortedByNameAndRank() {
1355
        NavigatorOrderEnum value = NavigatorOrderEnum.valueOf(getStringValue(PreferencePredicate.TaxonNodeOrder.getKey()));
1356
        return value.equals(NavigatorOrderEnum.RankAndNameOrder);
1357

    
1358
    }
1359
	/**
1360
	 * <p>
1361
	 * setStoreNavigatorState
1362
	 * </p>
1363
	 *
1364
	 * @param selection
1365
	 *            a boolean.
1366
	 */
1367
	public static boolean isStoreNavigatorState() {
1368
		return getBooleanValue(RESTORE_NAVIGATOR_STATE);
1369

    
1370
	}
1371

    
1372
	/**
1373
	 * <p>
1374
	 * setStoreNavigatorState
1375
	 * </p>
1376
	 *
1377
	 * @param selection
1378
	 *            a boolean.
1379
	 */
1380
	public static void setStoreNavigatorState(boolean selection) {
1381
		setBooleanValue(RESTORE_NAVIGATOR_STATE, selection);
1382

    
1383
	}
1384

    
1385
    /**
1386
     * @return
1387
     */
1388
    public static boolean isShowUpWidgetIsDisposedMessages() {
1389
       return getBooleanValue(IS_SHOW_UP_WIDGET_IS_DISPOSED);
1390
    }
1391
    public static void setShowUpWidgetIsDisposedMessages(boolean selection) {
1392
        setBooleanValue(IS_SHOW_UP_WIDGET_IS_DISPOSED, selection);
1393
    }
1394

    
1395
    /**
1396
     * @return
1397
     */
1398
    public static boolean isShowIdInVocabularyInChecklistEditor() {
1399
        String area_display = getStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey());
1400
        if (area_display.equals(TermDisplayEnum.IdInVocabulary.getKey())) {
1401
            return true;
1402
        }else{
1403
            return false;
1404
        }
1405
    }
1406
    public static boolean isShowSymbol1InChecklistEditor() {
1407
        String area_display = getStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey());
1408
        if (area_display.equals(TermDisplayEnum.Symbol1.getKey())) {
1409
            return true;
1410
        }else{
1411
            return false;
1412
        }
1413
     }
1414
    public static boolean isShowSymbol2InChecklistEditor() {
1415
        String area_display = getStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey());
1416
        if (area_display.equals(TermDisplayEnum.Symbol2.getKey())) {
1417
            return true;
1418
        }else{
1419
            return false;
1420
        }
1421
     }
1422
    public static void setAreaDisplayInChecklistEditor(String selection) {
1423
        setStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey(), selection);
1424
    }
1425

    
1426
    public static void setOwnDescriptionForChecklistEditor(boolean selection) {
1427
        setBooleanValue(PreferencePredicate.OwnDescriptionForDistributionEditor.getKey(), selection);
1428
    }
1429

    
1430
    public static boolean isOwnDescriptionForChecklistEditor() {
1431
        return getBooleanValue(PreferencePredicate.OwnDescriptionForDistributionEditor.getKey());
1432
    }
1433

    
1434
    /**
1435
     * @return
1436
     */
1437
    public static String displayAreaInChecklistEditor() {
1438
        String result = getStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey());
1439
        if (StringUtils.isBlank(result)){
1440
            return ((TermDisplayEnum) PreferencePredicate.DisplayOfAreasInDistributionEditor.getDefaultValue()).getKey();
1441
        }
1442
       return result;
1443
    }
1444

    
1445
    /**
1446
     * @return
1447
     */
1448
    public static String displayStatusInChecklistEditor() {
1449
        String result = getStringValue(PreferencePredicate.DisplayOfStatus.getKey());
1450
        if (StringUtils.isBlank(result)){
1451
            return((TermDisplayEnum) PreferencePredicate.DisplayOfStatus.getDefaultValue()).getKey();
1452
        }
1453
       return result;
1454
    }
1455
    public static void setDisplayStatusInChecklistEditor(String selection) {
1456
        setStringValue(PreferencePredicate.DisplayOfStatus.getKey(), selection);
1457

    
1458
    }
1459

    
1460
    /**
1461
     * @return
1462
     */
1463
    public static boolean isShowRankInChecklistEditor() {
1464
        return getBooleanValue(PreferencePredicate.ShowRankInDistributionEditor.getKey());
1465
    }
1466
    public static void setShowRankInChecklistEditor(boolean selection) {
1467
       setBooleanValue(PreferencePredicate.ShowRankInDistributionEditor.getKey(), selection);
1468
    }
1469

    
1470
    /**
1471
     * @param object
1472
     * @param b
1473
     * @return
1474
     */
1475
    public static NameDetailsConfigurator getPreferredNameDetailsConfiguration( boolean local) {
1476
        NameDetailsConfigurator config = new NameDetailsConfigurator(true);
1477
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1478
        CdmPreference preference = null;
1479
        String value;
1480
        if (!local) {
1481
            PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.NameDetailsView);
1482
            preference = cache.findBestMatching(key);
1483
            if (preference == null){
1484
                return null;
1485
            }
1486

    
1487
        //    setBooleanValue(ALLOW_OVERRIDE_NAME_DETAILS, preference.isAllowOverride());
1488
            value = preference.getValue();
1489
            config.setAllowOverride(preference.isAllowOverride());
1490
            //the preference value is build like this:
1491
            //<section1>:true;<section2>:false....
1492
        }else{
1493
            value = getStringValue(PreferencePredicate.NameDetailsView.getKey(), local);
1494
        }
1495
        String [] sections = value.split(";");
1496
        Map<String, Boolean> sectionMap = new HashMap<String, Boolean>();
1497
        String[] sectionValues;
1498
        for (String sectionValue: sections){
1499
            sectionValues = sectionValue.split(":");
1500
            sectionMap.put(sectionValues[0], Boolean.valueOf(sectionValues[1]));
1501
        }
1502

    
1503
        config.setSimpleDetailsViewActivated(getValue(sectionMap, "simpleViewActivated"));
1504

    
1505
        config.setTaxonSectionActivated(getValue(sectionMap, "taxon"));
1506

    
1507
        config.setSecDetailsActivated(getValue(sectionMap, "taxon.SecDetails"));
1508
        config.setSecEnabled(getValue(sectionMap, "taxon.SecEnabled"));
1509

    
1510
        config.setLSIDActivated(getValue(sectionMap, "lsid"));
1511

    
1512
        config.setNomenclaturalCodeActived(getValue(sectionMap, "nc"));
1513

    
1514
        config.setAppendedPhraseActivated(getValue(sectionMap, "ap"));
1515

    
1516
        config.setRankActivated(getValue(sectionMap, "rank"));
1517

    
1518
        config.setAtomisedEpithetsActivated(getValue(sectionMap, "atomisedEpithets"));
1519

    
1520
        config.setAuthorshipSectionActivated(getValue(sectionMap,"author"));
1521

    
1522
        config.setNomenclaturalReferenceSectionActivated(sectionMap.get("nomRef"));
1523

    
1524
        config.setNomenclaturalStatusSectionActivated(getValue(sectionMap, "nomStat"));
1525

    
1526
        config.setProtologueActivated(getValue(sectionMap,"protologue"));
1527

    
1528
        config.setTypeDesignationSectionActivated(getValue(sectionMap,"typeDes"));
1529

    
1530
        config.setNameRelationsSectionActivated(getValue(sectionMap,"nameRelation"));
1531

    
1532
            config.setHybridActivated(getValue(sectionMap,"hybrid"));
1533

    
1534
        return config;
1535
    }
1536

    
1537
    public static NameDetailsConfigurator getPreferredNameDetailsConfiguration() {
1538
        NameDetailsConfigurator config = new NameDetailsConfigurator(true);
1539

    
1540
        String value;
1541

    
1542
        value = getStringValue(PreferencePredicate.NameDetailsView.getKey(), false);
1543
        if (value != null){
1544
            String [] sections = value.split(";");
1545
            Map<String, Boolean> sectionMap = new HashMap<String, Boolean>();
1546
            String[] sectionValues;
1547
            for (String sectionValue: sections){
1548
                sectionValues = sectionValue.split(":");
1549
                sectionMap.put(sectionValues[0], Boolean.valueOf(sectionValues[1]));
1550
            }
1551

    
1552
            config.setSimpleDetailsViewActivated(getValue(sectionMap, "simpleViewActivated"));
1553

    
1554
            config.setTaxonSectionActivated(getValue(sectionMap, "taxon"));
1555

    
1556
            config.setSecDetailsActivated(getValue(sectionMap, "taxon.SecDetails"));
1557
            config.setSecEnabled(getValue(sectionMap, "taxon.SecEnabled"));
1558

    
1559
            config.setLSIDActivated(getValue(sectionMap, "lsid"));
1560

    
1561
            config.setNomenclaturalCodeActived(getValue(sectionMap, "nc"));
1562

    
1563
            config.setAppendedPhraseActivated(getValue(sectionMap, "ap"));
1564

    
1565
            config.setRankActivated(getValue(sectionMap, "rank"));
1566

    
1567
            config.setAtomisedEpithetsActivated(getValue(sectionMap, "atomisedEpithets"));
1568

    
1569
            config.setAuthorshipSectionActivated(getValue(sectionMap,"author"));
1570

    
1571
            config.setNomenclaturalReferenceSectionActivated(sectionMap.get("nomRef"));
1572

    
1573
            config.setNomenclaturalStatusSectionActivated(getValue(sectionMap, "nomStat"));
1574

    
1575
            config.setProtologueActivated(getValue(sectionMap,"protologue"));
1576

    
1577
            config.setTypeDesignationSectionActivated(getValue(sectionMap,"typeDes"));
1578

    
1579
            config.setNameRelationsSectionActivated(getValue(sectionMap,"nameRelation"));
1580

    
1581
                config.setHybridActivated(getValue(sectionMap,"hybrid"));
1582
        }
1583
        return config;
1584
    }
1585

    
1586

    
1587
    /**
1588
     * @param object
1589
     * @param b
1590
     * @return
1591
     */
1592
    public static void setPreferredNameDetailsConfiguration(NameDetailsConfigurator config, boolean local) {
1593
        CdmPreference preference = null;
1594

    
1595
        if (!local) {
1596
            preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.NameDetailsView, config.toString());
1597

    
1598
            setPreferenceToDB(preference);
1599
        }
1600
        else{
1601
            setStringValue(PreferencePredicate.NameDetailsView.getKey(), config.toString());
1602
        }
1603

    
1604

    
1605
    }
1606

    
1607
    private static Boolean getValue(Map<String, Boolean> sectionMap, String string) {
1608
		if (sectionMap.containsKey(string)){
1609
			return sectionMap.get(string);
1610
		}else{
1611
			return true;
1612
		}
1613

    
1614
	}
1615

    
1616

    
1617

    
1618
    /**
1619
     * <p>
1620
     * setAbcdConfigurator
1621
     * </p>
1622
     *
1623
     * @param preferredConfiguration
1624
     *            a {@link eu.etaxonomy.cdm.io.specimen.abcd206.in.Abcd206ImportConfigurator}
1625
     *            object.
1626
     */
1627
    public static Abcd206ImportConfigurator getDBAbcdImportConfigurationPreference() {
1628

    
1629
        Abcd206ImportConfigurator config = Abcd206ImportConfigurator.NewInstance(null,null);
1630
        ICdmRepository controller;
1631
        controller = CdmStore.getCurrentApplicationConfiguration();
1632
        PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AbcdImportConfig);
1633
        CdmPreference preference = null;
1634
        if (controller == null){
1635
            return null;
1636
        }
1637
        preference = controller.getPreferenceService().find(key);
1638
        if (preference == null){
1639
            return config;
1640
         } else{
1641
             String configString = preference.getValue();
1642
             String[] configArray = configString.split(";");
1643

    
1644
             for (String configItem: configArray){
1645
                 String[] keyValue = configItem.split(":");
1646
                 String keyString = keyValue[0];
1647
                 String valueString = null;
1648
                 if (keyValue.length>1){
1649
                      valueString = keyValue[1];
1650
                 }
1651
                 if (keyString.equals("ignoreImportOfExistingSpecimen")){
1652
                     config.setIgnoreImportOfExistingSpecimen(Boolean.valueOf(valueString));
1653
                 }else if (keyString.equals("addIndividualsAssociationsSuchAsSpecimenAndObservations")){
1654
                     config.setAddIndividualsAssociationsSuchAsSpecimenAndObservations(Boolean.valueOf(valueString));
1655
                 }else if (keyString.equals("reuseExistingTaxaWhenPossible")){
1656
                     config.setReuseExistingTaxaWhenPossible(Boolean.valueOf(valueString));
1657
                 }else if (keyString.equals("ignoreAuthorship")){
1658
                     config.setIgnoreAuthorship(Boolean.valueOf(valueString));
1659
                 }else if (keyString.equals("addMediaAsMediaSpecimen")){
1660
                     config.setAddMediaAsMediaSpecimen(Boolean.valueOf(valueString));
1661
                 }else if (keyString.equals("reuseExistingMetaData")){
1662
                     config.setReuseExistingMetaData(Boolean.valueOf(valueString));
1663
                 }else if (keyString.equals("reuseExistingDescriptiveGroups")){
1664
                     config.setReuseExistingDescriptiveGroups(Boolean.valueOf(valueString));
1665
                 }else if (keyString.equals("allowReuseOtherClassifications")){
1666
                     config.setAllowReuseOtherClassifications(Boolean.valueOf(valueString));
1667
                 }else if (keyString.equals("deduplicateReferences")){
1668
                     config.setDeduplicateReferences(Boolean.valueOf(valueString));
1669
                 }else if (keyString.equals("deduplicateClassifications")){
1670
                     config.setDeduplicateClassifications(Boolean.valueOf(valueString));
1671
                 }else if (keyString.equals("moveNewTaxaToDefaultClassification")){
1672
                     config.setMoveNewTaxaToDefaultClassification(Boolean.valueOf(valueString));
1673
                 }else if (keyString.equals("mapUnitIdToCatalogNumber")){
1674
                     config.setMapUnitIdToCatalogNumber(Boolean.valueOf(valueString));
1675
                 }else if (keyString.equals("mapUnitIdToAccessionNumber")){
1676
                     config.setMapUnitIdToAccessionNumber(Boolean.valueOf(valueString));
1677
                 }else if (keyString.equals("mapUnitIdToBarcode")){
1678
                     config.setMapUnitIdToBarcode(Boolean.valueOf(valueString));
1679
                 }else if (keyString.equals("overwriteExistingSpecimens")){
1680
                     config.setOverwriteExistingSpecimens(Boolean.valueOf(valueString));
1681
                 }else if (keyString.equals("nomenclaturalCode")){
1682
                         config.setNomenclaturalCode(NomenclaturalCode.fromString(valueString));
1683
                 }else{
1684
                     logger.debug("This key of the abcd configurator needs to be added to the transformer: " + keyString);
1685
                 }
1686

    
1687
             }
1688
        }
1689
        return config;
1690
    }
1691

    
1692
    public static Abcd206ImportConfigurator getLocalAbcdImportConfigurator(){
1693
       Abcd206ImportConfigurator config = Abcd206ImportConfigurator.NewInstance(null,null);
1694

    
1695
        config.setAddIndividualsAssociationsSuchAsSpecimenAndObservations(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_ADD_INDIVIDUALS_ASSOCIATIONS_SUCH_AS_SPECIMEN_AND_OBSERVATIONS));
1696

    
1697
        config.setAddMediaAsMediaSpecimen(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_ADD_MEDIA_AS_MEDIASPECIMEN));
1698

    
1699
        config.setAllowReuseOtherClassifications(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_ALLOW_REUSE_OTHER_CLASSIFICATIONS));
1700
        config.setDeduplicateClassifications(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_DEDUPLICATE_CLASSIFICATIONS));
1701
        config.setDeduplicateReferences(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_DEDUPLICATE_REFERENCES));
1702
        config.setRemoveCountryFromLocalityText(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_REMOVE_COUNTRY_FROM_LOCALITY_TEXT));
1703
        config.setGetSiblings(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_DO_SIBLINGS));
1704
        config.setIgnoreAuthorship(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_IGNORE_AUTHORSHIP));
1705
        config.setIgnoreImportOfExistingSpecimen(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_IGNORE_IMPORT_OF_EXISTING_SPECIMEN));
1706
        config.setMapUnitIdToAccessionNumber(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_MAP_UNIT_ID_TO_ACCESSION_NUMBER));
1707
        config.setMapUnitIdToBarcode(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_MAP_UNIT_ID_TO_BARCODE));
1708
        config.setMapUnitIdToCatalogNumber(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_MAP_UNIT_ID_TOCATALOG_NUMBER));
1709
        config.setMoveNewTaxaToDefaultClassification(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_MOVE_NEW_TAXA_TO_DEFAULT_CLASSIFICATION));
1710
        config.setOverwriteExistingSpecimens(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_OVERWRITE_EXISTING_SPECIMEN));
1711
        config.setReuseExistingDescriptiveGroups(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_REUSE_EXISTING_DESCRIPTIVE_GROUPS));
1712
        config.setReuseExistingMetaData(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_REUSE_EXISTING_META_DATA));
1713
        config.setReuseExistingTaxaWhenPossible(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_REUSE_EXISTING_TAXA_WHEN_POSSIBLE));
1714
        config.setNomenclaturalCode(NomenclaturalCode.getByKey(getStringValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_NOMENCLATURAL_CODE)));
1715

    
1716
        return config;
1717

    
1718
    }
1719

    
1720

    
1721
    public static void updateAbcdImportConfigurationPreference() {
1722
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1723

    
1724
        CdmPreference pref = cache.findBestMatching(CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AbcdImportConfig));
1725

    
1726
        if (!getBooleanValue(prefOverrideKey(PreferencePredicate.AbcdImportConfig.getKey())) || !pref.isAllowOverride()){
1727
            resetToDBPreferenceAbcdCOnfigurator();
1728

    
1729
        }
1730
    }
1731

    
1732
    public static void resetToDBPreferenceAbcdCOnfigurator(){
1733
        Abcd206ImportConfigurator config = getDBAbcdImportConfigurationPreference();
1734
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_ADD_INDIVIDUALS_ASSOCIATIONS_SUCH_AS_SPECIMEN_AND_OBSERVATIONS, config.isAddIndividualsAssociationsSuchAsSpecimenAndObservations());
1735
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_ADD_MEDIA_AS_MEDIASPECIMEN, config.isAddMediaAsMediaSpecimen());
1736

    
1737
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_ALLOW_REUSE_OTHER_CLASSIFICATIONS, config.isAllowReuseOtherClassifications());
1738
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_DEDUPLICATE_CLASSIFICATIONS, config.isDeduplicateClassifications());
1739
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_DEDUPLICATE_REFERENCES, config.isDeduplicateReferences());
1740

    
1741
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_DO_SIBLINGS, config.isGetSiblings());
1742
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_IGNORE_AUTHORSHIP, config.isIgnoreAuthorship());
1743
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_IGNORE_IMPORT_OF_EXISTING_SPECIMEN, config.isIgnoreImportOfExistingSpecimen());
1744
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_MAP_UNIT_ID_TO_ACCESSION_NUMBER, config.isMapUnitIdToAccessionNumber());
1745
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_MAP_UNIT_ID_TO_BARCODE, config.isMapUnitIdToBarcode());
1746
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_MAP_UNIT_ID_TOCATALOG_NUMBER, config.isMapUnitIdToCatalogNumber());
1747
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_MOVE_NEW_TAXA_TO_DEFAULT_CLASSIFICATION, config.isMoveNewTaxaToDefaultClassification());
1748
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_OVERWRITE_EXISTING_SPECIMEN, config.isOverwriteExistingSpecimens());
1749
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_REUSE_EXISTING_DESCRIPTIVE_GROUPS, config.isReuseExistingDescriptiveGroups());
1750
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_REUSE_EXISTING_META_DATA, config.isReuseExistingMetaData());
1751
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_REUSE_EXISTING_TAXA_WHEN_POSSIBLE, config.isReuseExistingTaxaWhenPossible());
1752
        if (config.getNomenclaturalCode() != null){
1753
            setStringValue(ABCD_IMPORT_CONFIGURATOR_NOMENCLATURAL_CODE, config.getNomenclaturalCode().getKey());
1754
        }
1755
    }
1756

    
1757

    
1758

    
1759

    
1760

    
1761

    
1762

    
1763
/**
1764
 * @return
1765
 */
1766
public static boolean isSortTaxaByRankAndName() {
1767

    
1768
    return getBooleanValue(IPreferenceKeys.SORT_TAXA_BY_RANK_AND_NAME);
1769
}
1770

    
1771
/**
1772
 * @return
1773
 */
1774
public static String getSortNamedAreasInDistributionEditor() {
1775

    
1776
    return getStringValue(PreferencePredicate.AreasSortedInDistributionEditor.getKey());
1777
}
1778

    
1779
public static void setSortNamedAreasInDistributionEditor(String isSortByVocabularyOrder) {
1780
    setStringValue(PreferencePredicate.AreasSortedInDistributionEditor.getKey(), isSortByVocabularyOrder);
1781

    
1782
}
1783

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

    
1795
        setStringValue(PreferencesUtil.LAST_SELECTED_REFERENCES, lastSelectedReferences.toString());
1796
    }
1797

    
1798
/**
1799
 * <p>
1800
 * setPreferredNamedAreasForDistributionEditor
1801
 * </p>
1802
 *
1803
 * @param saveCheckedElements
1804
 * @param saveGrayedElements
1805
 */
1806
public static List<String> getLastSelectedReferences() {
1807

    
1808
        //IPreferenceStore preferenceStore = PreferencesUtil.getPreferenceStore();
1809
        String lastSelected = getStringValue(PreferencesUtil.LAST_SELECTED_REFERENCES);
1810
        List<String> result = new ArrayList<>();
1811
        if (!StringUtils.isBlank(lastSelected)){
1812
            Collections.addAll(result, lastSelected.substring(1,lastSelected.length()-1).split(", "));
1813
        }
1814
        return result;
1815
    }
1816

    
1817

    
1818
/**
1819
 * <p>
1820
 * setPreferredNamedAreasForDistributionEditor
1821
 * </p>
1822
 *
1823
 * @param saveCheckedElements
1824
 * @param saveGrayedElements
1825
 */
1826
public static void setPreferredNamedAreasForDistributionEditor(
1827
        String saveCheckedElements, String saveGrayedElements, boolean local) {
1828
    if (local){
1829
        setStringValue(PreferencePredicate.AvailableDistributionAreaTerms.getKey(), saveCheckedElements);
1830

    
1831
    }
1832
    else{
1833
        CdmPreference preference = null;
1834

    
1835
        if (saveCheckedElements == null){
1836
            preference = getPreferenceFromDB(PreferencePredicate.AvailableDistributionAreaTerms);
1837

    
1838
            if (preference == null){
1839
                return ;
1840
            } else{
1841
                setStringValue(PreferencePredicate.AvailableDistributionAreaTerms.getKey(),
1842
                        saveCheckedElements);
1843
                preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AvailableDistributionAreaTerms, saveCheckedElements);
1844
                setPreferenceToDB(preference);
1845

    
1846
            }
1847
        } else{
1848
           preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AvailableDistributionAreaTerms, saveCheckedElements);
1849
           setPreferenceToDB(preference);
1850
           setStringValue(PreferencePredicate.AvailableDistributionAreaTerms.getKey(),
1851
                    saveCheckedElements);
1852

    
1853
        }
1854
    }
1855

    
1856
}
1857

    
1858
/**
1859
 * @param saveCheckedElements
1860
 * @param saveCheckedElements2
1861
 * @param b
1862
 */
1863
public static void setPreferredVocabulariesForDistributionEditor(String saveCheckedElements,
1864
        boolean local, boolean isOverride) {
1865
    if (local){
1866
      setStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(), saveCheckedElements);
1867
      setBooleanValue(prefOverrideKey(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey()), isOverride);
1868
    }
1869
    else{
1870
        ICdmRepository controller;
1871
        CdmPreference preference = null;
1872

    
1873
        if (saveCheckedElements == null){
1874
            preference = getPreferenceFromDB(PreferencePredicate.AvailableDistributionAreaVocabularies);
1875

    
1876
            if (preference == null){
1877
                return ;
1878
            } else{
1879
                setStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(),
1880
                        saveCheckedElements);
1881
                preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AvailableDistributionAreaVocabularies, saveCheckedElements);
1882
                preference.setAllowOverride(isOverride);
1883
                setPreferenceToDB(preference);
1884
            }
1885
        } else{
1886
            preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AvailableDistributionAreaVocabularies, saveCheckedElements);
1887
            preference.setAllowOverride(isOverride);
1888
            setPreferenceToDB(preference);
1889
            setStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(),
1890
                    saveCheckedElements);
1891

    
1892
        }
1893
    }
1894
}
1895

    
1896

    
1897
/**
1898
 * @param saveCheckedElements
1899
 * @param saveCheckedElements2
1900
 * @param b
1901
 */
1902
public static String getPreferredVocabulariesForDistributionEditor(boolean local) {
1903
    if (local){
1904

    
1905
        String pref = getStringValue(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey(), local);
1906
        return pref;
1907
    }
1908
    else{
1909
        CdmPreference preference = null;
1910
        preference = getPreferenceFromDB(PreferencePredicate.AvailableDistributionAreaVocabularies);
1911
        if (preference == null){
1912
            return null;
1913
        } else{
1914
            return preference.getValue();
1915
        }
1916

    
1917
    }
1918
}
1919

    
1920
public static List<UUID> createUUIDListFromStringPref(String prefKey) {
1921
    String prefValue = PreferencesUtil.getStringValue(prefKey);
1922
    String[] stringArray = prefValue.split(";");
1923
    List<UUID> uuidList = new ArrayList();
1924
    for (String uuid: stringArray){
1925
        if (!StringUtils.isBlank(uuid)){
1926
            uuidList.add(UUID.fromString(uuid));
1927
        }
1928
    }
1929
    return uuidList;
1930
}
1931

    
1932
public static boolean getFilterCommonNameReferences(){
1933
    return getBooleanValue(PreferencesUtil.FILTER_COMMON_NAME_REFERENCES);
1934
}
1935

    
1936
/**
1937
 *
1938
 */
1939
public static void updateDBPreferences() {
1940
    CdmPreference preference = null;
1941
    CdmPreferenceCache cache = CdmPreferenceCache.instance();
1942
    cache.getAllTaxEditorDBPreferences();
1943

    
1944
    //ABCD Configurator
1945

    
1946
    updateAbcdImportConfigurationPreference();
1947

    
1948
    //Name Details
1949
    NameDetailsConfigurator config = getPreferredNameDetailsConfiguration(false);
1950
//    if (config != null ){
1951
//        if (!getBooleanValue(OVERRIDE_NAME_DETAILS) ||  !getBooleanValue(ALLOW_OVERRIDE_NAME_DETAILS)){
1952
//            setPreferredNameDetailsConfiguration(config, false);
1953
//        }
1954
//    }
1955

    
1956

    
1957

    
1958

    
1959

    
1960

    
1961

    
1962

    
1963
}
1964

    
1965
/**
1966
 * @param string
1967
 * @param saveCheckedElements
1968
 */
1969
public static void setPreferencesToDB(List<CdmPreference> preferences) {
1970

    
1971
    ICdmRepository controller;
1972
    try{
1973
        if(CdmStore.isActive()){
1974
            controller = CdmStore.getCurrentApplicationConfiguration();
1975
            for (CdmPreference preference: preferences){
1976

    
1977
                controller.getPreferenceService().set(preference);
1978

    
1979
                CdmPreferenceCache.instance().put(preference);
1980
            }
1981
        }
1982
    }catch(Exception e){
1983
        e.printStackTrace();
1984
    }
1985
}
1986

    
1987

    
1988

    
1989

    
1990

    
1991

    
1992

    
1993

    
1994
}
(27-27/41)