Project

General

Profile

Download (68.7 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, boolean local) {
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

    
263
        String overrideKey =  createPreferenceString(createOverridePreferenceString(name));
264
        boolean override = true;
265
        if (getPreferenceStore().contains(overrideKey)){
266
            override = getPreferenceStore().getBoolean(overrideKey);
267
        }
268
        if (local || pref == null || (pref != null && pref.isAllowOverride() && override)){
269
            String dbSpecific = prefKey(name);
270
            if (getPreferenceStore().contains(dbSpecific)){
271
                result = getPreferenceStore().getInt(dbSpecific);
272
            }else{
273
                result =  getPreferenceStore().
274
                        getInt(name);
275
            }
276
        }
277
        return result;
278

    
279
    }
280

    
281
    public static boolean getBooleanValue(String name) {
282
        return getBooleanValue(name, false);
283
    }
284

    
285
    /**
286
     * <p>
287
     * getBooleanValue
288
     * </p>
289
     *
290
     *
291
     **/
292
    public static boolean getBooleanValue(String name, boolean local) {
293
        if (CdmStore.isActive()){
294
            CdmPreference pref = getDBPreferenceValue(name);
295

    
296
            String overrideKey =  createPreferenceString(createOverridePreferenceString(name));
297
            boolean override = true;
298
            if (getPreferenceStore().contains(overrideKey)){
299
                override = getPreferenceStore().getBoolean(overrideKey);
300
            }
301
            if (local || pref == null || (pref != null && pref.isAllowOverride() && override)){
302
                String dbSpecific = prefKey(name);
303
                return getPreferenceStore().getBoolean(dbSpecific);
304
             }else{
305
                return Boolean.valueOf(pref.getValue());
306
            }
307

    
308
        }else{
309
            return getPreferenceStore().getBoolean(name);
310
        }
311

    
312
    }
313

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

    
344
    }
345

    
346
    /**
347
     * <p>
348
     * getFloatValue
349
     * </p>
350
     *
351
     *
352
     **/
353
    public static float getFloatValue(String name, boolean local) {
354
        CdmPreference pref = getDBPreferenceValue(name);
355
        String prefValue = null;
356
        if (pref != null){
357
            prefValue = pref.getValue();
358
        }
359
        Float result = null;
360
        try{
361
            result = Float.parseFloat(prefValue);
362
        }catch(NumberFormatException e){
363
            logger.debug("Preference value of " + name + " is not a number");
364
        }
365
        String overrideKey =  createPreferenceString(createOverridePreferenceString(name));
366
        boolean override = true;
367
        if (getPreferenceStore().contains(overrideKey)){
368
            override = getPreferenceStore().getBoolean(overrideKey);
369
        }
370
        if (local || pref == null || (pref != null && pref.isAllowOverride() && override)){
371
            String dbSpecific = prefKey(name);
372
            if (getPreferenceStore().contains(dbSpecific)){
373
                result = getPreferenceStore().getFloat(dbSpecific);
374
            }else{
375
                result =  getPreferenceStore().
376
                        getFloat(name);
377
            }
378
        }
379
        return result;
380

    
381
    }
382

    
383
    /**
384
     * <p>
385
     * getLongValue
386
     * </p>
387
     *
388
     *
389
     **/
390
    public static long getLongValue(String name) {
391
        CdmPreference pref = getDBPreferenceValue(name);
392
        String prefValue = null;
393
        if (pref != null){
394
            prefValue = pref.getValue();
395
        }
396
        Long result = null;
397
        try{
398
            result = Long.parseLong(prefValue);
399
        }catch(NumberFormatException e){
400
            logger.debug("Preference value of " + name + " is not a number");
401
        }
402
        if (result == null){
403
            String dbSpecific = prefKey(name);
404
            if (getPreferenceStore().contains(dbSpecific)){
405
                result = getPreferenceStore().getLong(dbSpecific);
406
            }else{
407
                result =  getPreferenceStore().
408
                        getLong(name);
409
            }
410
        }
411
        return result;
412
    }
413

    
414

    
415
	/**
416
	 * <p>
417
	 * setPreferredNomenclaturalCode
418
	 * </p>
419
	 *
420
	 * @param preferredCode
421
	 *            a {@link eu.etaxonomy.cdm.model.name.NomenclaturalCode}
422
	 *            object.
423
	 */
424
	public static CdmPreference setPreferredNomenclaturalCode(
425
			String preferenceValue, boolean local) {
426
	    if (local){
427
	        setStringValue(PREFERRED_NOMENCLATURAL_CODE_KEY,
428
	                preferenceValue);
429
	    }
430
	    else{
431
    		ICdmRepository controller;
432
    		controller = CdmStore.getCurrentApplicationConfiguration();
433
    		if (controller == null){
434
                return null;
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
    		CdmPreference preference = null;
443

    
444
    		if (preferenceValue == null){
445
    			preference = controller.getPreferenceService().find(key);
446
    			if (preference == null){
447
    				return null;
448
    			} else{
449
    			    setStringValue(PREFERRED_NOMENCLATURAL_CODE_KEY,
450
    				        preference.getValue());
451

    
452
    				return preference;
453
    			}
454
    		} else{
455
    			preference = CdmPreference.NewInstance(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.NomenclaturalCode, preferenceValue);
456
    			controller.getPreferenceService().set(preference);
457

    
458
    		}
459
	    }
460
        return null;
461

    
462

    
463

    
464
	}
465

    
466
	/**
467
     * <p>
468
     * setPreferredNomenclaturalCode
469
     * </p>
470
     *
471
     * @param preferredCode
472
     *            a {@link eu.etaxonomy.cdm.model.name.NomenclaturalCode}
473
     *            object.
474
     */
475
    public static void setPreferredNomenclaturalCode(
476
        CdmPreference preference) {
477

    
478
        ICdmRepository controller;
479
        controller = CdmStore.getCurrentApplicationConfiguration();
480
        if (controller == null){
481
            return;
482
        }
483
        PrefKey key = null;
484
        try{
485
            key = CdmPreference.NewKey(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.NomenclaturalCode);
486
        }catch (Exception e){
487
            System.out.println(e.getStackTrace());
488
        }
489

    
490
        controller.getPreferenceService().set(preference);
491

    
492
    }
493

    
494

    
495

    
496

    
497
	/**
498
	 * <p>
499
	 * getPreferredNomenclaturalCode
500
	 * </p>
501
	 *
502
	 * @return a {@link eu.etaxonomy.cdm.model.name.NomenclaturalCode} object.
503
	 */
504
	public static NomenclaturalCode getPreferredNomenclaturalCode() {
505

    
506
		CdmPreference pref = getPreferenceFromDB(PreferencePredicate.NomenclaturalCode);
507

    
508

    
509
	    String preferredCode;
510
	    if(pref == null || (pref.isAllowOverride() && getBooleanValue(prefOverrideKey(PreferencePredicate.NomenclaturalCode.getKey())))){
511
	    	preferredCode = getStringValue(
512
	    	        PreferencePredicate.NomenclaturalCode.getKey(), true);
513

    
514
	    }else{
515
	    	preferredCode = pref.getValue();
516
	    }
517
	    if (StringUtils.isBlank(preferredCode)){
518
	        preferredCode = getPreferenceKey((NomenclaturalCode)PreferencePredicate.NomenclaturalCode.getDefaultValue());
519
	    }
520

    
521
	    return getPreferredNomenclaturalCode(preferredCode);
522

    
523
	}
524

    
525
	/**
526
     * <p>
527
     * getPreferredNomenclaturalCode
528
     * </p>
529
     *
530
     * @return a {@link eu.etaxonomy.cdm.model.name.NomenclaturalCode} object.
531
     */
532
    public static NomenclaturalCode getPreferredNomenclaturalCode(String preferenceKeyNomenclaturalCode) {
533

    
534
        for (NomenclaturalCode code : NomenclaturalCodeHelper.getAllCodes()) {
535
            if (getPreferenceKey(code).equals(preferenceKeyNomenclaturalCode)) {
536
                return code;
537
            }
538
        }
539
        return null;
540
    }
541

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

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

    
552
	public static boolean isDeterminationOnlyForFieldUnits(){
553
	    boolean result =  getBooleanValue(PreferencePredicate.DeterminationOnlyForFieldUnits.getKey());
554
        return result;
555
    }
556

    
557
	public static boolean isCollectingAreaInGeneralSection(){
558
	    boolean result =  getBooleanValue(PreferencePredicate.ShowCollectingAreasInGeneralSection.getKey());
559
        return result;
560
	}
561

    
562
	public static CdmPreference getPreferenceFromDB(IPreferencePredicate predicate){
563
        ICdmRepository controller;
564
        CdmPreference pref = null;
565

    
566
        try{
567
            if(CdmStore.isActive()){
568
                controller = CdmStore.getCurrentApplicationConfiguration();
569
                PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), predicate);
570
                pref = controller.getPreferenceService().find(key);
571
            }
572
        }catch(Exception e){
573
            e.printStackTrace();
574
        }
575

    
576
        return pref;
577

    
578
    }
579

    
580
	public static List<CdmPreference> getPreferencesFromDB(IPreferencePredicate predicate){
581
        ICdmRepository controller;
582
        List<CdmPreference> prefs = null;
583

    
584
        try{
585
            if(CdmStore.isActive()){
586
                controller = CdmStore.getCurrentApplicationConfiguration();
587
                PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), predicate);
588
                prefs = controller.getPreferenceService().list(predicate);
589
            }
590
        }catch(Exception e){
591
            e.printStackTrace();
592
        }
593

    
594
        return prefs;
595

    
596
    }
597

    
598
	public static CdmPreference getPreferenceFromDB(PrefKey key){
599
        ICdmRepository controller;
600
        CdmPreference pref = null;
601

    
602
        try{
603
            if(CdmStore.isActive()){
604
                controller = CdmStore.getCurrentApplicationConfiguration();
605
                pref = controller.getPreferenceService().find(key);
606
            }
607
        }catch(Exception e){
608
            e.printStackTrace();
609
        }
610

    
611
        return pref;
612

    
613
    }
614

    
615

    
616

    
617
    public static void setPreferenceToDB(CdmPreference preference){
618
        ICdmRepository controller;
619
        try{
620
            if(CdmStore.isActive()){
621
                controller = CdmStore.getCurrentApplicationConfiguration();
622
                controller.getPreferenceService().set(preference);
623
                CdmPreferenceCache.instance().put(preference);
624
            }
625
        }catch(Exception e){
626
            e.printStackTrace();
627
        }
628

    
629
    }
630

    
631

    
632

    
633
	public static String getPreferredDefaultLangugae(){
634
	    String preferredLanguage = getStringValue(DEFAULT_LANGUAGE_EDITOR);
635
	    if(StringUtils.isNotEmpty(preferredLanguage) && StringUtils.isNotBlank(preferredLanguage)){
636
	        return preferredLanguage;
637
	    }
638
	    return null;
639
	}
640

    
641
	public static boolean isShowMediaPreview(){
642
        boolean isShowMediaPreview = getBooleanValue(SHOW_MEDIA_PREVIEW);
643
        return isShowMediaPreview;
644
    }
645

    
646
	/**
647
	 * Get the match strategy for the given class that was stored in preferences
648
	 * or the default strategy if it was not stored in preferences
649
	 *
650
	 * @param clazz
651
	 *            a {@link java.lang.Class} object.
652
	 * @return a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy} object.
653
	 */
654
	public static IMatchStrategy getMatchStrategy(Class<?> clazz) {
655
		String className = clazz.getName();
656
		if (getBooleanValue(MATCH_STRATEGY_PREFIX + className)) {
657
			IMatchStrategy matchStrategy = getDefaultMatchStrategy(clazz);
658

    
659
			//TODO CacheMatchers (or multiple field matchers in future) are missing here
660
			for (FieldMatcher fieldMatcher : matchStrategy.getMatching().getFieldMatchers(false)) {
661
				String fieldName = fieldMatcher.getPropertyName();
662
				String matchModeName = getStringValue(
663
						getMatchStrategyFieldName(className, fieldName));
664
				MatchMode matchMode = MatchMode.valueOf(matchModeName);
665
				try {
666
					matchStrategy.setMatchMode(fieldName, matchMode);
667
				} catch (MatchException e) {
668
					MessagingUtils.error(PreferencesUtil.class, e);
669
					throw new RuntimeException(e);
670
				}
671
			}
672

    
673
			return matchStrategy;
674
		}
675
		return getDefaultMatchStrategy(clazz);
676
	}
677

    
678
	/**
679
	 * Stores a matchStrategy into the preference store.
680
	 *
681
	 * @param matchStrategy
682
	 *            a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy}
683
	 *            object.
684
	 */
685
	public static void setMatchStrategy(IMatchStrategy matchStrategy) {
686
		String className = "ANY class"; //FIXME was: matchStrategy.getMatchClass().getName(); seems currently not in use
687
		setBooleanValue(MATCH_STRATEGY_PREFIX + className, true);
688

    
689
		List<FieldMatcher> fieldMatchers = matchStrategy.getMatching().getFieldMatchers(false);
690

    
691
		for (FieldMatcher fieldMatcher : fieldMatchers) {
692
			String fieldName = fieldMatcher.getPropertyName();
693
			setStringValue(
694
					getMatchStrategyFieldName(className, fieldName),
695
					fieldMatcher.getMatchMode().name());
696
		}
697
	}
698

    
699
	/**
700
	 * Helper method to create the preference property for a match field.
701
	 *
702
	 * @param className
703
	 * @param fieldName
704
	 * @return
705
	 */
706
	private static String getMatchStrategyFieldName(String className,
707
			String fieldName) {
708
		return MATCH_STRATEGY_PREFIX + className + "." + fieldName;
709
	}
710

    
711
	/**
712
	 * Returns the default match strategy for a given class.
713
	 *
714
	 * @param clazz
715
	 *            a {@link java.lang.Class} object.
716
	 * @return a {@link eu.etaxonomy.cdm.strategy.match.IMatchStrategy} object.
717
	 */
718
	public static IMatchStrategy getDefaultMatchStrategy(Class clazz) {
719
		return DefaultMatchStrategy.NewInstance(clazz);
720
	}
721

    
722
	/**
723
	 * <p>
724
	 * getDateFormatPattern
725
	 * </p>
726
	 *
727
	 * @return a {@link java.lang.String} object.
728
	 */
729
	public static String getDateFormatPattern() {
730
		// TODO make this configurable in properties
731
		String pattern = "Y-M-d H:m";
732
		return pattern;
733
	}
734

    
735
	/**
736
	 * <p>
737
	 * addTermToPreferredTerms
738
	 * </p>
739
	 *
740
	 * @param term
741
	 *            a T object.
742
	 * @param <T>
743
	 *            a T object.
744
	 */
745
	public static <T extends TermBase> void addTermToPreferredTerms(T term) {
746

    
747
		// VocabularyEnum vocabulary =
748
		// VocabularyEnum.getVocabularyEnum(term.getClass());
749
		//
750
		// getPreferenceStore().setValue(getPreferenceKey(term),
751
		// VocabularyStore.getTermVocabulary(vocabulary).getTerms().contains(term));
752
		//
753
		// firePreferencesChanged(term.getClass());
754
	}
755

    
756
	/**
757
	 * Construct a unique key using the CdmBase object's uuid
758
	 *
759
	 * @param cdmBase
760
	 * @return
761
	 */
762
	private static String getPreferenceKey(ICdmBase cdmBase) {
763
		cdmBase = HibernateProxyHelper.deproxy(cdmBase);
764

    
765
		String key = cdmBase.getClass().getName().concat(".")
766
				.concat(cdmBase.getUuid().toString());
767
		if (key.contains("javassist")) {
768
			MessagingUtils.info("proxy");
769
		}
770
		return key;
771
	}
772

    
773
	/**
774
	 * Construct a unique key using the CdmBase object's uuid
775
	 *
776
	 * @param cdmBase
777
	 * @return
778
	 */
779
	public static String getPreferenceKey(ISimpleTerm simpleTerm) {
780
		simpleTerm = HibernateProxyHelper.deproxy(simpleTerm);
781
		String key = simpleTerm.getClass().getName().concat(".")
782
				.concat(simpleTerm.getUuid().toString());
783
		if (key.contains("javassist")) {
784
			MessagingUtils.warn(PreferencesUtil.class,
785
					"Trying to persist a preference based on a proxy class.");
786
		}
787
		return key;
788
	}
789

    
790

    
791

    
792
	/**
793
	 * Construct a unique key using the CdmBase object's uuid
794
	 *
795
	 * @param cdmBase
796
	 * @return
797
	 */
798
	public static String getPreferenceKey(IDefinedTerm definedTerm) {
799
		definedTerm = HibernateProxyHelper.deproxy(definedTerm);
800
		String key = definedTerm.getClass().getName().concat(".")
801
				.concat(definedTerm.getUuid().toString());
802
		if (key.contains("javassist")) {
803
			MessagingUtils.warn(PreferencesUtil.class,
804
					"Trying to persist a preference based on a proxy class.");
805
		}
806
		return key;
807
	}
808

    
809
	/**
810
	 * Retrieves search preferences from the preference store
811
	 *
812
	 * @return an {@link ITaxonServiceConfigurator} to pass to search methods
813
	 */
814
	public static IFindTaxaAndNamesConfigurator getSearchConfigurator() {
815
		IFindTaxaAndNamesConfigurator configurator = initializeSearchConfigurator();
816

    
817
		configurator.setDoTaxa(getBooleanValue(
818
				TAXON_SERVICE_CONFIGURATOR_TAXA));
819
		configurator.setDoSynonyms(getBooleanValue(
820
				TAXON_SERVICE_CONFIGURATOR_SYNONYMS));
821
		configurator.setDoNamesWithoutTaxa(getBooleanValue(
822
				TAXON_SERVICE_CONFIGURATOR_NAMES));
823
		configurator.setDoTaxaByCommonNames(getBooleanValue(
824
				TAXON_SERVICE_CONFIGURATOR_COMMON_NAMES));
825
		//configurator.setMatchMode(eu.etaxonomy.cdm.persistence.query.MatchMode.valueOf(getStringValue(TAXON_SERVICE_CONFIGURATOR_MATCH_MODE)));
826

    
827
		return configurator;
828
	}
829

    
830
	/**
831
	 * create new preferences, setting all search options to true
832
	 *
833
	 * @return a
834
	 *         {@link eu.etaxonomy.cdm.api.service.config.ITaxonServiceConfigurator}
835
	 *         object.
836
	 */
837
	public static IFindTaxaAndNamesConfigurator initializeSearchConfigurator() {
838
		IFindTaxaAndNamesConfigurator configurator = FindTaxaAndNamesConfiguratorImpl.NewInstance();
839

    
840
		configurator.setDoTaxa(true);
841
		configurator.setDoSynonyms(true);
842
		configurator.setDoNamesWithoutTaxa(true);
843
		configurator.setDoTaxaByCommonNames(true);
844

    
845
		configurator.setTaxonPropertyPath(Arrays.asList("$", "titleCache",
846
				"name", "name.$", "relationsFromThisTaxon.$"));
847

    
848
		configurator.setSynonymPropertyPath(Arrays.asList("$", "titleCache",
849
				"name", "name.$", "synonyms.relatedTo.*"));
850

    
851
		// DEFAULT VALUES
852
		// match mode is a simple like, actually all other match modes are kind
853
		// of bogus
854
		configurator
855
				.setMatchMode(eu.etaxonomy.cdm.persistence.query.MatchMode.ANYWHERE);
856
		// we set page number and size here as this should always be unlimited
857
		configurator.setPageNumber(0);
858
		// TODO currently limit results to 10000
859
		configurator.setPageSize(10000);
860
		//setSearchConfigurator(configurator) ;
861
		return configurator;
862
	}
863

    
864
	/**
865
	 * Store search preferences
866
	 *
867
	 * @param configurator
868
	 *            a
869
	 *            {@link eu.etaxonomy.cdm.api.service.config.ITaxonServiceConfigurator}
870
	 *            object.
871
	 */
872
	public static void setSearchConfigurator(
873
			IFindTaxaAndNamesConfigurator configurator) {
874
		getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_TAXA,
875
				configurator.isDoTaxa());
876
		getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_SYNONYMS,
877
				configurator.isDoSynonyms());
878
		getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_NAMES,
879
				configurator.isDoNamesWithoutTaxa());
880
		getPreferenceStore().setValue(TAXON_SERVICE_CONFIGURATOR_COMMON_NAMES,
881
				configurator.isDoTaxaByCommonNames());
882
	}
883

    
884
	/**
885
	 * <p>
886
	 * firePreferencesChanged
887
	 * </p>
888
	 *
889
	 * @param clazz
890
	 *            a {@link java.lang.Class} object.
891
	 */
892
	public static void firePreferencesChanged(Class clazz) {
893
		getPreferenceStore().firePropertyChangeEvent(PREFERRED_TERMS_CHANGE,
894
				null, clazz);
895
	}
896

    
897
	public static String createPreferenceString(String property){
898
	   return prefKey(property);
899

    
900
	}
901
	public static String createOverridePreferenceString(String property){
902
	       return prefOverrideKey(property);
903

    
904
	    }
905

    
906
	/**
907
	 * Set default values for preferences
908
	 */
909
	public static void setDefaults() {
910
		getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_TAXA, true);
911
		getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_SYNONYMS,
912
				true);
913
		getPreferenceStore().setDefault(createPreferenceString(EDIT_MAP_SERVICE_ACCES_POINT),
914
				"http://edit.africamuseum.be/edit_wp5/v1.2/rest_gen.php");
915
		//FIXME : changed default for SHOULD_CONNECT_AT_STARTUP to false (ticket 3828) until resolution
916
		getPreferenceStore().setDefault(createPreferenceString(SHOULD_CONNECT_AT_STARTUP), false);
917
		getPreferenceStore().setDefault(createPreferenceString(OPENURL_ACCESS_POINT),
918
				"http://www.biodiversitylibrary.org/openurl");
919
		getPreferenceStore().setDefault(createPreferenceString(OPENURL_IMAGE_MAX_WIDTH), "1000");
920
		getPreferenceStore().setDefault(createPreferenceString(OPENURL_IMAGE_MAX_HEIGHT), "1000");
921
		getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_TAXA, true);
922
		getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_SYNONYMS, true);
923
		getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_NAMES, true);
924
		getPreferenceStore().setDefault(TAXON_SERVICE_CONFIGURATOR_COMMON_NAMES, true);
925

    
926
		//Distribution Editor:
927
		getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.DistributionEditorActivated.getKey()), Boolean.valueOf(PreferencePredicate.DistributionEditorActivated.getDefaultValue().toString()));
928
//		getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey()), PreferencePredicate.DisplayOfAreasInDistributionEditor.getDefaultValue().toString());
929
//		getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.DisplayOfStatus.getKey()), PreferencePredicate.DisplayOfStatus.getDefaultValue().toString());
930

    
931

    
932
		//Name Details
933
		getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.NameDetailsView.getKey()), new NameDetailsConfigurator(false).toString());
934

    
935
		//Navigator preferences
936
		getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.TaxonNodeOrder.getKey()), NavigatorOrderEnum.RankAndNameOrder.getKey());
937

    
938
		//getPreferenceStore().setDefault(createPreferenceString(Prefe), true);
939

    
940
		getPreferenceStore().setDefault(createPreferenceString(SHOW_ADVANCED_MEDIA_SECTION), false);
941

    
942
        getPreferenceStore().setDefault(createPreferenceString(SHOW_MEDIA_PREVIEW), false);
943
		//override db preferences
944
		getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.AbcdImportConfig.getKey())), false);
945
		getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.ShowSpecimen.getKey())), true);
946
		getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.NameDetailsView.getKey())), false);
947
		getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.DistributionEditorActivated.getKey())), true);
948
		getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.AvailableDistributionStatus.getKey())), true);
949
		getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.AvailableDistributionAreaTerms.getKey())), true);
950
		getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.AvailableDistributionAreaVocabularies.getKey())), true);
951
		getPreferenceStore().setDefault(createPreferenceString(prefOverrideKey(PreferencePredicate.CommonNameAreaVocabularies.getKey())), false);
952
		getPreferenceStore().setDefault(createPreferenceString(FILTER_COMMON_NAME_REFERENCES), false);
953
		getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowTaxonNodeWizard.getKey()), Boolean.valueOf(PreferencePredicate.ShowTaxonNodeWizard.getDefaultValue().toString()));
954
		getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowNamespaceInSource.getKey()), Boolean.valueOf(PreferencePredicate.ShowNamespaceInSource.getDefaultValue().toString()));
955
		getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowIdInSource.getKey()), Boolean.valueOf(PreferencePredicate.ShowIdInSource.getDefaultValue().toString()));
956
		getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.DisableMultiClassification.getKey()), Boolean.valueOf(PreferencePredicate.DisableMultiClassification.getDefaultValue().toString()));
957
		getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowImportExportMenu.getKey()), Boolean.valueOf(PreferencePredicate.ShowImportExportMenu.getDefaultValue().toString()));
958
		getPreferenceStore().setDefault(createPreferenceString(PreferencePredicate.ShowSpecimen.getKey()), Boolean.valueOf(PreferencePredicate.ShowSpecimen.getDefaultValue().toString()));
959

    
960
	}
961

    
962
	/**
963
	 * <p>
964
	 * checkNomenclaturalCode
965
	 * </p>
966
	 */
967
	public static void checkNomenclaturalCode() {
968
		// First time Editor is opened, no nomenclatural code has been set
969
		if (PreferencesUtil.getPreferredNomenclaturalCode() == null) {
970
			PreferencesUtil.setPreferredNomenclaturalCode(getPreferenceKey(NomenclaturalCode.ICNAFP), true);
971
		}
972

    
973

    
974

    
975
	}
976
	public static void setNomenclaturalCodePreferences(){
977
	    ICdmRepository controller;
978
        controller = CdmStore.getCurrentApplicationConfiguration();
979
        PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewDatabaseInstance(), PreferencePredicate.NomenclaturalCode);
980
        CdmPreference preference = null;
981
        if (controller == null){
982
            return ;
983
        }
984
        preference = controller.getPreferenceService().find(key);
985
        if (preference == null){
986
            return;
987
        }
988
//        setBooleanValue(ALLOW_OVERRIDE_NOMENCLATURAL_CODE_KEY, preference.isAllowOverride());
989

    
990
        int index = StringUtils.lastIndexOf(preference.getValue(), ".");
991
        UUID uuid = UUID.fromString(preference.getValue().substring(index +1, preference.getValue().length()));
992
        NomenclaturalCode preferredCode = NomenclaturalCode.getByUuid(uuid);
993

    
994
        setStringValue(PREFERRED_NOMENCLATURAL_CODE_KEY,
995
                getPreferenceKey(preferredCode));
996

    
997
	}
998

    
999
	public static void checkDefaultLanguage(){
1000
	    if(PreferencesUtil.getPreferredDefaultLangugae() == null){
1001
	       Shell shell = AbstractUtility.getShell();
1002
	       int open = new DefaultLanguageDialog(shell).open();
1003
	       if(open == Window.OK){
1004
	           PlatformUI.getWorkbench().restart();
1005
	       }
1006
	    }else{
1007
	        //TODO:In case of a reinstall, the config.ini will be overwritten
1008
	        //     here you create config.ini with the stored key from preferences
1009
	    }
1010
	}
1011

    
1012
	/**
1013
	 * <p>
1014
	 * getMapServiceAccessPoint
1015
	 * </p>
1016
	 *
1017
	 * @return a {@link java.lang.String} object.
1018
	 */
1019
	public static String getMapServiceAccessPoint() {
1020
		return getStringValue(EDIT_MAP_SERVICE_ACCES_POINT);
1021
	}
1022

    
1023
	/**
1024
	 * <p>
1025
	 * shouldConnectAtStartUp
1026
	 * </p>
1027
	 *
1028
	 * @return a boolean.
1029
	 */
1030
	public static boolean shouldConnectAtStartUp() {
1031
		//FIXME :  force SHOULD_CONNECT_AT_STARTUP to false (ticket 3828) until resolution
1032
		//return getBooleanValue(SHOULD_CONNECT_AT_STARTUP);
1033
		return false;
1034
	}
1035

    
1036
	/**
1037
	 * <p>
1038
	 * getDefaultFeatureTreeForTextualDescription
1039
	 * </p>
1040
	 *
1041
	 * @return a {@link eu.etaxonomy.cdm.model.term.FeatureTree} object.
1042
	 */
1043
	public static FeatureTree getDefaultFeatureTreeForTextualDescription() {
1044
		String uuidString = getStringValue(
1045
				FEATURE_TREE_DEFAULT_TEXT);
1046
		if (StringUtils.isBlank(uuidString)) {
1047
            return null;
1048
        }
1049
		FeatureTree tree = CdmStore.getService(
1050
	                IFeatureTreeService.class).load(UUID.fromString(uuidString));
1051
		if (tree.getId() == 0) {
1052
            return null;
1053
        }
1054
		return tree;
1055
	}
1056

    
1057
	/**
1058
	 * <p>
1059
	 * getDefaultFeatureTreeForStructuredDescription
1060
	 * </p>
1061
	 *
1062
	 * @return a {@link eu.etaxonomy.cdm.model.term.FeatureTree} object.
1063
	 */
1064
	public static FeatureTree getDefaultFeatureTreeForStructuredDescription() {
1065
		String uuidString = getStringValue(
1066
				FEATURE_TREE_DEFAULT_STRUCTURE);
1067
		return CdmUtils.isEmpty(uuidString) ? null : CdmStore.getService(
1068
				IFeatureTreeService.class).load(UUID.fromString(uuidString));
1069
	}
1070

    
1071
	/**
1072
	 * <p>
1073
	 * setSortRanksHierarchichally
1074
	 * </p>
1075
	 *
1076
	 * @param selection
1077
	 *            a boolean.
1078
	 */
1079
	public static void setSortRanksHierarchichally(boolean selection) {
1080
		setBooleanValue(SORT_RANKS_HIERARCHICHALLY, selection);
1081
	}
1082

    
1083
	/**
1084
	 * <p>
1085
	 * getSortRanksHierarchichally
1086
	 * </p>
1087
	 *
1088
	 * @return a boolean.
1089
	 */
1090
	public static boolean getSortRanksHierarchichally() {
1091
		return getBooleanValue(SORT_RANKS_HIERARCHICHALLY);
1092
	}
1093

    
1094
	public static boolean isMultilanguageTextEditingCapability() {
1095
		return getBooleanValue(
1096
				MULTILANGUAGE_TEXT_EDITING_CAPABILITY);
1097
	}
1098

    
1099
	public static Language getGlobalLanguage() {
1100

    
1101

    
1102
		String languageUuidString = getStringValue(
1103
				GLOBAL_LANGUAGE_UUID);
1104

    
1105
		if(!CdmStore.isActive()) {
1106
            MessagingUtils.noDataSourceWarningDialog(languageUuidString);
1107
            return null;
1108
        }
1109

    
1110
		if (CdmUtils.isBlank(languageUuidString)) {
1111
			return Language.getDefaultLanguage();
1112
		}
1113

    
1114
		UUID languageUuid = UUID.fromString(languageUuidString);
1115
		return (Language) CdmStore.getService(ITermService.class).load(
1116
				languageUuid);
1117
	}
1118

    
1119
	public static void setGlobalLanguage(Language language) {
1120
	    if(language != null) {
1121
	        setStringValue(GLOBAL_LANGUAGE_UUID,language.getUuid().toString());
1122
	        CdmStore.setDefaultLanguage(language);
1123
	    }
1124

    
1125
	}
1126

    
1127
	/**
1128
	 * @return
1129
	 */
1130
	public static Map<MarkerType, Boolean> getEditMarkerTypePreferences() {
1131
		List<MarkerType> markerTypes = CdmStore.getTermManager()
1132
				.getPreferredTerms(MarkerType.class);
1133

    
1134
		Map<MarkerType, Boolean> result = new HashMap<MarkerType, Boolean>();
1135

    
1136
		for (MarkerType markerType : markerTypes) {
1137
			String name = getMarkerTypeEditingPreferenceKey(markerType);
1138
			Boolean value = getBooleanValue(name);
1139

    
1140
			result.put(markerType, value);
1141
		}
1142

    
1143
		return result;
1144
	}
1145

    
1146
	/**
1147
	 * @param markerTypeEditingMap
1148
	 */
1149
	public static void setEditMarkerTypePreferences(
1150
			Map<MarkerType, Boolean> markerTypeEditingMap) {
1151
		for (MarkerType markerType : markerTypeEditingMap.keySet()) {
1152
			String name = getMarkerTypeEditingPreferenceKey(markerType);
1153
			setBooleanValue(name,
1154
					markerTypeEditingMap.get(markerType));
1155
		}
1156

    
1157
	}
1158

    
1159
	private static String getMarkerTypeEditingPreferenceKey(
1160
			MarkerType markerType) {
1161
		markerType = HibernateProxyHelper.deproxy(markerType);
1162
		return markerType.getClass().getName() + EDIT_MARKER_TYPE_PREFIX;
1163
	}
1164

    
1165
	/**
1166
	 * <p>
1167
	 * setEditMarkerTypePreference
1168
	 * </p>
1169
	 *
1170
	 * @param input
1171
	 *            a {@link org.eclipse.ui.IEditorInput} object.
1172
	 * @param markerType
1173
	 *            a {@link eu.etaxonomy.cdm.model.common.MarkerType} object.
1174
	 * @param edit
1175
	 *            a boolean.
1176
	 */
1177
	public static void setEditMarkerTypePreference(MarkerType markerType,
1178
			boolean edit) {
1179
		setBooleanValue(
1180
				getMarkerTypeEditingPreferenceKey(markerType), edit);
1181
	}
1182

    
1183
	/**
1184
	 * @return
1185
	 */
1186
	public static DerivedUnitFacadeConfigurator getDerivedUnitConfigurator() {
1187
		DerivedUnitFacadeConfigurator configurator = DerivedUnitFacadeConfigurator
1188
				.NewInstance();
1189
		configurator.setMoveDerivedUnitMediaToGallery(true);
1190
		configurator.setMoveFieldObjectMediaToGallery(true);
1191
		return configurator;
1192
	}
1193

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

    
1223
    /**
1224
     * This method loads a property from a given file and returns it.
1225
     *
1226
     * @param filename
1227
     * @return
1228
     * @throws IOException
1229
     */
1230
    private Properties load(String filename) throws IOException {
1231
        FileInputStream in = new FileInputStream(filename);
1232
        Properties prop = new Properties();
1233
        prop.load(in);
1234
        in.close();
1235
        return prop;
1236
    }
1237

    
1238
    /**
1239
     * This method saves a property to the specified file.
1240
     *
1241
     * @param filename
1242
     * @param properties
1243
     * @throws IOException
1244
     */
1245
    private void save(String filename, Properties properties) throws IOException{
1246
        FileOutputStream fos =  new FileOutputStream(filename);
1247
        properties.store(fos, "");
1248
        fos.close();
1249
    }
1250

    
1251
    /**
1252
     * Saves a list of P2 Metadata Repositories as string with specified delimiters
1253
     *
1254
     * @param p2Repos
1255
     */
1256
    public static void setP2Repositories(List<MetadataRepositoryElement> p2Repos) {
1257
        StringBuilder sb = new StringBuilder();
1258
        for(MetadataRepositoryElement p2Repo : p2Repos) {
1259
            sb.append(P2_REPOSITORIES_DELIM);
1260
            if(p2Repo.getName() == null || p2Repo.getName().isEmpty()) {
1261
                sb.append("-");
1262
            } else {
1263
                sb.append(p2Repo.getName());
1264
            }
1265
            sb.append(P2_REPOSITORY_FIELDS_DELIM);
1266
            sb.append(p2Repo.getLocation().toString());
1267
            sb.append(P2_REPOSITORY_FIELDS_DELIM);
1268
            sb.append(String.valueOf(p2Repo.isEnabled()));
1269
        }
1270
        getPreferenceStore().setValue(P2_REPOSITORY_LIST, sb.toString());
1271
    }
1272

    
1273

    
1274
    /**
1275
     * Retrieves a list of previously saved P2 repositories
1276
     *
1277
     * @return
1278
     */
1279
    public static List<MetadataRepositoryElement> getP2Repositories() {
1280
        List<MetadataRepositoryElement> p2Repos = new ArrayList<MetadataRepositoryElement>();
1281
        String p2ReposPref =  getStringValue(P2_REPOSITORY_LIST);
1282
        if(p2ReposPref != null && !p2ReposPref.isEmpty()) {
1283
            StringTokenizer p2ReposPrefST = new StringTokenizer(p2ReposPref,P2_REPOSITORIES_DELIM);
1284

    
1285
            while(p2ReposPrefST.hasMoreTokens()) {
1286
                String p2RepoStr = p2ReposPrefST.nextToken();
1287
                StringTokenizer p2ReposStrST = new StringTokenizer(p2RepoStr,P2_REPOSITORY_FIELDS_DELIM);
1288
                if(p2ReposStrST.countTokens()==3) {
1289
                    String nickname = p2ReposStrST.nextToken();
1290
                    URI uri = null;
1291
                    try {
1292
                        uri = new URI(p2ReposStrST.nextToken());
1293
                    } catch (URISyntaxException e) {
1294
                        continue;
1295
                    }
1296
                    boolean enabled = Boolean.parseBoolean(p2ReposStrST.nextToken());
1297
                    MetadataRepositoryElement mre = new MetadataRepositoryElement(null, uri, true);
1298
                    mre.setNickname(nickname);
1299
                    mre.setEnabled(enabled);
1300
                    p2Repos.add(mre);
1301
                }
1302
            }
1303
        }
1304

    
1305
        return p2Repos;
1306
    }
1307

    
1308
    /**
1309
     * enables/disables nested composite. <br>
1310
     *
1311
     * @param ctrl - Composite to be en-/disabeld
1312
     * @param enabled - boolean
1313
     */
1314
    public static void recursiveSetEnabled(Control ctrl, boolean enabled) {
1315
        if (ctrl instanceof Composite) {
1316
            Composite comp = (Composite) ctrl;
1317
            for (Control c : comp.getChildren()) {
1318
                recursiveSetEnabled(c, enabled);
1319
            }
1320
        } else {
1321
            ctrl.setEnabled(enabled);
1322
        }
1323
    }
1324

    
1325

    
1326

    
1327

    
1328
    /**
1329
     * @param orderActivated
1330
     */
1331
    public static void setSortNodes(NavigatorOrderEnum nodesOrder) {
1332
        setStringValue(PreferencePredicate.TaxonNodeOrder.getKey(), nodesOrder.key);
1333

    
1334
    }
1335

    
1336
    /**
1337
     * @param orderActivated
1338
     */
1339
    public static NavigatorOrderEnum getSortNodes() {
1340
        return NavigatorOrderEnum.valueOf(getStringValue(PreferencePredicate.TaxonNodeOrder.getKey()));
1341

    
1342
    }
1343

    
1344
    /**
1345
     * @param orderActivated
1346
     */
1347
    public static boolean isNodesSortedNaturally() {
1348
        NavigatorOrderEnum value = NavigatorOrderEnum.valueOf(getStringValue(PreferencePredicate.TaxonNodeOrder.getKey()));
1349
        return value.equals(NavigatorOrderEnum.NaturalOrder);
1350

    
1351
    }
1352

    
1353
    /**
1354
     * @param orderActivated
1355
     */
1356
    public static boolean isNodesSortedByName() {
1357
        NavigatorOrderEnum value = NavigatorOrderEnum.valueOf(getStringValue(PreferencePredicate.TaxonNodeOrder.getKey()));
1358
        return value.equals(NavigatorOrderEnum.AlphabeticalOrder);
1359

    
1360
    }
1361

    
1362
    /**
1363
     * @param orderActivated
1364
     */
1365
    public static boolean isNodesSortedByNameAndRank() {
1366
        NavigatorOrderEnum value = NavigatorOrderEnum.valueOf(getStringValue(PreferencePredicate.TaxonNodeOrder.getKey()));
1367
        return value.equals(NavigatorOrderEnum.RankAndNameOrder);
1368

    
1369
    }
1370
	/**
1371
	 * <p>
1372
	 * setStoreNavigatorState
1373
	 * </p>
1374
	 *
1375
	 * @param selection
1376
	 *            a boolean.
1377
	 */
1378
	public static boolean isStoreNavigatorState() {
1379
		return getBooleanValue(RESTORE_NAVIGATOR_STATE);
1380

    
1381
	}
1382

    
1383
	/**
1384
	 * <p>
1385
	 * setStoreNavigatorState
1386
	 * </p>
1387
	 *
1388
	 * @param selection
1389
	 *            a boolean.
1390
	 */
1391
	public static void setStoreNavigatorState(boolean selection) {
1392
		setBooleanValue(RESTORE_NAVIGATOR_STATE, selection);
1393

    
1394
	}
1395

    
1396
    /**
1397
     * @return
1398
     */
1399
    public static boolean isShowUpWidgetIsDisposedMessages() {
1400
       return getBooleanValue(IS_SHOW_UP_WIDGET_IS_DISPOSED);
1401
    }
1402
    public static void setShowUpWidgetIsDisposedMessages(boolean selection) {
1403
        setBooleanValue(IS_SHOW_UP_WIDGET_IS_DISPOSED, selection);
1404
    }
1405

    
1406
    /**
1407
     * @return
1408
     */
1409
    public static boolean isShowIdInVocabularyInChecklistEditor() {
1410
        String area_display = getStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey());
1411
        if (area_display.equals(TermDisplayEnum.IdInVocabulary.getKey())) {
1412
            return true;
1413
        }else{
1414
            return false;
1415
        }
1416
    }
1417
    public static boolean isShowSymbol1InChecklistEditor() {
1418
        String area_display = getStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey());
1419
        if (area_display.equals(TermDisplayEnum.Symbol1.getKey())) {
1420
            return true;
1421
        }else{
1422
            return false;
1423
        }
1424
     }
1425
    public static boolean isShowSymbol2InChecklistEditor() {
1426
        String area_display = getStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey());
1427
        if (area_display.equals(TermDisplayEnum.Symbol2.getKey())) {
1428
            return true;
1429
        }else{
1430
            return false;
1431
        }
1432
     }
1433
    public static void setAreaDisplayInChecklistEditor(String selection) {
1434
        setStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey(), selection);
1435
    }
1436

    
1437
    public static void setOwnDescriptionForChecklistEditor(boolean selection) {
1438
        setBooleanValue(PreferencePredicate.OwnDescriptionForDistributionEditor.getKey(), selection);
1439
    }
1440

    
1441
    public static boolean isOwnDescriptionForChecklistEditor() {
1442
        return getBooleanValue(PreferencePredicate.OwnDescriptionForDistributionEditor.getKey());
1443
    }
1444

    
1445
    /**
1446
     * @return
1447
     */
1448
    public static String displayAreaInChecklistEditor() {
1449
        String result = getStringValue(PreferencePredicate.DisplayOfAreasInDistributionEditor.getKey());
1450
        if (StringUtils.isBlank(result)){
1451
            return ((TermDisplayEnum) PreferencePredicate.DisplayOfAreasInDistributionEditor.getDefaultValue()).getKey();
1452
        }
1453
       return result;
1454
    }
1455

    
1456
    /**
1457
     * @return
1458
     */
1459
    public static String displayStatusInChecklistEditor() {
1460
        String result = getStringValue(PreferencePredicate.DisplayOfStatus.getKey());
1461
        if (StringUtils.isBlank(result)){
1462
            return((TermDisplayEnum) PreferencePredicate.DisplayOfStatus.getDefaultValue()).getKey();
1463
        }
1464
       return result;
1465
    }
1466
    public static void setDisplayStatusInChecklistEditor(String selection) {
1467
        setStringValue(PreferencePredicate.DisplayOfStatus.getKey(), selection);
1468

    
1469
    }
1470

    
1471
    /**
1472
     * @return
1473
     */
1474
    public static boolean isShowRankInChecklistEditor() {
1475
        return getBooleanValue(PreferencePredicate.ShowRankInDistributionEditor.getKey());
1476
    }
1477
    public static void setShowRankInChecklistEditor(boolean selection) {
1478
       setBooleanValue(PreferencePredicate.ShowRankInDistributionEditor.getKey(), selection);
1479
    }
1480

    
1481
    /**
1482
     * @param object
1483
     * @param b
1484
     * @return
1485
     */
1486
    public static NameDetailsConfigurator getPreferredNameDetailsConfiguration( boolean local) {
1487
        NameDetailsConfigurator config = new NameDetailsConfigurator(true);
1488
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1489
        CdmPreference preference = null;
1490
        String value;
1491
        if (!local) {
1492
            PrefKey key = CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.NameDetailsView);
1493
            preference = cache.findBestMatching(key);
1494
            if (preference == null){
1495
                return null;
1496
            }
1497

    
1498
        //    setBooleanValue(ALLOW_OVERRIDE_NAME_DETAILS, preference.isAllowOverride());
1499
            value = preference.getValue();
1500
            config.setAllowOverride(preference.isAllowOverride());
1501
            //the preference value is build like this:
1502
            //<section1>:true;<section2>:false....
1503
        }else{
1504
            value = getStringValue(PreferencePredicate.NameDetailsView.getKey(), local);
1505
        }
1506
        if (value!= null){
1507
            String [] sections = value.split(";");
1508
            Map<String, Boolean> sectionMap = new HashMap<String, Boolean>();
1509
            String[] sectionValues;
1510
            for (String sectionValue: sections){
1511
                sectionValues = sectionValue.split(":");
1512
                sectionMap.put(sectionValues[0], Boolean.valueOf(sectionValues[1]));
1513
            }
1514
            config.setSimpleDetailsViewActivated(getValue(sectionMap, "simpleViewActivated"));
1515
            config.setTaxonSectionActivated(getValue(sectionMap, "taxon"));
1516
            config.setSecDetailsActivated(getValue(sectionMap, "taxon.SecDetails"));
1517
            config.setSecEnabled(getValue(sectionMap, "taxon.SecEnabled"));
1518
            config.setLSIDActivated(getValue(sectionMap, "lsid"));
1519
            config.setNomenclaturalCodeActived(getValue(sectionMap, "nc"));
1520
            config.setAppendedPhraseActivated(getValue(sectionMap, "ap"));
1521
            config.setRankActivated(getValue(sectionMap, "rank"));
1522
            config.setAtomisedEpithetsActivated(getValue(sectionMap, "atomisedEpithets"));
1523
            config.setAuthorshipSectionActivated(getValue(sectionMap,"author"));
1524
            config.setNomenclaturalReferenceSectionActivated(sectionMap.get("nomRef"));
1525
            config.setNomenclaturalStatusSectionActivated(getValue(sectionMap, "nomStat"));
1526
            config.setProtologueActivated(getValue(sectionMap,"protologue"));
1527
            config.setTypeDesignationSectionActivated(getValue(sectionMap,"typeDes"));
1528
            config.setNameRelationsSectionActivated(getValue(sectionMap,"nameRelation"));
1529
            config.setHybridActivated(getValue(sectionMap,"hybrid"));
1530
        }
1531
        return config;
1532
    }
1533

    
1534
    public static NameDetailsConfigurator getPreferredNameDetailsConfiguration() {
1535
        NameDetailsConfigurator config = new NameDetailsConfigurator(true);
1536

    
1537
        String value;
1538

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

    
1549
            config.setSimpleDetailsViewActivated(getValue(sectionMap, "simpleViewActivated"));
1550

    
1551
            config.setTaxonSectionActivated(getValue(sectionMap, "taxon"));
1552

    
1553
            config.setSecDetailsActivated(getValue(sectionMap, "taxon.SecDetails"));
1554
            config.setSecEnabled(getValue(sectionMap, "taxon.SecEnabled"));
1555

    
1556
            config.setLSIDActivated(getValue(sectionMap, "lsid"));
1557

    
1558
            config.setNomenclaturalCodeActived(getValue(sectionMap, "nc"));
1559

    
1560
            config.setAppendedPhraseActivated(getValue(sectionMap, "ap"));
1561

    
1562
            config.setRankActivated(getValue(sectionMap, "rank"));
1563

    
1564
            config.setAtomisedEpithetsActivated(getValue(sectionMap, "atomisedEpithets"));
1565

    
1566
            config.setAuthorshipSectionActivated(getValue(sectionMap,"author"));
1567

    
1568
            config.setNomenclaturalReferenceSectionActivated(sectionMap.get("nomRef"));
1569

    
1570
            config.setNomenclaturalStatusSectionActivated(getValue(sectionMap, "nomStat"));
1571

    
1572
            config.setProtologueActivated(getValue(sectionMap,"protologue"));
1573

    
1574
            config.setTypeDesignationSectionActivated(getValue(sectionMap,"typeDes"));
1575

    
1576
            config.setNameRelationsSectionActivated(getValue(sectionMap,"nameRelation"));
1577

    
1578
                config.setHybridActivated(getValue(sectionMap,"hybrid"));
1579
        }
1580
        return config;
1581
    }
1582

    
1583

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

    
1592
        if (!local) {
1593
            preference = CdmPreference.NewInstance(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.NameDetailsView, config.toString());
1594

    
1595
            setPreferenceToDB(preference);
1596
        }
1597
        else{
1598
            setStringValue(PreferencePredicate.NameDetailsView.getKey(), config.toString());
1599
        }
1600

    
1601

    
1602
    }
1603

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

    
1611
	}
1612

    
1613

    
1614

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

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

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

    
1684
             }
1685
        }
1686
        return config;
1687
    }
1688

    
1689
    public static Abcd206ImportConfigurator getLocalAbcdImportConfigurator(){
1690
       Abcd206ImportConfigurator config = Abcd206ImportConfigurator.NewInstance(null,null);
1691

    
1692
        config.setAddIndividualsAssociationsSuchAsSpecimenAndObservations(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_ADD_INDIVIDUALS_ASSOCIATIONS_SUCH_AS_SPECIMEN_AND_OBSERVATIONS));
1693

    
1694
        config.setAddMediaAsMediaSpecimen(getBooleanValue(IPreferenceKeys.ABCD_IMPORT_CONFIGURATOR_ADD_MEDIA_AS_MEDIASPECIMEN));
1695

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

    
1713
        return config;
1714

    
1715
    }
1716

    
1717

    
1718
    public static void updateAbcdImportConfigurationPreference() {
1719
        CdmPreferenceCache cache = CdmPreferenceCache.instance();
1720

    
1721
        CdmPreference pref = cache.findBestMatching(CdmPreference.NewKey(PreferenceSubject.NewTaxEditorInstance(), PreferencePredicate.AbcdImportConfig));
1722

    
1723
        if (!getBooleanValue(prefOverrideKey(PreferencePredicate.AbcdImportConfig.getKey())) || !pref.isAllowOverride()){
1724
            resetToDBPreferenceAbcdCOnfigurator();
1725

    
1726
        }
1727
    }
1728

    
1729
    public static void resetToDBPreferenceAbcdCOnfigurator(){
1730
        Abcd206ImportConfigurator config = getDBAbcdImportConfigurationPreference();
1731
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_ADD_INDIVIDUALS_ASSOCIATIONS_SUCH_AS_SPECIMEN_AND_OBSERVATIONS, config.isAddIndividualsAssociationsSuchAsSpecimenAndObservations());
1732
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_ADD_MEDIA_AS_MEDIASPECIMEN, config.isAddMediaAsMediaSpecimen());
1733

    
1734
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_ALLOW_REUSE_OTHER_CLASSIFICATIONS, config.isAllowReuseOtherClassifications());
1735
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_DEDUPLICATE_CLASSIFICATIONS, config.isDeduplicateClassifications());
1736
        setBooleanValue(ABCD_IMPORT_CONFIGURATOR_DEDUPLICATE_REFERENCES, config.isDeduplicateReferences());
1737

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

    
1754

    
1755

    
1756

    
1757

    
1758

    
1759

    
1760
/**
1761
 * @return
1762
 */
1763
public static boolean isSortTaxaByRankAndName() {
1764

    
1765
    return getBooleanValue(IPreferenceKeys.SORT_TAXA_BY_RANK_AND_NAME);
1766
}
1767

    
1768
/**
1769
 * @return
1770
 */
1771
public static String getSortNamedAreasInDistributionEditor() {
1772

    
1773
    return getStringValue(PreferencePredicate.AreasSortedInDistributionEditor.getKey());
1774
}
1775

    
1776
public static void setSortNamedAreasInDistributionEditor(String isSortByVocabularyOrder) {
1777
    setStringValue(PreferencePredicate.AreasSortedInDistributionEditor.getKey(), isSortByVocabularyOrder);
1778

    
1779
}
1780

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

    
1792
        setStringValue(PreferencesUtil.LAST_SELECTED_REFERENCES, lastSelectedReferences.toString());
1793
    }
1794

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

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

    
1814

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

    
1828
    }
1829
    else{
1830
        CdmPreference preference = null;
1831

    
1832
        if (saveCheckedElements == null){
1833
            preference = getPreferenceFromDB(PreferencePredicate.AvailableDistributionAreaTerms);
1834

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

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

    
1850
        }
1851
    }
1852

    
1853
}
1854

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

    
1870
        if (saveCheckedElements == null){
1871
            preference = getPreferenceFromDB(PreferencePredicate.AvailableDistributionAreaVocabularies);
1872

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

    
1889
        }
1890
    }
1891
}
1892

    
1893

    
1894
/**
1895
 * @param saveCheckedElements
1896
 * @param saveCheckedElements2
1897
 * @param b
1898
 */
1899
public static String getPreferredVocabulariesForDistributionEditor(boolean local) {
1900
    if (local){
1901

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

    
1914
    }
1915
}
1916

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

    
1929
public static boolean getFilterCommonNameReferences(){
1930
    return getBooleanValue(PreferencesUtil.FILTER_COMMON_NAME_REFERENCES);
1931
}
1932

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

    
1941
    //ABCD Configurator
1942

    
1943
    updateAbcdImportConfigurationPreference();
1944

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

    
1953

    
1954

    
1955

    
1956

    
1957

    
1958

    
1959

    
1960
}
1961

    
1962
/**
1963
 * @param string
1964
 * @param saveCheckedElements
1965
 */
1966
public static void setPreferencesToDB(List<CdmPreference> preferences) {
1967

    
1968
    ICdmRepository controller;
1969
    try{
1970
        if(CdmStore.isActive()){
1971
            controller = CdmStore.getCurrentApplicationConfiguration();
1972
            for (CdmPreference preference: preferences){
1973

    
1974
                controller.getPreferenceService().set(preference);
1975

    
1976
                CdmPreferenceCache.instance().put(preference);
1977
            }
1978
        }
1979
    }catch(Exception e){
1980
        e.printStackTrace();
1981
    }
1982
}
1983

    
1984

    
1985

    
1986

    
1987

    
1988

    
1989

    
1990

    
1991
}
(27-27/41)